dolibarr  7.0.0-beta
fileupload.class.php
1 <?php
2 /* Copyright (C) 2011-2012 Regis Houssin <regis.houssin@capnetworks.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 == 'action') {
98  $pathname = 'comm/action'; $filename='actioncomm';
99  $dir_output=$conf->agenda->dir_output;
100  }
101  elseif ($element == 'chargesociales') {
102  $pathname = 'compta/sociales'; $filename='chargesociales';
103  $dir_output=$conf->tax->dir_output;
104  } else {
105  $dir_output=$conf->$element->dir_output;
106  }
107 
108  dol_include_once('/'.$pathname.'/class/'.$filename.'.class.php');
109 
110  $classname = ucfirst($filename);
111 
112  if ($element == 'order_supplier') {
113  $classname = 'CommandeFournisseur';
114  } elseif ($element == 'invoice_supplier') {
115  $classname = 'FactureFournisseur';
116  }
117 
118  $object = new $classname($db);
119 
120  $object->fetch($fk_element);
121  if (!empty($parentForeignKey)) {
122  dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
123  $parent = new $parentClass($db);
124  $parent->fetch($object->$parentForeignKey);
125  if (!empty($parent->socid)) {
126  $parent->fetch_thirdparty();
127  }
128  $object->$parentObject = clone $parent;
129  } else {
130  $object->fetch_thirdparty();
131  }
132 
133  $object_ref = dol_sanitizeFileName($object->ref);
134  if ($element == 'invoice_supplier') {
135  $object_ref = get_exdir($object->id,2,0,0,$object,'invoice_supplier') . $object_ref;
136  } else if ($element == 'project_task') {
137  $object_ref = $object->project->ref . '/' . $object_ref;
138  }
139 
140  $this->options = array(
141  'script_url' => $_SERVER['PHP_SELF'],
142  'upload_dir' => $dir_output . '/' . $object_ref . '/',
143  'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
144  'param_name' => 'files',
145  // Set the following option to 'POST', if your server does not support
146  // DELETE requests. This is a parameter sent to the client:
147  'delete_type' => 'DELETE',
148  // The php.ini settings upload_max_filesize and post_max_size
149  // take precedence over the following max_file_size setting:
150  'max_file_size' => null,
151  'min_file_size' => 1,
152  'accept_file_types' => '/.+$/i',
153  // The maximum number of files for the upload directory:
154  'max_number_of_files' => null,
155  // Image resolution restrictions:
156  'max_width' => null,
157  'max_height' => null,
158  'min_width' => 1,
159  'min_height' => 1,
160  // Set the following option to false to enable resumable uploads:
161  'discard_aborted_uploads' => true,
162  'image_versions' => array(
163  // Uncomment the following version to restrict the size of
164  // uploaded images. You can also add additional versions with
165  // their own upload directories:
166  /*
167  'large' => array(
168  'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
169  'upload_url' => $this->getFullUrl().'/files/',
170  'max_width' => 1920,
171  'max_height' => 1200,
172  'jpeg_quality' => 95
173  ),
174  */
175  'thumbnail' => array(
176  'upload_dir' => $dir_output . '/' . $object_ref . '/thumbs/',
177  'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/thumbs/',
178  'max_width' => 80,
179  'max_height' => 80
180  )
181  )
182  );
183  if ($options) {
184  $this->options = array_replace_recursive($this->options, $options);
185  }
186  }
187 
193  protected function getFullUrl()
194  {
195  $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
196  return
197  ($https ? 'https://' : 'http://').
198  (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
199  (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
200  ($https && $_SERVER['SERVER_PORT'] === 443 ||
201  $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
202  substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
203  }
204 
211  protected function setFileDeleteUrl($file)
212  {
213  $file->delete_url = $this->options['script_url']
214  .'?file='.rawurlencode($file->name).'&fk_element='.$this->fk_element.'&element='.$this->element;
215  $file->delete_type = $this->options['delete_type'];
216  if ($file->delete_type !== 'DELETE') {
217  $file->delete_url .= '&_method=DELETE';
218  }
219  }
220 
227  protected function getFileObject($file_name)
228  {
229  $file_path = $this->options['upload_dir'].$file_name;
230  if (is_file($file_path) && $file_name[0] !== '.')
231  {
232  $file = new stdClass();
233  $file->name = $file_name;
234  $file->mime = dol_mimetype($file_name,'',2);
235  $file->size = filesize($file_path);
236  $file->url = $this->options['upload_url'].rawurlencode($file->name);
237  foreach($this->options['image_versions'] as $version => $options) {
238  if (is_file($options['upload_dir'].$file_name)) {
239  $tmp=explode('.',$file->name);
240  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
241  }
242  }
243  $this->setFileDeleteUrl($file);
244  return $file;
245  }
246  return null;
247  }
248 
254  protected function getFileObjects()
255  {
256  return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
257  }
258 
266  protected function createScaledImage($file_name, $options)
267  {
268  global $maxwidthmini, $maxheightmini;
269 
270  $file_path = $this->options['upload_dir'].$file_name;
271  $new_file_path = $options['upload_dir'].$file_name;
272 
273  if (dol_mkdir($options['upload_dir']) >= 0)
274  {
275  list($img_width, $img_height) = @getimagesize($file_path);
276  if (!$img_width || !$img_height) {
277  return false;
278  }
279 
280  $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".
281 
282  if (preg_match('/error/i',$res)) return false;
283  return true;
284  }
285  else
286  {
287  return false;
288  }
289  }
290 
300  protected function validate($uploaded_file, $file, $error, $index)
301  {
302  if ($error) {
303  $file->error = $error;
304  return false;
305  }
306  if (!$file->name) {
307  $file->error = 'missingFileName';
308  return false;
309  }
310  if (!preg_match($this->options['accept_file_types'], $file->name)) {
311  $file->error = 'acceptFileTypes';
312  return false;
313  }
314  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
315  $file_size = filesize($uploaded_file);
316  } else {
317  $file_size = $_SERVER['CONTENT_LENGTH'];
318  }
319  if ($this->options['max_file_size'] && (
320  $file_size > $this->options['max_file_size'] ||
321  $file->size > $this->options['max_file_size'])
322  ) {
323  $file->error = 'maxFileSize';
324  return false;
325  }
326  if ($this->options['min_file_size'] &&
327  $file_size < $this->options['min_file_size']) {
328  $file->error = 'minFileSize';
329  return false;
330  }
331  if (is_numeric($this->options['max_number_of_files']) && (
332  count($this->getFileObjects()) >= $this->options['max_number_of_files'])
333  ) {
334  $file->error = 'maxNumberOfFiles';
335  return false;
336  }
337  list($img_width, $img_height) = @getimagesize($uploaded_file);
338  if (is_numeric($img_width)) {
339  if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
340  $this->options['max_height'] && $img_height > $this->options['max_height']) {
341  $file->error = 'maxResolution';
342  return false;
343  }
344  if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
345  $this->options['min_height'] && $img_height < $this->options['min_height']) {
346  $file->error = 'minResolution';
347  return false;
348  }
349  }
350  return true;
351  }
352 
359  protected function upcountNameCallback($matches)
360  {
361  $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
362  $ext = isset($matches[2]) ? $matches[2] : '';
363  return ' ('.$index.')'.$ext;
364  }
365 
372  protected function upcountName($name)
373  {
374  return preg_replace_callback('/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
375  }
376 
385  protected function trimFileName($name, $type, $index)
386  {
387  // Remove path information and dots around the filename, to prevent uploading
388  // into different directories or replacing hidden system files.
389  // Also remove control characters and spaces (\x00..\x20) around the filename:
390  $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
391  // Add missing file extension for known image types:
392  if (strpos($file_name, '.') === false &&
393  preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
394  $file_name .= '.'.$matches[1];
395  }
396  if ($this->options['discard_aborted_uploads'])
397  {
398  while(is_file($this->options['upload_dir'].$file_name))
399  {
400  $file_name = $this->upcountName($file_name);
401  }
402  }
403  return $file_name;
404  }
405 
417  protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
418  {
419  $file = new stdClass();
420  $file->name = $this->trimFileName($name, $type, $index);
421  $file->mime = dol_mimetype($file->name,'',2);
422  $file->size = intval($size);
423  $file->type = $type;
424  if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0)
425  {
426  $file_path = $this->options['upload_dir'].$file->name;
427  $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
428  clearstatcache();
429  if ($uploaded_file && is_uploaded_file($uploaded_file)) {
430  // multipart/formdata uploads (POST method uploads)
431  if ($append_file)
432  {
433  file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
434  } else {
435  dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
436  }
437  }
438  else
439  {
440  // Non-multipart uploads (PUT method support)
441  file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
442  }
443  $file_size = filesize($file_path);
444  if ($file_size === $file->size)
445  {
446  $file->url = $this->options['upload_url'].rawurlencode($file->name);
447  foreach($this->options['image_versions'] as $version => $options)
448  {
449  if ($this->createScaledImage($file->name, $options))
450  {
451  $tmp=explode('.',$file->name);
452  $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
453  }
454  }
455  }
456  else if ($this->options['discard_aborted_uploads'])
457  {
458  unlink($file_path);
459  $file->error = 'abort';
460  }
461  $file->size = $file_size;
462  $this->setFileDeleteUrl($file);
463  }
464  return $file;
465  }
466 
472  public function get()
473  {
474  $file_name = isset($_REQUEST['file']) ?
475  basename(stripslashes($_REQUEST['file'])) : null;
476  if ($file_name)
477  {
478  $info = $this->getFileObject($file_name);
479  }
480  else
481  {
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.
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:962
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 ...
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)
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Return a prefix to use for this Dolibarr instance, for session/cookie names or email id...
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