dolibarr  17.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-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 
24 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
25 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
26 
27 
32 {
33  protected $options;
34  protected $fk_element;
35  protected $element;
36 
44  public function __construct($options = null, $fk_element = null, $element = null)
45  {
46  global $db, $conf;
47  global $object;
48  global $hookmanager;
49 
50  // Feature not enabled. Warning feature not used and not secured so disabled.
51  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
52  return;
53  }
54 
55  $hookmanager->initHooks(array('fileupload'));
56 
57  $this->fk_element = $fk_element;
58  $this->element = $element;
59 
60  $pathname = $filename = $element;
61  if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
62  $pathname = $regs[1];
63  $filename = $regs[2];
64  }
65 
66  $parentForeignKey = '';
67 
68  // For compatibility
69  if ($element == 'propal') {
70  $pathname = 'comm/propal';
71  $dir_output = $conf->$element->dir_output;
72  } elseif ($element == 'facture') {
73  $pathname = 'compta/facture';
74  $dir_output = $conf->$element->dir_output;
75  } elseif ($element == 'project') {
76  $element = $pathname = 'projet';
77  $dir_output = $conf->$element->dir_output;
78  } elseif ($element == 'project_task') {
79  $pathname = 'projet';
80  $filename = 'task';
81  $dir_output = $conf->project->dir_output;
82  $parentForeignKey = 'fk_project';
83  $parentClass = 'Project';
84  $parentElement = 'projet';
85  $parentObject = 'project';
86  } elseif ($element == 'fichinter') {
87  $element = 'ficheinter';
88  $dir_output = $conf->$element->dir_output;
89  } elseif ($element == 'order_supplier') {
90  $pathname = 'fourn';
91  $filename = 'fournisseur.commande';
92  $dir_output = $conf->fournisseur->commande->dir_output;
93  } elseif ($element == 'invoice_supplier') {
94  $pathname = 'fourn';
95  $filename = 'fournisseur.facture';
96  $dir_output = $conf->fournisseur->facture->dir_output;
97  } elseif ($element == 'product') {
98  $dir_output = $conf->product->multidir_output[$conf->entity];
99  } elseif ($element == 'productbatch') {
100  $dir_output = $conf->productbatch->multidir_output[$conf->entity];
101  } elseif ($element == 'action') {
102  $pathname = 'comm/action';
103  $filename = 'actioncomm';
104  $dir_output = $conf->agenda->dir_output;
105  } elseif ($element == 'chargesociales') {
106  $pathname = 'compta/sociales';
107  $filename = 'chargesociales';
108  $dir_output = $conf->tax->dir_output;
109  } else {
110  $dir_output = $conf->$element->dir_output;
111  }
112 
113  dol_include_once('/'.$pathname.'/class/'.$filename.'.class.php');
114 
115  $classname = ucfirst($filename);
116 
117  if ($element == 'order_supplier') {
118  $classname = 'CommandeFournisseur';
119  } elseif ($element == 'invoice_supplier') {
120  $classname = 'FactureFournisseur';
121  }
122 
123  $object = new $classname($db);
124 
125  $object->fetch($fk_element);
126  if (!empty($parentForeignKey)) {
127  dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
128  $parent = new $parentClass($db);
129  $parent->fetch($object->$parentForeignKey);
130  if (!empty($parent->socid)) {
131  $parent->fetch_thirdparty();
132  }
133  $object->$parentObject = clone $parent;
134  } else {
135  $object->fetch_thirdparty();
136  }
137 
138  $object_ref = dol_sanitizeFileName($object->ref);
139  if ($element == 'invoice_supplier') {
140  $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
141  } elseif ($element == 'project_task') {
142  $object_ref = $object->project->ref.'/'.$object_ref;
143  }
144 
145  $this->options = array(
146  'script_url' => $_SERVER['PHP_SELF'],
147  'upload_dir' => $dir_output.'/'.$object_ref.'/',
148  'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
149  'param_name' => 'files',
150  // Set the following option to 'POST', if your server does not support
151  // DELETE requests. This is a parameter sent to the client:
152  'delete_type' => 'DELETE',
153  // The php.ini settings upload_max_filesize and post_max_size
154  // take precedence over the following max_file_size setting:
155  'max_file_size' => null,
156  'min_file_size' => 1,
157  'accept_file_types' => '/.+$/i',
158  // The maximum number of files for the upload directory:
159  'max_number_of_files' => null,
160  // Image resolution restrictions:
161  'max_width' => null,
162  'max_height' => null,
163  'min_width' => 1,
164  'min_height' => 1,
165  // Set the following option to false to enable resumable uploads:
166  'discard_aborted_uploads' => true,
167  'image_versions' => array(
168  // Uncomment the following version to restrict the size of
169  // uploaded images. You can also add additional versions with
170  // their own upload directories:
171  /*
172  'large' => array(
173  'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
174  'upload_url' => $this->getFullUrl().'/files/',
175  'max_width' => 1920,
176  'max_height' => 1200,
177  'jpeg_quality' => 95
178  ),
179  */
180  'thumbnail' => array(
181  'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
182  'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/thumbs/',
183  'max_width' => 80,
184  'max_height' => 80
185  )
186  )
187  );
188 
189  global $action;
190 
191  $hookmanager->executeHooks(
192  'overrideUploadOptions',
193  array(
194  'options' => &$options,
195  'element' => $element
196  ),
197  $object,
198  $action
199  );
200 
201  if ($options) {
202  $this->options = array_replace_recursive($this->options, $options);
203  }
204  }
205 
211  protected function getFullUrl()
212  {
213  $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
214  return
215  ($https ? 'https://' : 'http://').
216  (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
217  (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
218  ($https && $_SERVER['SERVER_PORT'] === 443 ||
219  $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
220  substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
221  }
222 
229  protected function setFileDeleteUrl($file)
230  {
231  $file->delete_url = $this->options['script_url']
232  .'?file='.urlencode($file->name).'&fk_element='.urlencode($this->fk_element).'&element='.urlencode($this->element);
233  $file->delete_type = $this->options['delete_type'];
234  if ($file->delete_type !== 'DELETE') {
235  $file->delete_url .= '&_method=DELETE';
236  }
237  }
238 
245  protected function getFileObject($file_name)
246  {
247  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
248  return;
249  }
250 
251  $file_path = $this->options['upload_dir'].$file_name;
252  if (is_file($file_path) && $file_name[0] !== '.') {
253  $file = new stdClass();
254  $file->name = $file_name;
255  $file->mime = dol_mimetype($file_name, '', 2);
256  $file->size = filesize($file_path);
257  $file->url = $this->options['upload_url'].rawurlencode($file->name);
258  foreach ($this->options['image_versions'] as $version => $options) {
259  if (is_file($options['upload_dir'].$file_name)) {
260  $tmp = explode('.', $file->name);
261  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
262  }
263  }
264  $this->setFileDeleteUrl($file);
265  return $file;
266  }
267  return null;
268  }
269 
275  protected function getFileObjects()
276  {
277  return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
278  }
279 
287  protected function createScaledImage($file_name, $options)
288  {
289  global $maxwidthmini, $maxheightmini;
290 
291  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
292  return;
293  }
294 
295  $file_path = $this->options['upload_dir'].$file_name;
296  $new_file_path = $options['upload_dir'].$file_name;
297 
298  if (dol_mkdir($options['upload_dir']) >= 0) {
299  list($img_width, $img_height) = @getimagesize($file_path);
300  if (!$img_width || !$img_height) {
301  return false;
302  }
303 
304  $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object and we don't need all thumbs, only the "mini".
305 
306  if (preg_match('/error/i', $res)) {
307  return false;
308  }
309  return true;
310  } else {
311  return false;
312  }
313  }
314 
324  protected function validate($uploaded_file, $file, $error, $index)
325  {
326  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
327  return;
328  }
329 
330  if ($error) {
331  $file->error = $error;
332  return false;
333  }
334  if (!$file->name) {
335  $file->error = 'missingFileName';
336  return false;
337  }
338  if (!preg_match($this->options['accept_file_types'], $file->name)) {
339  $file->error = 'acceptFileTypes';
340  return false;
341  }
342  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
343  $file_size = filesize($uploaded_file);
344  } else {
345  $file_size = $_SERVER['CONTENT_LENGTH'];
346  }
347  if ($this->options['max_file_size'] && (
348  $file_size > $this->options['max_file_size'] ||
349  $file->size > $this->options['max_file_size'])
350  ) {
351  $file->error = 'maxFileSize';
352  return false;
353  }
354  if ($this->options['min_file_size'] &&
355  $file_size < $this->options['min_file_size']) {
356  $file->error = 'minFileSize';
357  return false;
358  }
359  if (is_numeric($this->options['max_number_of_files']) && (
360  count($this->getFileObjects()) >= $this->options['max_number_of_files'])
361  ) {
362  $file->error = 'maxNumberOfFiles';
363  return false;
364  }
365  list($img_width, $img_height) = @getimagesize($uploaded_file);
366  if (is_numeric($img_width)) {
367  if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
368  $this->options['max_height'] && $img_height > $this->options['max_height']) {
369  $file->error = 'maxResolution';
370  return false;
371  }
372  if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
373  $this->options['min_height'] && $img_height < $this->options['min_height']) {
374  $file->error = 'minResolution';
375  return false;
376  }
377  }
378  return true;
379  }
380 
387  protected function upcountNameCallback($matches)
388  {
389  $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
390  $ext = isset($matches[2]) ? $matches[2] : '';
391  return ' ('.$index.')'.$ext;
392  }
393 
400  protected function upcountName($name)
401  {
402  return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
403  }
404 
413  protected function trimFileName($name, $type, $index)
414  {
415  // Remove path information and dots around the filename, to prevent uploading
416  // into different directories or replacing hidden system files.
417  // Also remove control characters and spaces (\x00..\x20) around the filename:
418  $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
419  // Add missing file extension for known image types:
420  $matches = array();
421  if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
422  $file_name .= '.'.$matches[1];
423  }
424  if ($this->options['discard_aborted_uploads']) {
425  while (is_file($this->options['upload_dir'].$file_name)) {
426  $file_name = $this->upcountName($file_name);
427  }
428  }
429  return $file_name;
430  }
431 
443  protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
444  {
445  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
446  return;
447  }
448 
449  $file = new stdClass();
450  $file->name = $this->trimFileName($name, $type, $index);
451  $file->mime = dol_mimetype($file->name, '', 2);
452  $file->size = intval($size);
453  $file->type = $type;
454  if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0) {
455  $file_path = $this->options['upload_dir'].$file->name;
456  $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
457  clearstatcache();
458  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
459  // multipart/formdata uploads (POST method uploads)
460  if ($append_file) {
461  file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
462  } else {
463  dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
464  }
465  } else {
466  // Non-multipart uploads (PUT method support)
467  file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
468  }
469  $file_size = filesize($file_path);
470  if ($file_size === $file->size) {
471  $file->url = $this->options['upload_url'].rawurlencode($file->name);
472  foreach ($this->options['image_versions'] as $version => $options) {
473  if ($this->createScaledImage($file->name, $options)) {
474  $tmp = explode('.', $file->name);
475  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
476  }
477  }
478  } elseif ($this->options['discard_aborted_uploads']) {
479  unlink($file_path);
480  $file->error = 'abort';
481  }
482  $file->size = $file_size;
483  $this->setFileDeleteUrl($file);
484  }
485  return $file;
486  }
487 
493  public function get()
494  {
495  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
496  return;
497  }
498 
499  $file_name = isset($_REQUEST['file']) ?
500  basename(stripslashes($_REQUEST['file'])) : null;
501  if ($file_name) {
502  $info = $this->getFileObject($file_name);
503  } else {
504  $info = $this->getFileObjects();
505  }
506  header('Content-type: application/json');
507  echo json_encode($info);
508  }
509 
515  public function post()
516  {
517  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
518  return;
519  }
520 
521  if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
522  return $this->delete();
523  }
524  $upload = isset($_FILES[$this->options['param_name']]) ?
525  $_FILES[$this->options['param_name']] : null;
526  $info = array();
527  if ($upload && is_array($upload['tmp_name'])) {
528  // param_name is an array identifier like "files[]",
529  // $_FILES is a multi-dimensional array:
530  foreach ($upload['tmp_name'] as $index => $value) {
531  $info[] = $this->handleFileUpload(
532  $upload['tmp_name'][$index],
533  isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
534  isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
535  isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
536  $upload['error'][$index],
537  $index
538  );
539  }
540  } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
541  // param_name is a single object identifier like "file",
542  // $_FILES is a one-dimensional array:
543  $info[] = $this->handleFileUpload(
544  isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
545  isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
546  isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
547  isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
548  isset($upload['error']) ? $upload['error'] : null,
549  0
550  );
551  }
552  header('Vary: Accept');
553  $json = json_encode($info);
554  $redirect = isset($_REQUEST['redirect']) ?
555  stripslashes($_REQUEST['redirect']) : null;
556  if ($redirect) {
557  header('Location: '.sprintf($redirect, rawurlencode($json)));
558  return;
559  }
560  if (isset($_SERVER['HTTP_ACCEPT']) &&
561  (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
562  header('Content-type: application/json');
563  } else {
564  header('Content-type: text/plain');
565  }
566  echo $json;
567  }
568 
574  public function delete()
575  {
576  if (!getDolGlobalInt('MAIN_USE_JQUERY_FILEUPLOAD')) {
577  return;
578  }
579 
580  $file_name = isset($_REQUEST['file']) ?
581  basename(stripslashes($_REQUEST['file'])) : null;
582  $file_path = $this->options['upload_dir'].$file_name;
583  $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
584  if ($success) {
585  foreach ($this->options['image_versions'] as $version => $options) {
586  $file = $options['upload_dir'].$file_name;
587  if (is_file($file)) {
588  unlink($file);
589  }
590  }
591  }
592  header('Content-type: application/json');
593  echo json_encode($success);
594  }
595 }
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.
Definition: files.lib.php:1112
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
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_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).
Definition: images.lib.php:511