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