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