24require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
25require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
34 protected $fk_element;
45 public function __construct($options =
null, $fk_element =
null, $element =
null)
50 $hookmanager->initHooks(array(
'fileupload'));
55 $this->fk_element = $fk_element;
56 $this->element = $element;
58 $pathname = str_replace(
'/class',
'', $element_prop[
'classpath']);
59 $filename = $element_prop[
'classfile'];
60 $dir_output = $element_prop[
'dir_output'];
64 if (empty($dir_output)) {
65 setEventMessage(
'The element '.$element.
' is not supported for uploading file. dir_output is unknow.',
'errors');
66 throw new Exception(
'The element '.$element.
' is not supported for uploading file. dir_output is unknow.');
70 if ($pathname !==
null && $filename !==
null) {
77 if ($element ==
'invoice_supplier') {
78 $object_ref =
get_exdir($object->id, 2, 0, 0, $object,
'invoice_supplier').$object_ref;
79 } elseif ($element ==
'project_task') {
80 $parentForeignKey =
'fk_project';
81 $parentClass =
'Project';
82 $parentElement =
'projet';
83 $parentObject =
'project';
86 $parent =
new $parentClass($db);
87 $parent->fetch($object->$parentForeignKey);
88 if (!empty($parent->socid)) {
89 $parent->fetch_thirdparty();
91 $object->$parentObject = clone $parent;
97 $this->options = array(
98 'script_url' => $_SERVER[
'PHP_SELF'],
99 'upload_dir' => $dir_output.
'/'.$object_ref.
'/',
100 'upload_url' => DOL_URL_ROOT.
'/document.php?modulepart='.$element.
'&attachment=1&file=/'.$object_ref.
'/',
101 'param_name' =>
'files',
104 'delete_type' =>
'DELETE',
107 'max_file_size' =>
null,
108 'min_file_size' => 1,
109 'accept_file_types' =>
'/.+$/i',
111 'max_number_of_files' =>
null,
114 'max_height' =>
null,
118 'discard_aborted_uploads' =>
true,
119 'image_versions' => array(
132 'thumbnail' => array(
133 'upload_dir' => $dir_output.
'/'.$object_ref.
'/thumbs/',
134 'upload_url' => DOL_URL_ROOT.
'/document.php?modulepart='.urlencode($element).
'&attachment=1&file=/'.$object_ref.
'/thumbs/',
143 $hookmanager->executeHooks(
144 'overrideUploadOptions',
146 'options' => &$options,
147 'element' => $element
154 $this->options = array_replace_recursive($this->options, $options);
159 if ($pathname ===
null || $filename ===
null) {
160 if (!key_exists(
"upload_dir", $this->options)) {
161 setEventMessage(
'If $fk_element = null or $element = null you must specify upload_dir on $options',
'errors');
162 throw new Exception(
'If $fk_element = null or $element = null you must specify upload_dir on $options');
163 } elseif (!is_dir($this->options[
'upload_dir'])) {
164 setEventMessage(
'The directory '.$this->options[
'upload_dir'].
' doesn\'t exists',
'errors');
165 throw new Exception(
'The directory '.$this->options[
'upload_dir'].
' doesn\'t exists');
166 } elseif (!is_writable($this->options[
'upload_dir'])) {
167 setEventMessage(
'The directory '.$this->options[
'upload_dir'].
' is not writable',
'errors');
168 throw new Exception(
'The directory '.$this->options[
'upload_dir'].
' is not writable');
180 $https = !empty($_SERVER[
'HTTPS']) && $_SERVER[
'HTTPS'] !==
'off';
182 ($https ?
'https://' :
'http://').
183 (!empty($_SERVER[
'REMOTE_USER']) ? $_SERVER[
'REMOTE_USER'].
'@' :
'').
184 (isset($_SERVER[
'HTTP_HOST']) ? $_SERVER[
'HTTP_HOST'] : ($_SERVER[
'SERVER_NAME'].
185 ($https && $_SERVER[
'SERVER_PORT'] === 443 ||
186 $_SERVER[
'SERVER_PORT'] === 80 ?
'' :
':'.$_SERVER[
'SERVER_PORT']))).
187 substr($_SERVER[
'SCRIPT_NAME'], 0, strrpos($_SERVER[
'SCRIPT_NAME'],
'/'));
198 $file->delete_url = $this->options[
'script_url']
199 .
'?file='.urlencode($file->name).
'&fk_element='.urlencode($this->fk_element).
'&element='.urlencode($this->element);
200 $file->delete_type = $this->options[
'delete_type'];
201 if ($file->delete_type !==
'DELETE') {
202 $file->delete_url .=
'&_method=DELETE';
215 $file_path = $this->options[
'upload_dir'].$file_name;
216 if (is_file($file_path) && $file_name[0] !==
'.') {
217 $file =
new stdClass();
218 $file->name = $file_name;
220 $file->size = filesize($file_path);
221 $file->url = $this->options[
'upload_url'].rawurlencode($file->name);
222 foreach ($this->options[
'image_versions'] as $version => $options) {
223 if (is_file($options[
'upload_dir'].$file_name)) {
224 $tmp = explode(
'.', $file->name);
227 $keyforfile = $version.
'_url';
228 $file->$keyforfile = $options[
'upload_url'].rawurlencode($tmp[0].
'_mini.'.$tmp[1]);
244 return array_values(array_filter(array_map(array($this,
'getFileObject'), scandir($this->options[
'upload_dir']))));
256 global $maxwidthmini, $maxheightmini, $maxwidthsmall, $maxheightsmall;
258 $file_path = $this->options[
'upload_dir'].$file_name;
259 $new_file_path = $options[
'upload_dir'].$file_name;
261 if (
dol_mkdir($options[
'upload_dir']) >= 0) {
262 list($img_width, $img_height) = @getimagesize($file_path);
263 if (!$img_width || !$img_height) {
267 $res =
vignette($file_path, $maxwidthmini, $maxheightmini,
'_mini');
268 if (preg_match(
'/error/i', $res)) {
272 $res =
vignette($file_path, $maxwidthsmall, $maxheightsmall,
'_small');
273 if (preg_match(
'/error/i', $res)) {
292 protected function validate($uploaded_file, $file, $error, $index)
295 $file->error = $error;
299 $file->error =
'missingFileName';
302 if (!preg_match($this->options[
'accept_file_types'], $file->name)) {
303 $file->error =
'acceptFileTypes';
306 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
307 $file_size = filesize($uploaded_file);
309 $file_size = $_SERVER[
'CONTENT_LENGTH'];
311 if ($this->options[
'max_file_size'] && (
312 $file_size > $this->options[
'max_file_size'] ||
313 $file->size > $this->options[
'max_file_size'])
315 $file->error =
'maxFileSize';
318 if ($this->options[
'min_file_size'] &&
319 $file_size < $this->options[
'min_file_size']) {
320 $file->error =
'minFileSize';
323 if (is_numeric($this->options[
'max_number_of_files']) && (
324 count($this->
getFileObjects()) >= $this->options[
'max_number_of_files'])
326 $file->error =
'maxNumberOfFiles';
329 list($img_width, $img_height) = @getimagesize($uploaded_file);
330 if (is_numeric($img_width)) {
331 if ($this->options[
'max_width'] && $img_width > $this->options[
'max_width'] ||
332 $this->options[
'max_height'] && $img_height > $this->options[
'max_height']) {
333 $file->error =
'maxResolution';
336 if ($this->options[
'min_width'] && $img_width < $this->options[
'min_width'] ||
337 $this->options[
'min_height'] && $img_height < $this->options[
'min_height']) {
338 $file->error =
'minResolution';
353 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
354 $ext = isset($matches[2]) ? $matches[2] :
'';
355 return ' ('.$index.
')'.$ext;
366 return preg_replace_callback(
'/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this,
'upcountNameCallback'), $name, 1);
382 $file_name = trim(basename(stripslashes($name)),
".\x00..\x20");
385 if (strpos($file_name,
'.') ===
false && preg_match(
'/^image\/(gif|jpe?g|png)/', $type, $matches)) {
386 $file_name .=
'.'.$matches[1];
388 if ($this->options[
'discard_aborted_uploads']) {
389 while (is_file($this->options[
'upload_dir'].$file_name)) {
410 $file =
new stdClass();
411 $file->name = $this->
trimFileName($name, $type, $index);
413 $file->size = intval($size);
416 $validate = $this->
validate($uploaded_file, $file, $error, $index);
419 if (
dol_mkdir($this->options[
'upload_dir']) >= 0) {
420 $file_path = $this->options[
'upload_dir'].$file->name;
421 $append_file = !$this->options[
'discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
425 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
428 file_put_contents($file_path, fopen($uploaded_file,
'r'), FILE_APPEND);
434 file_put_contents($file_path, fopen(
'php://input',
'r'), $append_file ? FILE_APPEND : 0);
436 $file_size = filesize($file_path);
437 if ($file_size === $file->size) {
438 $file->url = $this->options[
'upload_url'].rawurlencode($file->name);
439 foreach ($this->options[
'image_versions'] as $version => $options) {
441 $tmp = explode(
'.', $file->name);
444 $keyforfile = $version.
'_url';
445 $file->$keyforfile = $options[
'upload_url'].rawurlencode($tmp[0].
'_mini.'.$tmp[1]);
448 } elseif ($this->options[
'discard_aborted_uploads']) {
450 $file->error =
'abort';
452 $file->size = $file_size;
455 $file->error =
'failedtocreatedestdir';
469 public function get()
471 $file_name = isset($_REQUEST[
'file']) ?
472 basename(stripslashes($_REQUEST[
'file'])) :
null;
478 header(
'Content-type: application/json');
479 echo json_encode($info);
491 if (isset($_REQUEST[
'_method']) && $_REQUEST[
'_method'] ===
'DELETE') {
492 return $this->
delete();
496 $upload = isset($_FILES[$this->options[
'param_name']]) ?
497 $_FILES[$this->options[
'param_name']] :
null;
499 if ($upload && is_array($upload[
'tmp_name'])) {
502 foreach ($upload[
'tmp_name'] as $index => $value) {
504 $upload[
'tmp_name'][$index],
505 isset($_SERVER[
'HTTP_X_FILE_NAME']) ? $_SERVER[
'HTTP_X_FILE_NAME'] : $upload[
'name'][$index],
506 isset($_SERVER[
'HTTP_X_FILE_SIZE']) ? $_SERVER[
'HTTP_X_FILE_SIZE'] : $upload[
'size'][$index],
507 isset($_SERVER[
'HTTP_X_FILE_TYPE']) ? $_SERVER[
'HTTP_X_FILE_TYPE'] : $upload[
'type'][$index],
508 $upload[
'error'][$index],
511 if (!empty($tmpres->error)) {
516 } elseif ($upload || isset($_SERVER[
'HTTP_X_FILE_NAME'])) {
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,
527 if (!empty($tmpres->error)) {
533 header(
'Vary: Accept');
534 $json = json_encode($info);
544 if (isset($_SERVER[
'HTTP_ACCEPT']) && (strpos($_SERVER[
'HTTP_ACCEPT'],
'application/json') !==
false)) {
545 header(
'Content-type: application/json');
547 header(
'Content-type: text/plain');
559 public function delete()
561 $file_name = isset($_REQUEST[
'file']) ?
562 basename(stripslashes($_REQUEST[
'file'])) :
null;
563 $file_path = $this->options[
'upload_dir'].$file_name;
564 $success = is_file($file_path) && $file_name[0] !==
'.' && unlink($file_path);
566 foreach ($this->options[
'image_versions'] as $version => $options) {
567 $file = $options[
'upload_dir'].$file_name;
568 if (is_file($file)) {
574 header(
'Content-type: application/json');
575 echo json_encode($success);
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)
Enter description here ...
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile', $upload_dir='')
Make control on an uploaded file from an GUI page and move it to 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)
Set event message in dol_events session object.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
getElementProperties($element_type)
Get an array with properties of an element.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
fetchObjectByElement($element_id, $element_type, $element_ref='')
Fetch an object from its id and element_type Inclusion of classes is automatic.
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).