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