29require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
30require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
45 protected $fk_element;
50 protected $object =
null;
67 public function __construct($options =
null, $fk_element =
null, $element =
null)
71 $hookmanager->initHooks(array(
'fileupload'));
76 $this->fk_element = $fk_element;
77 $this->element = $element;
79 $pathname = str_replace(
'/class',
'', $element_prop[
'classpath']);
86 $object_ref =
'UndefinedReference';
89 if ($pathname !==
'' && $filename !==
'') {
91 $object = fetchObjectByElement($fk_element, $element);
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);
100 $this->
object = $object;
112 if (!empty($tmpdir) && preg_match(
'/^([a-z]:)?[\\\\\/]/i', $tmpdir)) {
130 $object_ref =
get_exdir(0, 0, 0, 1, $object, $element);
134 if (in_array($element, array(
'invoice_supplier',
'supplier_invoice'))) {
135 $object_ref .=
'/'.dol_sanitizeFileName($object->ref);
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');
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',
158 'delete_type' =>
'DELETE',
161 'max_file_size' =>
null,
162 'min_file_size' => 1,
163 'accept_file_types' =>
'/.+$/i',
165 'max_number_of_files' =>
null,
168 'max_height' =>
null,
172 'discard_aborted_uploads' =>
true,
173 'image_versions' => array(
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/'),
197 $hookmanager->executeHooks(
198 'overrideUploadOptions',
200 'options' => &$options,
201 'element' => $element
208 $this->options = array_replace_recursive($this->options, $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');
233 $https = !empty($_SERVER[
'HTTPS']) && $_SERVER[
'HTTPS'] !==
'off';
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'],
'/'));
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';
266 $file_path = $this->options[
'upload_dir'].dol_sanitizeFileName($file_name);
268 if (
dol_is_file($file_path) && $file_name[0] !==
'.') {
270 $file->name = $file_name;
272 $file->size = filesize($file_path);
273 $file->url = $this->options[
'upload_url'].urlencode($file->name);
275 foreach ($this->options[
'image_versions'] as $version => $options) {
276 if (
dol_is_file($options[
'upload_dir'].$file_name)) {
277 $tmp = explode(
'.', $file->name);
280 $keyforfile = $version.
'_url';
281 $file->$keyforfile = $options[
'upload_url'].urlencode($tmp[0].
'_mini.'.$tmp[1]);
297 return array_values(array_filter(array_map(array($this,
'getFileObject'), scandir($this->options[
'upload_dir']))));
309 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
311 $file_path = $this->options[
'upload_dir'].$file_name;
312 $new_file_path = $options[
'upload_dir'].$file_name;
314 if (
dol_mkdir($options[
'upload_dir']) >= 0) {
315 $imagesize = @getimagesize($file_path);
316 list($img_width, $img_height) = (is_array($imagesize) ? $imagesize : array(
null,
null));
317 if (!$img_width || !$img_height) {
321 $res =
vignette($file_path, $maxwidthmini, $maxheightmini,
'_mini');
322 if (preg_match(
'/error/i', $res)) {
326 $res =
vignette($file_path, $maxwidthsmall, $maxheightsmall,
'_small');
327 if (preg_match(
'/error/i', $res)) {
346 protected function validate($uploaded_file, $file, $error, $index)
349 $file->error = $error;
353 $file->error =
'missingFileName';
356 if (!preg_match($this->options[
'accept_file_types'], $file->name)) {
357 $file->error =
'acceptFileTypes';
360 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
363 $file_size = $_SERVER[
'CONTENT_LENGTH'];
365 if ($this->options[
'max_file_size'] && (
366 $file_size > $this->options[
'max_file_size'] ||
367 $file->size > $this->options[
'max_file_size']
370 $file->error =
'maxFileSize';
373 if ($this->options[
'min_file_size'] &&
374 $file_size < $this->options[
'min_file_size']) {
375 $file->error =
'minFileSize';
378 if (is_numeric($this->options[
'max_number_of_files']) && (
379 count($this->
getFileObjects()) >= $this->options[
'max_number_of_files']
382 $file->error =
'maxNumberOfFiles';
385 $imagesize = @getimagesize($uploaded_file);
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';
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';
410 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
411 $ext = isset($matches[2]) ? $matches[2] :
'';
412 return ' ('.$index.
')'.$ext;
423 return preg_replace_callback(
'/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this,
'upcountNameCallback'), $name, 1);
439 $file_name = preg_replace(
'/ {2,}/',
' ', $file_name);
442 if (strpos($file_name,
'.') ===
false && preg_match(
'/^image\/(gif|jpe?g|png)/', $type, $matches)) {
443 $file_name .=
'.'.$matches[1];
445 if ($this->options[
'discard_aborted_uploads']) {
446 while (
dol_is_file($this->options[
'upload_dir'].$file_name)) {
469 $file->name = $this->
trimFileName($name, $type, $index);
471 $file->size = intval($size);
476 $uploaded_file = preg_replace(
'/\s*(http|ftp|sftp|)s?:/i',
'', $uploaded_file);
477 $uploaded_file = realpath($uploaded_file);
479 $validate = $this->
validate($uploaded_file, $file, $error, $index);
482 if (
dol_mkdir($this->options[
'upload_dir']) >= 0) {
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;
498 if ($this->options[
'discard_aborted_uploads']) {
500 while (
dol_is_file($tmppath.dol_sanitizeFileName($file->name)) ||
dol_is_file($tmppath.dol_sanitizeFileName($file->name).
'.noexe')) {
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);
510 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
513 file_put_contents($file_path, fopen($uploaded_file,
'r'), FILE_APPEND);
522 $file->name .=
'.noexe';
523 $file_path .=
'.noexe';
530 $file->error =
'notmultipartupload';
536 if ($file_size === $file->size) {
550 if (!$this->options[
'discard_aborted_uploads']) {
554 if (!is_numeric($resultindex) || $resultindex < 0) {
555 dol_syslog(get_class($this).
"::handleFileUpload failed to add file ".$file->name.
" into the index of files", LOG_WARNING);
558 $file->url = $this->options[
'upload_url'].urlencode($file->name);
559 foreach ($this->options[
'image_versions'] as $version => $options) {
561 $tmp = explode(
'.', $file->name);
564 $keyforfile = $version.
'_url';
565 $file->$keyforfile = $options[
'upload_url'].urlencode($tmp[0].
'_mini.'.$tmp[1]);
568 } elseif ($this->options[
'discard_aborted_uploads']) {
570 $file->error =
'abort';
572 $file->size = $file_size;
575 $file->error =
'failedtocreatedestdir';
612 $upload = isset($_FILES[$this->options[
'param_name']]) ? $_FILES[$this->options[
'param_name']] :
null;
615 if ($upload && is_array($upload[
'tmp_name'])) {
618 foreach ($upload[
'tmp_name'] as $index => $value) {
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],
627 if (!empty($tmpres->error)) {
632 } elseif ($upload || isset($_SERVER[
'HTTP_X_FILE_NAME'])) {
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,
643 if (!empty($tmpres->error)) {
649 header(
'Vary: Accept');
650 $json = json_encode($info);
660 if (isset($_SERVER[
'HTTP_ACCEPT']) && (strpos($_SERVER[
'HTTP_ACCEPT'],
'application/json') !==
false)) {
661 header(
'Content-type: application/json');
663 header(
'Content-type: text/plain');
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.
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).