dolibarr  x.y.z
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  global $action;
184 
185  $hookmanager->executeHooks(
186  'overrideUploadOptions',
187  array(
188  'options' => &$options,
189  'element' => $element
190  ),
191  $object,
192  $action
193  );
194 
195  if ($options) {
196  $this->options = array_replace_recursive($this->options, $options);
197  }
198  }
199 
205  protected function getFullUrl()
206  {
207  $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
208  return
209  ($https ? 'https://' : 'http://').
210  (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
211  (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
212  ($https && $_SERVER['SERVER_PORT'] === 443 ||
213  $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
214  substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
215  }
216 
223  protected function setFileDeleteUrl($file)
224  {
225  $file->delete_url = $this->options['script_url']
226  .'?file='.urlencode($file->name).'&fk_element='.urlencode($this->fk_element).'&element='.urlencode($this->element);
227  $file->delete_type = $this->options['delete_type'];
228  if ($file->delete_type !== 'DELETE') {
229  $file->delete_url .= '&_method=DELETE';
230  }
231  }
232 
239  protected function getFileObject($file_name)
240  {
241  $file_path = $this->options['upload_dir'].$file_name;
242  if (is_file($file_path) && $file_name[0] !== '.') {
243  $file = new stdClass();
244  $file->name = $file_name;
245  $file->mime = dol_mimetype($file_name, '', 2);
246  $file->size = filesize($file_path);
247  $file->url = $this->options['upload_url'].rawurlencode($file->name);
248  foreach ($this->options['image_versions'] as $version => $options) {
249  if (is_file($options['upload_dir'].$file_name)) {
250  $tmp = explode('.', $file->name);
251  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
252  }
253  }
254  $this->setFileDeleteUrl($file);
255  return $file;
256  }
257  return null;
258  }
259 
265  protected function getFileObjects()
266  {
267  return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
268  }
269 
277  protected function createScaledImage($file_name, $options)
278  {
279  global $maxwidthmini, $maxheightmini;
280 
281  $file_path = $this->options['upload_dir'].$file_name;
282  $new_file_path = $options['upload_dir'].$file_name;
283 
284  if (dol_mkdir($options['upload_dir']) >= 0) {
285  list($img_width, $img_height) = @getimagesize($file_path);
286  if (!$img_width || !$img_height) {
287  return false;
288  }
289 
290  $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".
291 
292  if (preg_match('/error/i', $res)) {
293  return false;
294  }
295  return true;
296  } else {
297  return false;
298  }
299  }
300 
310  protected function validate($uploaded_file, $file, $error, $index)
311  {
312  if ($error) {
313  $file->error = $error;
314  return false;
315  }
316  if (!$file->name) {
317  $file->error = 'missingFileName';
318  return false;
319  }
320  if (!preg_match($this->options['accept_file_types'], $file->name)) {
321  $file->error = 'acceptFileTypes';
322  return false;
323  }
324  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
325  $file_size = filesize($uploaded_file);
326  } else {
327  $file_size = $_SERVER['CONTENT_LENGTH'];
328  }
329  if ($this->options['max_file_size'] && (
330  $file_size > $this->options['max_file_size'] ||
331  $file->size > $this->options['max_file_size'])
332  ) {
333  $file->error = 'maxFileSize';
334  return false;
335  }
336  if ($this->options['min_file_size'] &&
337  $file_size < $this->options['min_file_size']) {
338  $file->error = 'minFileSize';
339  return false;
340  }
341  if (is_numeric($this->options['max_number_of_files']) && (
342  count($this->getFileObjects()) >= $this->options['max_number_of_files'])
343  ) {
344  $file->error = 'maxNumberOfFiles';
345  return false;
346  }
347  list($img_width, $img_height) = @getimagesize($uploaded_file);
348  if (is_numeric($img_width)) {
349  if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
350  $this->options['max_height'] && $img_height > $this->options['max_height']) {
351  $file->error = 'maxResolution';
352  return false;
353  }
354  if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
355  $this->options['min_height'] && $img_height < $this->options['min_height']) {
356  $file->error = 'minResolution';
357  return false;
358  }
359  }
360  return true;
361  }
362 
369  protected function upcountNameCallback($matches)
370  {
371  $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
372  $ext = isset($matches[2]) ? $matches[2] : '';
373  return ' ('.$index.')'.$ext;
374  }
375 
382  protected function upcountName($name)
383  {
384  return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
385  }
386 
395  protected function trimFileName($name, $type, $index)
396  {
397  // Remove path information and dots around the filename, to prevent uploading
398  // into different directories or replacing hidden system files.
399  // Also remove control characters and spaces (\x00..\x20) around the filename:
400  $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
401  // Add missing file extension for known image types:
402  if (strpos($file_name, '.') === false &&
403  preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
404  $file_name .= '.'.$matches[1];
405  }
406  if ($this->options['discard_aborted_uploads']) {
407  while (is_file($this->options['upload_dir'].$file_name)) {
408  $file_name = $this->upcountName($file_name);
409  }
410  }
411  return $file_name;
412  }
413 
425  protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
426  {
427  $file = new stdClass();
428  $file->name = $this->trimFileName($name, $type, $index);
429  $file->mime = dol_mimetype($file->name, '', 2);
430  $file->size = intval($size);
431  $file->type = $type;
432  if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0) {
433  $file_path = $this->options['upload_dir'].$file->name;
434  $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
435  clearstatcache();
436  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
437  // multipart/formdata uploads (POST method uploads)
438  if ($append_file) {
439  file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
440  } else {
441  dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
442  }
443  } else {
444  // Non-multipart uploads (PUT method support)
445  file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
446  }
447  $file_size = filesize($file_path);
448  if ($file_size === $file->size) {
449  $file->url = $this->options['upload_url'].rawurlencode($file->name);
450  foreach ($this->options['image_versions'] as $version => $options) {
451  if ($this->createScaledImage($file->name, $options)) {
452  $tmp = explode('.', $file->name);
453  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
454  }
455  }
456  } elseif ($this->options['discard_aborted_uploads']) {
457  unlink($file_path);
458  $file->error = 'abort';
459  }
460  $file->size = $file_size;
461  $this->setFileDeleteUrl($file);
462  }
463  return $file;
464  }
465 
471  public function get()
472  {
473  $file_name = isset($_REQUEST['file']) ?
474  basename(stripslashes($_REQUEST['file'])) : null;
475  if ($file_name) {
476  $info = $this->getFileObject($file_name);
477  } else {
478  $info = $this->getFileObjects();
479  }
480  header('Content-type: application/json');
481  echo json_encode($info);
482  }
483 
489  public function post()
490  {
491  if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
492  return $this->delete();
493  }
494  $upload = isset($_FILES[$this->options['param_name']]) ?
495  $_FILES[$this->options['param_name']] : null;
496  $info = array();
497  if ($upload && is_array($upload['tmp_name'])) {
498  // param_name is an array identifier like "files[]",
499  // $_FILES is a multi-dimensional array:
500  foreach ($upload['tmp_name'] as $index => $value) {
501  $info[] = $this->handleFileUpload(
502  $upload['tmp_name'][$index],
503  isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
504  isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
505  isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
506  $upload['error'][$index],
507  $index
508  );
509  }
510  } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
511  // param_name is a single object identifier like "file",
512  // $_FILES is a one-dimensional array:
513  $info[] = $this->handleFileUpload(
514  isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
515  isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
516  isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
517  isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
518  isset($upload['error']) ? $upload['error'] : null,
519  0
520  );
521  }
522  header('Vary: Accept');
523  $json = json_encode($info);
524  $redirect = isset($_REQUEST['redirect']) ?
525  stripslashes($_REQUEST['redirect']) : null;
526  if ($redirect) {
527  header('Location: '.sprintf($redirect, rawurlencode($json)));
528  return;
529  }
530  if (isset($_SERVER['HTTP_ACCEPT']) &&
531  (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
532  header('Content-type: application/json');
533  } else {
534  header('Content-type: text/plain');
535  }
536  echo $json;
537  }
538 
544  public function delete()
545  {
546  $file_name = isset($_REQUEST['file']) ?
547  basename(stripslashes($_REQUEST['file'])) : null;
548  $file_path = $this->options['upload_dir'].$file_name;
549  $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
550  if ($success) {
551  foreach ($this->options['image_versions'] as $version => $options) {
552  $file = $options['upload_dir'].$file_name;
553  if (is_file($file)) {
554  unlink($file);
555  }
556  }
557  }
558  header('Content-type: application/json');
559  echo json_encode($success);
560  }
561 }
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:1111
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.
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:485