dolibarr 25.0.0-alpha
fileupload.class.php
Go to the documentation of this file.
1<?php
2
3/* Copyright (C) 2011-2022 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2011-2023 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
29require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
31
32
37{
41 public $options;
45 protected $fk_element;
46
50 protected $object = null;
51
55 protected $element;
56
67 public function __construct($options = null, $fk_element = null, $element = null)
68 {
69 global $hookmanager;
70
71 $hookmanager->initHooks(array('fileupload'));
72
73 $element_prop = getElementProperties($element);
74 //var_dump($element_prop);
75
76 $this->fk_element = $fk_element;
77 $this->element = $element;
78
79 $pathname = str_replace('/class', '', $element_prop['classpath']);
80 $filename = dol_sanitizeFileName($element_prop['classfile']);
81 $dir_output = dol_sanitizePathName($element_prop['dir_output']);
82 $savingDocMask = '';
83
84 //print 'fileupload.class.php: element='.$element.' pathname='.$pathname.' filename='.$filename.' dir_output='.$dir_output."\n";
85
86 $object_ref = 'UndefinedReference';
87 $object = null;
88 // If pathname and filename are empty then we can still upload files if we have specified upload_dir on $options
89 if ($pathname !== '' && $filename !== '') {
90 // Get object from its id and type
91 $object = fetchObjectByElement($fk_element, $element);
92
93 // fetchObjectByElement() also returns an object when the record was not found (fetch() returning 0),
94 // so we must check the object was really loaded. Without this, files would be stored at the root of
95 // the module directory, out of any object and out of any permission check on the object.
96 if (!is_object($object) || empty($object->id)) {
97 dol_syslog(get_class($this)."::__construct object ".$element." with id ".((int) $fk_element)." was not found", LOG_WARNING);
98 throw new Exception('objectnotfound');
99 }
100 $this->object = $object;
101
102 // Directory of the module, including the sub directory used by some elements (/sending for a shipment,
103 // /commande for a supplier order, /<project ref> for a task, ...). We must use the same directory than
104 // the one used by the "Attached files" tab of the object, otherwise the uploaded file is stored but
105 // never shown to the user.
106 // Note: getMultidirOutput() only knows the elements of its own switch, that is a minority of them. For
107 // all the others it does not return an empty string but the string
108 // 'error-diroutput-not-defined-for-this-object=x', and keeping the directory of getElementProperties()
109 // is then the nominal case, not a degraded one. So we only accept an absolute path: that string is a
110 // relative path, and writing into it would create the files under the web root.
111 $tmpdir = getMultidirOutput($object, $element);
112 if (!empty($tmpdir) && preg_match('/^([a-z]:)?[\\\\\/]/i', $tmpdir)) {
113 $dir_output = dol_sanitizePathName($tmpdir);
114 }
115
116 // Add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
117 if (!getDolGlobalInt('MAIN_DISABLE_SUGGEST_REF_AS_PREFIX')) {
118 $savingDocMask = dol_sanitizeFileName($object->ref).'-__file__';
119 }
120
121 // get_exdir() forges the directory of an object the way the "Attached files" tabs do: it always
122 // uses the id for a thirdparty (a thirdparty ref is a company name, so it is not unique), and it
123 // falls back on the id when the ref is empty. Using anything else here would store the file into
124 // a directory the tab never reads.
125 // Note that a few tabs sanitize the ref themselves instead of calling this function, so they have
126 // no fallback: on an object whose ref is empty in database, which the interface does not produce
127 // but old records may hold, they read the root of the directory of the module while we store
128 // under the id. Storing at the root would mix the files of every object of the module, so the
129 // fallback is kept and those tabs are the ones that should be fixed.
130 $object_ref = get_exdir(0, 0, 0, 1, $object, $element);
131
132 // For the modules storing their documents on several levels, get_exdir() returned the level
133 // directories only, so we must append the directory of the object itself.
134 if (in_array($element, array('invoice_supplier', 'supplier_invoice'))) {
135 $object_ref .= '/'.dol_sanitizeFileName($object->ref);
136 }
137 }
138
139 // Tested after the call to getMultidirOutput(), because some elements have no 'dir_output' returned by
140 // getElementProperties() while getMultidirOutput() is still able to resolve their output directory.
141 if (empty($dir_output)) {
142 dol_syslog(get_class($this)."::__construct element ".$element." is not supported for uploading file, dir_output is unknown", LOG_WARNING);
143 throw new Exception('elementnotsupported');
144 }
145
146 // Note: 'upload_url' is not always the url of the file stored into 'upload_dir', because document.php
147 // forges the path of the file with its own rules for each value of modulepart. It is currently not a
148 // problem because the only caller of this class (the drag and drop of a file on a card) does not use
149 // the url returned into the json.
150 $this->options = array(
151 'script_url' => $_SERVER['PHP_SELF'],
152 'upload_dir' => $dir_output.'/'.$object_ref.'/',
153 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
154 'saving_doc_mask' => $savingDocMask,
155 'param_name' => 'files',
156 // Set the following option to 'POST', if your server does not support
157 // DELETE requests. This is a parameter sent to the client:
158 'delete_type' => 'DELETE',
159 // The php.ini settings upload_max_filesize and post_max_size
160 // take precedence over the following max_file_size setting:
161 'max_file_size' => null,
162 'min_file_size' => 1,
163 'accept_file_types' => '/.+$/i',
164 // The maximum number of files for the upload directory:
165 'max_number_of_files' => null,
166 // Image resolution restrictions:
167 'max_width' => null,
168 'max_height' => null,
169 'min_width' => 1,
170 'min_height' => 1,
171 // Set the following option to false to enable resumable uploads:
172 'discard_aborted_uploads' => true,
173 'image_versions' => array(
174 // Uncomment the following version to restrict the size of
175 // uploaded images. You can also add additional versions with
176 // their own upload directories:
177 /*
178 'large' => array(
179 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
180 'upload_url' => $this->getFullUrl().'/files/',
181 'max_width' => 1920,
182 'max_height' => 1200,
183 'jpeg_quality' => 95
184 ),
185 */
186 'thumbnail' => array(
187 'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
188 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.urlencode($element).'&attachment=1&file='.urlencode('/'.$object_ref.'/thumbs/'),
189 'max_width' => 80,
190 'max_height' => 80
191 )
192 )
193 );
194
195 global $action;
196
197 $hookmanager->executeHooks(
198 'overrideUploadOptions',
199 array(
200 'options' => &$options,
201 'element' => $element
202 ),
203 $object, // @phan-suppress-current-line PhanTypeMismatchArgumentNullable
204 $action
205 );
206
207 if ($options) {
208 $this->options = array_replace_recursive($this->options, $options);
209 }
210
211 // At this point we should have a valid upload_dir in this->options
212 if (empty($pathname) || empty($filename)) {
213 if (!array_key_exists("upload_dir", $this->options)) {
214 setEventMessage('If $fk_element = null or $element = null you must specify upload_dir on $options', 'errors');
215 throw new Exception('If $fk_element = null or $element = null you must specify upload_dir on $options');
216 } elseif (!is_dir($this->options['upload_dir'])) {
217 setEventMessage('The directory '.$this->options['upload_dir'].' doesn\'t exists', 'errors');
218 throw new Exception('The directory '.$this->options['upload_dir'].' doesn\'t exists');
219 } elseif (!is_writable($this->options['upload_dir'])) {
220 setEventMessage('The directory '.$this->options['upload_dir'].' is not writable', 'errors');
221 throw new Exception('The directory '.$this->options['upload_dir'].' is not writable');
222 }
223 }
224 }
225
231 protected function getFullUrl()
232 {
233 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
234 return
235 ($https ? 'https://' : 'http://').
236 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
237 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
238 ($https && $_SERVER['SERVER_PORT'] === 443 ||
239 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
240 substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
241 }
242
249 protected function setFileDeleteUrl($file)
250 {
251 $file->delete_url = $this->options['script_url'].'?file='.urlencode((string) ($file->name)).'&fk_element='.urlencode((string) ($this->fk_element)).'&element='.urlencode((string) ($this->element));
252 $file->delete_type = $this->options['delete_type'];
253 if ($file->delete_type !== 'DELETE') {
254 $file->delete_url .= '&_method=DELETE';
255 }
256 }
257
264 protected function getFileObject($file_name)
265 {
266 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
267
268 if (dol_is_file($file_path) && $file_name[0] !== '.') {
269 $file = new stdClass();
270 $file->name = $file_name;
271 $file->mime = dol_mimetype($file_name, '', 2);
272 $file->size = filesize($file_path);
273 $file->url = $this->options['upload_url'].urlencode($file->name);
274
275 foreach ($this->options['image_versions'] as $version => $options) {
276 if (dol_is_file($options['upload_dir'].$file_name)) {
277 $tmp = explode('.', $file->name);
278
279 // We save the path of mini file into file->... (seems not used)
280 $keyforfile = $version.'_url';
281 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
282 }
283 }
284 $this->setFileDeleteUrl($file);
285 return $file;
286 }
287 return null;
288 }
289
295 protected function getFileObjects()
296 {
297 return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
298 }
299
307 protected function createScaledImage($file_name, $options)
308 {
309 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
310
311 $file_path = $this->options['upload_dir'].$file_name;
312 $new_file_path = $options['upload_dir'].$file_name;
313
314 if (dol_mkdir($options['upload_dir']) >= 0) {
315 $imagesize = @getimagesize($file_path); // false if the file is not an image, and destructuring false raises a warning since PHP 8.5
316 list($img_width, $img_height) = (is_array($imagesize) ? $imagesize : array(null, null));
317 if (!$img_width || !$img_height) {
318 return false;
319 }
320
321 $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object
322 if (preg_match('/error/i', $res)) {
323 return false;
324 }
325
326 $res = vignette($file_path, $maxwidthsmall, $maxheightsmall, '_small'); // We don't use ->addThumbs here because there is no object
327 if (preg_match('/error/i', $res)) {
328 return false;
329 }
330
331 return true;
332 } else {
333 return false;
334 }
335 }
336
346 protected function validate($uploaded_file, $file, $error, $index)
347 {
348 if ($error) {
349 $file->error = $error;
350 return false;
351 }
352 if (!$file->name) {
353 $file->error = 'missingFileName';
354 return false;
355 }
356 if (!preg_match($this->options['accept_file_types'], $file->name)) {
357 $file->error = 'acceptFileTypes';
358 return false;
359 }
360 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
361 $file_size = dol_filesize($uploaded_file);
362 } else {
363 $file_size = $_SERVER['CONTENT_LENGTH'];
364 }
365 if ($this->options['max_file_size'] && (
366 $file_size > $this->options['max_file_size'] ||
367 $file->size > $this->options['max_file_size']
368 )
369 ) {
370 $file->error = 'maxFileSize';
371 return false;
372 }
373 if ($this->options['min_file_size'] &&
374 $file_size < $this->options['min_file_size']) {
375 $file->error = 'minFileSize';
376 return false;
377 }
378 if (is_numeric($this->options['max_number_of_files']) && (
379 count($this->getFileObjects()) >= $this->options['max_number_of_files']
380 )
381 ) {
382 $file->error = 'maxNumberOfFiles';
383 return false;
384 }
385 $imagesize = @getimagesize($uploaded_file); // false if the file is not an image, and destructuring false raises a warning since PHP 8.5
386 list($img_width, $img_height) = (is_array($imagesize) ? $imagesize : array(null, null));
387 if (is_numeric($img_width)) {
388 if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
389 $this->options['max_height'] && $img_height > $this->options['max_height']) {
390 $file->error = 'maxResolution';
391 return false;
392 }
393 if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
394 $this->options['min_height'] && $img_height < $this->options['min_height']) {
395 $file->error = 'minResolution';
396 return false;
397 }
398 }
399 return true;
400 }
401
408 protected function upcountNameCallback($matches)
409 {
410 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
411 $ext = isset($matches[2]) ? $matches[2] : '';
412 return ' ('.$index.')'.$ext;
413 }
414
421 protected function upcountName($name)
422 {
423 return preg_replace_callback('/(?:(?: \‍(([\d]+)\‍))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
424 }
425
434 protected function trimFileName($name, $type, $index)
435 {
436 // Remove path information and dots around the filename, to prevent uploading
437 // into different directories or replacing hidden system files.
438 $file_name = basename(dol_sanitizeFileName($name));
439 $file_name = preg_replace('/ {2,}/', ' ', $file_name); // replaces multiple spaces into one space like the upload flow via input field
440 // Add missing file extension for known image types:
441 $matches = array();
442 if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
443 $file_name .= '.'.$matches[1];
444 }
445 if ($this->options['discard_aborted_uploads']) {
446 while (dol_is_file($this->options['upload_dir'].$file_name)) {
447 $file_name = $this->upcountName($file_name);
448 }
449 }
450 return $file_name;
451 }
452
466 protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
467 {
468 $file = new stdClass();
469 $file->name = $this->trimFileName($name, $type, $index);
470 $file->mime = dol_mimetype($file->name, '', 2);
471 $file->size = intval($size);
472 $file->type = $type;
473
474 // Sanitize to avoid stream execution when calling file_size(). Not that this is a second security because
475 // most streams are already disabled by stream_wrapper_unregister() in filefunc.inc.php
476 $uploaded_file = preg_replace('/\s*(http|ftp|sftp|)s?:/i', '', $uploaded_file);
477 $uploaded_file = realpath($uploaded_file); // A hack to be sure the file point to an existing file on disk (and is not a SSRF attack)
478
479 $validate = $this->validate($uploaded_file, $file, $error, $index);
480
481 if ($validate) {
482 if (dol_mkdir($this->options['upload_dir']) >= 0) {
483 // Add object reference as file name prefix if const MAIN_DISABLE_SUGGEST_REF_AS_PREFIX is not enabled
484 $fileNameWithoutExt = preg_replace('/\.[^\.]+$/', '', $file->name);
485 $savingDocMask = $this->options['saving_doc_mask'];
486 if ($savingDocMask && strpos($savingDocMask, $fileNameWithoutExt) !== 0) {
487 $fileNameWithPrefix = preg_replace('/__file__/', $file->name, $savingDocMask);
488 $file->name = $fileNameWithPrefix;
489 }
490
491 // trimFileName() checked the name is not already used, but it did it before the reference of the
492 // object was added as a prefix above, so it compared a name that is not the one we store. We must
493 // check it again on the final name, otherwise uploading twice the same file silently overwrites
494 // the first one, because dol_move_uploaded_file() is called below with $allowoverwrite = 1.
495 // The .noexe suffix is appended by dol_move_uploaded_file() on an executable file, so we must also
496 // look for the suffixed name, otherwise such a file is never seen as already existing and it is
497 // overwritten at each upload.
498 if ($this->options['discard_aborted_uploads']) {
499 $tmppath = dol_sanitizePathName($this->options['upload_dir']);
500 while (dol_is_file($tmppath.dol_sanitizeFileName($file->name)) || dol_is_file($tmppath.dol_sanitizeFileName($file->name).'.noexe')) {
501 $file->name = $this->upcountName($file->name);
502 }
503 }
504
505 $file_path = dol_sanitizePathName($this->options['upload_dir']).dol_sanitizeFileName($file->name);
506 $append_file = !$this->options['discard_aborted_uploads'] && dol_is_file($file_path) && $file->size > dol_filesize($file_path);
507
508 clearstatcache();
509
510 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
511 // multipart/formdata uploads (POST method uploads)
512 if ($append_file) {
513 file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
514 } else {
515 // TODO Replace this with a call of dol_add_file_process(... $mode=1)
516 $result = dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
517
518 // A return of 2 means the file was stored with a .noexe suffix appended on its name.
519 // We must follow that renaming, otherwise the size check below is done on a file that
520 // does not exist, and we report an error on a file that was correctly stored.
521 if ($result == 2) {
522 $file->name .= '.noexe';
523 $file_path .= '.noexe';
524 }
525 }
526 } else {
527 // Non-multipart uploads (file sent as the body of the request) are refused: the file would be written
528 // without the checks done by dol_move_uploaded_file() on an uploaded file (antivirus, .noexe suffix on
529 // an executable file, file name). The drag and drop of a file sends a multipart upload.
530 $file->error = 'notmultipartupload';
531 return $file;
532 }
533 dolChmod($file_path);
534
535 $file_size = dol_filesize($file_path);
536 if ($file_size === $file->size) {
537 // Update index table of files (llx_ecm_files), as dol_add_file_process() does for the files added
538 // from the "Attached files" tab. The name with its .noexe suffix is given, it is removed by
539 // addFileIntoDatabaseIndex() as for any uploaded file.
540 $sharefile = 0;
541 if (dol_mimetype($file->name) == 'application/pdf' && $this->element == 'product' && getDolGlobalString('PRODUCT_ALLOW_EXTERNAL_DOWNLOAD')) {
542 $sharefile = 1;
543 }
544 // The directory is given with no trailing slash, as by the tab: with it, the test of a temporary
545 // directory done by addFileIntoDatabaseIndex() would match an object whose directory is named 'temp'.
546 $indexdir = rtrim(dol_sanitizePathName($this->options['upload_dir']), '/');
547 $indexfile = dol_sanitizeFileName($file->name);
548 // When aborted uploads are not discarded, an existing file with the same name was overwritten, so
549 // its index is removed first, as dol_add_file_process() does when it allows overwriting.
550 if (!$this->options['discard_aborted_uploads']) {
551 deleteFilesIntoDatabaseIndex($indexdir, $indexfile, '', $this->object);
552 }
553 $resultindex = addFileIntoDatabaseIndex($indexdir, $indexfile, $name, 'uploaded', $sharefile, $this->object);
554 if (!is_numeric($resultindex) || $resultindex < 0) { // An array is returned when the extraction of the text failed
555 dol_syslog(get_class($this)."::handleFileUpload failed to add file ".$file->name." into the index of files", LOG_WARNING);
556 }
557
558 $file->url = $this->options['upload_url'].urlencode($file->name);
559 foreach ($this->options['image_versions'] as $version => $options) {
560 if ($this->createScaledImage($file->name, $options)) { // Creation of thumbs mini and small is ok
561 $tmp = explode('.', $file->name);
562
563 // We save the path of mini file into file->... (seems not used)
564 $keyforfile = $version.'_url';
565 $file->$keyforfile = $options['upload_url'].urlencode($tmp[0].'_mini.'.$tmp[1]);
566 }
567 }
568 } elseif ($this->options['discard_aborted_uploads']) {
569 unlink($file_path);
570 $file->error = 'abort';
571 }
572 $file->size = $file_size;
573 $this->setFileDeleteUrl($file);
574 } else {
575 $file->error = 'failedtocreatedestdir';
576 }
577 } else {
578 // should not happen
579 }
580
581 return $file;
582 }
583
589 /*public function get()
590 {
591 $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
592 if ($file_name) {
593 $info = $this->getFileObject($file_name);
594 } else {
595 $info = $this->getFileObjects();
596 }
597
598 header('Content-type: application/json');
599 echo json_encode($info);
600 }
601 */
602
608 public function post()
609 {
610 $error = 0;
611
612 $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null;
613
614 $info = array();
615 if ($upload && is_array($upload['tmp_name'])) {
616 // param_name is an array identifier like "files[]",
617 // $_FILES is a multi-dimensional array:
618 foreach ($upload['tmp_name'] as $index => $value) {
619 $tmpres = $this->handleFileUpload(
620 $upload['tmp_name'][$index],
621 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
622 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
623 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
624 $upload['error'][$index],
625 (string) $index
626 );
627 if (!empty($tmpres->error)) {
628 $error++;
629 }
630 $info[] = $tmpres;
631 }
632 } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
633 // param_name is a single object identifier like "file",
634 // $_FILES is a one-dimensional array:
635 $tmpres = $this->handleFileUpload(
636 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
637 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
638 isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
639 isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
640 isset($upload['error']) ? $upload['error'] : null,
641 '0'
642 );
643 if (!empty($tmpres->error)) {
644 $error++;
645 }
646 $info[] = $tmpres;
647 }
648
649 header('Vary: Accept');
650 $json = json_encode($info);
651
652 /* disabled. Param redirect seems not used
653 $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null;
654 if ($redirect) {
655 header('Location: '.sprintf($redirect, urlencode($json)));
656 return;
657 }
658 */
659
660 if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
661 header('Content-type: application/json');
662 } else {
663 header('Content-type: text/plain');
664 }
665 echo $json;
666
667 return $error;
668 }
669
676 /*
677 public function delete($file)
678 {
679 $file_name = $file ? basename($file) : null;
680 $file_path = $this->options['upload_dir'].dol_sanitizeFileName($file_name);
681 $success = dol_is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
682 if ($success) {
683 foreach ($this->options['image_versions'] as $version => $options) {
684 $file = $options['upload_dir'].$file_name;
685 if (dol_is_file($file)) {
686 unlink($file);
687 }
688 }
689 }
690 // Return result in json format
691 header('Content-type: application/json');
692 echo json_encode($success);
693
694 return 0;
695 }
696 */
697}
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)
Make validation on an uploaded file.
dol_filesize($pathoffile)
Return size of a file.
addFileIntoDatabaseIndex($dir, $file, $fullpathorig='', $mode='uploaded', $setsharekey=0, $object=null, $forceFullTextIndexation='')
Add a file into database index.
dol_is_file($pathoffile)
Return if path is a file.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
deleteFilesIntoDatabaseIndex($dir, $file, $mode='uploaded', $object=null)
Delete files into database index using search criteria.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
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).