dolibarr 20.0.5
fileupload.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2011-2022 Regis Houssin <regis.houssin@inodbox.com>
3 * Copyright (C) 2011-2023 Laurent Destailleur <eldy@users.sourceforge.net>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
26require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
27require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
28
29
34{
35 public $options;
36 protected $fk_element;
37 protected $element;
38
47 public function __construct($options = null, $fk_element = null, $element = null)
48 {
49 global $db;
50 global $hookmanager;
51
52 $hookmanager->initHooks(array('fileupload'));
53
54 $element_prop = getElementProperties($element);
55 //var_dump($element_prop);
56
57 $this->fk_element = $fk_element;
58 $this->element = $element;
59
60 $pathname = str_replace('/class', '', $element_prop['classpath']);
61
62
63 $filename = dol_sanitizeFileName($element_prop['classfile']);
64 $dir_output = dol_sanitizePathName($element_prop['dir_output']);
65 $savingDocMask = '';
66
67 //print 'fileupload.class.php: element='.$element.' pathname='.$pathname.' filename='.$filename.' dir_output='.$dir_output."\n";
68
69 if (empty($dir_output)) {
70 setEventMessage('The element '.$element.' is not supported for uploading file. dir_output is unknown.', 'errors');
71 throw new Exception('The element '.$element.' is not supported for uploading file. dir_output is unknown.');
72 }
73
74 // If pathname and filename are null then we can still upload files if we have specified upload_dir on $options
75 if ($pathname !== null && $filename !== null) {
76 // Get object from its id and type
77 $object = fetchObjectByElement($fk_element, $element);
78
79 $object_ref = dol_sanitizeFileName($object->ref);
80
81 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
82 if (!getDolGlobalInt('MAIN_DISABLE_SUGGEST_REF_AS_PREFIX')) {
83 $savingDocMask = $object_ref.'-__file__';
84 }
85
86 // Special cases to forge $object_ref used to forge $upload_dir
87 if ($element == 'invoice_supplier') {
88 $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
89 } elseif ($element == 'project_task') {
90 $parentForeignKey = 'fk_project';
91 $parentClass = 'Project';
92 $parentElement = 'projet';
93 $parentObject = 'project';
94
95 dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
96 $parent = new $parentClass($db);
97 $parent->fetch($object->$parentForeignKey);
98 if (!empty($parent->socid)) {
99 $parent->fetch_thirdparty();
100 }
101 $object->$parentObject = clone $parent;
102
103 $object_ref = dol_sanitizeFileName($object->project->ref).'/'.$object_ref;
104 }
105 }
106
107 $this->options = array(
108 'script_url' => $_SERVER['PHP_SELF'],
109 'upload_dir' => $dir_output.'/'.$object_ref.'/',
110 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
111 'saving_doc_mask' => $savingDocMask,
112 'param_name' => 'files',
113 // Set the following option to 'POST', if your server does not support
114 // DELETE requests. This is a parameter sent to the client:
115 'delete_type' => 'DELETE',
116 // The php.ini settings upload_max_filesize and post_max_size
117 // take precedence over the following max_file_size setting:
118 'max_file_size' => null,
119 'min_file_size' => 1,
120 'accept_file_types' => '/.+$/i',
121 // The maximum number of files for the upload directory:
122 'max_number_of_files' => null,
123 // Image resolution restrictions:
124 'max_width' => null,
125 'max_height' => null,
126 'min_width' => 1,
127 'min_height' => 1,
128 // Set the following option to false to enable resumable uploads:
129 'discard_aborted_uploads' => true,
130 'image_versions' => array(
131 // Uncomment the following version to restrict the size of
132 // uploaded images. You can also add additional versions with
133 // their own upload directories:
134 /*
135 'large' => array(
136 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
137 'upload_url' => $this->getFullUrl().'/files/',
138 'max_width' => 1920,
139 'max_height' => 1200,
140 'jpeg_quality' => 95
141 ),
142 */
143 'thumbnail' => array(
144 'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
145 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.urlencode($element).'&attachment=1&file='.urlencode('/'.$object_ref.'/thumbs/'),
146 'max_width' => 80,
147 'max_height' => 80
148 )
149 )
150 );
151
152 global $action;
153
154 $hookmanager->executeHooks(
155 'overrideUploadOptions',
156 array(
157 'options' => &$options,
158 'element' => $element
159 ),
160 $object,
161 $action
162 );
163
164 if ($options) {
165 $this->options = array_replace_recursive($this->options, $options);
166 }
167
168 // At this point we should have a valid upload_dir in options
169 //if ($pathname === null && $filename === null) { // OR or AND???
170 if ($pathname === null || $filename === null) {
171 if (!array_key_exists("upload_dir", $this->options)) {
172 setEventMessage('If $fk_element = null or $element = null you must specify upload_dir on $options', 'errors');
173 throw new Exception('If $fk_element = null or $element = null you must specify upload_dir on $options');
174 } elseif (!is_dir($this->options['upload_dir'])) {
175 setEventMessage('The directory '.$this->options['upload_dir'].' doesn\'t exists', 'errors');
176 throw new Exception('The directory '.$this->options['upload_dir'].' doesn\'t exists');
177 } elseif (!is_writable($this->options['upload_dir'])) {
178 setEventMessage('The directory '.$this->options['upload_dir'].' is not writable', 'errors');
179 throw new Exception('The directory '.$this->options['upload_dir'].' is not writable');
180 }
181 }
182 }
183
189 protected function getFullUrl()
190 {
191 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
192 return
193 ($https ? 'https://' : 'http://').
194 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
195 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
196 ($https && $_SERVER['SERVER_PORT'] === 443 ||
197 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
198 substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
199 }
200
207 protected function setFileDeleteUrl($file)
208 {
209 $file->delete_url = $this->options['script_url'].'?file='.urlencode((string) ($file->name)).'&fk_element='.urlencode((string) ($this->fk_element)).'&element='.urlencode((string) ($this->element));
210 $file->delete_type = $this->options['delete_type'];
211 if ($file->delete_type !== 'DELETE') {
212 $file->delete_url .= '&_method=DELETE';
213 }
214 }
215
222 protected function getFileObject($file_name)
223 {
224 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
225
226 if (dol_is_file($file_path) && $file_name[0] !== '.') {
227 $file = new stdClass();
228 $file->name = $file_name;
229 $file->mime = dol_mimetype($file_name, '', 2);
230 $file->size = filesize($file_path);
231 $file->url = $this->options['upload_url'].urlencode($file->name);
232
233 foreach ($this->options['image_versions'] as $version => $options) {
234 if (dol_is_file($options['upload_dir'].$file_name)) {
235 $tmp = explode('.', $file->name);
236
237 // We save the path of mini file into file->... (seems not used)
238 $keyforfile = $version.'_url';
239 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
240 }
241 }
242 $this->setFileDeleteUrl($file);
243 return $file;
244 }
245 return null;
246 }
247
253 protected function getFileObjects()
254 {
255 return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
256 }
257
265 protected function createScaledImage($file_name, $options)
266 {
267 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
268
269 $file_path = $this->options['upload_dir'].$file_name;
270 $new_file_path = $options['upload_dir'].$file_name;
271
272 if (dol_mkdir($options['upload_dir']) >= 0) {
273 list($img_width, $img_height) = @getimagesize($file_path);
274 if (!$img_width || !$img_height) {
275 return false;
276 }
277
278 $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object
279 if (preg_match('/error/i', $res)) {
280 return false;
281 }
282
283 $res = vignette($file_path, $maxwidthsmall, $maxheightsmall, '_small'); // We don't use ->addThumbs here because there is no object
284 if (preg_match('/error/i', $res)) {
285 return false;
286 }
287
288 return true;
289 } else {
290 return false;
291 }
292 }
293
303 protected function validate($uploaded_file, $file, $error, $index)
304 {
305 if ($error) {
306 $file->error = $error;
307 return false;
308 }
309 if (!$file->name) {
310 $file->error = 'missingFileName';
311 return false;
312 }
313 if (!preg_match($this->options['accept_file_types'], $file->name)) {
314 $file->error = 'acceptFileTypes';
315 return false;
316 }
317 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
318 $file_size = dol_filesize($uploaded_file);
319 } else {
320 $file_size = $_SERVER['CONTENT_LENGTH'];
321 }
322 if ($this->options['max_file_size'] && (
323 $file_size > $this->options['max_file_size'] ||
324 $file->size > $this->options['max_file_size']
325 )
326 ) {
327 $file->error = 'maxFileSize';
328 return false;
329 }
330 if ($this->options['min_file_size'] &&
331 $file_size < $this->options['min_file_size']) {
332 $file->error = 'minFileSize';
333 return false;
334 }
335 if (is_numeric($this->options['max_number_of_files']) && (
336 count($this->getFileObjects()) >= $this->options['max_number_of_files']
337 )
338 ) {
339 $file->error = 'maxNumberOfFiles';
340 return false;
341 }
342 list($img_width, $img_height) = @getimagesize($uploaded_file);
343 if (is_numeric($img_width)) {
344 if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
345 $this->options['max_height'] && $img_height > $this->options['max_height']) {
346 $file->error = 'maxResolution';
347 return false;
348 }
349 if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
350 $this->options['min_height'] && $img_height < $this->options['min_height']) {
351 $file->error = 'minResolution';
352 return false;
353 }
354 }
355 return true;
356 }
357
364 protected function upcountNameCallback($matches)
365 {
366 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
367 $ext = isset($matches[2]) ? $matches[2] : '';
368 return ' ('.$index.')'.$ext;
369 }
370
377 protected function upcountName($name)
378 {
379 return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
380 }
381
390 protected function trimFileName($name, $type, $index)
391 {
392 // Remove path information and dots around the filename, to prevent uploading
393 // into different directories or replacing hidden system files.
394 $file_name = basename(dol_sanitizeFileName($name));
395 // Add missing file extension for known image types:
396 $matches = array();
397 if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
398 $file_name .= '.'.$matches[1];
399 }
400 if ($this->options['discard_aborted_uploads']) {
401 while (dol_is_file($this->options['upload_dir'].$file_name)) {
402 $file_name = $this->upcountName($file_name);
403 }
404 }
405 return $file_name;
406 }
407
420 protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
421 {
422 $file = new stdClass();
423 $file->name = $this->trimFileName($name, $type, $index);
424 $file->mime = dol_mimetype($file->name, '', 2);
425 $file->size = intval($size);
426 $file->type = $type;
427
428 // Sanitize to avoid stream execution when calling file_size(). Not that this is a second security because
429 // most streams are already disabled by stream_wrapper_unregister() in filefunc.inc.php
430 $uploaded_file = preg_replace('/\s*(http|ftp)s?:/i', '', $uploaded_file);
431 $uploaded_file = realpath($uploaded_file); // A hack to be sure the file point to an existing file on disk (and is not a SSRF attack)
432
433 $validate = $this->validate($uploaded_file, $file, $error, $index);
434
435 if ($validate) {
436 if (dol_mkdir($this->options['upload_dir']) >= 0) {
437 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
438 $fileNameWithoutExt = preg_replace('/\.[^\.]+$/', '', $file->name);
439 $savingDocMask = $this->options['saving_doc_mask'];
440 if ($savingDocMask && strpos($savingDocMask, $fileNameWithoutExt) !== 0) {
441 $fileNameWithPrefix = preg_replace('/__file__/', $file->name, $savingDocMask);
442 $file->name = $fileNameWithPrefix;
443 }
444
445 $file_path = dol_sanitizePathName($this->options['upload_dir']).dol_sanitizeFileName($file->name);
446 $append_file = !$this->options['discard_aborted_uploads'] && dol_is_file($file_path) && $file->size > dol_filesize($file_path);
447
448 clearstatcache();
449
450 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
451 // multipart/formdata uploads (POST method uploads)
452 if ($append_file) {
453 file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
454 } else {
455 $result = dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
456 }
457 } else {
458 // Non-multipart uploads (PUT method support)
459 file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
460 }
461 $file_size = dol_filesize($file_path);
462 if ($file_size === $file->size) {
463 $file->url = $this->options['upload_url'].urlencode($file->name);
464 foreach ($this->options['image_versions'] as $version => $options) {
465 if ($this->createScaledImage($file->name, $options)) { // Creation of thumbs mini and small is ok
466 $tmp = explode('.', $file->name);
467
468 // We save the path of mini file into file->... (seems not used)
469 $keyforfile = $version.'_url';
470 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
471 }
472 }
473 } elseif ($this->options['discard_aborted_uploads']) {
474 unlink($file_path);
475 $file->error = 'abort';
476 }
477 $file->size = $file_size;
478 $this->setFileDeleteUrl($file);
479 } else {
480 $file->error = 'failedtocreatedestdir';
481 }
482 } else {
483 // should not happen
484 }
485
486 return $file;
487 }
488
494 /*public function get()
495 {
496 $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
497 if ($file_name) {
498 $info = $this->getFileObject($file_name);
499 } else {
500 $info = $this->getFileObjects();
501 }
502
503 header('Content-type: application/json');
504 echo json_encode($info);
505 }
506 */
507
513 public function post()
514 {
515 $error = 0;
516
517 $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null;
518
519 $info = array();
520 if ($upload && is_array($upload['tmp_name'])) {
521 // param_name is an array identifier like "files[]",
522 // $_FILES is a multi-dimensional array:
523 foreach ($upload['tmp_name'] as $index => $value) {
524 $tmpres = $this->handleFileUpload(
525 $upload['tmp_name'][$index],
526 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
527 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
528 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
529 $upload['error'][$index],
530 $index
531 );
532 if (!empty($tmpres->error)) {
533 $error++;
534 }
535 $info[] = $tmpres;
536 }
537 } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
538 // param_name is a single object identifier like "file",
539 // $_FILES is a one-dimensional array:
540 $tmpres = $this->handleFileUpload(
541 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
542 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
543 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
544 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
545 isset($upload['error']) ? $upload['error'] : null,
546 0
547 );
548 if (!empty($tmpres->error)) {
549 $error++;
550 }
551 $info[] = $tmpres;
552 }
553
554 header('Vary: Accept');
555 $json = json_encode($info);
556
557 /* disabled. Param redirect seems not used
558 $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null;
559 if ($redirect) {
560 header('Location: '.sprintf($redirect, urlencode($json)));
561 return;
562 }
563 */
564
565 if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
566 header('Content-type: application/json');
567 } else {
568 header('Content-type: text/plain');
569 }
570 echo $json;
571
572 return $error;
573 }
574
581 /*
582 public function delete($file)
583 {
584 $file_name = $file ? basename($file) : null;
585 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
586 $success = dol_is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
587 if ($success) {
588 foreach ($this->options['image_versions'] as $version => $options) {
589 $file = $options['upload_dir'].$file_name;
590 if (dol_is_file($file)) {
591 unlink($file);
592 }
593 }
594 }
595 // Return result in json format
596 header('Content-type: application/json');
597 echo json_encode($success);
598
599 return 0;
600 }
601 */
602}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
This class is used to manage file upload using ajax.
getFileObjects()
getFileObjects
setFileDeleteUrl($file)
Set delete url.
__construct($options=null, $fk_element=null, $element=null)
Constructor.
post()
Output data.
handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
handleFileUpload.
upcountName($name)
Enter description here ...
getFileObject($file_name)
getFileObject
upcountNameCallback($matches)
Enter description here ...
createScaledImage($file_name, $options)
Create thumbs of a file uploaded.
getFullUrl()
Return full URL.
trimFileName($name, $type, $index)
trimFileName
validate($uploaded_file, $file, $error, $index)
Make validation on an uploaded file.
dol_filesize($pathoffile)
Return size of a file.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile', $upload_dir='')
Check validity of a file upload from an GUI page, and move it to its final destination.
dol_is_file($pathoffile)
Return if path is a file.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message in dol_events session object.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
fetchObjectByElement($element_id, $element_type, $element_ref='', $useCache=0, $maxCacheByType=10)
Fetch an object from its id and element_type Inclusion of classes is automatic.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).