dolibarr 19.0.4
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
25require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
27
28
33{
34 public $options;
35 protected $fk_element;
36 protected $element;
37
46 public function __construct($options = null, $fk_element = null, $element = null)
47 {
48 global $db;
49 global $hookmanager;
50
51 $hookmanager->initHooks(array('fileupload'));
52
53 $element_prop = getElementProperties($element);
54 //var_dump($element_prop);
55
56 $this->fk_element = $fk_element;
57 $this->element = $element;
58
59 $pathname = str_replace('/class', '', $element_prop['classpath']);
60
61
62 $filename = dol_sanitizeFileName($element_prop['classfile']);
63 $dir_output = dol_sanitizePathName($element_prop['dir_output']);
64 $savingDocMask = '';
65
66 //print 'fileupload.class.php: element='.$element.' pathname='.$pathname.' filename='.$filename.' dir_output='.$dir_output."\n";
67
68 if (empty($dir_output)) {
69 setEventMessage('The element '.$element.' is not supported for uploading file. dir_output is unknow.', 'errors');
70 throw new Exception('The element '.$element.' is not supported for uploading file. dir_output is unknow.');
71 }
72
73 // If pathname and filename are null then we can still upload files if we have specified upload_dir on $options
74 if ($pathname !== null && $filename !== null) {
75 // Get object from its id and type
76 $object = fetchObjectByElement($fk_element, $element);
77
78 $object_ref = dol_sanitizeFileName($object->ref);
79
80 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
81 if (!getDolGlobalInt('MAIN_DISABLE_SUGGEST_REF_AS_PREFIX')) {
82 $savingDocMask = $object_ref.'-__file__';
83 }
84
85 // Special cases to forge $object_ref used to forge $upload_dir
86 if ($element == 'invoice_supplier') {
87 $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
88 } elseif ($element == 'project_task') {
89 $parentForeignKey = 'fk_project';
90 $parentClass = 'Project';
91 $parentElement = 'projet';
92 $parentObject = 'project';
93
94 dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
95 $parent = new $parentClass($db);
96 $parent->fetch($object->$parentForeignKey);
97 if (!empty($parent->socid)) {
98 $parent->fetch_thirdparty();
99 }
100 $object->$parentObject = clone $parent;
101
102 $object_ref = dol_sanitizeFileName($object->project->ref).'/'.$object_ref;
103 }
104 }
105
106 $this->options = array(
107 'script_url' => $_SERVER['PHP_SELF'],
108 'upload_dir' => $dir_output.'/'.$object_ref.'/',
109 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
110 'saving_doc_mask' => $savingDocMask,
111 'param_name' => 'files',
112 // Set the following option to 'POST', if your server does not support
113 // DELETE requests. This is a parameter sent to the client:
114 'delete_type' => 'DELETE',
115 // The php.ini settings upload_max_filesize and post_max_size
116 // take precedence over the following max_file_size setting:
117 'max_file_size' => null,
118 'min_file_size' => 1,
119 'accept_file_types' => '/.+$/i',
120 // The maximum number of files for the upload directory:
121 'max_number_of_files' => null,
122 // Image resolution restrictions:
123 'max_width' => null,
124 'max_height' => null,
125 'min_width' => 1,
126 'min_height' => 1,
127 // Set the following option to false to enable resumable uploads:
128 'discard_aborted_uploads' => true,
129 'image_versions' => array(
130 // Uncomment the following version to restrict the size of
131 // uploaded images. You can also add additional versions with
132 // their own upload directories:
133 /*
134 'large' => array(
135 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
136 'upload_url' => $this->getFullUrl().'/files/',
137 'max_width' => 1920,
138 'max_height' => 1200,
139 'jpeg_quality' => 95
140 ),
141 */
142 'thumbnail' => array(
143 'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
144 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.urlencode($element).'&attachment=1&file='.urlencode('/'.$object_ref.'/thumbs/'),
145 'max_width' => 80,
146 'max_height' => 80
147 )
148 )
149 );
150
151 global $action;
152
153 $hookmanager->executeHooks(
154 'overrideUploadOptions',
155 array(
156 'options' => &$options,
157 'element' => $element
158 ),
159 $object,
160 $action
161 );
162
163 if ($options) {
164 $this->options = array_replace_recursive($this->options, $options);
165 }
166
167 // At this point we should have a valid upload_dir in options
168 //if ($pathname === null && $filename === null) { // OR or AND???
169 if ($pathname === null || $filename === null) {
170 if (!key_exists("upload_dir", $this->options)) {
171 setEventMessage('If $fk_element = null or $element = null you must specify upload_dir on $options', 'errors');
172 throw new Exception('If $fk_element = null or $element = null you must specify upload_dir on $options');
173 } elseif (!is_dir($this->options['upload_dir'])) {
174 setEventMessage('The directory '.$this->options['upload_dir'].' doesn\'t exists', 'errors');
175 throw new Exception('The directory '.$this->options['upload_dir'].' doesn\'t exists');
176 } elseif (!is_writable($this->options['upload_dir'])) {
177 setEventMessage('The directory '.$this->options['upload_dir'].' is not writable', 'errors');
178 throw new Exception('The directory '.$this->options['upload_dir'].' is not writable');
179 }
180 }
181 }
182
188 protected function getFullUrl()
189 {
190 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
191 return
192 ($https ? 'https://' : 'http://').
193 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
194 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
195 ($https && $_SERVER['SERVER_PORT'] === 443 ||
196 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
197 substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
198 }
199
206 protected function setFileDeleteUrl($file)
207 {
208 $file->delete_url = $this->options['script_url'].'?file='.urlencode($file->name).'&fk_element='.urlencode($this->fk_element).'&element='.urlencode($this->element);
209 $file->delete_type = $this->options['delete_type'];
210 if ($file->delete_type !== 'DELETE') {
211 $file->delete_url .= '&_method=DELETE';
212 }
213 }
214
221 protected function getFileObject($file_name)
222 {
223 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
224
225 if (dol_is_file($file_path) && $file_name[0] !== '.') {
226 $file = new stdClass();
227 $file->name = $file_name;
228 $file->mime = dol_mimetype($file_name, '', 2);
229 $file->size = filesize($file_path);
230 $file->url = $this->options['upload_url'].urlencode($file->name);
231 foreach ($this->options['image_versions'] as $version => $options) {
232 if (dol_is_file($options['upload_dir'].$file_name)) {
233 $tmp = explode('.', $file->name);
234
235 // We save the path of mini file into file->... (seems not used)
236 $keyforfile = $version.'_url';
237 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
238 }
239 }
240 $this->setFileDeleteUrl($file);
241 return $file;
242 }
243 return null;
244 }
245
251 protected function getFileObjects()
252 {
253 return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
254 }
255
263 protected function createScaledImage($file_name, $options)
264 {
265 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
266
267 $file_path = $this->options['upload_dir'].$file_name;
268 $new_file_path = $options['upload_dir'].$file_name;
269
270 if (dol_mkdir($options['upload_dir']) >= 0) {
271 list($img_width, $img_height) = @getimagesize($file_path);
272 if (!$img_width || !$img_height) {
273 return false;
274 }
275
276 $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object
277 if (preg_match('/error/i', $res)) {
278 return false;
279 }
280
281 $res = vignette($file_path, $maxwidthsmall, $maxheightsmall, '_small'); // We don't use ->addThumbs here because there is no object
282 if (preg_match('/error/i', $res)) {
283 return false;
284 }
285
286 return true;
287 } else {
288 return false;
289 }
290 }
291
301 protected function validate($uploaded_file, $file, $error, $index)
302 {
303 if ($error) {
304 $file->error = $error;
305 return false;
306 }
307 if (!$file->name) {
308 $file->error = 'missingFileName';
309 return false;
310 }
311 if (!preg_match($this->options['accept_file_types'], $file->name)) {
312 $file->error = 'acceptFileTypes';
313 return false;
314 }
315 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
316 $file_size = dol_filesize($uploaded_file);
317 } else {
318 $file_size = $_SERVER['CONTENT_LENGTH'];
319 }
320 if ($this->options['max_file_size'] && (
321 $file_size > $this->options['max_file_size'] ||
322 $file->size > $this->options['max_file_size']
323 )
324 ) {
325 $file->error = 'maxFileSize';
326 return false;
327 }
328 if ($this->options['min_file_size'] &&
329 $file_size < $this->options['min_file_size']) {
330 $file->error = 'minFileSize';
331 return false;
332 }
333 if (is_numeric($this->options['max_number_of_files']) && (
334 count($this->getFileObjects()) >= $this->options['max_number_of_files']
335 )
336 ) {
337 $file->error = 'maxNumberOfFiles';
338 return false;
339 }
340 list($img_width, $img_height) = @getimagesize($uploaded_file);
341 if (is_numeric($img_width)) {
342 if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
343 $this->options['max_height'] && $img_height > $this->options['max_height']) {
344 $file->error = 'maxResolution';
345 return false;
346 }
347 if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
348 $this->options['min_height'] && $img_height < $this->options['min_height']) {
349 $file->error = 'minResolution';
350 return false;
351 }
352 }
353 return true;
354 }
355
362 protected function upcountNameCallback($matches)
363 {
364 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
365 $ext = isset($matches[2]) ? $matches[2] : '';
366 return ' ('.$index.')'.$ext;
367 }
368
375 protected function upcountName($name)
376 {
377 return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
378 }
379
388 protected function trimFileName($name, $type, $index)
389 {
390 // Remove path information and dots around the filename, to prevent uploading
391 // into different directories or replacing hidden system files.
392 $file_name = basename(dol_sanitizeFileName($name));
393 // Add missing file extension for known image types:
394 $matches = array();
395 if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
396 $file_name .= '.'.$matches[1];
397 }
398 if ($this->options['discard_aborted_uploads']) {
399 while (dol_is_file($this->options['upload_dir'].$file_name)) {
400 $file_name = $this->upcountName($file_name);
401 }
402 }
403 return $file_name;
404 }
405
418 protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
419 {
420 $file = new stdClass();
421 $file->name = $this->trimFileName($name, $type, $index);
422 $file->mime = dol_mimetype($file->name, '', 2);
423 $file->size = intval($size);
424 $file->type = $type;
425
426 // Sanitize to avoid stream execution when calling file_size(). Not that this is a second security because
427 // most streams are already disabled by stream_wrapper_unregister() in filefunc.inc.php
428 $uploaded_file = preg_replace('/\s*(http|ftp)s?:/i', '', $uploaded_file);
429 $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)
430
431 $validate = $this->validate($uploaded_file, $file, $error, $index);
432
433 if ($validate) {
434 if (dol_mkdir($this->options['upload_dir']) >= 0) {
435 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
436 $fileNameWithoutExt = preg_replace('/\.[^\.]+$/', '', $file->name);
437 $savingDocMask = $this->options['saving_doc_mask'];
438 if ($savingDocMask && strpos($savingDocMask, $fileNameWithoutExt) !== 0) {
439 $fileNameWithPrefix = preg_replace('/__file__/', $file->name, $savingDocMask);
440 $file->name = $fileNameWithPrefix;
441 }
442
443 $file_path = dol_sanitizePathName($this->options['upload_dir']).dol_sanitizeFileName($file->name);
444 $append_file = !$this->options['discard_aborted_uploads'] && dol_is_file($file_path) && $file->size > dol_filesize($file_path);
445
446 clearstatcache();
447
448 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
449 // multipart/formdata uploads (POST method uploads)
450 if ($append_file) {
451 file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
452 } else {
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']) ?
495 basename(stripslashes($_REQUEST['file'])) : null;
496 if ($file_name) {
497 $info = $this->getFileObject($file_name);
498 } else {
499 $info = $this->getFileObjects();
500 }
501 header('Content-type: application/json');
502 echo json_encode($info);
503 }
504
510 public function post()
511 {
512 $error = 0;
513
514 if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
515 return $this->delete();
516 }
517 //var_dump($_FILES);
518
519 $upload = isset($_FILES[$this->options['param_name']]) ?
520 $_FILES[$this->options['param_name']] : null;
521 $info = array();
522 if ($upload && is_array($upload['tmp_name'])) {
523 // param_name is an array identifier like "files[]",
524 // $_FILES is a multi-dimensional array:
525 foreach ($upload['tmp_name'] as $index => $value) {
526 $tmpres = $this->handleFileUpload(
527 $upload['tmp_name'][$index],
528 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
529 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
530 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
531 $upload['error'][$index],
532 $index
533 );
534 if (!empty($tmpres->error)) {
535 $error++;
536 }
537 $info[] = $tmpres;
538 }
539 } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
540 // param_name is a single object identifier like "file",
541 // $_FILES is a one-dimensional array:
542 $tmpres = $this->handleFileUpload(
543 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
544 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
545 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
546 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
547 isset($upload['error']) ? $upload['error'] : null,
548 0
549 );
550 if (!empty($tmpres->error)) {
551 $error++;
552 }
553 $info[] = $tmpres;
554 }
555
556 header('Vary: Accept');
557 $json = json_encode($info);
558
559 /* disabled. Param redirect seems not used
560 $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null;
561 if ($redirect) {
562 header('Location: '.sprintf($redirect, urlencode($json)));
563 return;
564 }
565 */
566
567 if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
568 header('Content-type: application/json');
569 } else {
570 header('Content-type: text/plain');
571 }
572 echo $json;
573
574 return $error;
575 }
576
582 public function delete()
583 {
584 $file_name = GETPOST('file') ? basename(GETPOST('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}
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='')
Make control on an uploaded file from an GUI page and move it to 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.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
getElementProperties($element_type)
Get an array with properties of an element.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
fetchObjectByElement($element_id, $element_type, $element_ref='')
Fetch an object from its id and element_type Inclusion of classes is automatic.
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).