dolibarr 23.0.3
fileupload.class.php
Go to the documentation of this file.
1<?php
2
3/* Copyright (C) 2011-2022 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2011-2023 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
29require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
31
32
37{
41 public $options;
45 protected $fk_element;
46
50 protected $element;
51
60 public function __construct($options = null, $fk_element = null, $element = null)
61 {
62 global $db;
63 global $hookmanager;
64
65 $hookmanager->initHooks(array('fileupload'));
66
67 $element_prop = getElementProperties($element);
68 //var_dump($element_prop);
69
70 $this->fk_element = $fk_element;
71 $this->element = $element;
72
73 $pathname = str_replace('/class', '', $element_prop['classpath']);
74 $filename = dol_sanitizeFileName($element_prop['classfile']);
75 $dir_output = dol_sanitizePathName($element_prop['dir_output']);
76 $savingDocMask = '';
77
78 //print 'fileupload.class.php: element='.$element.' pathname='.$pathname.' filename='.$filename.' dir_output='.$dir_output."\n";
79
80 if (empty($dir_output)) {
81 setEventMessage('The element '.$element.' is not supported for uploading file. dir_output is unknown.', 'errors');
82 throw new Exception('The element '.$element.' is not supported for uploading file. dir_output is unknown.');
83 }
84
85 $object_ref = 'UndefinedReference';
86 // If pathname and filename are null then we can still upload files if we have specified upload_dir on $options
87 if ($pathname !== null && $filename !== null) {
88 // Get object from its id and type
89 $object = fetchObjectByElement($fk_element, $element);
90
91 $object_ref = dol_sanitizeFileName($object->ref);
92
93 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
94 if (!getDolGlobalInt('MAIN_DISABLE_SUGGEST_REF_AS_PREFIX')) {
95 $savingDocMask = $object_ref.'-__file__';
96 }
97
98 // Special cases to forge $object_ref used to forge $upload_dir
99 if ($element == 'invoice_supplier') {
100 $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
101 } elseif ($element == 'project_task') {
102 $parentForeignKey = 'fk_project';
103 $parentClass = 'Project';
104 $parentElement = 'projet';
105 $parentObject = 'project';
106
107 dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
108 $parent = new $parentClass($db);
109 $parent->fetch($object->$parentForeignKey);
110 if (!empty($parent->socid)) {
111 $parent->fetch_thirdparty();
112 }
113 $object->$parentObject = clone $parent;
114
115 $object_ref = dol_sanitizeFileName($object->project->ref).'/'.$object_ref;
116 }
117 }
118
119 $this->options = array(
120 'script_url' => $_SERVER['PHP_SELF'],
121 'upload_dir' => $dir_output.'/'.$object_ref.'/',
122 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
123 'saving_doc_mask' => $savingDocMask,
124 'param_name' => 'files',
125 // Set the following option to 'POST', if your server does not support
126 // DELETE requests. This is a parameter sent to the client:
127 'delete_type' => 'DELETE',
128 // The php.ini settings upload_max_filesize and post_max_size
129 // take precedence over the following max_file_size setting:
130 'max_file_size' => null,
131 'min_file_size' => 1,
132 'accept_file_types' => '/.+$/i',
133 // The maximum number of files for the upload directory:
134 'max_number_of_files' => null,
135 // Image resolution restrictions:
136 'max_width' => null,
137 'max_height' => null,
138 'min_width' => 1,
139 'min_height' => 1,
140 // Set the following option to false to enable resumable uploads:
141 'discard_aborted_uploads' => true,
142 'image_versions' => array(
143 // Uncomment the following version to restrict the size of
144 // uploaded images. You can also add additional versions with
145 // their own upload directories:
146 /*
147 'large' => array(
148 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
149 'upload_url' => $this->getFullUrl().'/files/',
150 'max_width' => 1920,
151 'max_height' => 1200,
152 'jpeg_quality' => 95
153 ),
154 */
155 'thumbnail' => array(
156 'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
157 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.urlencode($element).'&attachment=1&file='.urlencode('/'.$object_ref.'/thumbs/'),
158 'max_width' => 80,
159 'max_height' => 80
160 )
161 )
162 );
163
164 global $action;
165
166 $hookmanager->executeHooks(
167 'overrideUploadOptions',
168 array(
169 'options' => &$options,
170 'element' => $element
171 ),
172 $object, // @phan-suppress-current-line PhanTypeMismatchArgumentNullable
173 $action
174 );
175
176 if ($options) {
177 $this->options = array_replace_recursive($this->options, $options);
178 }
179
180 // At this point we should have a valid upload_dir in this->options
181 if (empty($pathname) || empty($filename)) {
182 if (!array_key_exists("upload_dir", $this->options)) {
183 setEventMessage('If $fk_element = null or $element = null you must specify upload_dir on $options', 'errors');
184 throw new Exception('If $fk_element = null or $element = null you must specify upload_dir on $options');
185 } elseif (!is_dir($this->options['upload_dir'])) {
186 setEventMessage('The directory '.$this->options['upload_dir'].' doesn\'t exists', 'errors');
187 throw new Exception('The directory '.$this->options['upload_dir'].' doesn\'t exists');
188 } elseif (!is_writable($this->options['upload_dir'])) {
189 setEventMessage('The directory '.$this->options['upload_dir'].' is not writable', 'errors');
190 throw new Exception('The directory '.$this->options['upload_dir'].' is not writable');
191 }
192 }
193 }
194
200 protected function getFullUrl()
201 {
202 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
203 return
204 ($https ? 'https://' : 'http://').
205 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
206 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
207 ($https && $_SERVER['SERVER_PORT'] === 443 ||
208 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
209 substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
210 }
211
218 protected function setFileDeleteUrl($file)
219 {
220 $file->delete_url = $this->options['script_url'].'?file='.urlencode((string) ($file->name)).'&fk_element='.urlencode((string) ($this->fk_element)).'&element='.urlencode((string) ($this->element));
221 $file->delete_type = $this->options['delete_type'];
222 if ($file->delete_type !== 'DELETE') {
223 $file->delete_url .= '&_method=DELETE';
224 }
225 }
226
233 protected function getFileObject($file_name)
234 {
235 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
236
237 if (dol_is_file($file_path) && $file_name[0] !== '.') {
238 $file = new stdClass();
239 $file->name = $file_name;
240 $file->mime = dol_mimetype($file_name, '', 2);
241 $file->size = filesize($file_path);
242 $file->url = $this->options['upload_url'].urlencode($file->name);
243
244 foreach ($this->options['image_versions'] as $version => $options) {
245 if (dol_is_file($options['upload_dir'].$file_name)) {
246 $tmp = explode('.', $file->name);
247
248 // We save the path of mini file into file->... (seems not used)
249 $keyforfile = $version.'_url';
250 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
251 }
252 }
253 $this->setFileDeleteUrl($file);
254 return $file;
255 }
256 return null;
257 }
258
264 protected function getFileObjects()
265 {
266 return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
267 }
268
276 protected function createScaledImage($file_name, $options)
277 {
278 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
279
280 $file_path = $this->options['upload_dir'].$file_name;
281 $new_file_path = $options['upload_dir'].$file_name;
282
283 if (dol_mkdir($options['upload_dir']) >= 0) {
284 list($img_width, $img_height) = @getimagesize($file_path);
285 if (!$img_width || !$img_height) {
286 return false;
287 }
288
289 $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object
290 if (preg_match('/error/i', $res)) {
291 return false;
292 }
293
294 $res = vignette($file_path, $maxwidthsmall, $maxheightsmall, '_small'); // We don't use ->addThumbs here because there is no object
295 if (preg_match('/error/i', $res)) {
296 return false;
297 }
298
299 return true;
300 } else {
301 return false;
302 }
303 }
304
314 protected function validate($uploaded_file, $file, $error, $index)
315 {
316 if ($error) {
317 $file->error = $error;
318 return false;
319 }
320 if (!$file->name) {
321 $file->error = 'missingFileName';
322 return false;
323 }
324 if (!preg_match($this->options['accept_file_types'], $file->name)) {
325 $file->error = 'acceptFileTypes';
326 return false;
327 }
328 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
329 $file_size = dol_filesize($uploaded_file);
330 } else {
331 $file_size = $_SERVER['CONTENT_LENGTH'];
332 }
333 if ($this->options['max_file_size'] && (
334 $file_size > $this->options['max_file_size'] ||
335 $file->size > $this->options['max_file_size']
336 )
337 ) {
338 $file->error = 'maxFileSize';
339 return false;
340 }
341 if ($this->options['min_file_size'] &&
342 $file_size < $this->options['min_file_size']) {
343 $file->error = 'minFileSize';
344 return false;
345 }
346 if (is_numeric($this->options['max_number_of_files']) && (
347 count($this->getFileObjects()) >= $this->options['max_number_of_files']
348 )
349 ) {
350 $file->error = 'maxNumberOfFiles';
351 return false;
352 }
353 list($img_width, $img_height) = @getimagesize($uploaded_file);
354 if (is_numeric($img_width)) {
355 if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
356 $this->options['max_height'] && $img_height > $this->options['max_height']) {
357 $file->error = 'maxResolution';
358 return false;
359 }
360 if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
361 $this->options['min_height'] && $img_height < $this->options['min_height']) {
362 $file->error = 'minResolution';
363 return false;
364 }
365 }
366 return true;
367 }
368
375 protected function upcountNameCallback($matches)
376 {
377 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
378 $ext = isset($matches[2]) ? $matches[2] : '';
379 return ' ('.$index.')'.$ext;
380 }
381
388 protected function upcountName($name)
389 {
390 return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
391 }
392
401 protected function trimFileName($name, $type, $index)
402 {
403 // Remove path information and dots around the filename, to prevent uploading
404 // into different directories or replacing hidden system files.
405 $file_name = basename(dol_sanitizeFileName($name));
406 // Add missing file extension for known image types:
407 $matches = array();
408 if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
409 $file_name .= '.'.$matches[1];
410 }
411 if ($this->options['discard_aborted_uploads']) {
412 while (dol_is_file($this->options['upload_dir'].$file_name)) {
413 $file_name = $this->upcountName($file_name);
414 }
415 }
416 return $file_name;
417 }
418
432 protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
433 {
434 $file = new stdClass();
435 $file->name = $this->trimFileName($name, $type, $index);
436 $file->mime = dol_mimetype($file->name, '', 2);
437 $file->size = intval($size);
438 $file->type = $type;
439
440 // Sanitize to avoid stream execution when calling file_size(). Not that this is a second security because
441 // most streams are already disabled by stream_wrapper_unregister() in filefunc.inc.php
442 $uploaded_file = preg_replace('/\s*(http|ftp|sftp|)s?:/i', '', $uploaded_file);
443 $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)
444
445 $validate = $this->validate($uploaded_file, $file, $error, $index);
446
447 if ($validate) {
448 if (dol_mkdir($this->options['upload_dir']) >= 0) {
449 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
450 $fileNameWithoutExt = preg_replace('/\.[^\.]+$/', '', $file->name);
451 $savingDocMask = $this->options['saving_doc_mask'];
452 if ($savingDocMask && strpos($savingDocMask, $fileNameWithoutExt) !== 0) {
453 $fileNameWithPrefix = preg_replace('/__file__/', $file->name, $savingDocMask);
454 $file->name = $fileNameWithPrefix;
455 }
456
457 $file_path = dol_sanitizePathName($this->options['upload_dir']).dol_sanitizeFileName($file->name);
458 $append_file = !$this->options['discard_aborted_uploads'] && dol_is_file($file_path) && $file->size > dol_filesize($file_path);
459
460 clearstatcache();
461
462 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
463 // multipart/formdata uploads (POST method uploads)
464 if ($append_file) {
465 file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
466 } else {
467 // TODO Replace this with a call of dol_add_file_process(... $mode=1)
468 $result = dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
469 }
470 } else {
471 // Non-multipart uploads (PUT method support)
472 file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
473 }
474 dolChmod($file_path);
475
476 $file_size = dol_filesize($file_path);
477 if ($file_size === $file->size) {
478 $file->url = $this->options['upload_url'].urlencode($file->name);
479 foreach ($this->options['image_versions'] as $version => $options) {
480 if ($this->createScaledImage($file->name, $options)) { // Creation of thumbs mini and small is ok
481 $tmp = explode('.', $file->name);
482
483 // We save the path of mini file into file->... (seems not used)
484 $keyforfile = $version.'_url';
485 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
486 }
487 }
488 } elseif ($this->options['discard_aborted_uploads']) {
489 unlink($file_path);
490 $file->error = 'abort';
491 }
492 $file->size = $file_size;
493 $this->setFileDeleteUrl($file);
494 } else {
495 $file->error = 'failedtocreatedestdir';
496 }
497 } else {
498 // should not happen
499 }
500
501 return $file;
502 }
503
509 /*public function get()
510 {
511 $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
512 if ($file_name) {
513 $info = $this->getFileObject($file_name);
514 } else {
515 $info = $this->getFileObjects();
516 }
517
518 header('Content-type: application/json');
519 echo json_encode($info);
520 }
521 */
522
528 public function post()
529 {
530 $error = 0;
531
532 $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null;
533
534 $info = array();
535 if ($upload && is_array($upload['tmp_name'])) {
536 // param_name is an array identifier like "files[]",
537 // $_FILES is a multi-dimensional array:
538 foreach ($upload['tmp_name'] as $index => $value) {
539 $tmpres = $this->handleFileUpload(
540 $upload['tmp_name'][$index],
541 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
542 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
543 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
544 $upload['error'][$index],
545 (string) $index
546 );
547 if (!empty($tmpres->error)) {
548 $error++;
549 }
550 $info[] = $tmpres;
551 }
552 } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
553 // param_name is a single object identifier like "file",
554 // $_FILES is a one-dimensional array:
555 $tmpres = $this->handleFileUpload(
556 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
557 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
558 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
559 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
560 isset($upload['error']) ? $upload['error'] : null,
561 '0'
562 );
563 if (!empty($tmpres->error)) {
564 $error++;
565 }
566 $info[] = $tmpres;
567 }
568
569 header('Vary: Accept');
570 $json = json_encode($info);
571
572 /* disabled. Param redirect seems not used
573 $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null;
574 if ($redirect) {
575 header('Location: '.sprintf($redirect, urlencode($json)));
576 return;
577 }
578 */
579
580 if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
581 header('Content-type: application/json');
582 } else {
583 header('Content-type: text/plain');
584 }
585 echo $json;
586
587 return $error;
588 }
589
596 /*
597 public function delete($file)
598 {
599 $file_name = $file ? basename($file) : null;
600 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
601 $success = dol_is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
602 if ($success) {
603 foreach ($this->options['image_versions'] as $version => $options) {
604 $file = $options['upload_dir'].$file_name;
605 if (dol_is_file($file)) {
606 unlink($file);
607 }
608 }
609 }
610 // Return result in json format
611 header('Content-type: application/json');
612 echo json_encode($success);
613
614 return 0;
615 }
616 */
617}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
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_is_file($pathoffile)
Return if path is a file.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
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, $attop=0)
Set event message in dol_events session object.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
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.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
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).