dolibarr 22.0.5
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
77 //print 'fileupload.class.php: element='.$element.' pathname='.$pathname.' filename='.$filename.' dir_output='.$dir_output."\n";
78
79 if (empty($dir_output)) {
80 setEventMessage('The element '.$element.' is not supported for uploading file. dir_output is unknown.', 'errors');
81 throw new Exception('The element '.$element.' is not supported for uploading file. dir_output is unknown.');
82 }
83
84 $object_ref = 'UndefinedReference';
85 // If pathname and filename are null then we can still upload files if we have specified upload_dir on $options
86 if ($pathname !== null && $filename !== null) {
87 // Get object from its id and type
88 $object = fetchObjectByElement($fk_element, $element);
89
90 $object_ref = dol_sanitizeFileName($object->ref);
91
92 // Special cases to forge $object_ref used to forge $upload_dir
93 if ($element == 'invoice_supplier') {
94 $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
95 } elseif ($element == 'project_task') {
96 $parentForeignKey = 'fk_project';
97 $parentClass = 'Project';
98 $parentElement = 'projet';
99 $parentObject = 'project';
100
101 dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
102 $parent = new $parentClass($db);
103 $parent->fetch($object->$parentForeignKey);
104 if (!empty($parent->socid)) {
105 $parent->fetch_thirdparty();
106 }
107 $object->$parentObject = clone $parent;
108
109 $object_ref = dol_sanitizeFileName($object->project->ref).'/'.$object_ref;
110 }
111 }
112
113 $this->options = array(
114 'script_url' => $_SERVER['PHP_SELF'],
115 'upload_dir' => $dir_output.'/'.$object_ref.'/',
116 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
117 'param_name' => 'files',
118 // Set the following option to 'POST', if your server does not support
119 // DELETE requests. This is a parameter sent to the client:
120 'delete_type' => 'DELETE',
121 // The php.ini settings upload_max_filesize and post_max_size
122 // take precedence over the following max_file_size setting:
123 'max_file_size' => null,
124 'min_file_size' => 1,
125 'accept_file_types' => '/.+$/i',
126 // The maximum number of files for the upload directory:
127 'max_number_of_files' => null,
128 // Image resolution restrictions:
129 'max_width' => null,
130 'max_height' => null,
131 'min_width' => 1,
132 'min_height' => 1,
133 // Set the following option to false to enable resumable uploads:
134 'discard_aborted_uploads' => true,
135 'image_versions' => array(
136 // Uncomment the following version to restrict the size of
137 // uploaded images. You can also add additional versions with
138 // their own upload directories:
139 /*
140 'large' => array(
141 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
142 'upload_url' => $this->getFullUrl().'/files/',
143 'max_width' => 1920,
144 'max_height' => 1200,
145 'jpeg_quality' => 95
146 ),
147 */
148 'thumbnail' => array(
149 'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
150 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.urlencode($element).'&attachment=1&file='.urlencode('/'.$object_ref.'/thumbs/'),
151 'max_width' => 80,
152 'max_height' => 80
153 )
154 )
155 );
156
157 global $action;
158
159 $hookmanager->executeHooks(
160 'overrideUploadOptions',
161 array(
162 'options' => &$options,
163 'element' => $element
164 ),
165 $object, // @phan-suppress-current-line PhanTypeMismatchArgumentNullable
166 $action
167 );
168
169 if ($options) {
170 $this->options = array_replace_recursive($this->options, $options);
171 }
172
173 // At this point we should have a valid upload_dir in this->options
174 if (empty($pathname) || empty($filename)) {
175 if (!array_key_exists("upload_dir", $this->options)) {
176 setEventMessage('If $fk_element = null or $element = null you must specify upload_dir on $options', 'errors');
177 throw new Exception('If $fk_element = null or $element = null you must specify upload_dir on $options');
178 } elseif (!is_dir($this->options['upload_dir'])) {
179 setEventMessage('The directory '.$this->options['upload_dir'].' doesn\'t exists', 'errors');
180 throw new Exception('The directory '.$this->options['upload_dir'].' doesn\'t exists');
181 } elseif (!is_writable($this->options['upload_dir'])) {
182 setEventMessage('The directory '.$this->options['upload_dir'].' is not writable', 'errors');
183 throw new Exception('The directory '.$this->options['upload_dir'].' is not writable');
184 }
185 }
186 }
187
193 protected function getFullUrl()
194 {
195 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
196 return
197 ($https ? 'https://' : 'http://').
198 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
199 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
200 ($https && $_SERVER['SERVER_PORT'] === 443 ||
201 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
202 substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
203 }
204
211 protected function setFileDeleteUrl($file)
212 {
213 $file->delete_url = $this->options['script_url'].'?file='.urlencode((string) ($file->name)).'&fk_element='.urlencode((string) ($this->fk_element)).'&element='.urlencode((string) ($this->element));
214 $file->delete_type = $this->options['delete_type'];
215 if ($file->delete_type !== 'DELETE') {
216 $file->delete_url .= '&_method=DELETE';
217 }
218 }
219
226 protected function getFileObject($file_name)
227 {
228 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
229
230 if (dol_is_file($file_path) && $file_name[0] !== '.') {
231 $file = new stdClass();
232 $file->name = $file_name;
233 $file->mime = dol_mimetype($file_name, '', 2);
234 $file->size = filesize($file_path);
235 $file->url = $this->options['upload_url'].urlencode($file->name);
236
237 foreach ($this->options['image_versions'] as $version => $options) {
238 if (dol_is_file($options['upload_dir'].$file_name)) {
239 $tmp = explode('.', $file->name);
240
241 // We save the path of mini file into file->... (seems not used)
242 $keyforfile = $version.'_url';
243 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
244 }
245 }
246 $this->setFileDeleteUrl($file);
247 return $file;
248 }
249 return null;
250 }
251
257 protected function getFileObjects()
258 {
259 return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
260 }
261
269 protected function createScaledImage($file_name, $options)
270 {
271 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
272
273 $file_path = $this->options['upload_dir'].$file_name;
274 $new_file_path = $options['upload_dir'].$file_name;
275
276 if (dol_mkdir($options['upload_dir']) >= 0) {
277 list($img_width, $img_height) = @getimagesize($file_path);
278 if (!$img_width || !$img_height) {
279 return false;
280 }
281
282 $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object
283 if (preg_match('/error/i', $res)) {
284 return false;
285 }
286
287 $res = vignette($file_path, $maxwidthsmall, $maxheightsmall, '_small'); // We don't use ->addThumbs here because there is no object
288 if (preg_match('/error/i', $res)) {
289 return false;
290 }
291
292 return true;
293 } else {
294 return false;
295 }
296 }
297
307 protected function validate($uploaded_file, $file, $error, $index)
308 {
309 if ($error) {
310 $file->error = $error;
311 return false;
312 }
313 if (!$file->name) {
314 $file->error = 'missingFileName';
315 return false;
316 }
317 if (!preg_match($this->options['accept_file_types'], $file->name)) {
318 $file->error = 'acceptFileTypes';
319 return false;
320 }
321 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
322 $file_size = dol_filesize($uploaded_file);
323 } else {
324 $file_size = $_SERVER['CONTENT_LENGTH'];
325 }
326 if ($this->options['max_file_size'] && (
327 $file_size > $this->options['max_file_size'] ||
328 $file->size > $this->options['max_file_size']
329 )
330 ) {
331 $file->error = 'maxFileSize';
332 return false;
333 }
334 if ($this->options['min_file_size'] &&
335 $file_size < $this->options['min_file_size']) {
336 $file->error = 'minFileSize';
337 return false;
338 }
339 if (is_numeric($this->options['max_number_of_files']) && (
340 count($this->getFileObjects()) >= $this->options['max_number_of_files']
341 )
342 ) {
343 $file->error = 'maxNumberOfFiles';
344 return false;
345 }
346 list($img_width, $img_height) = @getimagesize($uploaded_file);
347 if (is_numeric($img_width)) {
348 if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
349 $this->options['max_height'] && $img_height > $this->options['max_height']) {
350 $file->error = 'maxResolution';
351 return false;
352 }
353 if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
354 $this->options['min_height'] && $img_height < $this->options['min_height']) {
355 $file->error = 'minResolution';
356 return false;
357 }
358 }
359 return true;
360 }
361
368 protected function upcountNameCallback($matches)
369 {
370 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
371 $ext = isset($matches[2]) ? $matches[2] : '';
372 return ' ('.$index.')'.$ext;
373 }
374
381 protected function upcountName($name)
382 {
383 return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
384 }
385
394 protected function trimFileName($name, $type, $index)
395 {
396 // Remove path information and dots around the filename, to prevent uploading
397 // into different directories or replacing hidden system files.
398 $file_name = basename(dol_sanitizeFileName($name));
399 // Add missing file extension for known image types:
400 $matches = array();
401 if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
402 $file_name .= '.'.$matches[1];
403 }
404 if ($this->options['discard_aborted_uploads']) {
405 while (dol_is_file($this->options['upload_dir'].$file_name)) {
406 $file_name = $this->upcountName($file_name);
407 }
408 }
409 return $file_name;
410 }
411
425 protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
426 {
427 $file = new stdClass();
428 $file->name = $this->trimFileName($name, $type, $index);
429 $file->mime = dol_mimetype($file->name, '', 2);
430 $file->size = intval($size);
431 $file->type = $type;
432
433 // Sanitize to avoid stream execution when calling file_size(). Not that this is a second security because
434 // most streams are already disabled by stream_wrapper_unregister() in filefunc.inc.php
435 $uploaded_file = preg_replace('/\s*(http|ftp|sftp|)s?:/i', '', $uploaded_file);
436 $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)
437
438 $validate = $this->validate($uploaded_file, $file, $error, $index);
439
440 if ($validate) {
441 if (dol_mkdir($this->options['upload_dir']) >= 0) {
442 $file_path = dol_sanitizePathName($this->options['upload_dir']).dol_sanitizeFileName($file->name);
443 $append_file = !$this->options['discard_aborted_uploads'] && dol_is_file($file_path) && $file->size > dol_filesize($file_path);
444
445 clearstatcache();
446
447 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
448 // multipart/formdata uploads (POST method uploads)
449 if ($append_file) {
450 file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
451 } else {
452 // TODO Replace this with a call of dol_add_file_process(... $mode=1)
453 $result = dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
454 }
455 } else {
456 // Non-multipart uploads (PUT method support)
457 file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
458 }
459 $file_size = dol_filesize($file_path);
460 if ($file_size === $file->size) {
461 $file->url = $this->options['upload_url'].urlencode($file->name);
462 foreach ($this->options['image_versions'] as $version => $options) {
463 if ($this->createScaledImage($file->name, $options)) { // Creation of thumbs mini and small is ok
464 $tmp = explode('.', $file->name);
465
466 // We save the path of mini file into file->... (seems not used)
467 $keyforfile = $version.'_url';
468 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
469 }
470 }
471 } elseif ($this->options['discard_aborted_uploads']) {
472 unlink($file_path);
473 $file->error = 'abort';
474 }
475 $file->size = $file_size;
476 $this->setFileDeleteUrl($file);
477 } else {
478 $file->error = 'failedtocreatedestdir';
479 }
480 } else {
481 // should not happen
482 }
483
484 return $file;
485 }
486
492 /*public function get()
493 {
494 $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
495 if ($file_name) {
496 $info = $this->getFileObject($file_name);
497 } else {
498 $info = $this->getFileObjects();
499 }
500
501 header('Content-type: application/json');
502 echo json_encode($info);
503 }
504 */
505
511 public function post()
512 {
513 $error = 0;
514
515 $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null;
516
517 $info = array();
518 if ($upload && is_array($upload['tmp_name'])) {
519 // param_name is an array identifier like "files[]",
520 // $_FILES is a multi-dimensional array:
521 foreach ($upload['tmp_name'] as $index => $value) {
522 $tmpres = $this->handleFileUpload(
523 $upload['tmp_name'][$index],
524 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
525 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
526 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
527 $upload['error'][$index],
528 (string) $index
529 );
530 if (!empty($tmpres->error)) {
531 $error++;
532 }
533 $info[] = $tmpres;
534 }
535 } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
536 // param_name is a single object identifier like "file",
537 // $_FILES is a one-dimensional array:
538 $tmpres = $this->handleFileUpload(
539 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
540 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
541 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
542 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
543 isset($upload['error']) ? $upload['error'] : null,
544 '0'
545 );
546 if (!empty($tmpres->error)) {
547 $error++;
548 }
549 $info[] = $tmpres;
550 }
551
552 header('Vary: Accept');
553 $json = json_encode($info);
554
555 /* disabled. Param redirect seems not used
556 $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null;
557 if ($redirect) {
558 header('Location: '.sprintf($redirect, urlencode($json)));
559 return;
560 }
561 */
562
563 if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
564 header('Content-type: application/json');
565 } else {
566 header('Content-type: text/plain');
567 }
568 echo $json;
569
570 return $error;
571 }
572
579 /*
580 public function delete($file)
581 {
582 $file_name = $file ? basename($file) : null;
583 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
584 $success = dol_is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
585 if ($success) {
586 foreach ($this->options['image_versions'] as $version => $options) {
587 $file = $options['upload_dir'].$file_name;
588 if (dol_is_file($file)) {
589 unlink($file);
590 }
591 }
592 }
593 // Return result in json format
594 header('Content-type: application/json');
595 echo json_encode($success);
596
597 return 0;
598 }
599 */
600}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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.
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, $includequotes=0)
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).