29require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
30require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
45 protected $fk_element;
60 public function __construct($options =
null, $fk_element =
null, $element =
null)
65 $hookmanager->initHooks(array(
'fileupload'));
70 $this->fk_element = $fk_element;
71 $this->element = $element;
73 $pathname = str_replace(
'/class',
'', $element_prop[
'classpath']);
80 if (empty($dir_output)) {
81 setEventMessage(
'The element '.$element.
' is not supported for uploading file. dir_output is unknown.',
'errors');
82 throw new Exception(
'The element '.$element.
' is not supported for uploading file. dir_output is unknown.');
85 $object_ref =
'UndefinedReference';
87 if ($pathname !==
null && $filename !==
null) {
89 $object = fetchObjectByElement($fk_element, $element);
95 $savingDocMask = $object_ref.
'-__file__';
99 if ($element ==
'invoice_supplier') {
101 } elseif ($element ==
'project_task') {
102 $parentForeignKey =
'fk_project';
103 $parentClass =
'Project';
104 $parentElement =
'projet';
105 $parentObject =
'project';
108 $parent =
new $parentClass($db);
109 $parent->fetch(
$object->$parentForeignKey);
110 if (!empty($parent->socid)) {
111 $parent->fetch_thirdparty();
113 $object->$parentObject = clone $parent;
119 $this->options = array(
120 'script_url' => $_SERVER[
'PHP_SELF'],
121 'upload_dir' => $dir_output.
'/'.$object_ref.
'/',
122 'upload_url' => DOL_URL_ROOT.
'/document.php?modulepart='.$element.
'&attachment=1&file=/'.$object_ref.
'/',
123 'saving_doc_mask' => $savingDocMask,
124 'param_name' =>
'files',
127 'delete_type' =>
'DELETE',
130 'max_file_size' =>
null,
131 'min_file_size' => 1,
132 'accept_file_types' =>
'/.+$/i',
134 'max_number_of_files' =>
null,
137 'max_height' =>
null,
141 'discard_aborted_uploads' =>
true,
142 'image_versions' => array(
155 'thumbnail' => array(
156 'upload_dir' => $dir_output.
'/'.$object_ref.
'/thumbs/',
157 'upload_url' => DOL_URL_ROOT.
'/document.php?modulepart='.urlencode($element).
'&attachment=1&file='.urlencode(
'/'.$object_ref.
'/thumbs/'),
166 $hookmanager->executeHooks(
167 'overrideUploadOptions',
169 'options' => &$options,
170 'element' => $element
177 $this->options = array_replace_recursive($this->options, $options);
181 if (empty($pathname) || empty($filename)) {
182 if (!array_key_exists(
"upload_dir", $this->options)) {
183 setEventMessage(
'If $fk_element = null or $element = null you must specify upload_dir on $options',
'errors');
184 throw new Exception(
'If $fk_element = null or $element = null you must specify upload_dir on $options');
185 } elseif (!is_dir($this->options[
'upload_dir'])) {
186 setEventMessage(
'The directory '.$this->options[
'upload_dir'].
' doesn\'t exists',
'errors');
187 throw new Exception(
'The directory '.$this->options[
'upload_dir'].
' doesn\'t exists');
188 } elseif (!is_writable($this->options[
'upload_dir'])) {
189 setEventMessage(
'The directory '.$this->options[
'upload_dir'].
' is not writable',
'errors');
190 throw new Exception(
'The directory '.$this->options[
'upload_dir'].
' is not writable');
202 $https = !empty($_SERVER[
'HTTPS']) && $_SERVER[
'HTTPS'] !==
'off';
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'],
'/'));
220 $file->delete_url = $this->options[
'script_url'].
'?file='.urlencode((
string) ($file->name)).
'&fk_element='.urlencode((
string) ($this->fk_element)).
'&element='.urlencode((
string) ($this->element));
221 $file->delete_type = $this->options[
'delete_type'];
222 if ($file->delete_type !==
'DELETE') {
223 $file->delete_url .=
'&_method=DELETE';
235 $file_path = $this->options[
'upload_dir'].dol_sanitizeFileName($file_name);
237 if (
dol_is_file($file_path) && $file_name[0] !==
'.') {
239 $file->name = $file_name;
241 $file->size = filesize($file_path);
242 $file->url = $this->options[
'upload_url'].urlencode($file->name);
244 foreach ($this->options[
'image_versions'] as $version => $options) {
245 if (
dol_is_file($options[
'upload_dir'].$file_name)) {
246 $tmp = explode(
'.', $file->name);
249 $keyforfile = $version.
'_url';
250 $file->$keyforfile = $options[
'upload_url'].urlencode($tmp[0].
'_mini.'.$tmp[1]);
266 return array_values(array_filter(array_map(array($this,
'getFileObject'), scandir($this->options[
'upload_dir']))));
278 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
280 $file_path = $this->options[
'upload_dir'].$file_name;
281 $new_file_path = $options[
'upload_dir'].$file_name;
283 if (
dol_mkdir($options[
'upload_dir']) >= 0) {
284 list($img_width, $img_height) = @getimagesize($file_path);
285 if (!$img_width || !$img_height) {
289 $res =
vignette($file_path, $maxwidthmini, $maxheightmini,
'_mini');
290 if (preg_match(
'/error/i', $res)) {
294 $res =
vignette($file_path, $maxwidthsmall, $maxheightsmall,
'_small');
295 if (preg_match(
'/error/i', $res)) {
314 protected function validate($uploaded_file, $file, $error, $index)
317 $file->error = $error;
321 $file->error =
'missingFileName';
324 if (!preg_match($this->options[
'accept_file_types'], $file->name)) {
325 $file->error =
'acceptFileTypes';
328 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
331 $file_size = $_SERVER[
'CONTENT_LENGTH'];
333 if ($this->options[
'max_file_size'] && (
334 $file_size > $this->options[
'max_file_size'] ||
335 $file->size > $this->options[
'max_file_size']
338 $file->error =
'maxFileSize';
341 if ($this->options[
'min_file_size'] &&
342 $file_size < $this->options[
'min_file_size']) {
343 $file->error =
'minFileSize';
346 if (is_numeric($this->options[
'max_number_of_files']) && (
347 count($this->
getFileObjects()) >= $this->options[
'max_number_of_files']
350 $file->error =
'maxNumberOfFiles';
353 list($img_width, $img_height) = @getimagesize($uploaded_file);
354 if (is_numeric($img_width)) {
355 if ($this->options[
'max_width'] && $img_width > $this->options[
'max_width'] ||
356 $this->options[
'max_height'] && $img_height > $this->options[
'max_height']) {
357 $file->error =
'maxResolution';
360 if ($this->options[
'min_width'] && $img_width < $this->options[
'min_width'] ||
361 $this->options[
'min_height'] && $img_height < $this->options[
'min_height']) {
362 $file->error =
'minResolution';
377 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
378 $ext = isset($matches[2]) ? $matches[2] :
'';
379 return ' ('.$index.
')'.$ext;
390 return preg_replace_callback(
'/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this,
'upcountNameCallback'), $name, 1);
408 if (strpos($file_name,
'.') ===
false && preg_match(
'/^image\/(gif|jpe?g|png)/', $type, $matches)) {
409 $file_name .=
'.'.$matches[1];
411 if ($this->options[
'discard_aborted_uploads']) {
412 while (
dol_is_file($this->options[
'upload_dir'].$file_name)) {
435 $file->name = $this->
trimFileName($name, $type, $index);
437 $file->size = intval($size);
442 $uploaded_file = preg_replace(
'/\s*(http|ftp|sftp|)s?:/i',
'', $uploaded_file);
443 $uploaded_file = realpath($uploaded_file);
445 $validate = $this->
validate($uploaded_file, $file, $error, $index);
448 if (
dol_mkdir($this->options[
'upload_dir']) >= 0) {
450 $fileNameWithoutExt = preg_replace(
'/\.[^\.]+$/',
'', $file->name);
451 $savingDocMask = $this->options[
'saving_doc_mask'];
452 if ($savingDocMask && strpos($savingDocMask, $fileNameWithoutExt) !== 0) {
453 $fileNameWithPrefix = preg_replace(
'/__file__/', $file->name, $savingDocMask);
454 $file->name = $fileNameWithPrefix;
457 $file_path =
dol_sanitizePathName($this->options[
'upload_dir']).dol_sanitizeFileName($file->name);
458 $append_file = !$this->options[
'discard_aborted_uploads'] &&
dol_is_file($file_path) && $file->size >
dol_filesize($file_path);
462 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
465 file_put_contents($file_path, fopen($uploaded_file,
'r'), FILE_APPEND);
472 file_put_contents($file_path, fopen(
'php://input',
'r'), $append_file ? FILE_APPEND : 0);
477 if ($file_size === $file->size) {
478 $file->url = $this->options[
'upload_url'].urlencode($file->name);
479 foreach ($this->options[
'image_versions'] as $version => $options) {
481 $tmp = explode(
'.', $file->name);
484 $keyforfile = $version.
'_url';
485 $file->$keyforfile = $options[
'upload_url'].urlencode($tmp[0].
'_mini.'.$tmp[1]);
488 } elseif ($this->options[
'discard_aborted_uploads']) {
490 $file->error =
'abort';
492 $file->size = $file_size;
495 $file->error =
'failedtocreatedestdir';
532 $upload = isset($_FILES[$this->options[
'param_name']]) ? $_FILES[$this->options[
'param_name']] :
null;
535 if ($upload && is_array($upload[
'tmp_name'])) {
538 foreach ($upload[
'tmp_name'] as $index => $value) {
540 $upload[
'tmp_name'][$index],
541 isset($_SERVER[
'HTTP_X_FILE_NAME']) ? $_SERVER[
'HTTP_X_FILE_NAME'] : $upload[
'name'][$index],
542 isset($_SERVER[
'HTTP_X_FILE_SIZE']) ? $_SERVER[
'HTTP_X_FILE_SIZE'] : $upload[
'size'][$index],
543 isset($_SERVER[
'HTTP_X_FILE_TYPE']) ? $_SERVER[
'HTTP_X_FILE_TYPE'] : $upload[
'type'][$index],
544 $upload[
'error'][$index],
547 if (!empty($tmpres->error)) {
552 } elseif ($upload || isset($_SERVER[
'HTTP_X_FILE_NAME'])) {
556 isset($upload[
'tmp_name']) ? $upload[
'tmp_name'] :
null,
557 isset($_SERVER[
'HTTP_X_FILE_NAME']) ? $_SERVER[
'HTTP_X_FILE_NAME'] : (isset($upload[
'name']) ? $upload[
'name'] :
null),
558 isset($_SERVER[
'HTTP_X_FILE_SIZE']) ? $_SERVER[
'HTTP_X_FILE_SIZE'] : (isset($upload[
'size']) ? $upload[
'size'] :
null),
559 isset($_SERVER[
'HTTP_X_FILE_TYPE']) ? $_SERVER[
'HTTP_X_FILE_TYPE'] : (isset($upload[
'type']) ? $upload[
'type'] :
null),
560 isset($upload[
'error']) ? $upload[
'error'] :
null,
563 if (!empty($tmpres->error)) {
569 header(
'Vary: Accept');
570 $json = json_encode($info);
580 if (isset($_SERVER[
'HTTP_ACCEPT']) && (strpos($_SERVER[
'HTTP_ACCEPT'],
'application/json') !==
false)) {
581 header(
'Content-type: application/json');
583 header(
'Content-type: text/plain');
if(! $sortfield) if(! $sortorder) $object
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.
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.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
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.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
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).