dolibarr  16.0.5
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  $hookmanager->initHooks(array('fileupload'));
50 
51  $this->fk_element = $fk_element;
52  $this->element = $element;
53 
54  $pathname = $filename = $element;
55  if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
56  $pathname = $regs[1];
57  $filename = $regs[2];
58  }
59 
60  $parentForeignKey = '';
61 
62  // For compatibility
63  if ($element == 'propal') {
64  $pathname = 'comm/propal';
65  $dir_output = $conf->$element->dir_output;
66  } elseif ($element == 'facture') {
67  $pathname = 'compta/facture';
68  $dir_output = $conf->$element->dir_output;
69  } elseif ($element == 'project') {
70  $element = $pathname = 'projet';
71  $dir_output = $conf->$element->dir_output;
72  } elseif ($element == 'project_task') {
73  $pathname = 'projet';
74  $filename = 'task';
75  $dir_output = $conf->project->dir_output;
76  $parentForeignKey = 'fk_project';
77  $parentClass = 'Project';
78  $parentElement = 'projet';
79  $parentObject = 'project';
80  } elseif ($element == 'fichinter') {
81  $element = 'ficheinter';
82  $dir_output = $conf->$element->dir_output;
83  } elseif ($element == 'order_supplier') {
84  $pathname = 'fourn';
85  $filename = 'fournisseur.commande';
86  $dir_output = $conf->fournisseur->commande->dir_output;
87  } elseif ($element == 'invoice_supplier') {
88  $pathname = 'fourn';
89  $filename = 'fournisseur.facture';
90  $dir_output = $conf->fournisseur->facture->dir_output;
91  } elseif ($element == 'product') {
92  $dir_output = $conf->product->multidir_output[$conf->entity];
93  } elseif ($element == 'productbatch') {
94  $dir_output = $conf->productbatch->multidir_output[$conf->entity];
95  } elseif ($element == 'action') {
96  $pathname = 'comm/action';
97  $filename = 'actioncomm';
98  $dir_output = $conf->agenda->dir_output;
99  } elseif ($element == 'chargesociales') {
100  $pathname = 'compta/sociales';
101  $filename = 'chargesociales';
102  $dir_output = $conf->tax->dir_output;
103  } else {
104  $dir_output = $conf->$element->dir_output;
105  }
106 
107  dol_include_once('/'.$pathname.'/class/'.$filename.'.class.php');
108 
109  $classname = ucfirst($filename);
110 
111  if ($element == 'order_supplier') {
112  $classname = 'CommandeFournisseur';
113  } elseif ($element == 'invoice_supplier') {
114  $classname = 'FactureFournisseur';
115  }
116 
117  $object = new $classname($db);
118 
119  $object->fetch($fk_element);
120  if (!empty($parentForeignKey)) {
121  dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
122  $parent = new $parentClass($db);
123  $parent->fetch($object->$parentForeignKey);
124  if (!empty($parent->socid)) {
125  $parent->fetch_thirdparty();
126  }
127  $object->$parentObject = clone $parent;
128  } else {
129  $object->fetch_thirdparty();
130  }
131 
132  $object_ref = dol_sanitizeFileName($object->ref);
133  if ($element == 'invoice_supplier') {
134  $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
135  } elseif ($element == 'project_task') {
136  $object_ref = $object->project->ref.'/'.$object_ref;
137  }
138 
139  $this->options = array(
140  'script_url' => $_SERVER['PHP_SELF'],
141  'upload_dir' => $dir_output.'/'.$object_ref.'/',
142  'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
143  'param_name' => 'files',
144  // Set the following option to 'POST', if your server does not support
145  // DELETE requests. This is a parameter sent to the client:
146  'delete_type' => 'DELETE',
147  // The php.ini settings upload_max_filesize and post_max_size
148  // take precedence over the following max_file_size setting:
149  'max_file_size' => null,
150  'min_file_size' => 1,
151  'accept_file_types' => '/.+$/i',
152  // The maximum number of files for the upload directory:
153  'max_number_of_files' => null,
154  // Image resolution restrictions:
155  'max_width' => null,
156  'max_height' => null,
157  'min_width' => 1,
158  'min_height' => 1,
159  // Set the following option to false to enable resumable uploads:
160  'discard_aborted_uploads' => true,
161  'image_versions' => array(
162  // Uncomment the following version to restrict the size of
163  // uploaded images. You can also add additional versions with
164  // their own upload directories:
165  /*
166  'large' => array(
167  'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
168  'upload_url' => $this->getFullUrl().'/files/',
169  'max_width' => 1920,
170  'max_height' => 1200,
171  'jpeg_quality' => 95
172  ),
173  */
174  'thumbnail' => array(
175  'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
176  'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/thumbs/',
177  'max_width' => 80,
178  'max_height' => 80
179  )
180  )
181  );
182 
183  $hookmanager->executeHooks(
184  'overrideUploadOptions',
185  array(
186  'options' => &$options,
187  'element' => $element
188  ),
189  $object,
190  $action,
191  $hookmanager
192  );
193 
194  if ($options) {
195  $this->options = array_replace_recursive($this->options, $options);
196  }
197  }
198 
204  protected function getFullUrl()
205  {
206  $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
207  return
208  ($https ? 'https://' : 'http://').
209  (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
210  (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
211  ($https && $_SERVER['SERVER_PORT'] === 443 ||
212  $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
213  substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
214  }
215 
222  protected function setFileDeleteUrl($file)
223  {
224  $file->delete_url = $this->options['script_url']
225  .'?file='.urlencode($file->name).'&fk_element='.urlencode($this->fk_element).'&element='.urlencode($this->element);
226  $file->delete_type = $this->options['delete_type'];
227  if ($file->delete_type !== 'DELETE') {
228  $file->delete_url .= '&_method=DELETE';
229  }
230  }
231 
238  protected function getFileObject($file_name)
239  {
240  $file_path = $this->options['upload_dir'].$file_name;
241  if (is_file($file_path) && $file_name[0] !== '.') {
242  $file = new stdClass();
243  $file->name = $file_name;
244  $file->mime = dol_mimetype($file_name, '', 2);
245  $file->size = filesize($file_path);
246  $file->url = $this->options['upload_url'].rawurlencode($file->name);
247  foreach ($this->options['image_versions'] as $version => $options) {
248  if (is_file($options['upload_dir'].$file_name)) {
249  $tmp = explode('.', $file->name);
250  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
251  }
252  }
253  $this->setFileDeleteUrl($file);
254  return $file;
255  }
256  return null;
257  }
258 
264  protected function getFileObjects()
265  {
266  return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
267  }
268 
276  protected function createScaledImage($file_name, $options)
277  {
278  global $maxwidthmini, $maxheightmini;
279 
280  $file_path = $this->options['upload_dir'].$file_name;
281  $new_file_path = $options['upload_dir'].$file_name;
282 
283  if (dol_mkdir($options['upload_dir']) >= 0) {
284  list($img_width, $img_height) = @getimagesize($file_path);
285  if (!$img_width || !$img_height) {
286  return false;
287  }
288 
289  $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".
290 
291  if (preg_match('/error/i', $res)) {
292  return false;
293  }
294  return true;
295  } else {
296  return false;
297  }
298  }
299 
309  protected function validate($uploaded_file, $file, $error, $index)
310  {
311  if ($error) {
312  $file->error = $error;
313  return false;
314  }
315  if (!$file->name) {
316  $file->error = 'missingFileName';
317  return false;
318  }
319  if (!preg_match($this->options['accept_file_types'], $file->name)) {
320  $file->error = 'acceptFileTypes';
321  return false;
322  }
323  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
324  $file_size = filesize($uploaded_file);
325  } else {
326  $file_size = $_SERVER['CONTENT_LENGTH'];
327  }
328  if ($this->options['max_file_size'] && (
329  $file_size > $this->options['max_file_size'] ||
330  $file->size > $this->options['max_file_size'])
331  ) {
332  $file->error = 'maxFileSize';
333  return false;
334  }
335  if ($this->options['min_file_size'] &&
336  $file_size < $this->options['min_file_size']) {
337  $file->error = 'minFileSize';
338  return false;
339  }
340  if (is_numeric($this->options['max_number_of_files']) && (
341  count($this->getFileObjects()) >= $this->options['max_number_of_files'])
342  ) {
343  $file->error = 'maxNumberOfFiles';
344  return false;
345  }
346  list($img_width, $img_height) = @getimagesize($uploaded_file);
347  if (is_numeric($img_width)) {
348  if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
349  $this->options['max_height'] && $img_height > $this->options['max_height']) {
350  $file->error = 'maxResolution';
351  return false;
352  }
353  if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
354  $this->options['min_height'] && $img_height < $this->options['min_height']) {
355  $file->error = 'minResolution';
356  return false;
357  }
358  }
359  return true;
360  }
361 
368  protected function upcountNameCallback($matches)
369  {
370  $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
371  $ext = isset($matches[2]) ? $matches[2] : '';
372  return ' ('.$index.')'.$ext;
373  }
374 
381  protected function upcountName($name)
382  {
383  return preg_replace_callback('/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
384  }
385 
394  protected function trimFileName($name, $type, $index)
395  {
396  // Remove path information and dots around the filename, to prevent uploading
397  // into different directories or replacing hidden system files.
398  // Also remove control characters and spaces (\x00..\x20) around the filename:
399  $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
400  // Add missing file extension for known image types:
401  if (strpos($file_name, '.') === false &&
402  preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
403  $file_name .= '.'.$matches[1];
404  }
405  if ($this->options['discard_aborted_uploads']) {
406  while (is_file($this->options['upload_dir'].$file_name)) {
407  $file_name = $this->upcountName($file_name);
408  }
409  }
410  return $file_name;
411  }
412 
424  protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
425  {
426  $file = new stdClass();
427  $file->name = $this->trimFileName($name, $type, $index);
428  $file->mime = dol_mimetype($file->name, '', 2);
429  $file->size = intval($size);
430  $file->type = $type;
431  if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0) {
432  $file_path = $this->options['upload_dir'].$file->name;
433  $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
434  clearstatcache();
435  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
436  // multipart/formdata uploads (POST method uploads)
437  if ($append_file) {
438  file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
439  } else {
440  dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
441  }
442  } else {
443  // Non-multipart uploads (PUT method support)
444  file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
445  }
446  $file_size = filesize($file_path);
447  if ($file_size === $file->size) {
448  $file->url = $this->options['upload_url'].rawurlencode($file->name);
449  foreach ($this->options['image_versions'] as $version => $options) {
450  if ($this->createScaledImage($file->name, $options)) {
451  $tmp = explode('.', $file->name);
452  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
453  }
454  }
455  } elseif ($this->options['discard_aborted_uploads']) {
456  unlink($file_path);
457  $file->error = 'abort';
458  }
459  $file->size = $file_size;
460  $this->setFileDeleteUrl($file);
461  }
462  return $file;
463  }
464 
470  public function get()
471  {
472  $file_name = isset($_REQUEST['file']) ?
473  basename(stripslashes($_REQUEST['file'])) : null;
474  if ($file_name) {
475  $info = $this->getFileObject($file_name);
476  } else {
477  $info = $this->getFileObjects();
478  }
479  header('Content-type: application/json');
480  echo json_encode($info);
481  }
482 
488  public function post()
489  {
490  if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
491  return $this->delete();
492  }
493  $upload = isset($_FILES[$this->options['param_name']]) ?
494  $_FILES[$this->options['param_name']] : null;
495  $info = array();
496  if ($upload && is_array($upload['tmp_name'])) {
497  // param_name is an array identifier like "files[]",
498  // $_FILES is a multi-dimensional array:
499  foreach ($upload['tmp_name'] as $index => $value) {
500  $info[] = $this->handleFileUpload(
501  $upload['tmp_name'][$index],
502  isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
503  isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
504  isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
505  $upload['error'][$index],
506  $index
507  );
508  }
509  } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
510  // param_name is a single object identifier like "file",
511  // $_FILES is a one-dimensional array:
512  $info[] = $this->handleFileUpload(
513  isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
514  isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
515  isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
516  isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
517  isset($upload['error']) ? $upload['error'] : null,
518  0
519  );
520  }
521  header('Vary: Accept');
522  $json = json_encode($info);
523  $redirect = isset($_REQUEST['redirect']) ?
524  stripslashes($_REQUEST['redirect']) : null;
525  if ($redirect) {
526  header('Location: '.sprintf($redirect, rawurlencode($json)));
527  return;
528  }
529  if (isset($_SERVER['HTTP_ACCEPT']) &&
530  (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
531  header('Content-type: application/json');
532  } else {
533  header('Content-type: text/plain');
534  }
535  echo $json;
536  }
537 
543  public function delete()
544  {
545  $file_name = isset($_REQUEST['file']) ?
546  basename(stripslashes($_REQUEST['file'])) : null;
547  $file_path = $this->options['upload_dir'].$file_name;
548  $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
549  if ($success) {
550  foreach ($this->options['image_versions'] as $version => $options) {
551  $file = $options['upload_dir'].$file_name;
552  if (is_file($file)) {
553  unlink($file);
554  }
555  }
556  }
557  header('Content-type: application/json');
558  echo json_encode($success);
559  }
560 }
FileUpload\validate
validate($uploaded_file, $file, $error, $index)
Enter description here ...
Definition: fileupload.class.php:309
FileUpload
This class is used to manage file upload using ajax.
Definition: fileupload.class.php:31
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
FileUpload\trimFileName
trimFileName($name, $type, $index)
trimFileName
Definition: fileupload.class.php:394
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1033
FileUpload\createScaledImage
createScaledImage($file_name, $options)
Create thumbs of a file uploaded.
Definition: fileupload.class.php:276
dol_mimetype
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
Definition: functions.lib.php:9741
FileUpload\getFileObject
getFileObject($file_name)
getFileObject
Definition: fileupload.class.php:238
get_exdir
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
Definition: functions.lib.php:6549
dol_move_uploaded_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.
Definition: files.lib.php:1092
FileUpload\handleFileUpload
handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
handleFileUpload
Definition: fileupload.class.php:424
FileUpload\getFileObjects
getFileObjects()
getFileObjects
Definition: fileupload.class.php:264
FileUpload\__construct
__construct($options=null, $fk_element=null, $element=null)
Constructor.
Definition: fileupload.class.php:44
FileUpload\getFullUrl
getFullUrl()
Return full URL.
Definition: fileupload.class.php:204
FileUpload\upcountName
upcountName($name)
Enter description here ...
Definition: fileupload.class.php:381
FileUpload\upcountNameCallback
upcountNameCallback($matches)
Enter description here ...
Definition: fileupload.class.php:368
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603
vignette
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:507
FileUpload\setFileDeleteUrl
setFileDeleteUrl($file)
Set delete url.
Definition: fileupload.class.php:222
FileUpload\post
post()
Output data.
Definition: fileupload.class.php:488