40 return preg_replace(
'/^.*\/([^\/]+)$/',
'$1', rtrim($pathfile,
'/'));
63function dol_dir_list($utf8_path, $types =
"all", $recursive = 0, $filter =
"", $excludefilter =
null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename =
"", $donotfollowsymlinks = 0, $nbsecondsold = 0)
68 if ($recursive <= 1) {
73 if (!is_array($filter)) {
74 if (strlen($filter) > 25000) {
75 dol_syslog(
"Value for filter is too large", LOG_ERR);
79 if ((
int) preg_match(
'/(?:^|[^\\\\])\//', $filter) > 0) {
80 $excludefilter_ok =
false;
81 $error_info .=
" error='filter_has_unescaped_slash'";
82 dol_syslog(
"'$filter' has unescaped '/'", LOG_ERR);
88 $excludefilter_ok =
true;
89 $exclude_array = ($excludefilter ===
null || $excludefilter ===
'') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
90 foreach ($exclude_array as $f) {
92 if ((
int) preg_match(
'/(?:^|[^\\\\])\//', $f) > 0) {
93 $excludefilter_ok =
false;
94 $error_info .=
" error='excludefilter_has_unescaped_slash'";
99 dol_syslog(
"files.lib.php::dol_dir_list path=".$utf8_path.
" types=".$types.
" recursive=".$recursive.
" filter=".json_encode($filter).
" excludefilter=".json_encode($excludefilter).$error_info);
101 if (!$filter_ok || !$excludefilter_ok) {
107 $exclude_array = ($excludefilter ===
null || $excludefilter ===
'') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
111 $excludefilterarray = array_merge(array(
'^\.'), $exclude_array);
113 $loaddate = ($mode == 1 || $mode == 2 || $nbsecondsold != 0 || $sortcriteria ==
'date');
114 $loadsize = ($mode == 1 || $mode == 3 || $sortcriteria ==
'size');
115 $loadperm = ($mode == 1 || $mode == 4 || $sortcriteria ==
'perm');
119 $file_list = array();
122 $utf8_path = preg_replace(
'/([\\/]+)$/',
'', $utf8_path);
124 if (preg_match(
'/\*/', $utf8_path)) {
125 $utf8_path_array = glob($utf8_path, GLOB_ONLYDIR);
128 $utf8_path_array = array($utf8_path);
131 foreach ($utf8_path_array as $utf8_path_cursor) {
133 if (!$nohook && $hookmanager instanceof
HookManager) {
134 $hookmanager->resArray = array();
136 $hookmanager->initHooks(array(
'fileslib'));
141 'recursive' => $recursive,
143 'excludefilter' => $exclude_array,
144 'sortcriteria' => $sortcriteria,
145 'sortorder' => $sortorder,
146 'loaddate' => $loaddate,
147 'loadsize' => $loadsize,
150 $reshook = $hookmanager->executeHooks(
'getDirList', $parameters,
$object);
154 if (empty($reshook)) {
155 if (!is_dir($os_path)) {
159 if (($dir = opendir($os_path)) ===
false) {
167 while (
false !== ($os_file = readdir($dir))) {
168 $os_fullpathfile = ($os_path ? $os_path.
'/' :
'').$os_file;
171 $utf8_file = mb_convert_encoding($os_file,
'UTF-8',
'ISO-8859-1');
173 $utf8_file = $os_file;
176 $utf8_fullpathfile = $utf8_path_cursor.
"/".$utf8_file;
180 foreach ($excludefilterarray as $filt) {
181 if (preg_match(
'/'.$filt.
'/i', $utf8_file) || preg_match(
'/'.$filt.
'/i', $utf8_fullpathfile)) {
189 $isdir = is_dir($os_fullpathfile);
193 if (($types ==
"directories") || ($types ==
"all")) {
194 if ($loaddate || $sortcriteria ==
'date') {
197 if ($loadsize || $sortcriteria ==
'size') {
200 if ($loadperm || $sortcriteria ==
'perm') {
204 $qualifiedforfilter = 0;
205 if (empty($filter)) {
206 $qualifiedforfilter = 1;
208 $testpregmatch =
false;
209 if (is_array($filter)) {
210 $chunks = array_chunk($filter, 500);
211 foreach ($chunks as $chunk) {
212 $testpregmatch = preg_match(
'/'.implode(
'|', $chunk).
'/i', $utf8_file);
213 if ($testpregmatch) {
218 $testpregmatch = preg_match(
'/'.$filter.
'/i', $utf8_file);
220 if ($testpregmatch) {
221 $qualifiedforfilter = 1;
225 if ($qualifiedforfilter) {
227 preg_match(
'/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
228 $level1name = (isset($reg[1]) ? $reg[1] :
'');
229 $file_list[] = array(
230 "name" => $utf8_file,
231 "path" => $utf8_path,
232 "level1name" => $level1name,
233 "relativename" => ($relativename ? $relativename.
'/' :
'').$utf8_file,
234 "fullname" => $utf8_fullpathfile,
244 if ($recursive > 0) {
245 if (empty($donotfollowsymlinks) || !is_link($os_fullpathfile)) {
247 $file_list = array_merge($file_list,
dol_dir_list($utf8_fullpathfile, $types, $recursive + 1, $filter, $exclude_array, $sortcriteria, $sortorder, $mode, $nohook, ($relativename !=
'' ? $relativename.
'/' :
'').$utf8_file, $donotfollowsymlinks, $nbsecondsold));
250 } elseif (in_array($types, array(
"files",
"all"))) {
252 if ($loaddate || $sortcriteria ==
'date') {
255 if ($loadsize || $sortcriteria ==
'size') {
259 $qualifiedforfilter = 0;
260 if (empty($filter)) {
261 $qualifiedforfilter = 1;
263 $testpregmatch =
false;
264 if (is_array($filter)) {
265 $chunks = array_chunk($filter, 500);
266 foreach ($chunks as $chunk) {
267 $testpregmatch = preg_match(
'/'.implode(
'|', $chunk).
'/i', $utf8_file);
268 if ($testpregmatch) {
273 $testpregmatch = preg_match(
'/'.$filter.
'/i', $utf8_file);
275 if ($testpregmatch) {
276 $qualifiedforfilter = 1;
280 if ($qualifiedforfilter) {
281 if (empty($nbsecondsold) || $filedate <= ($now - $nbsecondsold)) {
282 preg_match(
'/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
283 $level1name = (isset($reg[1]) ? $reg[1] :
'');
284 $file_list[] = array(
285 "name" => $utf8_file,
286 "path" => $utf8_path,
287 "level1name" => $level1name,
288 "relativename" => ($relativename ? $relativename.
'/' :
'').$utf8_file,
289 "fullname" => $utf8_fullpathfile,
304 if (!empty($sortcriteria) && $sortorder) {
305 $file_list =
dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ?
'asc' :
'desc'));
308 if ($hookmanager instanceof
HookManager && is_array($hookmanager->resArray)) {
309 $file_list = array_merge($file_list, $hookmanager->resArray);
332function dol_dir_list_in_database($path, $filter =
"", $excludefilter =
null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0, $sqlfilters =
"",
$object =
null)
340 $sql =
"SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,";
341 $sql .=
" date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share";
343 $sql .=
", description";
345 $sql .=
" FROM ".MAIN_DB_PREFIX.
"ecm_files";
347 $sql .=
" WHERE entity = ".((int)
$object->entity);
349 $sql .=
" WHERE entity = ".((int)
$conf->entity);
351 if (preg_match(
'/%$/', $path)) {
352 $sql .=
" AND (filepath LIKE '".$db->escape($path).
"' OR filepath = '".$db->escape(preg_replace(
'/\/%$/',
'', $path)).
"')";
354 $sql .=
" AND filepath = '".$db->escape($path).
"'";
365 $resql = $db->query($sql);
367 $file_list = array();
368 $num = $db->num_rows($resql);
371 $obj = $db->fetch_object($resql);
374 preg_match(
'/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename, $reg);
375 $level1name = (isset($reg[1]) ? $reg[1] :
'');
376 $file_list[] = array(
377 "rowid" => $obj->rowid,
378 "label" => $obj->label,
379 "name" => $obj->filename,
380 "path" => DOL_DATA_ROOT.
'/'.$obj->filepath,
381 "level1name" => $level1name,
382 "fullname" => DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename,
383 "fullpath_orig" => $obj->fullpath_orig,
384 "date_c" => $db->jdate($obj->date_c),
385 "date_m" => $db->jdate($obj->date_m),
387 "keywords" => $obj->keywords,
388 "cover" => $obj->cover,
389 "position" => (
int) $obj->position,
391 "share" => $obj->share,
392 "description" => ($mode ? $obj->description :
'')
400 if (!empty($sortcriteria)) {
402 foreach ($file_list as $key => $row) {
403 $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] :
'');
407 array_multisort($myarray, $sortorder, SORT_REGULAR, $file_list);
430 global
$conf, $db, $user;
439 if ($modulepart ==
'produit' &&
getDolGlobalInt(
'PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
443 if (isModEnabled(
"product")) {
444 $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";
446 $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";
449 $relativedirold = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dirold);
450 $relativedirold = ltrim($relativedirold,
"/\\");
452 $filearrayindatabase = array_merge($filearrayindatabase,
dol_dir_list_in_database($relativedirold,
'',
null,
'name', SORT_ASC));
454 } elseif ($modulepart ==
'ticket') {
455 foreach ($filearray as $key => $val) {
456 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filearray[$key][
'path']);
457 $rel_dir = trim($rel_dir,
"/\\");
458 if ($rel_dir != $relativedir) {
459 $filearrayindatabase = array_merge($filearrayindatabase,
dol_dir_list_in_database($rel_dir,
'',
null,
'name', SORT_ASC));
470 foreach ($filearray as $key => $val) {
471 $tmpfilename = preg_replace(
'/\.noexe$/',
'', $filearray[$key][
'name']);
474 foreach ($filearrayindatabase as $key2 => $val2) {
475 if (($filearrayindatabase[$key2][
'path'] == $filearray[$key][
'path']) && ($filearrayindatabase[$key2][
'name'] == $tmpfilename)) {
476 $filearray[$key][
'position_name'] = ($filearrayindatabase[$key2][
'position'] ? $filearrayindatabase[$key2][
'position'] :
'0').
'_'.$filearrayindatabase[$key2][
'name'];
477 $filearray[$key][
'position'] = $filearrayindatabase[$key2][
'position'];
478 $filearray[$key][
'cover'] = $filearrayindatabase[$key2][
'cover'];
479 $filearray[$key][
'keywords'] = $filearrayindatabase[$key2][
'keywords'];
480 $filearray[$key][
'acl'] = $filearrayindatabase[$key2][
'acl'];
481 $filearray[$key][
'rowid'] = $filearrayindatabase[$key2][
'rowid'];
482 $filearray[$key][
'label'] = $filearrayindatabase[$key2][
'label'];
483 $filearray[$key][
'share'] = $filearrayindatabase[$key2][
'share'];
490 $filearray[$key][
'position'] =
'999999';
491 $filearray[$key][
'cover'] = 0;
492 $filearray[$key][
'acl'] =
'';
493 $filearray[$key][
'share'] = 0;
495 $rel_filename = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filearray[$key][
'fullname']);
497 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filename)) {
498 dol_syslog(
"list_of_documents We found a file called '".$filearray[$key][
'name'].
"' not indexed into database. We add it");
500 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
504 $filename = basename($rel_filename);
505 $rel_dir = dirname($rel_filename);
506 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
507 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
509 $ecmfile->filepath = $rel_dir;
510 $ecmfile->filename = $filename;
511 $ecmfile->label = md5_file(
dol_osencode($filearray[$key][
'fullname']));
512 $ecmfile->fullpath_orig = $filearray[$key][
'fullname'];
513 $ecmfile->gen_or_uploaded =
'unknown';
514 $ecmfile->description =
'';
515 $ecmfile->keywords =
'';
520 $result = $ecmfile->create($user);
524 $filearray[$key][
'rowid'] = $result;
527 $filearray[$key][
'rowid'] = 0;
544 global $sortorder, $sortfield;
546 $sortorder = strtoupper($sortorder);
548 if ($sortorder ==
'ASC') {
556 if ($sortfield ==
'name') {
557 if ($a->name == $b->name) {
560 return ($a->name < $b->name) ? $retup : $retdown;
562 if ($sortfield ==
'date') {
563 if ($a->date == $b->date) {
566 return ($a->date < $b->date) ? $retup : $retdown;
568 if ($sortfield ==
'size') {
569 if ($a->size == $b->size) {
572 return ($a->size < $b->size) ? $retup : $retdown;
588 if (is_dir($newfolder)) {
603 if (!is_readable($dir)) {
606 return (count(scandir($dir)) == 2);
618 return is_file($newpathoffile);
630 return is_link($newpathoffile);
642 return is_writable($newfolderorfile);
655 $prots = array(
'file',
'http',
'https',
'ftp',
'zlib',
'data',
'ssh',
'ssh2',
'ogg',
'expect');
656 return false !== preg_match(
'/^('.implode(
'|', $prots).
'):/i', $uri);
668 if (is_dir($newfolder)) {
669 $handle = opendir($newfolder);
670 $folder_content =
'';
672 while ((gettype($name = readdir($handle)) !=
"boolean")) {
673 $name_array[] = $name;
675 foreach ($name_array as $temp) {
676 $folder_content .= $temp;
681 if ($folder_content ==
"...") {
704 $fp = fopen($newfile,
'r');
711 if ($line !==
false) {
734 return filesize($newpathoffile);
746 return @filemtime($newpathoffile);
758 return fileperms($newpathoffile);
773function dolReplaceInFile($srcfile, $arrayreplacement, $destfile =
'', $newmask =
'0', $indexdatabase = 0, $arrayreplacementisregex = 0)
775 dol_syslog(
"files.lib.php::dolReplaceInFile srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" indexdatabase=".$indexdatabase.
" arrayreplacementisregex=".$arrayreplacementisregex);
777 if (empty($srcfile)) {
780 if (empty($destfile)) {
781 $destfile = $srcfile;
785 $srcfile = preg_replace(
'/\.\.\/?/',
'', $srcfile);
786 $destfile = preg_replace(
'/\.\.\/?/',
'', $destfile);
789 if (($destfile != $srcfile) && $destexists) {
795 dol_syslog(
"files.lib.php::dolReplaceInFile failed to read src file", LOG_WARNING);
799 $tmpdestfile = $destfile.
'.tmp';
804 $newdirdestfile = dirname($newpathofdestfile);
806 if ($destexists && !is_writable($newpathofdestfile)) {
807 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
810 if (!is_writable($newdirdestfile)) {
811 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
818 $content = file_get_contents($newpathofsrcfile);
820 if (empty($arrayreplacementisregex)) {
823 foreach ($arrayreplacement as $key => $value) {
824 $content = preg_replace($key, $value, $content);
828 file_put_contents($newpathoftmpdestfile, $content);
829 dolChmod($newpathoftmpdestfile, $newmask);
832 $moreinfo = array(
'gen_or_uploaded' =>
'unknown');
833 $result =
dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase, $moreinfo);
835 dol_syslog(
"files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
841 if (empty($newmask)) {
842 dol_syslog(
"Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
846 dolChmod($newpathofdestfile, $newmask);
864function dol_copy($srcfile, $destfile, $newmask =
'0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 0)
868 dol_syslog(
"files.lib.php::dol_copy srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
870 if (empty($srcfile) || empty($destfile)) {
875 if (!$overwriteifexists && $destexists) {
881 $newdirdestfile = dirname($newpathofdestfile);
883 if ($destexists && !is_writable($newpathofdestfile)) {
884 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
887 if (!is_writable($newdirdestfile)) {
888 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
893 $testvirusarray = array();
896 if (count($testvirusarray)) {
897 dol_syslog(
"files.lib.php::dol_copy canceled because a virus was found into source file. we ignore the copy request.", LOG_WARNING);
903 $result = @copy($newpathofsrcfile, $newpathofdestfile);
906 dol_syslog(
"files.lib.php::dol_copy failed to copy", LOG_WARNING);
912 if (empty($newmask)) {
913 dol_syslog(
"Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
917 dolChmod($newpathofdestfile, $newmask);
919 if ($result && $indexdatabase) {
921 $rel_filetocopyafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $newpathofdestfile);
922 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetocopyafter)) {
923 $rel_filetocopyafter = preg_replace(
'/^[\\/]/',
'', $rel_filetocopyafter);
926 dol_syslog(
"Try to copy also entries in database for: ".$rel_filetocopyafter, LOG_DEBUG);
927 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
930 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetocopyafter);
931 if ($resultecmtarget > 0) {
932 dol_syslog(
"ECM dest file found, remove it", LOG_DEBUG);
933 $ecmfiletarget->delete($user);
935 dol_syslog(
"ECM dest file not found, create it", LOG_DEBUG);
939 $resultecm = $ecmSrcfile->fetch(0,
'', $srcfile);
943 dol_syslog(
"Fetch src file error", LOG_DEBUG);
947 $filename = basename($rel_filetocopyafter);
948 $rel_dir = dirname($rel_filetocopyafter);
949 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
950 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
952 $ecmfile->filepath = $rel_dir;
953 $ecmfile->filename = $filename;
955 $ecmfile->fullpath_orig = $srcfile;
956 $ecmfile->gen_or_uploaded =
'copy';
957 $ecmfile->description = $ecmSrcfile->description;
958 $ecmfile->keywords = $ecmSrcfile->keywords;
959 $resultecm = $ecmfile->create($user);
960 if ($resultecm < 0) {
964 dol_syslog(
"Create ECM file error", LOG_DEBUG);
968 if ($resultecm > 0) {
976 return (
int) $result;
993function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement =
null, $excludesubdir = 0, $excludefileext =
null, $excludearchivefiles = 0)
997 dol_syslog(
"files.lib.php::dolCopyDir srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
999 if (empty($srcfile) || empty($destfile)) {
1010 $dirmaskdec = octdec($newmask);
1014 $dirmaskdec |= octdec(
'0200');
1016 $result =
dol_mkdir($destfile,
'', decoct($dirmaskdec));
1028 if (is_dir($ossrcfile)) {
1029 $dir_handle = opendir($ossrcfile);
1031 while ($file = readdir($dir_handle)) {
1032 if ($file !=
"." && $file !=
".." && !is_link($ossrcfile.
"/".$file)) {
1033 if (is_dir($ossrcfile.
"/".$file)) {
1034 if (empty($excludesubdir) || ($excludesubdir == 2 && strlen($file) == 2)) {
1037 if (is_array($arrayreplacement)) {
1038 foreach ($arrayreplacement as $key => $val) {
1039 $newfile = str_replace($key, $val, $newfile);
1043 $tmpresult =
dolCopyDir($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir, $excludefileext, $excludearchivefiles);
1048 if (is_array($excludefileext)) {
1049 $extension = pathinfo($file, PATHINFO_EXTENSION);
1050 if (in_array($extension, $excludefileext)) {
1056 if ($excludearchivefiles == 1) {
1057 $extension = pathinfo($file, PATHINFO_EXTENSION);
1058 if (preg_match(
'/^[v|d]\d+$/', $extension)) {
1064 if (is_array($arrayreplacement)) {
1065 foreach ($arrayreplacement as $key => $val) {
1066 $newfile = str_replace($key, $val, $newfile);
1069 $tmpresult =
dol_copy($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists);
1072 if ($result > 0 && $tmpresult >= 0) {
1075 $result = $tmpresult;
1082 closedir($dir_handle);
1088 return (
int) $result;
1110function dol_move($srcfile, $destfile, $newmask =
'0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1, $moreinfo = array(), $entity = 0)
1115 dol_syslog(
"files.lib.php::dol_move srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwritifexists=".$overwriteifexists);
1120 dol_syslog(
"files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
1124 if ($overwriteifexists || !$destexists) {
1129 $testvirusarray = array();
1132 $testvirusarray =
dolCheckVirus($newpathofsrcfile, $newpathofdestfile);
1133 if (count($testvirusarray)) {
1134 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1140 if (count($testvirusarray)) {
1141 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1146 global $dolibarr_main_restrict_os_commands;
1147 if (!empty($dolibarr_main_restrict_os_commands)) {
1148 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
1149 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
1150 if (in_array(basename($destfile), $arrayofallowedcommand)) {
1153 dol_syslog(
"files.lib.php::dol_move canceled because target filename ".basename($destfile).
" is using a reserved command name. we ignore the move request.", LOG_WARNING);
1158 $result = @rename($newpathofsrcfile, $newpathofdestfile);
1161 dol_syslog(
"files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
1164 $result = @rename($newpathofsrcfile, $newpathofdestfile);
1166 dol_syslog(
"files.lib.php::dol_move Failed.", LOG_WARNING);
1171 if ($result && $indexdatabase) {
1173 $rel_filetorenamebefore = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $srcfile);
1174 $rel_filetorenameafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $destfile);
1175 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) {
1176 $rel_filetorenamebefore = preg_replace(
'/^[\\/]/',
'', $rel_filetorenamebefore);
1177 $rel_filetorenameafter = preg_replace(
'/^[\\/]/',
'', $rel_filetorenameafter);
1180 dol_syslog(
"Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore.
" after = ".$rel_filetorenameafter, LOG_DEBUG);
1181 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1183 $ecmfiletarget =
new EcmFiles($db);
1184 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetorenameafter,
'',
'',
'', 0, $entity);
1185 if ($resultecmtarget > 0) {
1186 $ecmfiletarget->delete($user);
1190 $resultecm = $ecmfile->fetch(0,
'', $rel_filetorenamebefore,
'',
'',
'', 0, $entity);
1191 if ($resultecm > 0) {
1192 $filename = basename($rel_filetorenameafter);
1193 $rel_dir = dirname($rel_filetorenameafter);
1194 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1195 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1197 $ecmfile->filepath = $rel_dir;
1198 $ecmfile->filename = $filename;
1200 $resultecm = $ecmfile->update($user);
1201 } elseif ($resultecm == 0) {
1202 $filename = basename($rel_filetorenameafter);
1203 $rel_dir = dirname($rel_filetorenameafter);
1204 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1205 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1207 $ecmfile->filepath = $rel_dir;
1208 $ecmfile->filename = $filename;
1210 $ecmfile->fullpath_orig = basename($srcfile);
1211 if (!empty($moreinfo) && !empty($moreinfo[
'gen_or_uploaded'])) {
1212 $ecmfile->gen_or_uploaded = $moreinfo[
'gen_or_uploaded'];
1214 $ecmfile->gen_or_uploaded =
'unknown';
1216 if (!empty($moreinfo) && !empty($moreinfo[
'description'])) {
1217 $ecmfile->description = $moreinfo[
'description'];
1219 $ecmfile->description =
'';
1221 if (!empty($moreinfo) && !empty($moreinfo[
'keywords'])) {
1222 $ecmfile->keywords = $moreinfo[
'keywords'];
1224 $ecmfile->keywords =
'';
1226 if (!empty($moreinfo) && !empty($moreinfo[
'note_private'])) {
1227 $ecmfile->note_private = $moreinfo[
'note_private'];
1229 if (!empty($moreinfo) && !empty($moreinfo[
'note_public'])) {
1230 $ecmfile->note_public = $moreinfo[
'note_public'];
1232 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_type'])) {
1233 $ecmfile->src_object_type = $moreinfo[
'src_object_type'];
1235 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_id'])) {
1236 $ecmfile->src_object_id = $moreinfo[
'src_object_id'];
1238 if (!empty($moreinfo) && !empty($moreinfo[
'position'])) {
1239 $ecmfile->position = $moreinfo[
'position'];
1241 if (!empty($moreinfo) && !empty($moreinfo[
'cover'])) {
1242 $ecmfile->cover = $moreinfo[
'cover'];
1244 if (! empty($entity)) {
1245 $ecmfile->entity = $entity;
1248 $resultecm = $ecmfile->create($user);
1249 if ($resultecm < 0) {
1252 if (!empty($moreinfo) && !empty($moreinfo[
'array_options']) && is_array($moreinfo[
'array_options'])) {
1253 $ecmfile->array_options = $moreinfo[
'array_options'];
1254 $resultecm = $ecmfile->insertExtraFields();
1255 if ($resultecm < 0) {
1260 } elseif ($resultecm < 0) {
1264 if ($resultecm > 0) {
1272 if (empty($newmask)) {
1279 dolChmod($newpathofdestfile, $newmask);
1295function dol_move_dir($srcdir, $destdir, $overwriteifexists = 1, $indexdatabase = 1, $renamedircontent = 1)
1299 dol_syslog(
"files.lib.php::dol_move_dir srcdir=".$srcdir.
" destdir=".$destdir.
" overwritifexists=".$overwriteifexists.
" indexdatabase=".$indexdatabase.
" renamedircontent=".$renamedircontent);
1301 $srcbasename = basename($srcdir);
1305 dol_syslog(
"files.lib.php::dol_move_dir srcdir does not exists. Move fails");
1309 if ($overwriteifexists || !$destexists) {
1316 if ($overwriteifexists) {
1317 if (strtoupper(substr(PHP_OS, 0, 3)) ===
'WIN') {
1318 if (is_dir($newpathofdestdir)) {
1319 @rmdir($newpathofdestdir);
1324 $result = @rename($newpathofsrcdir, $newpathofdestdir);
1327 if ($result && $renamedircontent) {
1328 if (file_exists($newpathofdestdir)) {
1329 $destbasename = basename($newpathofdestdir);
1331 if (!empty($files) && is_array($files)) {
1332 foreach ($files as $key => $file) {
1333 if (!file_exists($file[
"fullname"])) {
1336 $filepath = $file[
"path"];
1337 $oldname = $file[
"name"];
1339 $newname = str_replace($srcbasename, $destbasename, $oldname);
1340 if (!empty($newname) && $newname !== $oldname) {
1341 if ($file[
"type"] ==
"dir") {
1342 $res =
dol_move_dir($filepath.
'/'.$oldname, $filepath.
'/'.$newname, $overwriteifexists, $indexdatabase, $renamedircontent);
1344 $moreinfo = array(
'gen_or_uploaded' =>
'unknown');
1345 $res =
dol_move($filepath.
'/'.$oldname, $filepath.
'/'.$newname,
'0', $overwriteifexists, 0, $indexdatabase, $moreinfo);
1372 return trim(basename($filename),
".\x00..\x20");
1388 if (!empty($reterrors)) {
1393 if (!class_exists(
'AntiVir')) {
1394 require_once DOL_DOCUMENT_ROOT.
'/core/class/antivir.class.php';
1397 $result = $antivir->dol_avscan_file($src_file);
1399 $reterrors = $antivir->errors;
1415 if (preg_match(
'/\.pdf$/i', $dest_file)) {
1417 dol_syslog(
"dolCheckOnFileName Check that pdf does not contains js code");
1419 $tmp = file_get_contents(trim($src_file));
1420 if (preg_match(
'/[\n\s]+\/JavaScript[\n\s]+/m', $tmp)) {
1421 return array(
'File is a PDF with javascript inside');
1424 dol_syslog(
"dolCheckOnFileName Check js into pdf disabled");
1453function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $keyforsourcefile =
'addedfile', $upload_dir =
'', $mode = 0)
1459 $file_name = $dest_file;
1462 if (empty($nohook)) {
1463 $reshook = $hookmanager->initHooks(array(
'fileslib'));
1465 $parameters = array(
'dest_file' => $dest_file,
'src_file' => $src_file,
'file_name' => $file_name,
'varfiles' => $keyforsourcefile,
'allowoverwrite' => $allowoverwrite);
1466 $reshook = $hookmanager->executeHooks(
'moveUploadedFile', $parameters,
$object);
1469 if (empty($reshook)) {
1471 if ($uploaderrorcode) {
1472 switch ($uploaderrorcode) {
1473 case UPLOAD_ERR_INI_SIZE:
1474 return 'ErrorFileSizeTooLarge';
1475 case UPLOAD_ERR_FORM_SIZE:
1476 return 'ErrorFileSizeTooLarge';
1477 case UPLOAD_ERR_PARTIAL:
1478 return 'ErrorPartialFile';
1479 case UPLOAD_ERR_NO_TMP_DIR:
1480 return 'ErrorNoTmpDir';
1481 case UPLOAD_ERR_CANT_WRITE:
1482 return 'ErrorFailedToWriteInDir';
1483 case UPLOAD_ERR_EXTENSION:
1484 return 'ErrorUploadBlockedByAddon';
1492 if (empty($disablevirusscan) && file_exists($src_file)) {
1494 if (count($checkvirusarray)) {
1495 dol_syslog(
'Files.lib::dol_move_uploaded_file File "'.$src_file.
'" (target name "'.$dest_file.
'") KO with antivirus: errors='.implode(
',', $checkvirusarray), LOG_WARNING);
1496 return 'ErrorFileIsInfectedWithAVirus: '.implode(
',', $checkvirusarray);
1505 $publicmediasdirwithslash =
$conf->medias->multidir_output[
$conf->entity];
1506 if (!preg_match(
'/\/$/', $publicmediasdirwithslash)) {
1507 $publicmediasdirwithslash .=
'/';
1510 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0 || !
getDolGlobalInt(
"MAIN_DOCUMENT_DISABLE_NOEXE_IN_MEDIAS_DIR")) {
1511 $file_name .=
'.noexe';
1518 if (preg_match(
'/^\./', basename($src_file)) || preg_match(
'/\.\./', $src_file) || preg_match(
'/[<>|]/', $src_file)) {
1519 dol_syslog(
"Refused to deliver file ".$src_file, LOG_WARNING);
1525 if (preg_match(
'/^\./', basename($dest_file)) || preg_match(
'/\.\./', $dest_file) || preg_match(
'/[<>|]/', $dest_file)) {
1526 dol_syslog(
"Refused to deliver file ".$dest_file, LOG_WARNING);
1532 $errmsg = implode(
',', $hookmanager->errors);
1533 if (empty($errmsg)) {
1534 $errmsg =
'ErrorReturnedBySomeHooks';
1537 } elseif (empty($reshook)) {
1543 if (!is_writable(dirname($file_name_osencoded))) {
1544 dol_syslog(
"Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded).
" is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1545 return 'ErrorDirNotWritable';
1549 if (!$allowoverwrite) {
1550 if (file_exists($file_name_osencoded)) {
1551 dol_syslog(
"Files.lib::dol_move_uploaded_file File ".$file_name.
" already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1552 return 'ErrorFileAlreadyExists';
1555 if (is_dir($file_name_osencoded)) {
1556 dol_syslog(
"Files.lib::dol_move_uploaded_file A directory with name ".$file_name.
" already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
1557 return 'ErrorDirWithFileNameAlreadyExists';
1563 $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1565 $return = rename($src_file_osencoded, $file_name_osencoded);
1570 dol_syslog(
"Files.lib::dol_move_uploaded_file Success to move ".$src_file.
" to ".$file_name.
" - Umask=" .
getDolGlobalString(
'MAIN_UMASK'), LOG_DEBUG);
1571 return $successcode;
1573 dol_syslog(
"Files.lib::dol_move_uploaded_file Failed to move ".$src_file.
" to ".$file_name, LOG_ERR);
1578 return $successcode;
1596function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0,
$object =
null, $allowdotdot =
false, $indexdatabase = 1, $nolog = 0)
1599 global $hookmanager;
1601 if (empty($nolog)) {
1602 dol_syslog(
"dol_delete_file file=".$file.
" disableglob=".$disableglob.
" nophperrors=".$nophperrors.
" nohook=".$nohook);
1607 if ((!$allowdotdot && preg_match(
'/\.\./', $file)) || preg_match(
'/[<>|]/', $file)) {
1608 dol_syslog(
"Refused to delete file ".$file, LOG_WARNING);
1613 if (empty($nohook) && !empty($hookmanager)) {
1614 $hookmanager->initHooks(array(
'fileslib'));
1616 $parameters = array(
1618 'disableglob' => $disableglob,
1619 'nophperrors' => $nophperrors
1621 $reshook = $hookmanager->executeHooks(
'deleteFile', $parameters,
$object);
1624 if (empty($nohook) && $reshook != 0) {
1632 if (empty($disableglob) && !empty($file_osencoded)) {
1634 $globencoded = str_replace(
'[',
'\[', $file_osencoded);
1635 $globencoded = str_replace(
']',
'\]', $globencoded);
1636 $listofdir = glob($globencoded);
1638 if (!empty($listofdir) && is_array($listofdir)) {
1639 foreach ($listofdir as $filename) {
1641 $ok = @unlink($filename);
1643 $ok = unlink($filename);
1647 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1648 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);
1649 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1652 $ok = @unlink($filename);
1654 $ok = unlink($filename);
1659 if (empty($nolog)) {
1660 dol_syslog(
"Removed file ".$filename, LOG_DEBUG);
1664 $rel_filetodelete = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filename);
1665 if (!preg_match(
'/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) {
1666 if (is_object($db) && $indexdatabase) {
1667 $rel_filetodelete = preg_replace(
'/^[\\/]/',
'', $rel_filetodelete);
1668 $rel_filetodelete = preg_replace(
'/\.noexe$/',
'', $rel_filetodelete);
1670 dol_syslog(
"Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1671 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1673 $result = $ecmfile->fetch(0,
'', $rel_filetodelete,
'',
'',
'', 0,
$object->entity ?? 0);
1674 if ($result >= 0 && $ecmfile->id > 0) {
1675 $result = $ecmfile->delete($user);
1683 dol_syslog(
"Failed to remove file ".$filename, LOG_WARNING);
1690 dol_syslog(
"No files to delete found", LOG_DEBUG);
1695 $ok = @unlink($file_osencoded);
1697 $ok = unlink($file_osencoded);
1700 if (empty($nolog)) {
1701 dol_syslog(
"Removed file ".$file_osencoded, LOG_DEBUG);
1704 dol_syslog(
"Failed to remove file ".$file_osencoded, LOG_WARNING);
1725 if (preg_match(
'/\.\./', $dir) || preg_match(
'/[<>|]/', $dir)) {
1726 dol_syslog(
"Refused to delete dir ".$dir.
' (contains invalid char sequence)', LOG_WARNING);
1731 return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1747function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0, $indexdatabase = 1, $nolog = 0, $level = 0)
1749 if (empty($nolog) || empty($level)) {
1750 dol_syslog(
"functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1752 if ($level > 1000) {
1753 dol_syslog(
"functions.lib:dol_delete_dir_recursive too many depth", LOG_WARNING);
1758 if ($handle = opendir(
"$dir_osencoded")) {
1759 while (
false !== ($item = readdir($handle))) {
1761 $item = mb_convert_encoding($item,
'UTF-8',
'ISO-8859-1');
1764 if ($item !=
"." && $item !=
"..") {
1766 $count =
dol_delete_dir_recursive(
"$dir/$item", $count, $nophperrors, 0, $countdeleted, $indexdatabase, $nolog, ($level + 1));
1768 $result =
dol_delete_file(
"$dir/$item", 1, $nophperrors, 0,
null,
false, $indexdatabase, $nolog);
1780 if (empty($onlysub)) {
1805 global $langs,
$conf;
1810 if (
$object->element ==
'order_supplier') {
1811 $dir =
$conf->fournisseur->commande->dir_output;
1812 } elseif (
$object->element ==
'invoice_supplier') {
1813 $dir =
$conf->fournisseur->facture->dir_output;
1814 } elseif (
$object->element ==
'project') {
1815 $dir =
$conf->project->dir_output;
1816 } elseif (
$object->element ==
'shipping') {
1817 $dir =
$conf->expedition->dir_output.
'/sending';
1818 } elseif (
$object->element ==
'delivery') {
1819 $dir =
$conf->expedition->dir_output.
'/receipt';
1820 } elseif (
$object->element ==
'fichinter') {
1821 $dir =
$conf->ficheinter->dir_output;
1823 $dir = empty(
$conf->$element->dir_output) ?
'' :
$conf->$element->dir_output;
1827 $object->error = $langs->trans(
'ErrorObjectNoSupportedByFunction');
1832 $dir = $dir.
"/".$refsan;
1833 $filepreviewnew = $dir.
"/".$refsan.
".pdf_preview.png";
1834 $filepreviewnewbis = $dir.
"/".$refsan.
".pdf_preview-0.png";
1835 $filepreviewold = $dir.
"/".$refsan.
".pdf.png";
1838 if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
1840 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnew);
1844 if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
1846 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnewbis);
1851 if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
1853 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewold);
1857 $multiple = $filepreviewold.
".";
1858 for ($i = 0; $i < 20; $i++) {
1859 $preview = $multiple.$i;
1861 if (file_exists($preview) && is_writable($preview)) {
1863 $object->error = $langs->trans(
"ErrorFailedToOpenFile", $preview);
1893 if (
$object->element ==
'order_supplier') {
1894 $dir =
$conf->fournisseur->dir_output.
'/commande';
1895 } elseif (
$object->element ==
'invoice_supplier') {
1896 $dir =
$conf->fournisseur->dir_output.
'/facture';
1897 } elseif (
$object->element ==
'project') {
1898 $dir =
$conf->project->dir_output;
1899 } elseif (
$object->element ==
'shipping') {
1900 $dir =
$conf->expedition->dir_output.
'/sending';
1901 } elseif (
$object->element ==
'delivery') {
1902 $dir =
$conf->expedition->dir_output.
'/receipt';
1903 } elseif (
$object->element ==
'fichinter') {
1904 $dir =
$conf->ficheinter->dir_output;
1906 $dir = empty(
$conf->$element->dir_output) ?
'' :
$conf->$element->dir_output;
1913 $dir = $dir.
"/".$objectref;
1914 $file = $dir.
"/".$objectref.
".meta";
1916 if (!is_dir($dir)) {
1923 $nblines = count(
$object->lines);
1928 $meta =
"REFERENCE=\"".$object->ref.
"\"
1930 NB_ITEMS=\"" . $nblines.
"\"
1931 CLIENT=\"" . $client.
"\"
1932 AMOUNT_EXCL_TAX=\"" .
$object->total_ht.
"\"
1933 AMOUNT=\"" .
$object->total_ttc.
"\"\n";
1935 for ($i = 0; $i < $nblines; $i++) {
1937 $meta .=
"ITEM_".$i.
"_QUANTITY=\"".
$object->lines[$i]->qty.
"\"
1938 ITEM_" . $i.
"_AMOUNT_WO_TAX=\"".
$object->lines[$i]->total_ht.
"\"
1939 ITEM_" . $i.
"_VAT=\"".
$object->lines[$i]->tva_tx.
"\"
1940 ITEM_" . $i.
"_DESCRIPTION=\"".str_replace(
"\r\n",
"", nl2br(
$object->lines[$i]->desc)).
"\"
1945 $fp = fopen($file,
"w");
1953 dol_syslog(
'FailedToDetectDirInDolMetaCreateFor'.
$object->element, LOG_WARNING);
1971 $listofpaths = array();
1972 $listofnames = array();
1973 $listofmimes = array();
1977 foreach ($listoffiles as $key => $val) {
1978 $listofpaths[] = $val[
'fullname'];
1979 $listofnames[] = $val[
'name'];
1983 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
1984 $_SESSION[
"listofpaths".$keytoavoidconflict] = implode(
';', $listofpaths);
1985 $_SESSION[
"listofnames".$keytoavoidconflict] = implode(
';', $listofnames);
1986 $_SESSION[
"listofmimes".$keytoavoidconflict] = implode(
';', $listofmimes);
2010function dol_add_file_process($upload_dir, $allowoverwrite = 0, $updatesessionordb = 0, $keyforsourcefile =
'addedfile', $savingdocmask =
'', $link =
null, $trackid =
'', $generatethumbs = 1,
$object =
null, $forceFullTextIndexation =
'', $mode = 0)
2012 global $db, $user,
$conf, $langs;
2018 $_FILES = array($keyforsourcefile => array());
2019 $_FILES[$keyforsourcefile][
'tmp_name'] = $keyforsourcefile;
2020 $_FILES[$keyforsourcefile][
'name'] = $keyforsourcefile;
2024 if (!empty($_FILES[$keyforsourcefile])) {
2025 dol_syslog(
'dol_add_file_process varfiles = '.$keyforsourcefile.
' upload_dir='.$upload_dir.
' allowoverwrite='.$allowoverwrite.
' updatesessionordb='.$updatesessionordb.
' savingdocmask='.$savingdocmask, LOG_DEBUG);
2026 $maxfilesinform =
getDolGlobalInt(
"MAIN_SECURITY_MAX_ATTACHMENT_ON_FORMS", 10);
2027 if (is_array($_FILES[$keyforsourcefile][
"name"]) && count($_FILES[$keyforsourcefile][
"name"]) > $maxfilesinform) {
2028 $langs->load(
"errors");
2029 setEventMessages($langs->trans(
"ErrorTooMuchFileInForm", $maxfilesinform),
null,
"errors");
2037 $TFile = $_FILES[$keyforsourcefile];
2039 if (!is_array($TFile[
'name'])) {
2040 foreach ($TFile as $key => &$val) {
2045 $nbfile = count($TFile[
'name']);
2047 for ($i = 0; $i < $nbfile; $i++) {
2048 if (empty($TFile[
'name'][$i])) {
2053 $destfile = trim($TFile[
'name'][$i]);
2054 $destfull = $upload_dir.
"/".$destfile;
2055 $destfilewithoutext = preg_replace(
'/\.[^\.]+$/',
'', $destfile);
2057 if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
2058 $destfile = trim(preg_replace(
'/__file__/', $TFile[
'name'][$i], $savingdocmask));
2059 $destfull = $upload_dir.
"/".$destfile;
2062 $filenameto = basename($destfile);
2063 if (preg_match(
'/^\./', $filenameto)) {
2064 $langs->load(
"errors");
2065 setEventMessages($langs->trans(
"ErrorFilenameCantStartWithDot", $filenameto),
null,
'errors');
2069 $info = pathinfo($destfull);
2070 $destfull = $info[
'dirname'].
'/'.
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
2071 $info = pathinfo($destfile);
2072 $destfile =
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
2076 if (!empty($fileextensionrestriction)) {
2077 $arrayofregexextension = explode(
",", $fileextensionrestriction);
2079 foreach ($arrayofregexextension as $fileextension) {
2080 if (preg_match(
'/\.'.preg_quote(trim($fileextension),
'/').
'$/i', $destfull)) {
2081 $langs->load(
"errors");
2082 setEventMessages($langs->trans(
"ErrorFilenameExtensionNotAllowed", $filenameto),
null,
'errors');
2094 global $dolibarr_main_restrict_os_commands;
2095 if (!empty($dolibarr_main_restrict_os_commands)) {
2096 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
2097 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
2098 if (in_array($destfile, $arrayofallowedcommand)) {
2099 $langs->load(
"errors");
2100 setEventMessages($langs->trans(
"ErrorFilenameReserved", $destfile),
null,
'errors');
2106 $resupload =
dol_move_uploaded_file($TFile[
'tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile[
'error'][$i], 0, $keyforsourcefile, $upload_dir, $mode);
2108 if (is_numeric($resupload) && $resupload > 0) {
2109 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
2112 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
2113 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
2114 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
2115 $maxheightmini = $tmparraysize[
'maxheightmini'];
2120 if ($generatethumbs) {
2126 $imgThumbSmall =
vignette($destfull, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
2129 $imgThumbMini =
vignette($destfull, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
2134 if (empty($updatesessionordb)) {
2135 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2137 $formmail->trackid = $trackid;
2138 $formmail->add_attached_files($destfull, $destfile, $TFile[
'type'][$i]);
2142 if ($updatesessionordb == 1) {
2144 if ($TFile[
'type'][$i] ==
'application/pdf' && strpos($_SERVER[
"REQUEST_URI"],
'product') !==
false &&
getDolGlobalString(
'PRODUCT_ALLOW_EXTERNAL_DOWNLOAD')) {
2149 if ($allowoverwrite) {
2153 $result =
addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ?
'.noexe' :
''), $TFile[
'name'][$i],
'uploaded', $sharefile,
$object, $forceFullTextIndexation);
2155 if ($allowoverwrite) {
2158 setEventMessages(
'WarningFailedToAddFileIntoDatabaseIndex',
null,
'warnings');
2165 $langs->load(
"errors");
2166 if (is_numeric($resupload) && $resupload < 0) {
2168 } elseif (preg_match(
'/ErrorFileIsInfectedWithAVirus/', $resupload)) {
2169 if (preg_match(
'/File is a PDF with javascript inside/', $resupload)) {
2170 setEventMessages($langs->trans(
"ErrorFileIsAnInfectedPDFWithJSInside"),
null,
'errors');
2184 setEventMessages($langs->trans(
"ErrorFailedToCreateDir", $upload_dir),
null,
'errors');
2187 require_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
2188 $linkObject =
new Link($db);
2189 $linkObject->entity =
$conf->entity;
2190 $linkObject->url = $link;
2191 $linkObject->objecttype =
GETPOST(
'objecttype',
'alpha');
2192 $linkObject->objectid =
GETPOSTINT(
'objectid');
2193 $linkObject->label =
GETPOST(
'label',
'alpha');
2194 $res = $linkObject->create($user);
2202 $langs->load(
"errors");
2203 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"File")),
null,
'errors');
2223 global $db, $user,
$conf, $langs, $_FILES;
2225 $keytodelete = $filenb;
2228 $listofpaths = array();
2229 $listofnames = array();
2230 $listofmimes = array();
2231 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
2232 if (!empty($_SESSION[
"listofpaths".$keytoavoidconflict])) {
2233 $listofpaths = explode(
';', $_SESSION[
"listofpaths".$keytoavoidconflict]);
2235 if (!empty($_SESSION[
"listofnames".$keytoavoidconflict])) {
2236 $listofnames = explode(
';', $_SESSION[
"listofnames".$keytoavoidconflict]);
2238 if (!empty($_SESSION[
"listofmimes".$keytoavoidconflict])) {
2239 $listofmimes = explode(
';', $_SESSION[
"listofmimes".$keytoavoidconflict]);
2242 if ($keytodelete >= 0) {
2243 $pathtodelete = $listofpaths[$keytodelete];
2244 $filetodelete = $listofnames[$keytodelete];
2245 if (empty($donotdeletefile)) {
2251 if (empty($donotdeletefile)) {
2252 $langs->load(
"other");
2253 setEventMessages($langs->trans(
"FileWasRemoved", $filetodelete),
null,
'mesgs');
2255 if (empty($donotupdatesession)) {
2256 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2258 $formmail->trackid = $trackid;
2259 $formmail->remove_attached_files($keytodelete);
2282 global $db, $user,
$conf;
2287 dol_syslog(
"addFileIntoDatabaseIndex dir=".$dir.
" file=".$file, LOG_DEBUG);
2289 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2291 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
2292 $filename = basename(preg_replace(
'/\.noexe$/',
'', $file));
2293 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2294 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2296 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
2298 $ecmfile->filepath = $rel_dir;
2299 $ecmfile->filename = $filename;
2300 $ecmfile->label = md5_file(
dol_osencode($dir.
'/'.$file));
2301 $ecmfile->fullpath_orig = $fullpathorig;
2302 $ecmfile->gen_or_uploaded = $mode;
2303 $ecmfile->description =
'';
2304 $ecmfile->keywords =
'';
2307 $ecmfile->src_object_id =
$object->id;
2308 if (isset(
$object->table_element)) {
2309 $ecmfile->src_object_type =
$object->table_element;
2311 dol_syslog(
'Error: object ' . get_class(
$object) .
' has no table_element attribute.');
2314 if (isset(
$object->src_object_description)) {
2315 $ecmfile->description =
$object->src_object_description;
2317 if (isset(
$object->src_object_keywords)) {
2318 $ecmfile->keywords =
$object->src_object_keywords;
2321 $ecmfile->entity =
$object->entity;
2330 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
2336 if (empty($useFullTextIndexation) && $forceFullTextIndexation ==
'1') {
2338 $useFullTextIndexation =
'pdftotext';
2340 $useFullTextIndexation =
'docling';
2345 if ($useFullTextIndexation) {
2346 $ecmfile->filepath = $rel_dir;
2347 $ecmfile->filename = $filename;
2349 $filetoprocess = $dir.
'/'.$ecmfile->filename;
2351 $textforfulltextindex =
'';
2354 if (preg_match(
'/\.pdf/i', $filename)) {
2360 if (preg_match(
'/pdftotext/i', $useFullTextIndexation)) {
2361 include_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
2362 $utils =
new Utils($db);
2363 $outputfile =
$conf->admin->dir_temp.
'/tmppdftotext.'.$user->id.
'.out';
2367 $cmd =
getDolGlobalString(
'MAIN_SAVE_FILE_CONTENT_AS_TEXT_PDFTOTEXT',
'pdftotext').
" -htmlmeta '".escapeshellcmd($filetoprocess).
"' - ";
2368 $resultexec = $utils->executeCLI($cmd, $outputfile, 0,
null, 1);
2370 if (!$resultexec[
'error']) {
2371 $txt = $resultexec[
'output'];
2373 if (preg_match(
'/<meta name="Keywords" content="([^\/]+)"\s*\/>/i', $txt, $matches)) {
2374 $keywords = $matches[1];
2376 if (preg_match(
'/<pre>(.*)<\/pre>/si', $txt, $matches)) {
2386 if (preg_match(
'/docling/i', $useFullTextIndexation)) {
2387 include_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
2388 $utils =
new Utils($db);
2389 $outputfile =
$conf->admin->dir_temp.
'/tmpdocling.'.$user->id.
'.out';
2393 $cmd =
getDolGlobalString(
'MAIN_SAVE_FILE_CONTENT_AS_TEXT_DOCLING',
'docling').
" --from pdf --to text '".escapeshellcmd($filetoprocess).
"'";
2394 $resultexec = $utils->executeCLI($cmd, $outputfile, 0,
null, 1);
2396 if (!$resultexec[
'error']) {
2397 $txt = $resultexec[
'output'];
2405 $textforfulltextindex = $txt;
2414 $ecmfile->description =
'File content generated by '.$cmd;
2416 $ecmfile->content = $textforfulltextindex;
2417 $ecmfile->keywords = $keywords;
2421 $result = $ecmfile->create($user);
2447 dol_syslog(
"deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
2451 dol_syslog(
"deleteFilesIntoDatabaseIndex dir=".$dir.
" file=".$file, LOG_DEBUG);
2455 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2457 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
2458 $filename = basename($file);
2459 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2460 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2463 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'ecm_files';
2465 $sql .=
' WHERE entity = ' . ((int)
$object->entity);
2467 $sql .=
' WHERE entity = ' . ((int)
$conf->entity);
2469 $sql .=
" AND filepath = '".$db->escape($rel_dir).
"'";
2471 $sql .=
" AND filename = '".$db->escape($file).
"'";
2474 $sql .=
" AND gen_or_uploaded = '".$db->escape($mode).
"'";
2477 $resql = $db->query($sql);
2480 dol_syslog(__FUNCTION__.
' '.$db->lasterror(), LOG_ERR);
2509 if (class_exists(
'Imagick')) {
2510 $image =
new Imagick();
2512 $filetoconvert = $fileinput.(($page !=
'') ?
'['.$page.
']' :
'');
2514 $ret = $image->readImage($filetoconvert);
2516 $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
2517 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.
" conversion in /etc/ImageMagick*/policy.xml): ".$e->getMessage(), LOG_WARNING);
2521 $ret = $image->setImageFormat($ext);
2523 if (empty($fileoutput)) {
2524 $fileoutput = $fileinput.
".".$ext;
2527 $count = $image->getNumberImages();
2529 if (!
dol_is_file($fileoutput) || is_writable($fileoutput)) {
2531 $ret = $image->writeImages($fileoutput,
true);
2536 dol_syslog(
"Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
2566function dol_compress_file($inputfile, $outputfile, $mode =
"gz", &$errorstring =
null)
2572 dol_syslog(
"dol_compress_file mode=".$mode.
" inputfile=".$inputfile.
" outputfile=".$outputfile);
2575 $compressdata =
null;
2576 if ($mode ==
'gz' && function_exists(
'gzencode')) {
2578 $compressdata = gzencode($data, 9);
2579 } elseif ($mode ==
'bz' && function_exists(
'bzcompress')) {
2581 $compressdata = bzcompress($data, 9);
2582 } elseif ($mode ==
'zstd' && function_exists(
'zstd_compress')) {
2584 $compressdata = zstd_compress($data, 9);
2585 } elseif ($mode ==
'zip') {
2586 if (class_exists(
'ZipArchive') &&
getDolGlobalString(
'MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS')) {
2589 $rootPath = realpath($inputfile);
2591 dol_syslog(
"Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.
' rootPath='.$rootPath);
2592 $zip =
new ZipArchive();
2594 if ($zip->open($outputfile, ZipArchive::CREATE) !==
true) {
2595 $errorstring =
"dol_compress_file failure - Failed to open file ".$outputfile.
"\n";
2599 $errormsg = $errorstring;
2606 $files =
new RecursiveIteratorIterator(
2607 new RecursiveDirectoryIterator($rootPath, FilesystemIterator::UNIX_PATHS),
2608 RecursiveIteratorIterator::LEAVES_ONLY
2610 '@phan-var-force SplFileInfo[] $files';
2612 foreach ($files as $name => $file) {
2614 if (!$file->isDir()) {
2616 $filePath = $file->getPath();
2617 $fileName = $file->getFilename();
2618 $fileFullRealPath = $file->getRealPath();
2621 $relativePath = substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($rootPath) + 1);
2624 $zip->addFile($fileFullRealPath, $relativePath);
2631 dol_syslog(
"dol_compress_file success - ".$zip->numFiles.
" files");
2635 if (defined(
'ODTPHP_PATHTOPCLZIP')) {
2638 include_once ODTPHP_PATHTOPCLZIP.
'pclzip.lib.php';
2639 $archive =
new PclZip($outputfile);
2641 $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2643 if ($result === 0) {
2645 $errormsg = $archive->errorInfo(
true);
2647 if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
2648 $errorstring =
"PCLZIP_ERR_WRITE_OPEN_FAIL";
2649 dol_syslog(
"dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
2653 $errorstring =
"dol_compress_file error archive->errorCode = ".$archive->errorCode().
" errormsg=".$errormsg;
2654 dol_syslog(
"dol_compress_file failure - ".$errormsg, LOG_ERR);
2657 dol_syslog(
"dol_compress_file success - ".count($result).
" files");
2663 if ($foundhandler && is_string($compressdata)) {
2664 $fp = fopen($outputfile,
"w");
2665 fwrite($fp, $compressdata);
2669 $errorstring =
"Try to zip with format ".$mode.
" with no handler for this format";
2673 $errormsg = $errorstring;
2677 global $langs, $errormsg;
2678 $langs->load(
"errors");
2679 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
2681 $errorstring =
"Failed to open file ".$outputfile;
2699 $fileinfo = pathinfo($inputfile);
2700 $fileinfo[
"extension"] = strtolower($fileinfo[
"extension"]);
2702 if ($fileinfo[
"extension"] ==
"zip") {
2703 if (defined(
'ODTPHP_PATHTOPCLZIP') && !
getDolGlobalString(
'MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS')) {
2704 dol_syslog(
"Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.
", so we use Pclzip to unzip into ".$outputdir);
2705 include_once ODTPHP_PATHTOPCLZIP.
'pclzip.lib.php';
2706 $archive =
new PclZip($inputfile);
2713 $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG,
'/^((?!\.\.).)*$/');
2715 return array(
'error' => $e->getMessage());
2718 if (!is_array($result) && $result <= 0) {
2719 return array(
'error' => $archive->errorInfo(
true));
2724 foreach ($result as $key => $val) {
2725 if ($val[
'status'] ==
'path_creation_fail') {
2726 $langs->load(
"errors");
2728 $errmsg = $langs->trans(
"ErrorFailToCreateDir", $val[
'filename']);
2731 if ($val[
'status'] ==
'write_protected') {
2732 $langs->load(
"errors");
2734 $errmsg = $langs->trans(
"ErrorFailToCreateFile", $val[
'filename']);
2742 return array(
'error' => $errmsg);
2747 if (class_exists(
'ZipArchive')) {
2748 dol_syslog(
"Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
2749 $zip =
new ZipArchive();
2750 $res = $zip->open($inputfile);
2751 if ($res ===
true) {
2757 for ($i = 0; $i < $zip->numFiles; $i++) {
2758 if (preg_match(
'/\.\./', $zip->getNameIndex($i))) {
2759 dol_syslog(
"Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
2762 $zip->extractTo($outputdir.
'/', array($zip->getNameIndex($i)));
2768 return array(
'error' =>
'ErrUnzipFails');
2772 return array(
'error' =>
'ErrNoZipEngine');
2773 } elseif (in_array($fileinfo[
"extension"], array(
'gz',
'bz2',
'zst'))) {
2774 include_once DOL_DOCUMENT_ROOT.
"/core/class/utils.class.php";
2775 $utils =
new Utils($db);
2782 $extension = strtolower(pathinfo($fileinfo[
"filename"], PATHINFO_EXTENSION));
2783 if ($extension ==
"tar") {
2786 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0, $outputfilename.
'.err', 0);
2787 if ($resarray[
"result"] != 0) {
2788 $resarray[
"error"] .= file_get_contents($outputfilename.
'.err');
2792 if ($fileinfo[
"extension"] ==
"gz") {
2794 } elseif ($fileinfo[
"extension"] ==
"bz2") {
2796 } elseif ($fileinfo[
"extension"] ==
"zst") {
2799 return array(
'error' =>
'ErrorBadFileExtension');
2802 $cmd .=
' > '.$outputfilename;
2804 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0,
null, 1, $outputfilename.
'.err');
2805 if ($resarray[
"result"] != 0) {
2806 $errfilecontent = @file_get_contents($outputfilename.
'.err');
2807 if ($errfilecontent) {
2808 $resarray[
"error"] .=
" - ".$errfilecontent;
2812 return $resarray[
"result"] != 0 ? array(
'error' => $resarray[
"error"]) : array();
2815 return array(
'error' =>
'ErrorBadFileExtension');
2831function dol_compress_dir($inputdir, $outputfile, $mode =
"zip", $excludefiles =
'', $rootdirinzip =
'', $newmask =
'0')
2835 dol_syslog(
"Try to zip dir ".$inputdir.
" into ".$outputfile.
" mode=".$mode);
2837 if (!
dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
2838 global $langs, $errormsg;
2839 $langs->load(
"errors");
2840 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir", $outputfile);
2845 if ($mode ==
'gz') {
2847 } elseif ($mode ==
'bz') {
2849 } elseif ($mode ==
'zip') {
2863 if (class_exists(
'ZipArchive')) {
2867 $zip =
new ZipArchive();
2868 $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2869 if ($result !==
true) {
2870 global $langs, $errormsg;
2871 $langs->load(
"errors");
2872 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile);
2879 $files =
new RecursiveIteratorIterator(
2880 new RecursiveDirectoryIterator($inputdir, FilesystemIterator::UNIX_PATHS),
2881 RecursiveIteratorIterator::LEAVES_ONLY
2883 '@phan-var-force SplFileInfo[] $files';
2886 foreach ($files as $name => $file) {
2888 if (!$file->isDir()) {
2890 $filePath = $file->getPath();
2891 $fileName = $file->getFilename();
2892 $fileFullRealPath = $file->getRealPath();
2895 $relativePath = ($rootdirinzip ? $rootdirinzip.
'/' :
'').substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($inputdir) + 1);
2898 if (empty($excludefiles) || !preg_match($excludefiles, $fileFullRealPath)) {
2900 $zip->addFile($fileFullRealPath, $relativePath);
2911 if (empty($newmask)) {
2912 dol_syslog(
"Warning: dol_compress_dir called with empty value for newmask and no default value defined", LOG_WARNING);
2922 if (!$foundhandler) {
2923 dol_syslog(
"Try to zip with format ".$mode.
" with no handler for this format", LOG_ERR);
2929 global $langs, $errormsg;
2930 $langs->load(
"errors");
2931 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
2933 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile).
' - '.$e->getMessage();
2950function dol_most_recent_file($dir, $regexfilter =
'', $excludefilter = array(
'(\.meta|_preview.*\.png)$',
'^\.'), $nohook = 0, $mode = 0)
2952 $tmparray =
dol_dir_list($dir,
'files', 0, $regexfilter, $excludefilter,
'date', SORT_DESC, $mode, $nohook);
2953 return isset($tmparray[0]) ? $tmparray[0] :
null;
2971 global
$conf, $db, $user, $hookmanager;
2972 global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2975 if (!is_object($fuser)) {
2979 if (empty($modulepart)) {
2980 return 'ErrorBadParameter';
2982 if (empty($entity)) {
2983 if (!isModEnabled(
'multicompany')) {
2990 if ($modulepart ==
'facture') {
2991 $modulepart =
'invoice';
2992 } elseif ($modulepart ==
'users') {
2993 $modulepart =
'user';
2994 } elseif ($modulepart ==
'tva') {
2995 $modulepart =
'tax-vat';
2996 } elseif ($modulepart ==
'expedition' && strpos($original_file,
'receipt/') === 0) {
2998 $modulepart =
'delivery';
2999 } elseif ($modulepart ==
'propale') {
3000 $modulepart =
'propal';
3004 dol_syslog(
'dol_check_secure_access_document modulepart='.$modulepart.
' original_file='.$original_file.
' entity='.$entity);
3008 $sqlprotectagainstexternals =
'';
3012 if (empty($refname)) {
3013 $refname = basename(dirname($original_file).
"/");
3014 if ($refname ==
'thumbs' || $refname ==
'temp') {
3016 $refname = basename(dirname(dirname($original_file)).
"/");
3023 $download =
'download';
3024 if ($mode ==
'write') {
3027 $download =
'upload';
3031 if ($modulepart ==
'common') {
3034 $original_file = DOL_DOCUMENT_ROOT.
'/public/theme/common/'.$original_file;
3035 } elseif ($modulepart ==
'medias' && !empty($dolibarr_main_data_root)) {
3040 if (empty($entity)) {
3044 $original_file = (empty(
$conf->medias->multidir_output[$entity]) ? (empty(
$conf->medias->dir_output) ? DOL_DATA_ROOT.
'/medias' :
$conf->medias->dir_output) :
$conf->medias->multidir_output[$entity]).
'/'.$original_file;
3045 } elseif ($modulepart ==
'logs' && !empty($dolibarr_main_data_root)) {
3047 $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match(
'/^dolibarr.*\.(log|json)$/', basename($original_file)));
3048 $original_file = $dolibarr_main_data_root.
'/'.$original_file;
3049 } elseif ($modulepart ==
'doctemplates' && !empty($dolibarr_main_data_root)) {
3050 $accessallowed = $user->admin;
3051 $relative_file = $original_file;
3052 $ent = ($entity > 0 ? $entity :
$conf->entity);
3053 $path_with_entity = $dolibarr_main_data_root .
'/' . $ent .
'/doctemplates/' . $relative_file;
3054 if ($ent > 1 && file_exists(
dol_osencode($path_with_entity))) {
3055 $original_file = $path_with_entity;
3057 $original_file = $dolibarr_main_data_root .
'/doctemplates/' . $relative_file;
3059 } elseif ($modulepart ==
'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
3061 $accessallowed = ($fuser->hasRight(
'website',
'write') && preg_match(
'/\.jpg$/i', basename($original_file)));
3062 $original_file = $dolibarr_main_data_root.
'/doctemplates/websites/'.$original_file;
3063 } elseif ($modulepart ==
'packages' && !empty($dolibarr_main_data_root)) {
3066 $tmp = explode(
',', $dolibarr_main_document_root_alt);
3069 $accessallowed = ($user->admin && preg_match(
'/^module_.*\.zip$/', basename($original_file)));
3070 $original_file = $dirins.
'/'.$original_file;
3071 } elseif ($modulepart ==
'mycompany' && !empty(
$conf->mycompany->dir_output)) {
3074 $original_file =
$conf->mycompany->dir_output.
'/'.$original_file;
3075 } elseif ($modulepart ==
'userphoto' && !empty(
$conf->user->dir_output)) {
3078 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
3081 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3082 } elseif ($modulepart ==
'userphotopublic' && !empty(
$conf->user->dir_output)) {
3087 if (preg_match(
'/^(\d+)\/photos\//', $original_file, $reg)) {
3088 if ((
int) $reg[1]) {
3089 $tmpobject =
new User($db);
3090 $tmpobject->fetch((
int) $reg[1],
'',
'', 1);
3092 $securekey =
GETPOST(
'securekey',
'alpha', 1);
3094 global $dolibarr_main_cookie_cryptkey, $dolibarr_main_instance_unique_id;
3095 $valuetouse = $dolibarr_main_instance_unique_id ? $dolibarr_main_instance_unique_id : $dolibarr_main_cookie_cryptkey;
3096 $encodedsecurekey =
dol_hash($valuetouse.
'uservirtualcard'.$tmpobject->id.
'-'.$tmpobject->login,
'md5');
3097 if ($encodedsecurekey == $securekey) {
3106 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3107 } elseif (($modulepart ==
'companylogo') && !empty(
$conf->mycompany->dir_output)) {
3110 $original_file =
$conf->mycompany->dir_output.
'/logos/'.$original_file;
3111 } elseif ($modulepart ==
'memberphoto' && !empty(
$conf->member->dir_output)) {
3115 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
3119 if (preg_match(
'/^MEM\d\d\d\d-\d\d\d\d\/photos\//', $original_file)) {
3122 $original_file =
$conf->member->dir_output.
'/'.$original_file;
3123 } elseif ($modulepart ==
'apercufacture' && !empty(
$conf->invoice->multidir_output[$entity])) {
3125 if ($fuser->hasRight(
'facture', $lire)) {
3128 $original_file =
$conf->invoice->multidir_output[$entity].
'/'.$original_file;
3129 } elseif ($modulepart ==
'apercupropal' && !empty(
$conf->propal->multidir_output[$entity])) {
3131 if ($fuser->hasRight(
'propal', $lire)) {
3134 $original_file =
$conf->propal->multidir_output[$entity].
'/'.$original_file;
3135 } elseif ($modulepart ==
'apercucommande' && !empty(
$conf->order->multidir_output[$entity])) {
3137 if ($fuser->hasRight(
'commande', $lire)) {
3140 $original_file =
$conf->order->multidir_output[$entity].
'/'.$original_file;
3141 } elseif (($modulepart ==
'apercufichinter' || $modulepart ==
'apercuficheinter') && !empty(
$conf->ficheinter->dir_output)) {
3143 if ($fuser->hasRight(
'ficheinter', $lire)) {
3146 $original_file =
$conf->ficheinter->dir_output.
'/'.$original_file;
3147 } elseif (($modulepart ==
'apercucontract') && !empty(
$conf->contract->multidir_output[$entity])) {
3149 if ($fuser->hasRight(
'contrat', $lire)) {
3152 $original_file =
$conf->contract->multidir_output[$entity].
'/'.$original_file;
3153 } elseif (($modulepart ==
'apercusupplier_proposal') && !empty(
$conf->supplier_proposal->dir_output)) {
3155 if ($fuser->hasRight(
'supplier_proposal', $lire)) {
3158 $original_file =
$conf->supplier_proposal->dir_output.
'/'.$original_file;
3159 } elseif (($modulepart ==
'apercusupplier_order') && !empty(
$conf->fournisseur->commande->dir_output)) {
3161 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
3164 $original_file =
$conf->fournisseur->commande->dir_output.
'/'.$original_file;
3165 } elseif (($modulepart ==
'apercusupplier_invoice') && !empty(
$conf->fournisseur->facture->dir_output)) {
3167 if ($fuser->hasRight(
'fournisseur', $lire)) {
3170 $original_file =
$conf->fournisseur->facture->dir_output.
'/'.$original_file;
3171 } elseif (($modulepart ==
'holiday') && !empty(
$conf->holiday->dir_output)) {
3172 if ($fuser->hasRight(
'holiday', $read) || $fuser->hasRight(
'holiday',
'readall') || preg_match(
'/^specimen/i', $original_file)) {
3175 if ($refname && !$fuser->hasRight(
'holiday',
'readall') && !preg_match(
'/^specimen/i', $original_file)) {
3176 include_once DOL_DOCUMENT_ROOT.
'/holiday/class/holiday.class.php';
3177 $tmpholiday =
new Holiday($db);
3178 $tmpholiday->fetch(0, $refname);
3179 $accessallowed =
checkUserAccessToObject($user, array(
'holiday'), $tmpholiday,
'holiday',
'',
'',
'rowid',
'');
3182 $original_file =
$conf->holiday->dir_output.
'/'.$original_file;
3183 } elseif (($modulepart ==
'expensereport') && !empty(
$conf->expensereport->dir_output)) {
3184 if ($fuser->hasRight(
'expensereport', $lire) || $fuser->hasRight(
'expensereport',
'readall') || preg_match(
'/^specimen/i', $original_file)) {
3187 if ($refname && !$fuser->hasRight(
'expensereport',
'readall') && !preg_match(
'/^specimen/i', $original_file)) {
3188 include_once DOL_DOCUMENT_ROOT.
'/expensereport/class/expensereport.class.php';
3190 $tmpexpensereport->fetch(0, $refname);
3191 $accessallowed =
checkUserAccessToObject($user, array(
'expensereport'), $tmpexpensereport,
'expensereport',
'',
'',
'rowid',
'');
3194 $original_file =
$conf->expensereport->dir_output.
'/'.$original_file;
3195 } elseif (($modulepart ==
'apercuexpensereport') && !empty(
$conf->expensereport->dir_output)) {
3197 if ($fuser->hasRight(
'expensereport', $lire)) {
3200 $original_file =
$conf->expensereport->dir_output.
'/'.$original_file;
3201 } elseif ($modulepart ==
'propalstats' && !empty(
$conf->propal->multidir_temp[$entity])) {
3203 if ($fuser->hasRight(
'propal', $lire)) {
3206 $original_file =
$conf->propal->multidir_temp[$entity].
'/'.$original_file;
3207 } elseif ($modulepart ==
'orderstats' && !empty(
$conf->order->dir_temp)) {
3209 if ($fuser->hasRight(
'commande', $lire)) {
3212 $original_file =
$conf->order->dir_temp.
'/'.$original_file;
3213 } elseif ($modulepart ==
'orderstatssupplier' && !empty(
$conf->fournisseur->dir_output)) {
3214 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
3217 $original_file =
$conf->fournisseur->commande->dir_temp.
'/'.$original_file;
3218 } elseif ($modulepart ==
'billstats' && !empty(
$conf->invoice->dir_temp)) {
3220 if ($fuser->hasRight(
'facture', $lire)) {
3223 $original_file =
$conf->invoice->dir_temp.
'/'.$original_file;
3224 } elseif ($modulepart ==
'billstatssupplier' && !empty(
$conf->fournisseur->dir_output)) {
3225 if ($fuser->hasRight(
'fournisseur',
'facture', $lire)) {
3228 $original_file =
$conf->fournisseur->facture->dir_temp.
'/'.$original_file;
3229 } elseif ($modulepart ==
'expeditionstats' && !empty(
$conf->expedition->dir_temp)) {
3231 if ($fuser->hasRight(
'expedition', $lire)) {
3234 $original_file =
$conf->expedition->dir_temp.
'/'.$original_file;
3235 } elseif ($modulepart ==
'tripsexpensesstats' && !empty(
$conf->deplacement->dir_temp)) {
3237 if ($fuser->hasRight(
'deplacement', $lire)) {
3240 $original_file =
$conf->deplacement->dir_temp.
'/'.$original_file;
3241 } elseif ($modulepart ==
'memberstats' && !empty(
$conf->member->dir_temp)) {
3243 if ($fuser->hasRight(
'adherent', $lire)) {
3246 $original_file =
$conf->member->dir_temp.
'/'.$original_file;
3247 } elseif (preg_match(
'/^productstats_/i', $modulepart) && !empty(
$conf->product->dir_temp)) {
3249 if ($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) {
3252 $original_file = (!empty(
$conf->product->multidir_temp[$entity]) ?
$conf->product->multidir_temp[$entity] :
$conf->service->multidir_temp[$entity]).
'/'.$original_file;
3253 } elseif (in_array($modulepart, array(
'tax',
'tax-vat',
'tva')) && !empty(
$conf->tax->dir_output)) {
3255 if ($fuser->hasRight(
'tax',
'charges', $lire)) {
3258 $modulepartsuffix = str_replace(
'tax-',
'', $modulepart);
3259 $original_file =
$conf->tax->dir_output.
'/'.($modulepartsuffix !=
'tax' ? $modulepartsuffix.
'/' :
'').$original_file;
3260 } elseif ($modulepart ==
'actions' && !empty(
$conf->agenda->dir_output)) {
3262 if ($fuser->hasRight(
'agenda',
'myactions', $read)) {
3265 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3266 include_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
3268 $tmpobject->fetch((
int) $refname);
3269 $accessallowed =
checkUserAccessToObject($user, array(
'agenda'), $tmpobject->id,
'actioncomm&societe',
'myactions|allactions',
'fk_soc',
'id',
'');
3270 if ($user->socid && $tmpobject->socid) {
3275 $original_file =
$conf->agenda->dir_output.
'/'.$original_file;
3276 } elseif ($modulepart ==
'category' && !empty(
$conf->categorie->multidir_output[$entity])) {
3278 if (empty($entity) || empty(
$conf->categorie->multidir_output[$entity])) {
3279 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3281 if ($fuser->hasRight(
"categorie", $lire) || $fuser->hasRight(
"takepos",
"run")) {
3284 $original_file =
$conf->categorie->multidir_output[$entity].
'/'.$original_file;
3285 } elseif ($modulepart ==
'prelevement' && !empty(
$conf->prelevement->dir_output)) {
3287 if ($fuser->hasRight(
'prelevement',
'bons', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3290 $original_file =
$conf->prelevement->dir_output.
'/'.$original_file;
3291 } elseif ($modulepart ==
'graph_stock' && !empty(
$conf->stock->dir_temp)) {
3294 $original_file =
$conf->stock->dir_temp.
'/'.$original_file;
3295 } elseif ($modulepart ==
'graph_fourn' && !empty(
$conf->fournisseur->dir_temp)) {
3298 $original_file =
$conf->fournisseur->dir_temp.
'/'.$original_file;
3299 } elseif ($modulepart ==
'graph_product' && !empty(
$conf->product->dir_temp)) {
3302 $original_file =
$conf->product->multidir_temp[$entity].
'/'.$original_file;
3303 } elseif ($modulepart ==
'barcode') {
3308 $original_file =
'';
3309 } elseif ($modulepart ==
'iconmailing' && !empty(
$conf->mailing->dir_temp)) {
3312 $original_file =
$conf->mailing->dir_temp.
'/'.$original_file;
3313 } elseif ($modulepart ==
'scanner_user_temp' && !empty(
$conf->scanner->dir_temp)) {
3316 $original_file =
$conf->scanner->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3317 } elseif ($modulepart ==
'fckeditor' && !empty(
$conf->fckeditor->dir_output)) {
3320 $original_file =
$conf->fckeditor->dir_output.
'/'.$original_file;
3321 } elseif ($modulepart ==
'user' && !empty(
$conf->user->dir_output)) {
3323 $canreaduser = (!empty($fuser->admin) || $fuser->hasRight(
'user',
'user', $lire));
3324 if ($fuser->id == (
int) $refname) {
3327 if ($canreaduser || preg_match(
'/^specimen/i', $original_file)) {
3330 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3331 } elseif (($modulepart ==
'company' || $modulepart ==
'societe' || $modulepart ==
'thirdparty') && !empty(
$conf->societe->multidir_output[$entity])) {
3333 if (empty($entity) || empty(
$conf->societe->multidir_output[$entity])) {
3334 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3336 if ($fuser->hasRight(
'societe', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3339 $original_file =
$conf->societe->multidir_output[$entity].
'/'.$original_file;
3340 $sqlprotectagainstexternals =
"SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX.
"societe WHERE rowid='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'societe').
")";
3341 } elseif ($modulepart ==
'contact' && !empty(
$conf->societe->multidir_output[$entity])) {
3343 if (empty($entity) || empty(
$conf->societe->multidir_output[$entity])) {
3344 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3346 if ($fuser->hasRight(
'societe', $lire)) {
3349 $original_file =
$conf->societe->multidir_output[$entity].
'/contact/'.$original_file;
3350 } elseif (($modulepart ==
'facture' || $modulepart ==
'invoice') && !empty(
$conf->invoice->multidir_output[$entity])) {
3352 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3355 $original_file =
$conf->invoice->multidir_output[$entity].
'/'.$original_file;
3356 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'invoice').
")";
3357 } elseif ($modulepart ==
'massfilesarea_proposals' && !empty(
$conf->propal->multidir_output[$entity])) {
3359 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3362 $original_file =
$conf->propal->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3363 } elseif ($modulepart ==
'massfilesarea_orders') {
3364 if ($fuser->hasRight(
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3367 $original_file =
$conf->order->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3368 } elseif ($modulepart ==
'massfilesarea_sendings') {
3369 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3372 $original_file =
$conf->expedition->dir_output.
'/sending/temp/massgeneration/'.$user->id.
'/'.$original_file;
3373 } elseif ($modulepart ==
'massfilesarea_receipts') {
3374 if ($fuser->hasRight(
'reception', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3377 $original_file =
$conf->reception->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3378 } elseif ($modulepart ==
'massfilesarea_invoices') {
3379 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3382 $original_file =
$conf->invoice->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3383 } elseif ($modulepart ==
'massfilesarea_expensereport') {
3384 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3387 $original_file =
$conf->expensereport->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3388 } elseif ($modulepart ==
'massfilesarea_interventions') {
3389 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3392 $original_file =
$conf->ficheinter->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3393 } elseif ($modulepart ==
'massfilesarea_supplier_proposal' && !empty(
$conf->supplier_proposal->dir_output)) {
3394 if ($fuser->hasRight(
'supplier_proposal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3397 $original_file =
$conf->supplier_proposal->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3398 } elseif ($modulepart ==
'massfilesarea_supplier_order') {
3399 if ($fuser->hasRight(
'fournisseur',
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3402 $original_file =
$conf->fournisseur->commande->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3403 } elseif ($modulepart ==
'massfilesarea_supplier_invoice') {
3404 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3407 $original_file =
$conf->fournisseur->facture->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3408 } elseif ($modulepart ==
'massfilesarea_contract' && !empty(
$conf->contract->dir_output)) {
3409 if ($fuser->hasRight(
'contrat', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3412 $original_file =
$conf->contract->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3413 } elseif (($modulepart ==
'fichinter' || $modulepart ==
'ficheinter') && !empty(
$conf->ficheinter->dir_output)) {
3415 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3418 $original_file =
$conf->ficheinter->dir_output.
'/'.$original_file;
3419 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"fichinter WHERE ref='".$db->escape($refname).
"' AND entity=".
$conf->entity;
3420 } elseif ($modulepart ==
'deplacement' && !empty(
$conf->deplacement->dir_output)) {
3422 if ($fuser->hasRight(
'deplacement', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3425 $original_file =
$conf->deplacement->dir_output.
'/'.$original_file;
3427 } elseif (($modulepart ==
'propal' || $modulepart ==
'propale') && isset(
$conf->propal->multidir_output[$entity])) {
3429 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3432 $original_file =
$conf->propal->multidir_output[$entity].
'/'.$original_file;
3433 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"propal WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'propal').
")";
3434 } elseif (($modulepart ==
'commande' || $modulepart ==
'order') && !empty(
$conf->order->multidir_output[$entity])) {
3436 if ($fuser->hasRight(
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3439 $original_file =
$conf->order->multidir_output[$entity].
'/'.$original_file;
3440 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'order').
")";
3441 } elseif ($modulepart ==
'project' && !empty(
$conf->project->multidir_output[$entity])) {
3443 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3446 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3447 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
3448 $tmpproject =
new Project($db);
3449 $tmpproject->fetch(0, $refname);
3450 $accessallowed =
checkUserAccessToObject($user, array(
'projet'), $tmpproject->id,
'projet&project',
'',
'',
'rowid',
'');
3453 $original_file =
$conf->project->multidir_output[$entity].
'/'.$original_file;
3454 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3455 } elseif ($modulepart ==
'project_task' && !empty(
$conf->project->multidir_output[$entity])) {
3456 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3459 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3460 include_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
3461 $tmptask =
new Task($db);
3462 $tmptask->fetch(0, $refname);
3463 $accessallowed =
checkUserAccessToObject($user, array(
'projet_task'), $tmptask->id,
'projet_task&project',
'',
'',
'rowid',
'');
3466 $original_file =
$conf->project->multidir_output[$entity].
'/'.$original_file;
3467 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3468 } elseif (($modulepart ==
'commande_fournisseur' || $modulepart ==
'order_supplier') && !empty(
$conf->fournisseur->commande->dir_output)) {
3470 if ($fuser->hasRight(
'fournisseur',
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3473 $original_file =
$conf->fournisseur->commande->dir_output.
'/'.$original_file;
3474 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande_fournisseur WHERE ref='".$db->escape($refname).
"' AND entity=".
$conf->entity;
3475 } elseif (($modulepart ==
'facture_fournisseur' || $modulepart ==
'invoice_supplier') && !empty(
$conf->fournisseur->facture->dir_output)) {
3477 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3480 $original_file =
$conf->fournisseur->facture->dir_output.
'/'.$original_file;
3481 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture_fourn WHERE ref='".$db->escape($refname).
"' AND entity=".
$conf->entity;
3482 } elseif ($modulepart ==
'supplier_payment') {
3484 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3487 $original_file = preg_replace(
"/payment\//",
"", $original_file);
3488 $original_file =
$conf->fournisseur->payment->dir_output.
'/'.$original_file;
3489 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"paiementfournisseur WHERE ref='".$db->escape($refname).
"' AND entity=".
$conf->entity;
3490 } elseif ($modulepart ==
'payment') {
3492 if ($fuser->rights->facture->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
3495 $original_file =
$conf->compta->payment->dir_output.
'/'.$original_file;
3496 } elseif ($modulepart ==
'facture_paiement' && !empty(
$conf->invoice->dir_output)) {
3498 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3501 if ($fuser->socid > 0) {
3502 $original_file =
$conf->invoice->dir_output.
'/payments/private/'.$fuser->id.
'/'.$original_file;
3504 $original_file =
$conf->invoice->dir_output.
'/payments/'.$original_file;
3506 } elseif ($modulepart ==
'export_compta' && !empty(
$conf->accounting->dir_output)) {
3508 if ($fuser->hasRight(
'accounting',
'bind',
'write') || preg_match(
'/^specimen/i', $original_file)) {
3511 $original_file =
$conf->accounting->dir_output.
'/'.$original_file;
3512 } elseif (($modulepart ==
'expedition' || $modulepart ==
'shipment') && !empty(
$conf->expedition->dir_output)) {
3514 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3517 $original_file =
$conf->expedition->dir_output.
"/".(strpos($original_file,
'sending/') === 0 ?
'' :
'sending/').$original_file;
3519 } elseif (($modulepart ==
'livraison' || $modulepart ==
'delivery') && !empty(
$conf->expedition->dir_output)) {
3521 if ($fuser->hasRight(
'expedition',
'delivery', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3524 $original_file =
$conf->expedition->dir_output.
"/".(strpos($original_file,
'receipt/') === 0 ?
'' :
'receipt/').$original_file;
3525 } elseif ($modulepart ==
'actionsreport' && !empty(
$conf->agenda->dir_temp)) {
3527 if ($fuser->hasRight(
'agenda',
'allactions', $read) || preg_match(
'/^specimen/i', $original_file)) {
3530 $original_file =
$conf->agenda->dir_temp.
"/".$original_file;
3531 } elseif ($modulepart ==
'product' || $modulepart ==
'produit' || $modulepart ==
'service' || $modulepart ==
'produit|service') {
3533 if (empty($entity) || (empty(
$conf->product->multidir_output[$entity]) && empty(
$conf->service->multidir_output[$entity]))) {
3534 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3536 if (($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3539 if (isModEnabled(
"product")) {
3540 $original_file =
$conf->product->multidir_output[$entity].
'/'.$original_file;
3541 } elseif (isModEnabled(
"service")) {
3542 $original_file =
$conf->service->multidir_output[$entity].
'/'.$original_file;
3544 } elseif ($modulepart ==
'product_batch' || $modulepart ==
'produitlot') {
3546 if (empty($entity) || (empty(
$conf->productbatch->multidir_output[$entity]))) {
3547 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3549 if (($fuser->hasRight(
'produit', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3552 if (isModEnabled(
'productbatch')) {
3553 $original_file =
$conf->productbatch->multidir_output[$entity].
'/'.$original_file;
3555 } elseif ($modulepart ==
'movement' || $modulepart ==
'mouvement') {
3557 if (empty($entity) || empty(
$conf->stock->multidir_output[$entity])) {
3558 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3560 if (($fuser->hasRight(
'stock', $lire) || $fuser->hasRight(
'stock',
'movement', $lire) || $fuser->hasRight(
'stock',
'mouvement', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3563 if (isModEnabled(
'stock')) {
3564 $original_file =
$conf->stock->multidir_output[$entity].
'/movement/'.$original_file;
3566 } elseif ($modulepart ==
'contract' && !empty(
$conf->contract->multidir_output[$entity])) {
3568 if ($fuser->hasRight(
'contrat', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3571 $original_file =
$conf->contract->multidir_output[$entity].
'/'.$original_file;
3572 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"contrat WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'contract').
")";
3573 } elseif ($modulepart ==
'donation' && !empty(
$conf->don->dir_output)) {
3575 if ($fuser->hasRight(
'don', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3578 $original_file =
$conf->don->dir_output.
'/'.$original_file;
3579 } elseif ($modulepart ==
'dolresource' && !empty(
$conf->resource->dir_output)) {
3581 if ($fuser->hasRight(
'resource', $read) || preg_match(
'/^specimen/i', $original_file)) {
3584 $original_file =
$conf->resource->dir_output.
'/'.$original_file;
3585 } elseif (($modulepart ==
'remisecheque' || $modulepart ==
'chequereceipt') && !empty(
$conf->bank->dir_output)) {
3587 if ($fuser->hasRight(
'banque', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3590 $original_file =
$conf->bank->dir_output.
'/checkdeposits/'.$original_file;
3591 } elseif (($modulepart ==
'banque' || $modulepart ==
'bank') && !empty(
$conf->bank->dir_output)) {
3593 if ($fuser->hasRight(
'banque', $lire)) {
3596 $original_file =
$conf->bank->dir_output.
'/'.$original_file;
3597 } elseif ($modulepart ==
'export' && !empty(
$conf->export->dir_temp)) {
3600 $accessallowed = $user->hasRight(
'export',
'lire');
3601 $original_file =
$conf->export->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3602 } elseif ($modulepart ==
'import' && !empty(
$conf->import->dir_temp)) {
3604 $accessallowed = $user->hasRight(
'import',
'run');
3605 $original_file =
$conf->import->dir_temp.
'/'.$original_file;
3606 } elseif ($modulepart ==
'recruitment' && !empty(
$conf->recruitment->dir_output)) {
3608 $accessallowed = $user->hasRight(
'recruitment',
'recruitmentjobposition',
'read');
3609 $original_file =
$conf->recruitment->dir_output.
'/'.$original_file;
3610 } elseif ($modulepart ==
'hrm' && !empty(
$conf->hrm->dir_output)) {
3612 $accessallowed = $user->hasRight(
'hrm',
'all',
'read');
3613 $original_file =
$conf->hrm->dir_output.
'/'.$original_file;
3614 } elseif ($modulepart ==
'editor' && !empty(
$conf->fckeditor->dir_output)) {
3617 $original_file =
$conf->fckeditor->dir_output.
'/'.$original_file;
3618 } elseif ($modulepart ==
'systemtools' && !empty(
$conf->admin->dir_output)) {
3620 if ($fuser->admin) {
3623 $original_file =
$conf->admin->dir_output.
'/'.$original_file;
3624 } elseif ($modulepart ==
'admin_temp' && !empty(
$conf->admin->dir_temp)) {
3626 if ($fuser->admin) {
3629 $original_file =
$conf->admin->dir_temp.
'/'.$original_file;
3630 } elseif ($modulepart ==
'bittorrent' && !empty(
$conf->bittorrent->dir_output)) {
3634 if (
dol_mimetype($original_file) ==
'application/x-bittorrent') {
3637 $original_file =
$conf->bittorrent->dir_output.
'/'.$dir.
'/'.$original_file;
3638 } elseif ($modulepart ==
'member' && !empty(
$conf->member->dir_output)) {
3640 if ($fuser->hasRight(
'adherent', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3643 $original_file =
$conf->member->dir_output.
'/'.$original_file;
3653 if (preg_match(
'/^specimen/i', $original_file)) {
3656 if ($fuser->admin) {
3660 $tmpmodulepart = explode(
'-', $modulepart);
3661 if (!empty($tmpmodulepart[1])) {
3662 $modulepart = $tmpmodulepart[0];
3663 $original_file = $tmpmodulepart[1].
'/'.$original_file;
3668 if (preg_match(
'/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
3669 $tmpmodule = $reg[1];
3670 if (empty(
$conf->$tmpmodule->dir_temp)) {
3671 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3674 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3677 $original_file =
$conf->{$reg[1]}->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3678 } elseif (preg_match(
'/^([a-z]+)_temp$/i', $modulepart, $reg)) {
3679 $tmpmodule = $reg[1];
3680 if (empty(
$conf->$tmpmodule->dir_temp)) {
3681 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3684 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3687 $original_file =
$conf->$tmpmodule->dir_temp.
'/'.$original_file;
3688 } elseif (preg_match(
'/^([a-z]+)_user$/i', $modulepart, $reg)) {
3689 $tmpmodule = $reg[1];
3690 if (empty(
$conf->$tmpmodule->dir_output)) {
3691 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3694 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3697 $original_file =
$conf->$tmpmodule->dir_output.
'/'.$fuser->id.
'/'.$original_file;
3698 } elseif (preg_match(
'/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
3699 $tmpmodule = $reg[1];
3700 if (empty(
$conf->$tmpmodule->dir_output)) {
3701 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3706 $partsofdirinoriginalfile = explode(
'/', $original_file);
3707 if (!empty($partsofdirinoriginalfile[1])) {
3708 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3709 if (($partofdirinoriginalfile && $fuser->hasRight($tmpmodule, $partofdirinoriginalfile,
'read')) || preg_match(
'/^specimen/i', $original_file)) {
3713 if ($fuser->hasRight($tmpmodule, $read) || preg_match(
'/^specimen/i', $original_file)) {
3716 $original_file =
$conf->$tmpmodule->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3718 if (empty(
$conf->$modulepart->dir_output)) {
3719 dol_print_error(
null,
'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.');
3724 $partsofdirinoriginalfile = explode(
'/', $original_file);
3725 if (!empty($partsofdirinoriginalfile[1])) {
3726 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3727 if ($partofdirinoriginalfile && ($fuser->hasRight($modulepart, $partofdirinoriginalfile,
'lire') || $fuser->hasRight($modulepart, $partofdirinoriginalfile,
'read'))) {
3731 if (($fuser->hasRight($modulepart, $lire) || $fuser->hasRight($modulepart, $read)) || ($fuser->hasRight($modulepart,
'all', $lire) || $fuser->hasRight($modulepart,
'all', $read))) {
3735 if (is_array(
$conf->$modulepart->multidir_output) && !empty(
$conf->$modulepart->multidir_output[$entity])) {
3736 $original_file =
$conf->$modulepart->multidir_output[$entity].
'/'.$original_file;
3738 $original_file =
$conf->$modulepart->dir_output.
'/'.$original_file;
3742 $parameters = array(
3743 'modulepart' => $modulepart,
3744 'original_file' => $original_file,
3745 'entity' => $entity,
3750 $reshook = $hookmanager->executeHooks(
'checkSecureAccess', $parameters,
$object);
3752 if (!empty($hookmanager->resArray[
'original_file'])) {
3753 $original_file = $hookmanager->resArray[
'original_file'];
3755 if (!empty($hookmanager->resArray[
'accessallowed'])) {
3756 $accessallowed = $hookmanager->resArray[
'accessallowed'];
3758 if (!empty($hookmanager->resArray[
'sqlprotectagainstexternals'])) {
3759 $sqlprotectagainstexternals = $hookmanager->resArray[
'sqlprotectagainstexternals'];
3765 'accessallowed' => ($accessallowed ? 1 : 0),
3766 'sqlprotectagainstexternals' => $sqlprotectagainstexternals,
3767 'original_file' => $original_file
3786 dol_syslog(
"Failed to create the cache directory ".$directory, LOG_WARNING);
3789 $cachefile = $directory.$filename;
3791 file_put_contents($cachefile, serialize(
$object), LOCK_EX);
3807 $cachefile = $directory.$filename;
3808 $refresh = !file_exists($cachefile) || ($now - $cachetime) >
dol_filemtime($cachefile);
3821 $cachefile = $directory.$filename;
3822 $object = unserialize(file_get_contents($cachefile));
3834 return preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\//',
'', $pathfile);
3849function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path =
'', $pathref =
'', &$checksumconcat = array())
3853 $exclude =
'install';
3855 foreach ($dir->md5file as $file) {
3856 $filename = $path.$file[
'name'];
3857 $file_list[
'insignature'][] = $filename;
3858 $expectedsize = (empty($file[
'size']) ?
'' : $file[
'size']);
3859 $expectedmd5 = (string) $file;
3861 if (!file_exists($pathref.
'/'.$filename)) {
3862 $file_list[
'missing'][] = array(
'filename' => $filename,
'expectedmd5' => $expectedmd5,
'expectedsize' => $expectedsize);
3864 $md5_local = md5_file($pathref.
'/'.$filename);
3866 if ($conffile ==
'/etc/dolibarr/conf.php' && $filename ==
'/filefunc.inc.php') {
3867 $checksumconcat[] = $expectedmd5;
3869 if ($md5_local != $expectedmd5) {
3870 $file_list[
'updated'][] = array(
'filename' => $filename,
'expectedmd5' => $expectedmd5,
'expectedsize' => $expectedsize,
'md5' => (
string) $md5_local);
3872 $checksumconcat[] = $md5_local;
3877 foreach ($dir->dir as $subdir) {
3878 getFilesUpdated($file_list, $subdir, $path.$subdir[
'name'].
'/', $pathref, $checksumconcat);
3896 $out .=
'<div id="'.$htmlname.
'Message" class="dragDropAreaMessage hidden"><span>'.
img_picto(
"",
'download').
'<br>'.$langs->trans(
"DropFileToAddItToObject").
'</span></div>';
3897 $out .=
"\n<!-- JS CODE TO ENABLE DRAG AND DROP OF FILE -->\n";
3900 jQuery(document).ready(function() {
3901 var enterTargetDragDrop = null;
3903 $("#'.$htmlname.
'").addClass("cssDragDropArea");
3905 $(".cssDragDropArea").on("dragenter", function(ev, ui) {
3906 var dataTransfer = ev.originalEvent.dataTransfer;
3907 var dataTypes = dataTransfer.types;
3908 //console.log(dataTransfer);
3909 //console.log(dataTypes);
3911 if (!dataTypes || ($.inArray(\'Files\', dataTypes) === -1)) {
3912 // The element dragged is not a file, so we avoid the "dragenter"
3913 ev.preventDefault();
3917 // Entering drop area. Highlight area
3918 console.log("dragAndDropFileUpload: We add class highlightDragDropArea")
3919 enterTargetDragDrop = ev.target;
3920 $(this).addClass("highlightDragDropArea");
3921 $("#'.$htmlname.
'Message").removeClass("hidden");
3922 ev.preventDefault();
3925 $(".cssDragDropArea").on("dragleave", function(ev) {
3926 // Going out of drop area. Remove Highlight
3927 if (enterTargetDragDrop == ev.target){
3928 console.log("dragAndDropFileUpload: We remove class highlightDragDropArea")
3929 $("#'.$htmlname.
'Message").addClass("hidden");
3930 $(this).removeClass("highlightDragDropArea");
3934 $(".cssDragDropArea").on("dragover", function(ev) {
3935 ev.preventDefault();
3939 $(".cssDragDropArea").on("drop", function(e) {
3942 fd = new FormData();
3946 fd.append("action", "linkit");
3948 var dataTransfer = e.originalEvent.dataTransfer;
3950 if (dataTransfer.files && dataTransfer.files.length){
3951 var droppedFiles = e.originalEvent.dataTransfer.files;
3952 $.each(droppedFiles, function(index,file){
3953 fd.append("files[]", file,file.name)
3956 $(".cssDragDropArea").removeClass("highlightDragDropArea");
3957 counterdragdrop = 0;
3959 url: "'.DOL_URL_ROOT.
'/core/ajax/fileupload.php",
3964 success:function() {
3965 console.log("Uploaded.", arguments);
3966 /* arguments[0] is the json string of files */
3967 /* arguments[1] is the value for variable "success", can be 0 or 1 */
3968 let listoffiles = JSON.parse(arguments[0]);
3969 console.log(listoffiles);
3971 for (let i = 0; i < listoffiles.length; i++) {
3972 console.log(listoffiles[i].error);
3973 if (listoffiles[i].error) {
3977 console.log(nboferror);
3978 if (nboferror > 0) {
3979 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=ErrorOnAtLeastOneFileUpload:warnings";
3981 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=UploadFileDragDropSuccess:mesgs";
3985 console.log("Error Uploading.", arguments)
3986 if (arguments[0].status == 403) {
3987 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=ErrorUploadPermissionDenied:errors";
3989 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=ErrorUploadFileDragDropPermissionDenied:errors";
3995 $out .=
"</script>\n";
4009function archiveOrBackupFile($srcfile, $max_versions = 5, $archivedir =
'', $suffix =
"v", $moveorcopy =
'move')
4011 $base_file_pattern = ($archivedir ? $archivedir : dirname($srcfile)).
'/'.basename($srcfile).
".".$suffix;
4012 $files_in_directory = glob($base_file_pattern .
"*");
4015 $files_with_timestamps = [];
4016 foreach ($files_in_directory as $file) {
4017 $files_with_timestamps[] = [
4019 'timestamp' => filemtime($file)
4025 while (count($files_with_timestamps) > 0) {
4026 $latest_file =
null;
4027 $latest_index =
null;
4030 foreach ($files_with_timestamps as $index => $file_info) {
4031 if ($latest_file ===
null || (is_array($latest_file) && $file_info[
'timestamp'] > $latest_file[
'timestamp'])) {
4032 $latest_file = $file_info;
4033 $latest_index = $index;
4038 if ($latest_file !==
null) {
4039 $sorted_files[] = $latest_file[
'file'];
4040 unset($files_with_timestamps[$latest_index]);
4045 if (count($sorted_files) >= $max_versions) {
4046 $oldest_files = array_slice($sorted_files, $max_versions - 1);
4047 foreach ($oldest_files as $oldest_file) {
4053 $new_backup = $srcfile .
".v" . $timestamp;
4056 if ($moveorcopy ==
'move') {
4057 $result =
dol_move($srcfile, $new_backup,
'0', 1, 0, 0);
4059 $result =
dol_copy($srcfile, $new_backup,
'0', 1, 0, 0);
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Class to manage agenda events (actions)
Class to manage ECM files.
Class to manage Trips and Expenses.
Class of the module paid holiday.
Class to manage projects.
Class to manage Dolibarr users.
Class to manage utility methods.
dirbasename($pathfile)
Return the relative dirname (relative to DOL_DATA_ROOT) of a full path string.
dol_dir_list_in_database($path, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $sqlfilters="", $object=null)
Scan a directory and return a list of files/directories.
dol_is_link($pathoffile)
Return if path is a symbolic link.
dol_compare_file($a, $b)
Fast compare of 2 files identified by their properties ->name, ->date and ->size.
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_is_url($uri)
Return if path is an URI (the name of the method is misleading).
dol_basename($pathfile)
Make a basename working with all page code (default PHP basenamed fails with cyrillic).
getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path='', $pathref='', &$checksumconcat=array())
Function to get list of updated or modified files.
dol_filemtime($pathoffile)
Return time of a file.
dol_filesize($pathoffile)
Return size of a file.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=0)
Move a file into another name.
dol_add_file_process($upload_dir, $allowoverwrite=0, $updatesessionordb=0, $keyforsourcefile='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null, $forceFullTextIndexation='', $mode=0)
Get and save an upload file (for example after submitting a new file in a mail form).
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object=null)
Complete $filearray with data from database.
archiveOrBackupFile($srcfile, $max_versions=5, $archivedir='', $suffix="v", $moveorcopy='move')
Manage backup versions for a given file, ensuring only a maximum number of versions are kept.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_move_dir($srcdir, $destdir, $overwriteifexists=1, $indexdatabase=1, $renamedircontent=1)
Move a directory into another name.
addFileIntoDatabaseIndex($dir, $file, $fullpathorig='', $mode='uploaded', $setsharekey=0, $object=null, $forceFullTextIndexation='')
Add a file into database index.
dol_fileperm($pathoffile)
Return permissions of a file.
dol_is_writable($folderorfile)
Test if directory or filename is writable.
dol_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_uncompress($inputfile, $outputdir)
Uncompress a file.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser=null, $refname='', $mode='read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices to g...
dol_init_file_process($pathtoscan='', $trackid='')
Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
dol_convert_file($fileinput, $ext='png', $fileoutput='', $page='')
Convert an image file or a PDF into another image format.
dol_filecache($directory, $filename, $object)
Store object in file.
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0, $excludefileext=null, $excludearchivefiles=0)
Copy a dir to another dir.
dragAndDropFileUpload($htmlname)
Function to manage the drag and drop of a file.
dol_is_file($pathoffile)
Return if path is a file.
dol_count_nb_of_line($file)
Count number of lines in a file.
dolCheckVirus($src_file, $dest_file='')
Check virus into a file.
dol_unescapefile($filename)
Unescape a file submitted by upload.
dol_dir_is_emtpy($folder)
Test if a folder is empty.
dol_remove_file_process($filenb, $donotupdatesession=0, $donotdeletefile=1, $trackid='')
Remove an uploaded file (for example after submitting a new file a mail form).
dolCheckOnFileName($src_file, $dest_file='')
Check virus into a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_readcachefile($directory, $filename)
Read object from cachefile.
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0)
Return file(s) into a directory (by default most recent)
dol_is_dir($folder)
Test if filename is a directory.
dol_cache_refresh($directory, $filename, $cachetime)
Test if Refresh needed.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask='0', $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_is_dir_empty($dir)
Return if path is empty.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
deleteFilesIntoDatabaseIndex($dir, $file, $mode='uploaded', $object=null)
Delete files into database index using search criteria.
getExecutableContent()
Return array of extension for executable files of text files that can contains executable code.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
getDolUserInt($key, $default=0, $tmpuser=null)
Return Dolibarr user constant int value.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
currentToken()
Return the value of token currently saved into session with name 'token'.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_string_nounprintableascii($str, $removetabcrlf=1)
Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
utf8_check($str)
Check if a string is in UTF8.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
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).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.