dolibarr 18.0.6
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-2012 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
24require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
25require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
26
27
32{
33 public $options;
34 protected $fk_element;
35 protected $element;
36
45 public function __construct($options = null, $fk_element = null, $element = null)
46 {
47 global $db, $conf;
48 global $hookmanager;
49
50 $hookmanager->initHooks(array('fileupload'));
51
52 $element_prop = getElementProperties($element);
53 //var_dump($element_prop);
54
55 $this->fk_element = $fk_element;
56 $this->element = $element;
57
58 $pathname = str_replace('/class', '', $element_prop['classpath']);
59 $filename = $element_prop['classfile'];
60 $dir_output = $element_prop['dir_output'];
61 $savingDocMask = '';
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 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
78 if (!getDolGlobalInt('MAIN_DISABLE_SUGGEST_REF_AS_PREFIX')) {
79 $savingDocMask = $object_ref.'-__file__';
80 }
81
82 // Special cases to forge $object_ref used to forge $upload_dir
83 if ($element == 'invoice_supplier') {
84 $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
85 } elseif ($element == 'project_task') {
86 $parentForeignKey = 'fk_project';
87 $parentClass = 'Project';
88 $parentElement = 'projet';
89 $parentObject = 'project';
90
91 dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
92 $parent = new $parentClass($db);
93 $parent->fetch($object->$parentForeignKey);
94 if (!empty($parent->socid)) {
95 $parent->fetch_thirdparty();
96 }
97 $object->$parentObject = clone $parent;
98
99 $object_ref = dol_sanitizeFileName($object->project->ref).'/'.$object_ref;
100 }
101 }
102
103 $this->options = array(
104 'script_url' => $_SERVER['PHP_SELF'],
105 'upload_dir' => $dir_output.'/'.$object_ref.'/',
106 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
107 'saving_doc_mask' => $savingDocMask,
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=/'.$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 options
165 //if ($pathname === null && $filename === null) { // OR or AND???
166 if ($pathname === null || $filename === null) {
167 if (!key_exists("upload_dir", $this->options)) {
168 setEventMessage('If $fk_element = null or $element = null you must specify upload_dir on $options', 'errors');
169 throw new Exception('If $fk_element = null or $element = null you must specify upload_dir on $options');
170 } elseif (!is_dir($this->options['upload_dir'])) {
171 setEventMessage('The directory '.$this->options['upload_dir'].' doesn\'t exists', 'errors');
172 throw new Exception('The directory '.$this->options['upload_dir'].' doesn\'t exists');
173 } elseif (!is_writable($this->options['upload_dir'])) {
174 setEventMessage('The directory '.$this->options['upload_dir'].' is not writable', 'errors');
175 throw new Exception('The directory '.$this->options['upload_dir'].' is not writable');
176 }
177 }
178 }
179
185 protected function getFullUrl()
186 {
187 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
188 return
189 ($https ? 'https://' : 'http://').
190 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
191 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
192 ($https && $_SERVER['SERVER_PORT'] === 443 ||
193 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
194 substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
195 }
196
203 protected function setFileDeleteUrl($file)
204 {
205 $file->delete_url = $this->options['script_url']
206 .'?file='.urlencode($file->name).'&fk_element='.urlencode($this->fk_element).'&element='.urlencode($this->element);
207 $file->delete_type = $this->options['delete_type'];
208 if ($file->delete_type !== 'DELETE') {
209 $file->delete_url .= '&_method=DELETE';
210 }
211 }
212
219 protected function getFileObject($file_name)
220 {
221
222 $file_path = $this->options['upload_dir'].$file_name;
223 if (is_file($file_path) && $file_name[0] !== '.') {
224 $file = new stdClass();
225 $file->name = $file_name;
226 $file->mime = dol_mimetype($file_name, '', 2);
227 $file->size = filesize($file_path);
228 $file->url = $this->options['upload_url'].rawurlencode($file->name);
229 foreach ($this->options['image_versions'] as $version => $options) {
230 if (is_file($options['upload_dir'].$file_name)) {
231 $tmp = explode('.', $file->name);
232
233 // We save the path of mini file into file->... (seems not used)
234 $keyforfile = $version.'_url';
235 $file->$keyforfile = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
236 }
237 }
238 $this->setFileDeleteUrl($file);
239 return $file;
240 }
241 return null;
242 }
243
249 protected function getFileObjects()
250 {
251 return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
252 }
253
261 protected function createScaledImage($file_name, $options)
262 {
263 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
264
265 $file_path = $this->options['upload_dir'].$file_name;
266 $new_file_path = $options['upload_dir'].$file_name;
267
268 if (dol_mkdir($options['upload_dir']) >= 0) {
269 list($img_width, $img_height) = @getimagesize($file_path);
270 if (!$img_width || !$img_height) {
271 return false;
272 }
273
274 $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object
275 if (preg_match('/error/i', $res)) {
276 return false;
277 }
278
279 $res = vignette($file_path, $maxwidthsmall, $maxheightsmall, '_small'); // We don't use ->addThumbs here because there is no object
280 if (preg_match('/error/i', $res)) {
281 return false;
282 }
283
284 return true;
285 } else {
286 return false;
287 }
288 }
289
299 protected function validate($uploaded_file, $file, $error, $index)
300 {
301 if ($error) {
302 $file->error = $error;
303 return false;
304 }
305 if (!$file->name) {
306 $file->error = 'missingFileName';
307 return false;
308 }
309 if (!preg_match($this->options['accept_file_types'], $file->name)) {
310 $file->error = 'acceptFileTypes';
311 return false;
312 }
313 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
314 $file_size = filesize($uploaded_file);
315 } else {
316 $file_size = $_SERVER['CONTENT_LENGTH'];
317 }
318 if ($this->options['max_file_size'] && (
319 $file_size > $this->options['max_file_size'] ||
320 $file->size > $this->options['max_file_size'])
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 $file->error = 'maxNumberOfFiles';
334 return false;
335 }
336 list($img_width, $img_height) = @getimagesize($uploaded_file);
337 if (is_numeric($img_width)) {
338 if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
339 $this->options['max_height'] && $img_height > $this->options['max_height']) {
340 $file->error = 'maxResolution';
341 return false;
342 }
343 if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
344 $this->options['min_height'] && $img_height < $this->options['min_height']) {
345 $file->error = 'minResolution';
346 return false;
347 }
348 }
349 return true;
350 }
351
358 protected function upcountNameCallback($matches)
359 {
360 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
361 $ext = isset($matches[2]) ? $matches[2] : '';
362 return ' ('.$index.')'.$ext;
363 }
364
371 protected function upcountName($name)
372 {
373 return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
374 }
375
384 protected function trimFileName($name, $type, $index)
385 {
386 // Remove path information and dots around the filename, to prevent uploading
387 // into different directories or replacing hidden system files.
388 // Also remove control characters and spaces (\x00..\x20) around the filename:
389 $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
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 (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 $validate = $this->validate($uploaded_file, $file, $error, $index);
424
425 if ($validate) {
426 if (dol_mkdir($this->options['upload_dir']) >= 0) {
427 // add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
428 $fileNameWithoutExt = preg_replace('/\.[^\.]+$/', '', $file->name);
429 $savingDocMask = $this->options['saving_doc_mask'];
430 if ($savingDocMask && strpos($savingDocMask, $fileNameWithoutExt) !== 0) {
431 $fileNameWithPrefix = preg_replace('/__file__/', $file->name, $savingDocMask);
432 $file->name = $fileNameWithPrefix;
433 }
434
435 $file_path = $this->options['upload_dir'].$file->name;
436 $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
437
438 clearstatcache();
439
440 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
441 // multipart/formdata uploads (POST method uploads)
442 if ($append_file) {
443 file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
444 } else {
445 $result = dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
446 }
447 } else {
448 // Non-multipart uploads (PUT method support)
449 file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
450 }
451 $file_size = filesize($file_path);
452 if ($file_size === $file->size) {
453 $file->url = $this->options['upload_url'].rawurlencode($file->name);
454 foreach ($this->options['image_versions'] as $version => $options) {
455 if ($this->createScaledImage($file->name, $options)) { // Creation of thumbs mini and small is ok
456 $tmp = explode('.', $file->name);
457
458 // We save the path of mini file into file->... (seems not used)
459 $keyforfile = $version.'_url';
460 $file->$keyforfile = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
461 }
462 }
463 } elseif ($this->options['discard_aborted_uploads']) {
464 unlink($file_path);
465 $file->error = 'abort';
466 }
467 $file->size = $file_size;
468 $this->setFileDeleteUrl($file);
469 } else {
470 $file->error = 'failedtocreatedestdir';
471 }
472 } else {
473 // should not happen
474 }
475
476 return $file;
477 }
478
484 public function get()
485 {
486 $file_name = isset($_REQUEST['file']) ?
487 basename(stripslashes($_REQUEST['file'])) : null;
488 if ($file_name) {
489 $info = $this->getFileObject($file_name);
490 } else {
491 $info = $this->getFileObjects();
492 }
493 header('Content-type: application/json');
494 echo json_encode($info);
495 }
496
502 public function post()
503 {
504 $error = 0;
505
506 if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
507 return $this->delete();
508 }
509 //var_dump($_FILES);
510
511 $upload = isset($_FILES[$this->options['param_name']]) ?
512 $_FILES[$this->options['param_name']] : null;
513 $info = array();
514 if ($upload && is_array($upload['tmp_name'])) {
515 // param_name is an array identifier like "files[]",
516 // $_FILES is a multi-dimensional array:
517 foreach ($upload['tmp_name'] as $index => $value) {
518 $tmpres = $this->handleFileUpload(
519 $upload['tmp_name'][$index],
520 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
521 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
522 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
523 $upload['error'][$index],
524 $index
525 );
526 if (!empty($tmpres->error)) {
527 $error++;
528 }
529 $info[] = $tmpres;
530 }
531 } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
532 // param_name is a single object identifier like "file",
533 // $_FILES is a one-dimensional array:
534 $tmpres = $this->handleFileUpload(
535 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
536 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
537 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
538 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
539 isset($upload['error']) ? $upload['error'] : null,
540 0
541 );
542 if (!empty($tmpres->error)) {
543 $error++;
544 }
545 $info[] = $tmpres;
546 }
547
548 header('Vary: Accept');
549 $json = json_encode($info);
550
551 /* disabled. Param redirect seems not used
552 $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null;
553 if ($redirect) {
554 header('Location: '.sprintf($redirect, rawurlencode($json)));
555 return;
556 }
557 */
558
559 if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
560 header('Content-type: application/json');
561 } else {
562 header('Content-type: text/plain');
563 }
564 echo $json;
565
566 return $error;
567 }
568
574 public function delete()
575 {
576 $file_name = isset($_REQUEST['file']) ?
577 basename(stripslashes($_REQUEST['file'])) : null;
578 $file_path = $this->options['upload_dir'].$file_name;
579 $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
580 if ($success) {
581 foreach ($this->options['image_versions'] as $version => $options) {
582 $file = $options['upload_dir'].$file_name;
583 if (is_file($file)) {
584 unlink($file);
585 }
586 }
587 }
588 // Return result in json format
589 header('Content-type: application/json');
590 echo json_encode($success);
591
592 return 0;
593 }
594}
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)
Enter description here ...
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_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 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.
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_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).