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