dolibarr 24.0.0-beta
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-2026 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 $object = null;
87 // If pathname and filename are null then we can still upload files if we have specified upload_dir on $options
88 if ($pathname !== null && $filename !== null) {
89 // Get object from its id and type
90 $object = fetchObjectByElement($fk_element, $element);
91
92 $object_ref = dol_sanitizeFileName($object->ref);
93
94 // Add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
95 if (!getDolGlobalInt('MAIN_DISABLE_SUGGEST_REF_AS_PREFIX')) {
96 $savingDocMask = $object_ref . '-__file__';
97 }
98
99 // Special cases to forge $object_ref used to forge $upload_dir
100 if ($element == 'invoice_supplier') {
101 $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
102 } elseif ($element == 'project_task') {
103 $parentForeignKey = 'fk_project';
104 $parentClass = 'Project';
105 $parentElement = 'projet';
106 $parentObject = 'project';
107
108 dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
109 $parent = new $parentClass($db);
110 if ($object->$parentForeignKey !== null) {
111 $parent->fetch((int) $object->$parentForeignKey);
112 if (!empty($parent->socid)) {
113 $parent->fetch_thirdparty();
114 }
115 $object->$parentObject = clone $parent;
116 }
117
118 $object_ref = dol_sanitizeFileName($object->project->ref).'/'.$object_ref;
119 }
120 }
121
122 $this->options = array(
123 'script_url' => $_SERVER['PHP_SELF'],
124 'upload_dir' => $dir_output.'/'.$object_ref.'/',
125 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
126 'saving_doc_mask' => $savingDocMask,
127 'param_name' => 'files',
128 // Set the following option to 'POST', if your server does not support
129 // DELETE requests. This is a parameter sent to the client:
130 'delete_type' => 'DELETE',
131 // The php.ini settings upload_max_filesize and post_max_size
132 // take precedence over the following max_file_size setting:
133 'max_file_size' => null,
134 'min_file_size' => 1,
135 'accept_file_types' => '/.+$/i',
136 // The maximum number of files for the upload directory:
137 'max_number_of_files' => null,
138 // Image resolution restrictions:
139 'max_width' => null,
140 'max_height' => null,
141 'min_width' => 1,
142 'min_height' => 1,
143 // Set the following option to false to enable resumable uploads:
144 'discard_aborted_uploads' => true,
145 'image_versions' => array(
146 // Uncomment the following version to restrict the size of
147 // uploaded images. You can also add additional versions with
148 // their own upload directories:
149 /*
150 'large' => array(
151 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
152 'upload_url' => $this->getFullUrl().'/files/',
153 'max_width' => 1920,
154 'max_height' => 1200,
155 'jpeg_quality' => 95
156 ),
157 */
158 'thumbnail' => array(
159 'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
160 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.urlencode($element).'&attachment=1&file='.urlencode('/'.$object_ref.'/thumbs/'),
161 'max_width' => 80,
162 'max_height' => 80
163 )
164 )
165 );
166
167 global $action;
168
169 $hookmanager->executeHooks(
170 'overrideUploadOptions',
171 array(
172 'options' => &$options,
173 'element' => $element
174 ),
175 $object, // @phan-suppress-current-line PhanTypeMismatchArgumentNullable
176 $action
177 );
178
179 if ($options) {
180 $this->options = array_replace_recursive($this->options, $options);
181 }
182
183 // At this point we should have a valid upload_dir in this->options
184 if (empty($pathname) || empty($filename)) {
185 if (!array_key_exists("upload_dir", $this->options)) {
186 setEventMessage('If $fk_element = null or $element = null you must specify upload_dir on $options', 'errors');
187 throw new Exception('If $fk_element = null or $element = null you must specify upload_dir on $options');
188 } elseif (!is_dir($this->options['upload_dir'])) {
189 setEventMessage('The directory '.$this->options['upload_dir'].' doesn\'t exists', 'errors');
190 throw new Exception('The directory '.$this->options['upload_dir'].' doesn\'t exists');
191 } elseif (!is_writable($this->options['upload_dir'])) {
192 setEventMessage('The directory '.$this->options['upload_dir'].' is not writable', 'errors');
193 throw new Exception('The directory '.$this->options['upload_dir'].' is not writable');
194 }
195 }
196 }
197
203 protected function getFullUrl()
204 {
205 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
206 return
207 ($https ? 'https://' : 'http://').
208 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
209 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
210 ($https && $_SERVER['SERVER_PORT'] === 443 ||
211 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
212 substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
213 }
214
221 protected function setFileDeleteUrl($file)
222 {
223 $file->delete_url = $this->options['script_url'].'?file='.urlencode((string) ($file->name)).'&fk_element='.urlencode((string) ($this->fk_element)).'&element='.urlencode((string) ($this->element));
224 $file->delete_type = $this->options['delete_type'];
225 if ($file->delete_type !== 'DELETE') {
226 $file->delete_url .= '&_method=DELETE';
227 }
228 }
229
236 protected function getFileObject($file_name)
237 {
238 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
239
240 if (dol_is_file($file_path) && $file_name[0] !== '.') {
241 $file = new stdClass();
242 $file->name = $file_name;
243 $file->mime = dol_mimetype($file_name, '', 2);
244 $file->size = filesize($file_path);
245 $file->url = $this->options['upload_url'].urlencode($file->name);
246
247 foreach ($this->options['image_versions'] as $version => $options) {
248 if (dol_is_file($options['upload_dir'].$file_name)) {
249 $tmp = explode('.', $file->name);
250
251 // We save the path of mini file into file->... (seems not used)
252 $keyforfile = $version.'_url';
253 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
254 }
255 }
256 $this->setFileDeleteUrl($file);
257 return $file;
258 }
259 return null;
260 }
261
267 protected function getFileObjects()
268 {
269 return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
270 }
271
279 protected function createScaledImage($file_name, $options)
280 {
281 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
282
283 $file_path = $this->options['upload_dir'].$file_name;
284 $new_file_path = $options['upload_dir'].$file_name;
285
286 if (dol_mkdir($options['upload_dir']) >= 0) {
287 list($img_width, $img_height) = @getimagesize($file_path);
288 if (!$img_width || !$img_height) {
289 return false;
290 }
291
292 $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object
293 if (preg_match('/error/i', $res)) {
294 return false;
295 }
296
297 $res = vignette($file_path, $maxwidthsmall, $maxheightsmall, '_small'); // We don't use ->addThumbs here because there is no object
298 if (preg_match('/error/i', $res)) {
299 return false;
300 }
301
302 return true;
303 } else {
304 return false;
305 }
306 }
307
317 protected function validate($uploaded_file, $file, $error, $index)
318 {
319 if ($error) {
320 $file->error = $error;
321 return false;
322 }
323 if (!$file->name) {
324 $file->error = 'missingFileName';
325 return false;
326 }
327 if (!preg_match($this->options['accept_file_types'], $file->name)) {
328 $file->error = 'acceptFileTypes';
329 return false;
330 }
331 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
332 $file_size = dol_filesize($uploaded_file);
333 } else {
334 $file_size = $_SERVER['CONTENT_LENGTH'];
335 }
336 if ($this->options['max_file_size'] && (
337 $file_size > $this->options['max_file_size'] ||
338 $file->size > $this->options['max_file_size']
339 )
340 ) {
341 $file->error = 'maxFileSize';
342 return false;
343 }
344 if ($this->options['min_file_size'] &&
345 $file_size < $this->options['min_file_size']) {
346 $file->error = 'minFileSize';
347 return false;
348 }
349 if (is_numeric($this->options['max_number_of_files']) && (
350 count($this->getFileObjects()) >= $this->options['max_number_of_files']
351 )
352 ) {
353 $file->error = 'maxNumberOfFiles';
354 return false;
355 }
356 list($img_width, $img_height) = @getimagesize($uploaded_file);
357 if (is_numeric($img_width)) {
358 if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
359 $this->options['max_height'] && $img_height > $this->options['max_height']) {
360 $file->error = 'maxResolution';
361 return false;
362 }
363 if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
364 $this->options['min_height'] && $img_height < $this->options['min_height']) {
365 $file->error = 'minResolution';
366 return false;
367 }
368 }
369 return true;
370 }
371
378 protected function upcountNameCallback($matches)
379 {
380 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
381 $ext = isset($matches[2]) ? $matches[2] : '';
382 return ' ('.$index.')'.$ext;
383 }
384
391 protected function upcountName($name)
392 {
393 return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
394 }
395
404 protected function trimFileName($name, $type, $index)
405 {
406 // Remove path information and dots around the filename, to prevent uploading
407 // into different directories or replacing hidden system files.
408 $file_name = basename(dol_sanitizeFileName($name));
409 $file_name = preg_replace('/ {2,}/', ' ', $file_name); // replaces multiple spaces into one space like the upload flow via input field
410 // Add missing file extension for known image types:
411 $matches = array();
412 if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
413 $file_name .= '.'.$matches[1];
414 }
415 if ($this->options['discard_aborted_uploads']) {
416 while (dol_is_file($this->options['upload_dir'].$file_name)) {
417 $file_name = $this->upcountName($file_name);
418 }
419 }
420 return $file_name;
421 }
422
436 protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
437 {
438 $file = new stdClass();
439 $file->name = $this->trimFileName($name, $type, $index);
440 $file->mime = dol_mimetype($file->name, '', 2);
441 $file->size = intval($size);
442 $file->type = $type;
443
444 // Sanitize to avoid stream execution when calling file_size(). Not that this is a second security because
445 // most streams are already disabled by stream_wrapper_unregister() in filefunc.inc.php
446 $uploaded_file = preg_replace('/\s*(http|ftp|sftp|)s?:/i', '', $uploaded_file);
447 $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)
448
449 $validate = $this->validate($uploaded_file, $file, $error, $index);
450
451 if ($validate) {
452 if (dol_mkdir($this->options['upload_dir']) >= 0) {
453 // Add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
454 $fileNameWithoutExt = preg_replace('/\.[^\.]+$/', '', $file->name);
455 $savingDocMask = $this->options['saving_doc_mask'];
456 if ($savingDocMask && strpos($savingDocMask, $fileNameWithoutExt) !== 0) {
457 $fileNameWithPrefix = preg_replace('/__file__/', $file->name, $savingDocMask);
458 $file->name = $fileNameWithPrefix;
459 }
460
461 $file_path = dol_sanitizePathName($this->options['upload_dir']).dol_sanitizeFileName($file->name);
462 $append_file = !$this->options['discard_aborted_uploads'] && dol_is_file($file_path) && $file->size > dol_filesize($file_path);
463
464 clearstatcache();
465
466 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
467 // multipart/formdata uploads (POST method uploads)
468 if ($append_file) {
469 file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
470 } else {
471 // TODO Replace this with a call of dol_add_file_process(... $mode=1)
472 $result = dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
473 }
474 } else {
475 // Non-multipart uploads (PUT method support)
476 file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
477 }
478 dolChmod($file_path);
479
480 $file_size = dol_filesize($file_path);
481 if ($file_size === $file->size) {
482 $file->url = $this->options['upload_url'].urlencode($file->name);
483 foreach ($this->options['image_versions'] as $version => $options) {
484 if ($this->createScaledImage($file->name, $options)) { // Creation of thumbs mini and small is ok
485 $tmp = explode('.', $file->name);
486
487 // We save the path of mini file into file->... (seems not used)
488 $keyforfile = $version.'_url';
489 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
490 }
491 }
492 } elseif ($this->options['discard_aborted_uploads']) {
493 unlink($file_path);
494 $file->error = 'abort';
495 }
496 $file->size = $file_size;
497 $this->setFileDeleteUrl($file);
498 } else {
499 $file->error = 'failedtocreatedestdir';
500 }
501 } else {
502 // should not happen
503 }
504
505 return $file;
506 }
507
513 /*public function get()
514 {
515 $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
516 if ($file_name) {
517 $info = $this->getFileObject($file_name);
518 } else {
519 $info = $this->getFileObjects();
520 }
521
522 header('Content-type: application/json');
523 echo json_encode($info);
524 }
525 */
526
532 public function post()
533 {
534 $error = 0;
535
536 $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null;
537
538 $info = array();
539 if ($upload && is_array($upload['tmp_name'])) {
540 // param_name is an array identifier like "files[]",
541 // $_FILES is a multi-dimensional array:
542 foreach ($upload['tmp_name'] as $index => $value) {
543 $tmpres = $this->handleFileUpload(
544 $upload['tmp_name'][$index],
545 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
546 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
547 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
548 $upload['error'][$index],
549 (string) $index
550 );
551 if (!empty($tmpres->error)) {
552 $error++;
553 }
554 $info[] = $tmpres;
555 }
556 } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
557 // param_name is a single object identifier like "file",
558 // $_FILES is a one-dimensional array:
559 $tmpres = $this->handleFileUpload(
560 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
561 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
562 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
563 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
564 isset($upload['error']) ? $upload['error'] : null,
565 '0'
566 );
567 if (!empty($tmpres->error)) {
568 $error++;
569 }
570 $info[] = $tmpres;
571 }
572
573 header('Vary: Accept');
574 $json = json_encode($info);
575
576 /* disabled. Param redirect seems not used
577 $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null;
578 if ($redirect) {
579 header('Location: '.sprintf($redirect, urlencode($json)));
580 return;
581 }
582 */
583
584 if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
585 header('Content-type: application/json');
586 } else {
587 header('Content-type: text/plain');
588 }
589 echo $json;
590
591 return $error;
592 }
593
600 /*
601 public function delete($file)
602 {
603 $file_name = $file ? basename($file) : null;
604 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
605 $success = dol_is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
606 if ($success) {
607 foreach ($this->options['image_versions'] as $version => $options) {
608 $file = $options['upload_dir'].$file_name;
609 if (dol_is_file($file)) {
610 unlink($file);
611 }
612 }
613 }
614 // Return result in json format
615 header('Content-type: application/json');
616 echo json_encode($success);
617
618 return 0;
619 }
620 */
621}
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
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.
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).
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php