38 return preg_replace(
'/^.*\/([^\/]+)$/',
'$1', rtrim($pathfile,
'/'));
60 function dol_dir_list($path, $types =
"all", $recursive = 0, $filter =
"", $excludefilter = null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename =
"", $donotfollowsymlinks = 0)
62 global $db, $hookmanager;
65 dol_syslog(
"files.lib.php::dol_dir_list path=".$path.
" types=".$types.
" recursive=".$recursive.
" filter=".$filter.
" excludefilter=".json_encode($excludefilter));
68 $loaddate = ($mode == 1 || $mode == 2) ?
true:
false;
69 $loadsize = ($mode == 1 || $mode == 3) ?
true:
false;
72 $path = preg_replace(
'/([\\/]+)$/i',
'', $path);
78 if (is_object($hookmanager) && !$nohook)
80 $hookmanager->resArray = array();
82 $hookmanager->initHooks(array(
'fileslib'));
87 'recursive' => $recursive,
89 'excludefilter' => $excludefilter,
90 'sortcriteria' => $sortcriteria,
91 'sortorder' => $sortorder,
92 'loaddate' => $loaddate,
93 'loadsize' => $loadsize,
96 $reshook = $hookmanager->executeHooks(
'getDirList', $parameters, $object);
102 if (!is_dir($newpath))
return array();
104 if ($dir = opendir($newpath))
109 while (
false !== ($file = readdir($dir)))
111 if (!
utf8_check($file)) $file = utf8_encode($file);
112 $fullpathfile = ($newpath ? $newpath.
'/' :
'').$file;
117 $excludefilterarray = array(
'^\.');
118 if (is_array($excludefilter))
120 $excludefilterarray = array_merge($excludefilterarray, $excludefilter);
121 } elseif ($excludefilter) $excludefilterarray[] = $excludefilter;
123 foreach ($excludefilterarray as $filt)
125 if (preg_match(
'/'.$filt.
'/i', $file) || preg_match(
'/'.$filt.
'/i', $fullpathfile)) {
126 $qualified = 0;
break;
135 if ($isdir && (($types ==
"directories") || ($types ==
"all") || $recursive))
138 if (($types ==
"directories") || ($types ==
"all"))
140 if ($loaddate || $sortcriteria ==
'date') $filedate =
dol_filemtime($path.
"/".$file);
141 if ($loadsize || $sortcriteria ==
'size') $filesize =
dol_filesize($path.
"/".$file);
143 if (!$filter || preg_match(
'/'.$filter.
'/i', $file))
146 preg_match(
'/([^\/]+)\/[^\/]+$/', $path.
'/'.$file, $reg);
147 $level1name = (isset($reg[1]) ? $reg[1] :
'');
148 $file_list[] = array(
151 "level1name" => $level1name,
152 "relativename" => ($relativename ? $relativename.
'/' :
'').$file,
153 "fullname" => $path.
'/'.$file,
164 if (empty($donotfollowsymlinks) || !is_link($path.
"/".$file))
167 $file_list = array_merge($file_list,
dol_dir_list($path.
"/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename !=
'' ? $relativename.
'/' :
'').$file, $donotfollowsymlinks));
170 } elseif (!$isdir && (($types ==
"files") || ($types ==
"all")))
173 if ($loaddate || $sortcriteria ==
'date') $filedate =
dol_filemtime($path.
"/".$file);
174 if ($loadsize || $sortcriteria ==
'size') $filesize =
dol_filesize($path.
"/".$file);
176 if (!$filter || preg_match(
'/'.$filter.
'/i', $file))
178 preg_match(
'/([^\/]+)\/[^\/]+$/', $path.
'/'.$file, $reg);
179 $level1name = (isset($reg[1]) ? $reg[1] :
'');
180 $file_list[] = array(
183 "level1name" => $level1name,
184 "relativename" => ($relativename ? $relativename.
'/' :
'').$file,
185 "fullname" => $path.
'/'.$file,
197 if (!empty($sortcriteria) && $sortorder)
199 $file_list =
dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ?
'asc' :
'desc'));
204 if (is_object($hookmanager) && is_array($hookmanager->resArray)) $file_list = array_merge($file_list, $hookmanager->resArray);
223 function dol_dir_list_in_database($path, $filter =
"", $excludefilter = null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0)
227 $sql =
" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,";
228 $sql .=
" date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share";
229 if ($mode) $sql .=
", description";
230 $sql .=
" FROM ".MAIN_DB_PREFIX.
"ecm_files";
231 $sql .=
" WHERE entity = ".$conf->entity;
232 if (preg_match(
'/%$/', $path)) {
233 $sql .=
" AND filepath LIKE '".$db->escape($path).
"'";
235 $sql .=
" AND filepath = '".$db->escape($path).
"'";
238 $resql = $db->query($sql);
241 $file_list = array();
242 $num = $db->num_rows(
$resql);
246 $obj = $db->fetch_object(
$resql);
250 preg_match(
'/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename, $reg);
251 $level1name = (isset($reg[1]) ? $reg[1] :
'');
252 $file_list[] = array(
253 "rowid" => $obj->rowid,
254 "label" => $obj->label,
255 "name" => $obj->filename,
256 "path" => DOL_DATA_ROOT.
'/'.$obj->filepath,
257 "level1name" => $level1name,
258 "fullname" => DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename,
259 "fullpath_orig" => $obj->fullpath_orig,
260 "date_c" => $db->jdate($obj->date_c),
261 "date_m" => $db->jdate($obj->date_m),
263 "keywords" => $obj->keywords,
264 "cover" => $obj->cover,
265 "position" => (int) $obj->position,
267 "share" => $obj->share
274 if (!empty($sortcriteria))
277 foreach ($file_list as $key => $row)
279 $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] :
'');
282 if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
303 global $conf, $db, $user;
309 if ($modulepart ==
'produit' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
311 if (!empty($object->id))
313 if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].
'/'.substr(substr(
"000".$object->id, -2), 1, 1).
'/'.substr(substr(
"000".$object->id, -2), 0, 1).
'/'.$object->id.
"/photos";
314 else $upload_dirold = $conf->service->multidir_output[$object->entity].
'/'.substr(substr(
"000".$object->id, -2), 1, 1).
'/'.substr(substr(
"000".$object->id, -2), 0, 1).
'/'.$object->id.
"/photos";
316 $relativedirold = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dirold);
317 $relativedirold = preg_replace(
'/^[\\/]/',
'', $relativedirold);
319 $filearrayindatabase = array_merge($filearrayindatabase,
dol_dir_list_in_database($relativedirold,
'', null,
'name', SORT_ASC));
328 foreach ($filearray as $key => $val)
330 $tmpfilename = preg_replace(
'/\.noexe$/',
'', $filearray[$key][
'name']);
333 foreach ($filearrayindatabase as $key2 => $val2)
335 if (($filearrayindatabase[$key2][
'path'] == $filearray[$key][
'path']) && ($filearrayindatabase[$key2][
'name'] == $tmpfilename))
337 $filearray[$key][
'position_name'] = ($filearrayindatabase[$key2][
'position'] ? $filearrayindatabase[$key2][
'position'] :
'0').
'_'.$filearrayindatabase[$key2][
'name'];
338 $filearray[$key][
'position'] = $filearrayindatabase[$key2][
'position'];
339 $filearray[$key][
'cover'] = $filearrayindatabase[$key2][
'cover'];
340 $filearray[$key][
'acl'] = $filearrayindatabase[$key2][
'acl'];
341 $filearray[$key][
'rowid'] = $filearrayindatabase[$key2][
'rowid'];
342 $filearray[$key][
'label'] = $filearrayindatabase[$key2][
'label'];
343 $filearray[$key][
'share'] = $filearrayindatabase[$key2][
'share'];
351 $filearray[$key][
'position'] =
'999999';
352 $filearray[$key][
'cover'] = 0;
353 $filearray[$key][
'acl'] =
'';
355 $rel_filename = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filearray[$key][
'fullname']);
357 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filename))
359 dol_syslog(
"list_of_documents We found a file called '".$filearray[$key][
'name'].
"' not indexed into database. We add it");
360 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
364 $filename = basename($rel_filename);
365 $rel_dir = dirname($rel_filename);
366 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
367 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
369 $ecmfile->filepath = $rel_dir;
370 $ecmfile->filename = $filename;
371 $ecmfile->label = md5_file(
dol_osencode($filearray[$key][
'fullname']));
372 $ecmfile->fullpath_orig = $filearray[$key][
'fullname'];
373 $ecmfile->gen_or_uploaded =
'unknown';
374 $ecmfile->description =
'';
375 $ecmfile->keyword =
'';
376 $result = $ecmfile->create($user);
381 $filearray[$key][
'rowid'] = $result;
384 $filearray[$key][
'rowid'] = 0;
404 $sortorder = strtoupper($sortorder);
406 if ($sortorder ==
'ASC') { $retup = -1; $retdown = 1; }
else { $retup = 1; $retdown = -1; }
408 if ($sortfield ==
'name')
410 if ($a->name == $b->name)
return 0;
411 return ($a->name < $b->name) ? $retup : $retdown;
413 if ($sortfield ==
'date')
415 if ($a->date == $b->date)
return 0;
416 return ($a->date < $b->date) ? $retup : $retdown;
418 if ($sortfield ==
'size')
420 if ($a->size == $b->size)
return 0;
421 return ($a->size < $b->size) ? $retup : $retdown;
435 if (is_dir($newfolder))
return true;
447 if (!is_readable($dir))
return false;
448 return (count(scandir($dir)) == 2);
460 return is_file($newpathoffile);
472 return is_link($newpathoffile);
483 $tmpprot = array(
'file',
'http',
'https',
'ftp',
'zlib',
'data',
'ssh',
'ssh2',
'ogg',
'expect');
484 foreach ($tmpprot as $prot)
486 if (preg_match(
'/^'.$prot.
':/i', $url))
return true;
500 if (is_dir($newfolder))
502 $handle = opendir($newfolder);
503 $folder_content =
'';
504 while ((gettype($name = readdir($handle)) !=
"boolean"))
506 $name_array[] = $name;
508 foreach ($name_array as $temp) $folder_content .= $temp;
512 if ($folder_content ==
"...")
return true;
530 $fp = fopen($newfile,
'r');
537 if (!$line ===
false) $nb++;
558 return filesize($newpathoffile);
570 return @filemtime($newpathoffile);
585 function dolReplaceInFile($srcfile, $arrayreplacement, $destfile =
'', $newmask = 0, $indexdatabase = 0, $arrayreplacementisregex = 0)
589 dol_syslog(
"files.lib.php::dolReplaceInFile srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" indexdatabase=".$indexdatabase.
" arrayreplacementisregex=".$arrayreplacementisregex);
591 if (empty($srcfile))
return -1;
592 if (empty($destfile)) $destfile = $srcfile;
595 if (($destfile != $srcfile) && $destexists)
return 0;
597 $tmpdestfile = $destfile.
'.tmp';
602 $newdirdestfile = dirname($newpathofdestfile);
604 if ($destexists && !is_writable($newpathofdestfile))
606 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
609 if (!is_writable($newdirdestfile))
611 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
618 $content = file_get_contents($newpathofsrcfile,
'r');
620 if (empty($arrayreplacementisregex))
624 foreach ($arrayreplacement as $key => $value)
626 $content = preg_replace($key, $value, $content);
630 file_put_contents($newpathoftmpdestfile, $content);
631 @chmod($newpathoftmpdestfile, octdec($newmask));
634 $result =
dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase);
637 dol_syslog(
"files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
640 if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
643 dol_syslog(
"Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
647 @chmod($newpathofdestfile, octdec($newmask));
663 function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1)
667 dol_syslog(
"files.lib.php::dol_copy srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
669 if (empty($srcfile) || empty($destfile))
return -1;
672 if (!$overwriteifexists && $destexists)
return 0;
676 $newdirdestfile = dirname($newpathofdestfile);
678 if ($destexists && !is_writable($newpathofdestfile))
680 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
683 if (!is_writable($newdirdestfile))
685 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
689 $result = @copy($newpathofsrcfile, $newpathofdestfile);
693 dol_syslog(
"files.lib.php::dol_copy failed to copy", LOG_WARNING);
696 if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
699 dol_syslog(
"Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
703 @chmod($newpathofdestfile, octdec($newmask));
720 function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement = null, $excludesubdir = 0)
726 dol_syslog(
"files.lib.php::dolCopyDir srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
728 if (empty($srcfile) || empty($destfile))
return -1;
737 $dirmaskdec = octdec($newmask);
738 if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $dirmaskdec = octdec($conf->global->MAIN_UMASK);
739 $dirmaskdec |= octdec(
'0200');
740 dol_mkdir($destfile,
'', decoct($dirmaskdec));
747 if (is_dir($ossrcfile))
749 $dir_handle = opendir($ossrcfile);
750 while ($file = readdir($dir_handle))
752 if ($file !=
"." && $file !=
".." && !is_link($ossrcfile.
"/".$file))
754 if (is_dir($ossrcfile.
"/".$file))
756 if (empty($excludesubdir) || ($excludesubdir == 2 && strlen($file) == 2)) {
759 if (is_array($arrayreplacement))
761 foreach ($arrayreplacement as $key => $val)
763 $newfile = str_replace($key, $val, $newfile);
767 $tmpresult =
dolCopyDir($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir);
772 if (is_array($arrayreplacement))
774 foreach ($arrayreplacement as $key => $val)
776 $newfile = str_replace($key, $val, $newfile);
779 $tmpresult =
dol_copy($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists);
782 if ($result > 0 && $tmpresult >= 0)
786 $result = $tmpresult;
788 if ($result < 0)
break;
791 closedir($dir_handle);
817 function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1)
819 global $user, $db, $conf;
822 dol_syslog(
"files.lib.php::dol_move srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwritifexists=".$overwriteifexists);
828 dol_syslog(
"files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
832 if ($overwriteifexists || !$destexists)
838 $testvirusarray = array();
842 if (count($testvirusarray))
844 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING);
849 $result = @rename($newpathofsrcfile, $newpathofdestfile);
854 dol_syslog(
"files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
857 $result = @rename($newpathofsrcfile, $newpathofdestfile);
858 }
else dol_syslog(
"files.lib.php::dol_move Failed.", LOG_WARNING);
862 if ($result && $indexdatabase)
865 $rel_filetorenamebefore = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $srcfile);
866 $rel_filetorenameafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $destfile);
867 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))
869 $rel_filetorenamebefore = preg_replace(
'/^[\\/]/',
'', $rel_filetorenamebefore);
870 $rel_filetorenameafter = preg_replace(
'/^[\\/]/',
'', $rel_filetorenameafter);
873 dol_syslog(
"Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore.
" after = ".$rel_filetorenameafter, LOG_DEBUG);
874 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
877 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetorenameafter);
878 if ($resultecmtarget > 0)
880 $ecmfiletarget->delete($user);
884 $resultecm = $ecmfile->fetch(0,
'', $rel_filetorenamebefore);
887 $filename = basename($rel_filetorenameafter);
888 $rel_dir = dirname($rel_filetorenameafter);
889 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
890 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
892 $ecmfile->filepath = $rel_dir;
893 $ecmfile->filename = $filename;
895 $resultecm = $ecmfile->update($user);
896 } elseif ($resultecm == 0)
898 $filename = basename($rel_filetorenameafter);
899 $rel_dir = dirname($rel_filetorenameafter);
900 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
901 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
903 $ecmfile->filepath = $rel_dir;
904 $ecmfile->filename = $filename;
906 $ecmfile->fullpath_orig = $srcfile;
907 $ecmfile->gen_or_uploaded =
'unknown';
908 $ecmfile->description =
'';
909 $ecmfile->keyword =
'';
910 $resultecm = $ecmfile->create($user);
915 } elseif ($resultecm < 0)
920 if ($resultecm > 0) $result =
true;
921 else $result =
false;
925 if (empty($newmask)) $newmask = empty($conf->global->MAIN_UMASK) ?
'0755' : $conf->global->MAIN_UMASK;
926 $newmaskdec = octdec($newmask);
930 @chmod($newpathofdestfile, $newmaskdec);
948 return trim(basename($filename),
".\x00..\x20");
962 if (!empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
964 if (!class_exists(
'AntiVir')) {
965 require_once DOL_DOCUMENT_ROOT.
'/core/class/antivir.class.php';
968 $result = $antivir->dol_avscan_file($src_file);
971 $reterrors = $antivir->errors;
999 function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $varfiles =
'addedfile', $upload_dir =
'')
1001 global $conf, $db, $user, $langs;
1002 global $object, $hookmanager;
1005 $file_name = $dest_file;
1010 $reshook = $hookmanager->initHooks(array(
'fileslib'));
1012 $parameters = array(
'dest_file' => $dest_file,
'src_file' => $src_file,
'file_name' => $file_name,
'varfiles' => $varfiles,
'allowoverwrite' => $allowoverwrite);
1013 $reshook = $hookmanager->executeHooks(
'moveUploadedFile', $parameters, $object);
1016 if (empty($reshook))
1019 if ($uploaderrorcode)
1021 switch ($uploaderrorcode)
1023 case UPLOAD_ERR_INI_SIZE:
1024 return 'ErrorFileSizeTooLarge';
1025 case UPLOAD_ERR_FORM_SIZE:
1026 return 'ErrorFileSizeTooLarge';
1027 case UPLOAD_ERR_PARTIAL:
1028 return 'ErrorPartialFile';
1029 case UPLOAD_ERR_NO_TMP_DIR:
1030 return 'ErrorNoTmpDir';
1031 case UPLOAD_ERR_CANT_WRITE:
1032 return 'ErrorFailedToWriteInDir';
1033 case UPLOAD_ERR_EXTENSION:
1034 return 'ErrorUploadBlockedByAddon';
1041 if (empty($disablevirusscan) && file_exists($src_file))
1044 if (count($checkvirusarray))
1046 dol_syslog(
'Files.lib::dol_move_uploaded_file File "'.$src_file.
'" (target name "'.$dest_file.
'") KO with antivirus: errors='.join(
',', $checkvirusarray), LOG_WARNING);
1047 return 'ErrorFileIsInfectedWithAVirus: '.join(
',', $checkvirusarray);
1057 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
1058 if (!preg_match(
'/\/$/', $publicmediasdirwithslash)) $publicmediasdirwithslash .=
'/';
1060 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) {
1061 $file_name .=
'.noexe';
1068 if (preg_match(
'/^\./', basename($src_file)) || preg_match(
'/\.\./', $src_file) || preg_match(
'/[<>|]/', $src_file))
1070 dol_syslog(
"Refused to deliver file ".$src_file, LOG_WARNING);
1076 if (preg_match(
'/^\./', basename($dest_file)) || preg_match(
'/\.\./', $dest_file) || preg_match(
'/[<>|]/', $dest_file))
1078 dol_syslog(
"Refused to deliver file ".$dest_file, LOG_WARNING);
1084 $errmsg = join(
',', $hookmanager->errors);
1085 if (empty($errmsg)) $errmsg =
'ErrorReturnedBySomeHooks';
1087 } elseif (empty($reshook)) {
1093 if (!is_writable(dirname($file_name_osencoded)))
1095 dol_syslog(
"Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded).
" is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1096 return 'ErrorDirNotWritable';
1100 if (!$allowoverwrite)
1102 if (file_exists($file_name_osencoded))
1104 dol_syslog(
"Files.lib::dol_move_uploaded_file File ".$file_name.
" already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1105 return 'ErrorFileAlreadyExists';
1108 if (is_dir($file_name_osencoded)) {
1109 dol_syslog(
"Files.lib::dol_move_uploaded_file A directory with name ".$file_name.
" already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
1110 return 'ErrorDirWithFileNameAlreadyExists';
1115 $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1118 if (!empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1119 dol_syslog(
"Files.lib::dol_move_uploaded_file Success to move ".$src_file.
" to ".$file_name.
" - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
1120 return $successcode;
1122 dol_syslog(
"Files.lib::dol_move_uploaded_file Failed to move ".$src_file.
" to ".$file_name, LOG_ERR);
1127 return $successcode;
1144 function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, $object = null, $allowdotdot =
false, $indexdatabase = 1)
1146 global $db, $conf, $user, $langs;
1147 global $hookmanager;
1150 $langs->loadLangs(array(
'other',
'errors'));
1152 dol_syslog(
"dol_delete_file file=".$file.
" disableglob=".$disableglob.
" nophperrors=".$nophperrors.
" nohook=".$nohook);
1156 if ((!$allowdotdot && preg_match(
'/\.\./', $file)) || preg_match(
'/[<>|]/', $file))
1158 dol_syslog(
"Refused to delete file ".$file, LOG_WARNING);
1165 $hookmanager->initHooks(array(
'fileslib'));
1167 $parameters = array(
1170 'disableglob'=> $disableglob,
1171 'nophperrors' => $nophperrors
1173 $reshook = $hookmanager->executeHooks(
'deleteFile', $parameters, $object);
1176 if (empty($nohook) && $reshook != 0)
1179 if ($reshook < 0)
return false;
1183 if (empty($disableglob) && !empty($file_osencoded))
1186 $globencoded = str_replace(
'[',
'\[', $file_osencoded);
1187 $globencoded = str_replace(
']',
'\]', $globencoded);
1188 $listofdir = glob($globencoded);
1189 if (!empty($listofdir) && is_array($listofdir))
1191 foreach ($listofdir as $filename)
1193 if ($nophperrors) $ok = @unlink($filename);
1194 else $ok = unlink($filename);
1197 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1198 dol_syslog(
"Error in deletion, but parent directory exists with no permission to write, we try to change permission on parent directory and retry...", LOG_DEBUG);
1199 @chmod(dirname($filename), fileperms(dirname($filename)) | 0200);
1201 if ($nophperrors) $ok = @unlink($filename);
1202 else $ok = unlink($filename);
1207 dol_syslog(
"Removed file ".$filename, LOG_DEBUG);
1210 $rel_filetodelete = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filename);
1211 if (!preg_match(
'/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete))
1213 if (is_object($db) && $indexdatabase)
1215 $rel_filetodelete = preg_replace(
'/^[\\/]/',
'', $rel_filetodelete);
1216 $rel_filetodelete = preg_replace(
'/\.noexe$/',
'', $rel_filetodelete);
1218 dol_syslog(
"Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1219 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1221 $result = $ecmfile->fetch(0,
'', $rel_filetodelete);
1222 if ($result >= 0 && $ecmfile->id > 0)
1224 $result = $ecmfile->delete($user);
1233 dol_syslog(
"Failed to remove file ".$filename, LOG_WARNING);
1239 dol_syslog(
"No files to delete found", LOG_DEBUG);
1243 if ($nophperrors) $ok = @unlink($file_osencoded);
1244 else $ok = unlink($file_osencoded);
1245 if ($ok)
dol_syslog(
"Removed file ".$file_osencoded, LOG_DEBUG);
1246 else dol_syslog(
"Failed to remove file ".$file_osencoded, LOG_WARNING);
1266 if (preg_match(
'/\.\./', $dir) || preg_match(
'/[<>|]/', $dir))
1268 dol_syslog(
"Refused to delete dir ".$dir, LOG_WARNING);
1273 return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1288 dol_syslog(
"functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1292 if ($handle = opendir(
"$dir_osencoded"))
1294 while (
false !== ($item = readdir($handle)))
1296 if (!
utf8_check($item)) $item = utf8_encode($item);
1298 if ($item !=
"." && $item !=
"..")
1306 if ($result) $countdeleted++;
1313 if (empty($onlysub))
1317 if ($result) $countdeleted++;
1337 global $langs, $conf;
1340 $element = $object->element;
1342 if ($object->element ==
'order_supplier') $dir = $conf->fournisseur->commande->dir_output;
1343 elseif ($object->element ==
'invoice_supplier') $dir = $conf->fournisseur->facture->dir_output;
1344 elseif ($object->element ==
'project') $dir = $conf->projet->dir_output;
1345 elseif ($object->element ==
'shipping') $dir = $conf->expedition->dir_output.
'/sending';
1346 elseif ($object->element ==
'delivery') $dir = $conf->expedition->dir_output.
'/receipt';
1347 elseif ($object->element ==
'fichinter') $dir = $conf->ficheinter->dir_output;
1348 else $dir = empty($conf->$element->dir_output) ?
'' : $conf->$element->dir_output;
1350 if (empty($dir))
return 'ErrorObjectNoSupportedByFunction';
1353 $dir = $dir.
"/".$refsan;
1354 $filepreviewnew = $dir.
"/".$refsan.
".pdf_preview.png";
1355 $filepreviewnewbis = $dir.
"/".$refsan.
".pdf_preview-0.png";
1356 $filepreviewold = $dir.
"/".$refsan.
".pdf.png";
1359 if (file_exists($filepreviewnew) && is_writable($filepreviewnew))
1363 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnew);
1367 if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis))
1371 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnewbis);
1376 if (file_exists($filepreviewold) && is_writable($filepreviewold))
1380 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewold);
1384 $multiple = $filepreviewold.
".";
1385 for ($i = 0; $i < 20; $i++)
1387 $preview = $multiple.$i;
1389 if (file_exists($preview) && is_writable($preview))
1393 $object->error = $langs->trans(
"ErrorFailedToOpenFile", $preview);
1416 if (empty($conf->global->MAIN_DOC_CREATE_METAFILE))
return 0;
1419 $element = $object->element;
1421 if ($object->element ==
'order_supplier') $dir = $conf->fournisseur->dir_output.
'/commande';
1422 elseif ($object->element ==
'invoice_supplier') $dir = $conf->fournisseur->dir_output.
'/facture';
1423 elseif ($object->element ==
'project') $dir = $conf->projet->dir_output;
1424 elseif ($object->element ==
'shipping') $dir = $conf->expedition->dir_output.
'/sending';
1425 elseif ($object->element ==
'delivery') $dir = $conf->expedition->dir_output.
'/receipt';
1426 elseif ($object->element ==
'fichinter') $dir = $conf->ficheinter->dir_output;
1427 else $dir = empty($conf->$element->dir_output) ?
'' : $conf->$element->dir_output;
1431 $object->fetch_thirdparty();
1434 $dir = $dir.
"/".$objectref;
1435 $file = $dir.
"/".$objectref.
".meta";
1444 $nblines = count($object->lines);
1445 $client = $object->thirdparty->name.
" ".$object->thirdparty->address.
" ".$object->thirdparty->zip.
" ".$object->thirdparty->town;
1446 $meta =
"REFERENCE=\"".$object->ref.
"\"
1448 NB_ITEMS=\"" . $nblines.
"\"
1449 CLIENT=\"" . $client.
"\"
1450 AMOUNT_EXCL_TAX=\"" . $object->total_ht.
"\"
1451 AMOUNT=\"" . $object->total_ttc.
"\"\n";
1453 for ($i = 0; $i < $nblines; $i++)
1456 $meta .=
"ITEM_".$i.
"_QUANTITY=\"".$object->lines[$i]->qty.
"\"
1457 ITEM_" . $i.
"_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht.
"\"
1458 ITEM_" . $i.
"_VAT=\"".$object->lines[$i]->tva_tx.
"\"
1459 ITEM_" . $i.
"_DESCRIPTION=\"".str_replace(
"\r\n",
"", nl2br($object->lines[$i]->desc)).
"\"
1464 $fp = fopen($file,
"w");
1467 if (!empty($conf->global->MAIN_UMASK))
1468 @chmod($file, octdec($conf->global->MAIN_UMASK));
1472 dol_syslog(
'FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
1490 $listofpaths = array();
1491 $listofnames = array();
1492 $listofmimes = array();
1497 foreach ($listoffiles as $key => $val)
1499 $listofpaths[] = $val[
'fullname'];
1500 $listofnames[] = $val[
'name'];
1504 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
1505 $_SESSION[
"listofpaths".$keytoavoidconflict] = join(
';', $listofpaths);
1506 $_SESSION[
"listofnames".$keytoavoidconflict] = join(
';', $listofnames);
1507 $_SESSION[
"listofmimes".$keytoavoidconflict] = join(
';', $listofmimes);
1528 function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles =
'addedfile', $savingdocmask =
'', $link = null, $trackid =
'', $generatethumbs = 1, $object = null)
1530 global $db, $user, $conf, $langs;
1534 if (!empty($_FILES[$varfiles]))
1536 dol_syslog(
'dol_add_file_process upload_dir='.$upload_dir.
' allowoverwrite='.$allowoverwrite.
' donotupdatesession='.$donotupdatesession.
' savingdocmask='.$savingdocmask, LOG_DEBUG);
1540 $TFile = $_FILES[$varfiles];
1541 if (!is_array($TFile[
'name']))
1543 foreach ($TFile as $key => &$val)
1549 $nbfile = count($TFile[
'name']);
1551 for ($i = 0; $i < $nbfile; $i++)
1553 if (empty($TFile[
'name'][$i]))
continue;
1556 $destfull = $upload_dir.
"/".$TFile[
'name'][$i];
1557 $destfile = $TFile[
'name'][$i];
1558 $destfilewithoutext = preg_replace(
'/\.[^\.]+$/',
'', $destfile);
1560 if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0)
1562 $destfull = $upload_dir.
"/".preg_replace(
'/__file__/', $TFile[
'name'][$i], $savingdocmask);
1563 $destfile = preg_replace(
'/__file__/', $TFile[
'name'][$i], $savingdocmask);
1566 $filenameto = basename($destfile);
1567 if (preg_match(
'/^\./', $filenameto)) {
1568 $langs->load(
"errors");
1569 setEventMessages($langs->trans(
"ErrorFilenameCantStartWithDot", $filenameto), null,
'errors');
1574 $info = pathinfo($destfull);
1575 $destfull = $info[
'dirname'].
'/'.
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
1576 $info = pathinfo($destfile);
1578 $destfile =
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
1586 $resupload =
dol_move_uploaded_file($TFile[
'tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile[
'error'][$i], 0, $varfiles, $upload_dir);
1588 if (is_numeric($resupload) && $resupload > 0)
1590 global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
1592 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
1595 if ($generatethumbs)
1603 $imgThumbSmall =
vignette($destfull, $maxwidthsmall, $maxheightsmall,
'_small', 50,
"thumbs");
1606 $imgThumbMini =
vignette($destfull, $maxwidthmini, $maxheightmini,
'_mini', 50,
"thumbs");
1611 if (empty($donotupdatesession))
1613 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
1615 $formmail->trackid = $trackid;
1616 $formmail->add_attached_files($destfull, $destfile, $TFile[
'type'][$i]);
1620 if ($donotupdatesession == 1)
1622 $result =
addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ?
'.noexe' :
''), $TFile[
'name'][$i],
'uploaded', 0, $object);
1625 if ($allowoverwrite) {
1628 setEventMessages(
'WarningFailedToAddFileIntoDatabaseIndex',
'',
'warnings');
1635 $langs->load(
"errors");
1639 } elseif (preg_match(
'/ErrorFileIsInfectedWithAVirus/', $resupload))
1641 setEventMessages($langs->trans(
"ErrorFileIsInfectedWithAVirus"), null,
'errors');
1655 require_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
1656 $linkObject =
new Link($db);
1657 $linkObject->entity = $conf->entity;
1658 $linkObject->url = $link;
1659 $linkObject->objecttype =
GETPOST(
'objecttype',
'alpha');
1660 $linkObject->objectid =
GETPOST(
'objectid',
'int');
1661 $linkObject->label =
GETPOST(
'label',
'alpha');
1662 $res = $linkObject->create($user);
1663 $langs->load(
'link');
1670 $langs->load(
"errors");
1671 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"File")), null,
'errors');
1691 global $db, $user, $conf, $langs, $_FILES;
1693 $keytodelete = $filenb;
1696 $listofpaths = array();
1697 $listofnames = array();
1698 $listofmimes = array();
1699 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
1700 if (!empty($_SESSION[
"listofpaths".$keytoavoidconflict])) $listofpaths = explode(
';', $_SESSION[
"listofpaths".$keytoavoidconflict]);
1701 if (!empty($_SESSION[
"listofnames".$keytoavoidconflict])) $listofnames = explode(
';', $_SESSION[
"listofnames".$keytoavoidconflict]);
1702 if (!empty($_SESSION[
"listofmimes".$keytoavoidconflict])) $listofmimes = explode(
';', $_SESSION[
"listofmimes".$keytoavoidconflict]);
1704 if ($keytodelete >= 0)
1706 $pathtodelete = $listofpaths[$keytodelete];
1707 $filetodelete = $listofnames[$keytodelete];
1708 if (empty($donotdeletefile)) $result =
dol_delete_file($pathtodelete, 1);
1712 if (empty($donotdeletefile))
1714 $langs->load(
"other");
1715 setEventMessages($langs->trans(
"FileWasRemoved", $filetodelete), null,
'mesgs');
1717 if (empty($donotupdatesession))
1719 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
1721 $formmail->trackid = $trackid;
1722 $formmail->remove_attached_files($keytodelete);
1748 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
1750 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))
1752 $filename = basename(preg_replace(
'/\.noexe$/',
'', $file));
1753 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1754 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1756 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1758 $ecmfile->filepath = $rel_dir;
1759 $ecmfile->filename = $filename;
1760 $ecmfile->label = md5_file(
dol_osencode($dir.
'/'.$file));
1761 $ecmfile->fullpath_orig = $fullpathorig;
1762 $ecmfile->gen_or_uploaded = $mode;
1763 $ecmfile->description =
'';
1764 $ecmfile->keyword =
'';
1766 if (is_object($object) && $object->id > 0) {
1767 $ecmfile->src_object_id = $object->id;
1768 $ecmfile->src_object_type = $object->table_element;
1773 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1777 $result = $ecmfile->create($user);
1797 global $conf, $db, $user;
1803 dol_syslog(
"deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
1809 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
1811 $filename = basename($file);
1812 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1813 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1817 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'ecm_files';
1818 $sql .=
' WHERE entity = '.$conf->entity;
1819 $sql .=
" AND filepath = '".$db->escape($rel_dir).
"'";
1820 if ($file) $sql .=
" AND filename = '".$db->escape($file).
"'";
1821 if ($mode) $sql .=
" AND gen_or_uploaded = '".$db->escape($mode).
"'";
1823 $resql = $db->query($sql);
1827 dol_syslog(__METHOD__.
' '.$db->lasterror(), LOG_ERR);
1855 if (class_exists(
'Imagick'))
1857 $image =
new Imagick();
1859 $filetoconvert = $fileinput.(($page !=
'') ?
'['.$page.
']' :
'');
1861 $ret = $image->readImage($filetoconvert);
1863 $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
1864 dol_syslog(
"Failed to read image using Imagick (Try to install package 'apt-get install php-imagick ghostscript' and check there is no policy to disable ".$ext.
" convertion in /etc/ImageMagick*/policy.xml): ".$e->getMessage(), LOG_WARNING);
1869 $ret = $image->setImageFormat($ext);
1872 if (empty($fileoutput)) $fileoutput = $fileinput.
".".$ext;
1874 $count = $image->getNumberImages();
1876 if (!
dol_is_file($fileoutput) || is_writeable($fileoutput))
1879 $ret = $image->writeImages($fileoutput,
true);
1885 dol_syslog(
"Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
1887 if ($ret)
return $count;
1911 function dol_compress_file($inputfile, $outputfile, $mode =
"gz", &$errorstring = null)
1918 dol_syslog(
"dol_compress_file mode=".$mode.
" inputfile=".$inputfile.
" outputfile=".$outputfile);
1921 if ($mode ==
'gz') { $foundhandler = 1; $compressdata = gzencode($data, 9); } elseif ($mode ==
'bz') { $foundhandler = 1; $compressdata = bzcompress($data, 9); } elseif ($mode ==
'zip')
1923 if (class_exists(
'ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS))
1927 $rootPath = realpath($inputfile);
1929 dol_syslog(
"Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.
' rootPath='.$rootPath);
1930 $zip =
new ZipArchive;
1932 if ($zip->open($outputfile, ZipArchive::CREATE) !==
true) {
1933 $errorstring =
"dol_compress_file failure - Failed to open file ".$outputfile.
"\n";
1937 $errormsg = $errorstring;
1944 $files =
new RecursiveIteratorIterator(
1945 new RecursiveDirectoryIterator($rootPath),
1946 RecursiveIteratorIterator::LEAVES_ONLY
1949 foreach ($files as $name => $file)
1952 if (!$file->isDir())
1955 $filePath = $file->getRealPath();
1956 $relativePath = substr($filePath, strlen($rootPath) + 1);
1959 $zip->addFile($filePath, $relativePath);
1966 dol_syslog(
"dol_compress_file success - ".count($zip->numFiles).
" files");
1970 if (defined(
'ODTPHP_PATHTOPCLZIP'))
1974 include_once ODTPHP_PATHTOPCLZIP.
'/pclzip.lib.php';
1975 $archive =
new PclZip($outputfile);
1976 $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
1981 $errormsg = $archive->errorInfo(
true);
1983 if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL)
1985 $errorstring =
"PCLZIP_ERR_WRITE_OPEN_FAIL";
1986 dol_syslog(
"dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
1990 $errorstring =
"dol_compress_file error archive->errorCode = ".$archive->errorCode().
" errormsg=".$errormsg;
1991 dol_syslog(
"dol_compress_file failure - ".$errormsg, LOG_ERR);
1994 dol_syslog(
"dol_compress_file success - ".count($result).
" files");
2002 $fp = fopen($outputfile,
"w");
2003 fwrite($fp, $compressdata);
2007 $errorstring =
"Try to zip with format ".$mode.
" with no handler for this format";
2011 $errormsg = $errorstring;
2016 global $langs, $errormsg;
2017 $langs->load(
"errors");
2018 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
2020 $errorstring =
"Failed to open file ".$outputfile;
2035 global $conf, $langs;
2037 if (defined(
'ODTPHP_PATHTOPCLZIP') && empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS))
2039 dol_syslog(
"Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.
", so we use Pclzip to unzip into ".$outputdir);
2040 include_once ODTPHP_PATHTOPCLZIP.
'/pclzip.lib.php';
2041 $archive =
new PclZip($inputfile);
2044 $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG,
'/^((?!\.\.).)*$/');
2046 if (!is_array($result) && $result <= 0)
return array(
'error'=>$archive->errorInfo(
true));
2048 $ok = 1; $errmsg =
'';
2050 foreach ($result as $key => $val)
2052 if ($val[
'status'] ==
'path_creation_fail')
2054 $langs->load(
"errors");
2056 $errmsg = $langs->trans(
"ErrorFailToCreateDir", $val[
'filename']);
2061 if ($ok)
return array();
2062 else return array(
'error'=>$errmsg);
2066 if (class_exists(
'ZipArchive'))
2068 dol_syslog(
"Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
2069 $zip =
new ZipArchive;
2070 $res = $zip->open($inputfile);
2078 for ($i = 0; $i < $zip->numFiles; $i++) {
2079 if (preg_match(
'/\.\./', $zip->getNameIndex($i))) {
2080 dol_syslog(
"Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
2083 $zip->extractTo($outputdir.
'/', array($zip->getNameIndex($i)));
2089 return array(
'error'=>
'ErrUnzipFails');
2093 return array(
'error'=>
'ErrNoZipEngine');
2107 function dol_compress_dir($inputdir, $outputfile, $mode =
"zip", $excludefiles =
'', $rootdirinzip =
'')
2111 dol_syslog(
"Try to zip dir ".$inputdir.
" into ".$outputfile.
" mode=".$mode);
2113 if (!
dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile)))
2115 global $langs, $errormsg;
2116 $langs->load(
"errors");
2117 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir", $outputfile);
2122 if ($mode ==
'gz') { $foundhandler = 0; } elseif ($mode ==
'bz') { $foundhandler = 0; } elseif ($mode ==
'zip')
2136 if (class_exists(
'ZipArchive'))
2141 $zip =
new ZipArchive();
2142 $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2145 global $langs, $errormsg;
2146 $langs->load(
"errors");
2147 $errormsg = $langs->trans(
"ErrorFailedToWriteInFile", $outputfile);
2153 $files =
new RecursiveIteratorIterator(
2154 new RecursiveDirectoryIterator($inputdir),
2155 RecursiveIteratorIterator::LEAVES_ONLY
2158 foreach ($files as $name => $file)
2161 if (!$file->isDir())
2164 $filePath = $file->getRealPath();
2165 $relativePath = ($rootdirinzip ? $rootdirinzip.
'/' :
'').substr($filePath, strlen($inputdir) + 1);
2167 if (empty($excludefiles) || !preg_match($excludefiles, $filePath))
2170 $zip->addFile($filePath, $relativePath);
2184 dol_syslog(
"Try to zip with format ".$mode.
" with no handler for this format", LOG_ERR);
2191 global $langs, $errormsg;
2192 $langs->load(
"errors");
2193 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
2195 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir", $outputfile);
2212 function dol_most_recent_file($dir, $regexfilter =
'', $excludefilter = array(
'(\.meta|_preview.*\.png)$',
'^\.'), $nohook =
false, $mode =
'')
2214 $tmparray =
dol_dir_list($dir,
'files', 0, $regexfilter, $excludefilter,
'date', SORT_DESC, $mode, $nohook);
2215 return $tmparray[0];
2232 global $conf, $db, $user;
2233 global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2235 if (!is_object($fuser)) $fuser = $user;
2237 if (empty($modulepart))
return 'ErrorBadParameter';
2240 if (empty($conf->multicompany->enabled)) $entity = 1;
2244 if ($modulepart ==
'users') $modulepart =
'user';
2246 dol_syslog(
'dol_check_secure_access_document modulepart='.$modulepart.
' original_file='.$original_file.
' entity='.$entity);
2250 $sqlprotectagainstexternals =
'';
2254 if (empty($refname)) $refname = basename(dirname($original_file).
"/");
2257 $lire =
'lire'; $read =
'read'; $download =
'download';
2258 if ($mode ==
'write')
2260 $lire =
'creer'; $read =
'write'; $download =
'upload';
2264 if ($modulepart ==
'medias' && !empty($dolibarr_main_data_root))
2266 if (empty($entity) || empty($conf->medias->multidir_output[$entity]))
return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2268 $original_file = $conf->medias->multidir_output[$entity].
'/'.$original_file;
2270 elseif ($modulepart ==
'logs' && !empty($dolibarr_main_data_root))
2272 $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match(
'/^dolibarr.*\.log$/', basename($original_file)));
2273 $original_file = $dolibarr_main_data_root.
'/'.$original_file;
2275 elseif ($modulepart ==
'doctemplates' && !empty($dolibarr_main_data_root))
2277 $accessallowed = $user->admin;
2278 $original_file = $dolibarr_main_data_root.
'/doctemplates/'.$original_file;
2280 elseif ($modulepart ==
'doctemplateswebsite' && !empty($dolibarr_main_data_root))
2282 $accessallowed = ($fuser->rights->website->write && preg_match(
'/\.jpg$/i', basename($original_file)));
2283 $original_file = $dolibarr_main_data_root.
'/doctemplates/websites/'.$original_file;
2285 elseif ($modulepart ==
'packages' && !empty($dolibarr_main_data_root))
2288 $tmp = explode(
',', $dolibarr_main_document_root_alt);
2291 $accessallowed = ($user->admin && preg_match(
'/^module_.*\.zip$/', basename($original_file)));
2292 $original_file = $dirins.
'/'.$original_file;
2294 elseif ($modulepart ==
'mycompany' && !empty($conf->mycompany->dir_output))
2297 $original_file = $conf->mycompany->dir_output.
'/'.$original_file;
2299 elseif ($modulepart ==
'userphoto' && !empty($conf->user->dir_output))
2302 $original_file = $conf->user->dir_output.
'/'.$original_file;
2304 elseif ($modulepart ==
'memberphoto' && !empty($conf->adherent->dir_output))
2307 $original_file = $conf->adherent->dir_output.
'/'.$original_file;
2309 elseif ($modulepart ==
'apercufacture' && !empty($conf->facture->multidir_output[$entity]))
2311 if ($fuser->rights->facture->{$lire}) $accessallowed = 1;
2312 $original_file = $conf->facture->multidir_output[$entity].
'/'.$original_file;
2314 elseif ($modulepart ==
'apercupropal' && !empty($conf->propal->multidir_output[$entity]))
2316 if ($fuser->rights->propale->{$lire}) $accessallowed = 1;
2317 $original_file = $conf->propal->multidir_output[$entity].
'/'.$original_file;
2319 elseif ($modulepart ==
'apercucommande' && !empty($conf->commande->multidir_output[$entity]))
2321 if ($fuser->rights->commande->{$lire}) $accessallowed = 1;
2322 $original_file = $conf->commande->multidir_output[$entity].
'/'.$original_file;
2324 elseif (($modulepart ==
'apercufichinter' || $modulepart ==
'apercuficheinter') && !empty($conf->ficheinter->dir_output))
2326 if ($fuser->rights->ficheinter->{$lire}) $accessallowed = 1;
2327 $original_file = $conf->ficheinter->dir_output.
'/'.$original_file;
2329 elseif (($modulepart ==
'apercucontract') && !empty($conf->contrat->multidir_output[$entity]))
2331 if ($fuser->rights->contrat->{$lire}) $accessallowed = 1;
2332 $original_file = $conf->contrat->multidir_output[$entity].
'/'.$original_file;
2334 elseif (($modulepart ==
'apercusupplier_proposal' || $modulepart ==
'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output))
2336 if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed = 1;
2337 $original_file = $conf->supplier_proposal->dir_output.
'/'.$original_file;
2339 elseif (($modulepart ==
'apercusupplier_order' || $modulepart ==
'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output))
2341 if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1;
2342 $original_file = $conf->fournisseur->commande->dir_output.
'/'.$original_file;
2344 elseif (($modulepart ==
'apercusupplier_invoice' || $modulepart ==
'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output))
2346 if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1;
2347 $original_file = $conf->fournisseur->facture->dir_output.
'/'.$original_file;
2349 elseif (($modulepart ==
'apercuexpensereport') && !empty($conf->expensereport->dir_output))
2351 if ($fuser->rights->expensereport->{$lire}) $accessallowed = 1;
2352 $original_file = $conf->expensereport->dir_output.
'/'.$original_file;
2354 elseif ($modulepart ==
'propalstats' && !empty($conf->propal->multidir_temp[$entity]))
2356 if ($fuser->rights->propale->{$lire}) $accessallowed = 1;
2357 $original_file = $conf->propal->multidir_temp[$entity].
'/'.$original_file;
2359 elseif ($modulepart ==
'orderstats' && !empty($conf->commande->dir_temp))
2361 if ($fuser->rights->commande->{$lire}) $accessallowed = 1;
2362 $original_file = $conf->commande->dir_temp.
'/'.$original_file;
2363 } elseif ($modulepart ==
'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
2365 if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1;
2366 $original_file = $conf->fournisseur->commande->dir_temp.
'/'.$original_file;
2368 elseif ($modulepart ==
'billstats' && !empty($conf->facture->dir_temp))
2370 if ($fuser->rights->facture->{$lire}) $accessallowed = 1;
2371 $original_file = $conf->facture->dir_temp.
'/'.$original_file;
2372 } elseif ($modulepart ==
'billstatssupplier' && !empty($conf->fournisseur->dir_output))
2374 if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1;
2375 $original_file = $conf->fournisseur->facture->dir_temp.
'/'.$original_file;
2377 elseif ($modulepart ==
'expeditionstats' && !empty($conf->expedition->dir_temp))
2379 if ($fuser->rights->expedition->{$lire}) $accessallowed = 1;
2380 $original_file = $conf->expedition->dir_temp.
'/'.$original_file;
2382 elseif ($modulepart ==
'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
2384 if ($fuser->rights->deplacement->{$lire}) $accessallowed = 1;
2385 $original_file = $conf->deplacement->dir_temp.
'/'.$original_file;
2387 elseif ($modulepart ==
'memberstats' && !empty($conf->adherent->dir_temp))
2389 if ($fuser->rights->adherent->{$lire}) $accessallowed = 1;
2390 $original_file = $conf->adherent->dir_temp.
'/'.$original_file;
2392 elseif (preg_match(
'/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp))
2394 if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed = 1;
2395 $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).
'/'.$original_file;
2397 elseif (in_array($modulepart, array(
'tax',
'tax-vat')) && !empty($conf->tax->dir_output))
2399 if ($fuser->rights->tax->charges->{$lire}) $accessallowed = 1;
2400 $modulepartsuffix = str_replace(
'tax-',
'', $modulepart);
2401 $original_file = $conf->tax->dir_output.
'/'.($modulepartsuffix !=
'tax' ? $modulepartsuffix.
'/' :
'').$original_file;
2403 elseif ($modulepart ==
'actions' && !empty($conf->agenda->dir_output))
2405 if ($fuser->rights->agenda->myactions->{$read}) $accessallowed = 1;
2406 $original_file = $conf->agenda->dir_output.
'/'.$original_file;
2408 elseif ($modulepart ==
'category' && !empty($conf->categorie->multidir_output[$entity]))
2410 if (empty($entity) || empty($conf->categorie->multidir_output[$entity]))
return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2411 if ($fuser->rights->categorie->{$lire}) $accessallowed = 1;
2412 $original_file = $conf->categorie->multidir_output[$entity].
'/'.$original_file;
2414 elseif ($modulepart ==
'prelevement' && !empty($conf->prelevement->dir_output))
2416 if ($fuser->rights->prelevement->bons->{$lire} || preg_match(
'/^specimen/i', $original_file)) $accessallowed = 1;
2417 $original_file = $conf->prelevement->dir_output.
'/'.$original_file;
2419 elseif ($modulepart ==
'graph_stock' && !empty($conf->stock->dir_temp))
2422 $original_file = $conf->stock->dir_temp.
'/'.$original_file;
2424 elseif ($modulepart ==
'graph_fourn' && !empty($conf->fournisseur->dir_temp))
2427 $original_file = $conf->fournisseur->dir_temp.
'/'.$original_file;
2429 elseif ($modulepart ==
'graph_product' && !empty($conf->product->dir_temp))
2432 $original_file = $conf->product->multidir_temp[$entity].
'/'.$original_file;
2434 elseif ($modulepart ==
'barcode')
2439 $original_file =
'';
2441 elseif ($modulepart ==
'iconmailing' && !empty($conf->mailing->dir_temp))
2444 $original_file = $conf->mailing->dir_temp.
'/'.$original_file;
2446 elseif ($modulepart ==
'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2449 $original_file = $conf->scanner->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
2451 elseif ($modulepart ==
'fckeditor' && !empty($conf->fckeditor->dir_output))
2454 $original_file = $conf->fckeditor->dir_output.
'/'.$original_file;
2456 elseif ($modulepart ==
'user' && !empty($conf->user->dir_output))
2458 $canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire});
2459 if ($fuser->id == (
int) $refname) { $canreaduser = 1; }
2460 if ($canreaduser || preg_match(
'/^specimen/i', $original_file))
2464 $original_file = $conf->user->dir_output.
'/'.$original_file;
2466 elseif (($modulepart ==
'company' || $modulepart ==
'societe' || $modulepart ==
'thirdparty') && !empty($conf->societe->multidir_output[$entity]))
2468 if (empty($entity) || empty($conf->societe->multidir_output[$entity]))
return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2469 if ($fuser->rights->societe->{$lire} || preg_match(
'/^specimen/i', $original_file))
2473 $original_file = $conf->societe->multidir_output[$entity].
'/'.$original_file;
2474 $sqlprotectagainstexternals =
"SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX.
"societe WHERE rowid='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'societe').
")";
2476 elseif ($modulepart ==
'contact' && !empty($conf->societe->multidir_output[$entity]))
2478 if (empty($entity) || empty($conf->societe->multidir_output[$entity]))
return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2479 if ($fuser->rights->societe->{$lire})
2483 $original_file = $conf->societe->multidir_output[$entity].
'/contact/'.$original_file;
2485 elseif (($modulepart ==
'facture' || $modulepart ==
'invoice') && !empty($conf->facture->multidir_output[$entity]))
2487 if ($fuser->rights->facture->{$lire} || preg_match(
'/^specimen/i', $original_file))
2491 $original_file = $conf->facture->multidir_output[$entity].
'/'.$original_file;
2492 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'invoice').
")";
2494 elseif ($modulepart ==
'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity]))
2496 if ($fuser->rights->propal->{$lire} || preg_match(
'/^specimen/i', $original_file))
2500 $original_file = $conf->propal->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2501 } elseif ($modulepart ==
'massfilesarea_orders')
2503 if ($fuser->rights->commande->{$lire} || preg_match(
'/^specimen/i', $original_file))
2507 $original_file = $conf->commande->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2508 } elseif ($modulepart ==
'massfilesarea_sendings')
2510 if ($fuser->rights->expedition->{$lire} || preg_match(
'/^specimen/i', $original_file))
2514 $original_file = $conf->expedition->dir_output.
'/sending/temp/massgeneration/'.$user->id.
'/'.$original_file;
2515 } elseif ($modulepart ==
'massfilesarea_invoices')
2517 if ($fuser->rights->facture->{$lire} || preg_match(
'/^specimen/i', $original_file))
2521 $original_file = $conf->facture->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2522 } elseif ($modulepart ==
'massfilesarea_expensereport')
2524 if ($fuser->rights->facture->{$lire} || preg_match(
'/^specimen/i', $original_file))
2528 $original_file = $conf->expensereport->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2529 } elseif ($modulepart ==
'massfilesarea_interventions')
2531 if ($fuser->rights->ficheinter->{$lire} || preg_match(
'/^specimen/i', $original_file))
2535 $original_file = $conf->ficheinter->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2536 } elseif ($modulepart ==
'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output))
2538 if ($fuser->rights->supplier_proposal->{$lire} || preg_match(
'/^specimen/i', $original_file))
2542 $original_file = $conf->supplier_proposal->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2543 } elseif ($modulepart ==
'massfilesarea_supplier_order')
2545 if ($fuser->rights->fournisseur->commande->{$lire} || preg_match(
'/^specimen/i', $original_file))
2549 $original_file = $conf->fournisseur->commande->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2550 } elseif ($modulepart ==
'massfilesarea_supplier_invoice')
2552 if ($fuser->rights->fournisseur->facture->{$lire} || preg_match(
'/^specimen/i', $original_file))
2556 $original_file = $conf->fournisseur->facture->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2557 } elseif ($modulepart ==
'massfilesarea_contract' && !empty($conf->contrat->dir_output))
2559 if ($fuser->rights->contrat->{$lire} || preg_match(
'/^specimen/i', $original_file))
2563 $original_file = $conf->contrat->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2565 elseif (($modulepart ==
'fichinter' || $modulepart ==
'ficheinter') && !empty($conf->ficheinter->dir_output))
2567 if ($fuser->rights->ficheinter->{$lire} || preg_match(
'/^specimen/i', $original_file))
2571 $original_file = $conf->ficheinter->dir_output.
'/'.$original_file;
2572 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"fichinter WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
2574 elseif ($modulepart ==
'deplacement' && !empty($conf->deplacement->dir_output))
2576 if ($fuser->rights->deplacement->{$lire} || preg_match(
'/^specimen/i', $original_file))
2580 $original_file = $conf->deplacement->dir_output.
'/'.$original_file;
2583 elseif (($modulepart ==
'propal' || $modulepart ==
'propale') && !empty($conf->propal->multidir_output[$entity]))
2585 if ($fuser->rights->propale->{$lire} || preg_match(
'/^specimen/i', $original_file))
2589 $original_file = $conf->propal->multidir_output[$entity].
'/'.$original_file;
2590 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"propal WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'propal').
")";
2592 elseif (($modulepart ==
'commande' || $modulepart ==
'order') && !empty($conf->commande->multidir_output[$entity]))
2594 if ($fuser->rights->commande->{$lire} || preg_match(
'/^specimen/i', $original_file))
2598 $original_file = $conf->commande->multidir_output[$entity].
'/'.$original_file;
2599 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'order').
")";
2601 elseif ($modulepart ==
'project' && !empty($conf->projet->dir_output))
2603 if ($fuser->rights->projet->{$lire} || preg_match(
'/^specimen/i', $original_file))
2607 $original_file = $conf->projet->dir_output.
'/'.$original_file;
2608 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
2609 } elseif ($modulepart ==
'project_task' && !empty($conf->projet->dir_output))
2611 if ($fuser->rights->projet->{$lire} || preg_match(
'/^specimen/i', $original_file))
2615 $original_file = $conf->projet->dir_output.
'/'.$original_file;
2616 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
2618 elseif (($modulepart ==
'commande_fournisseur' || $modulepart ==
'order_supplier') && !empty($conf->fournisseur->commande->dir_output))
2620 if ($fuser->rights->fournisseur->commande->{$lire} || preg_match(
'/^specimen/i', $original_file))
2624 $original_file = $conf->fournisseur->commande->dir_output.
'/'.$original_file;
2625 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande_fournisseur WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
2627 elseif (($modulepart ==
'facture_fournisseur' || $modulepart ==
'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output))
2629 if ($fuser->rights->fournisseur->facture->{$lire} || preg_match(
'/^specimen/i', $original_file))
2633 $original_file = $conf->fournisseur->facture->dir_output.
'/'.$original_file;
2634 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture_fourn WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
2636 elseif ($modulepart ==
'supplier_payment')
2638 if ($fuser->rights->fournisseur->facture->{$lire} || preg_match(
'/^specimen/i', $original_file))
2642 $original_file = $conf->fournisseur->payment->dir_output.
'/'.$original_file;
2643 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"paiementfournisseur WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
2645 elseif ($modulepart ==
'facture_paiement' && !empty($conf->facture->dir_output))
2647 if ($fuser->rights->facture->{$lire} || preg_match(
'/^specimen/i', $original_file))
2651 if ($fuser->societe_id > 0) $original_file = $conf->facture->dir_output.
'/payments/private/'.$fuser->id.
'/'.$original_file;
2652 else $original_file = $conf->facture->dir_output.
'/payments/'.$original_file;
2654 elseif ($modulepart ==
'export_compta' && !empty($conf->accounting->dir_output))
2656 if ($fuser->rights->accounting->bind->write || preg_match(
'/^specimen/i', $original_file))
2660 $original_file = $conf->accounting->dir_output.
'/'.$original_file;
2662 elseif (($modulepart ==
'expedition' || $modulepart ==
'shipment') && !empty($conf->expedition->dir_output))
2664 if ($fuser->rights->expedition->{$lire} || preg_match(
'/^specimen/i', $original_file))
2668 $original_file = $conf->expedition->dir_output.
"/sending/".$original_file;
2670 elseif (($modulepart ==
'livraison' || $modulepart ==
'delivery') && !empty($conf->expedition->dir_output))
2672 if ($fuser->rights->expedition->delivery->{$lire} || preg_match(
'/^specimen/i', $original_file))
2676 $original_file = $conf->expedition->dir_output.
"/receipt/".$original_file;
2678 elseif ($modulepart ==
'actions' && !empty($conf->agenda->dir_output))
2680 if ($fuser->rights->agenda->myactions->{$read} || preg_match(
'/^specimen/i', $original_file))
2684 $original_file = $conf->agenda->dir_output.
'/'.$original_file;
2686 elseif ($modulepart ==
'actionsreport' && !empty($conf->agenda->dir_temp))
2688 if ($fuser->rights->agenda->allactions->{$read} || preg_match(
'/^specimen/i', $original_file))
2692 $original_file = $conf->agenda->dir_temp.
"/".$original_file;
2694 elseif ($modulepart ==
'product' || $modulepart ==
'produit' || $modulepart ==
'service' || $modulepart ==
'produit|service')
2696 if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity])))
return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2697 if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match(
'/^specimen/i', $original_file))
2701 if (!empty($conf->product->enabled)) $original_file = $conf->product->multidir_output[$entity].
'/'.$original_file;
2702 elseif (!empty($conf->service->enabled)) $original_file = $conf->service->multidir_output[$entity].'/'.$original_file;
2704 elseif ($modulepart == 'product_batch' || $modulepart == 'produitlot')
2706 if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity])))
return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2707 if (($fuser->rights->produit->{$lire} ) || preg_match(
'/^specimen/i', $original_file))
2711 if (!empty($conf->productbatch->enabled)) $original_file = $conf->productbatch->multidir_output[$entity].
'/'.$original_file;
2713 elseif ($modulepart ==
'movement' || $modulepart ==
'mouvement')
2715 if (empty($entity) || empty($conf->stock->multidir_output[$entity]))
return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2716 if (($fuser->rights->stock->{$lire} || $fuser->rights->stock->movement->{$lire} || $fuser->rights->stock->mouvement->{$lire}) || preg_match(
'/^specimen/i', $original_file))
2720 if (!empty($conf->stock->enabled)) $original_file = $conf->stock->multidir_output[$entity].
'/movement/'.$original_file;
2722 elseif ($modulepart ==
'contract' && !empty($conf->contrat->multidir_output[$entity]))
2724 if ($fuser->rights->contrat->{$lire} || preg_match(
'/^specimen/i', $original_file))
2728 $original_file = $conf->contrat->multidir_output[$entity].
'/'.$original_file;
2729 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"contrat WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'contract').
")";
2731 elseif ($modulepart ==
'donation' && !empty($conf->don->dir_output))
2733 if ($fuser->rights->don->{$lire} || preg_match(
'/^specimen/i', $original_file))
2737 $original_file = $conf->don->dir_output.
'/'.$original_file;
2739 elseif ($modulepart ==
'dolresource' && !empty($conf->resource->dir_output))
2741 if ($fuser->rights->resource->{$read} || preg_match(
'/^specimen/i', $original_file))
2745 $original_file = $conf->resource->dir_output.
'/'.$original_file;
2747 elseif ($modulepart ==
'remisecheque' && !empty($conf->bank->dir_output))
2749 if ($fuser->rights->banque->{$lire} || preg_match(
'/^specimen/i', $original_file))
2754 $original_file = $conf->bank->dir_output.
'/checkdeposits/'.$original_file;
2756 elseif (($modulepart ==
'banque' || $modulepart ==
'bank') && !empty($conf->bank->dir_output))
2758 if ($fuser->rights->banque->{$lire})
2762 $original_file = $conf->bank->dir_output.
'/'.$original_file;
2764 elseif ($modulepart ==
'export' && !empty($conf->export->dir_temp))
2769 $original_file = $conf->export->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
2771 elseif ($modulepart ==
'import' && !empty($conf->import->dir_temp))
2774 $original_file = $conf->import->dir_temp.
'/'.$original_file;
2776 elseif ($modulepart ==
'editor' && !empty($conf->fckeditor->dir_output))
2779 $original_file = $conf->fckeditor->dir_output.
'/'.$original_file;
2781 elseif ($modulepart ==
'systemtools' && !empty($conf->admin->dir_output))
2783 if ($fuser->admin) $accessallowed = 1;
2784 $original_file = $conf->admin->dir_output.
'/'.$original_file;
2786 elseif ($modulepart ==
'admin_temp' && !empty($conf->admin->dir_temp))
2788 if ($fuser->admin) $accessallowed = 1;
2789 $original_file = $conf->admin->dir_temp.
'/'.$original_file;
2791 elseif ($modulepart ==
'bittorrent' && !empty($conf->bittorrent->dir_output))
2795 if (
dol_mimetype($original_file) ==
'application/x-bittorrent') $dir =
'torrents';
2796 $original_file = $conf->bittorrent->dir_output.
'/'.$dir.
'/'.$original_file;
2798 elseif ($modulepart ==
'member' && !empty($conf->adherent->dir_output))
2800 if ($fuser->rights->adherent->{$lire} || preg_match(
'/^specimen/i', $original_file))
2804 $original_file = $conf->adherent->dir_output.
'/'.$original_file;
2806 elseif ($modulepart ==
'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2809 $original_file = $conf->scanner->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
2819 if (preg_match(
'/^specimen/i', $original_file)) $accessallowed = 1;
2820 if ($fuser->admin) $accessallowed = 1;
2821 $tmpmodulepart = explode(
'-', $modulepart);
2822 if (!empty($tmpmodulepart[1])) {
2823 $modulepart = $tmpmodulepart[0];
2824 $original_file = $tmpmodulepart[1].
'/'.$original_file;
2829 if (preg_match(
'/^([a-z]+)_user_temp$/i', $modulepart, $reg))
2831 if (empty($conf->{$reg[1]}->dir_temp))
2833 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
2836 if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1;
2837 $original_file = $conf->{$reg[1]}->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
2838 } elseif (preg_match(
'/^([a-z]+)_temp$/i', $modulepart, $reg))
2840 if (empty($conf->{$reg[1]}->dir_temp))
2842 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
2845 if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1;
2846 $original_file = $conf->{$reg[1]}->dir_temp.
'/'.$original_file;
2847 } elseif (preg_match(
'/^([a-z]+)_user$/i', $modulepart, $reg))
2849 if (empty($conf->{$reg[1]}->dir_output))
2851 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
2854 if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1;
2855 $original_file = $conf->{$reg[1]}->dir_output.
'/'.$fuser->id.
'/'.$original_file;
2856 } elseif (preg_match(
'/^massfilesarea_([a-z]+)$/i', $modulepart, $reg))
2858 if (empty($conf->{$reg[1]}->dir_output))
2860 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
2863 if ($fuser->rights->{$reg[1]}->{$lire} || preg_match(
'/^specimen/i', $original_file))
2867 $original_file = $conf->{$reg[1]}->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2869 if (empty($conf->$modulepart->dir_output))
2871 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
'). The module for this modulepart value may not be activated.');
2876 $partsofdirinoriginalfile = explode(
'/', $original_file);
2877 if (!empty($partsofdirinoriginalfile[1])) {
2878 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
2879 if ($partofdirinoriginalfile && !empty($fuser->rights->$modulepart->$partofdirinoriginalfile) && ($fuser->rights->$modulepart->$partofdirinoriginalfile->{$lire} || $fuser->rights->$modulepart->$partofdirinoriginalfile->{$read})) $accessallowed = 1;
2881 if (!empty($fuser->rights->$modulepart->{$lire}) || !empty($fuser->rights->$modulepart->{$read})) $accessallowed = 1;
2883 if (is_array($conf->$modulepart->multidir_output) && !empty($conf->$modulepart->multidir_output[$entity])) {
2884 $original_file = $conf->$modulepart->multidir_output[$entity].
'/'.$original_file;
2886 $original_file = $conf->$modulepart->dir_output.
'/'.$original_file;
2891 $subPermCategoryConstName = strtoupper($modulepart).
'_SUBPERMCATEGORY_FOR_DOCUMENTS';
2892 if (!empty($conf->global->$subPermCategoryConstName))
2894 $subPermCategory = $conf->global->$subPermCategoryConstName;
2895 if (!empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download})))
2902 $sqlProtectConstName = strtoupper($modulepart).
'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
2903 if (!empty($conf->global->$sqlProtectConstName))
2906 eval(
'$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.
'";');
2911 'accessallowed' => $accessallowed,
2912 'sqlprotectagainstexternals'=>$sqlprotectagainstexternals,
2913 'original_file'=>$original_file
2930 $cachefile = $directory.$filename;
2931 file_put_contents($cachefile, serialize($object), LOCK_EX);
2932 @chmod($cachefile, 0644);
2946 $cachefile = $directory.$filename;
2947 $refresh = !file_exists($cachefile) || ($now - $cachetime) >
dol_filemtime($cachefile);
2960 $cachefile = $directory.$filename;
2961 $object = unserialize(file_get_contents($cachefile));
2977 function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path =
'', $pathref =
'', &$checksumconcat = array())
2981 $exclude =
'install';
2983 foreach ($dir->md5file as $file)
2985 $filename = $path.$file[
'name'];
2986 $file_list[
'insignature'][] = $filename;
2987 $expectedsize = (empty($file[
'size']) ?
'' : $file[
'size']);
2988 $expectedmd5 = (string) $file;
2992 if (!file_exists($pathref.
'/'.$filename))
2994 $file_list[
'missing'][] = array(
'filename'=>$filename,
'expectedmd5'=>$expectedmd5,
'expectedsize'=>$expectedsize);
2996 $md5_local = md5_file($pathref.
'/'.$filename);
2998 if ($conffile ==
'/etc/dolibarr/conf.php' && $filename ==
'/filefunc.inc.php')
3000 $checksumconcat[] = $expectedmd5;
3002 if ($md5_local != $expectedmd5) $file_list[
'updated'][] = array(
'filename'=>$filename,
'expectedmd5'=>$expectedmd5,
'expectedsize'=>$expectedsize,
'md5'=>(
string) $md5_local);
3003 $checksumconcat[] = $md5_local;
3008 foreach ($dir->dir as $subdir)
3010 getFilesUpdated($file_list, $subdir, $path.$subdir[
'name'].
'/', $pathref, $checksumconcat);
dol_convert_file($fileinput, $ext= 'png', $fileoutput= '', $page= '')
Convert an image file into another format.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_compare_file($a, $b)
Fast compare of 2 files identified by their properties ->name, ->date and ->size. ...
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto= 'UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
Copy a file to another file.
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)...
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0)
Copy a dir to another dir.
getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path= '', $pathref= '', &$checksumconcat=array())
Function to get list of updated or modified files.
dol_unescapefile($filename)
Unescape a file submitted by upload.
dol_dir_list_in_database($path, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0)
Scan a directory and return a list of files/directories.
dol_cache_refresh($directory, $filename, $cachetime)
Test if Refresh needed.
deleteFilesIntoDatabaseIndex($dir, $file, $mode= 'uploaded')
Delete files into database index using search criterias.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
dol_now($mode= 'auto')
Return date for now.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_filesize($pathoffile)
Return size of a file.
dol_is_dir($folder)
Test if filename is a directory.
dolCheckVirus($src_file)
Check virus into a file.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
dol_is_url($url)
Return if path is an URL.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser= '', $refname= '', $mode= 'read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices) ...
dol_mimetype($file, $default= 'application/octet-stream', $mode=0)
Return mime type of a file.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
dol_basename($pathfile)
Make a basename working with all page code (default PHP basenamed fails with cyrillic).
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
utf8_check($str)
Check if a string is in UTF8.
dol_count_nb_of_line($file)
Count number of lines in a file.
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_is_file($pathoffile)
Return if path is a file.
dol_remove_file_process($filenb, $donotupdatesession=0, $donotdeletefile=1, $trackid= '')
Remove an uploaded file (for example after submitting a new file a mail form).
dolReplaceInFile($srcfile, $arrayreplacement, $destfile= '', $newmask=0, $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_init_file_process($pathtoscan= '', $trackid= '')
Scan a directory and init $_SESSION to manage uploaded files with list of all found files...
dol_sort_array(&$array, $index, $order= 'asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
dol_uncompress($inputfile, $outputdir)
Uncompress a file.
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_filemtime($pathoffile)
Return time of a file.
dol_most_recent_file($dir, $regexfilter= '', $excludefilter=array('(\.meta|_preview.*\.png)$', '^\.'), $nohook=false, $mode= '')
Return file(s) into a directory (by default most recent)
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
addFileIntoDatabaseIndex($dir, $file, $fullpathorig= '', $mode= 'uploaded', $setsharekey=0, $object=null)
Add a file into database index.
dol_readcachefile($directory, $filename)
Read object from cachefile.
dol_is_link($pathoffile)
Return if path is a symbolic link.
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles= 'addedfile', $savingdocmask= '', $link=null, $trackid= '', $generatethumbs=1, $object=null)
Get and save an upload file (for example after submitting a new file a mail form).
dol_dir_is_emtpy($folder)
Test if a folder is empty.
dol_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
Class to manage ECM files.
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_filecache($directory, $filename, $object)
Store object in file.
dol_mkdir($dir, $dataroot= '', $newmask=null)
Creation of a directory (this can create recursive subdir)
dol_is_dir_empty($dir)
Return if path is empty.