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