41 return preg_replace(
'/^.*\/([^\/]+)$/',
'$1', rtrim($pathfile,
'/'));
64function 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)
69 if ($recursive <= 1) {
74 if (!empty($filter) && !is_array($filter)) {
75 if (strlen($filter) > 25000) {
76 dol_syslog(
"Value for filter is too large", LOG_ERR);
80 if ((
int) preg_match(
'/(?:^|[^\\\\])\//', $filter) > 0) {
81 $excludefilter_ok =
false;
82 $error_info .=
" error='filter_has_unescaped_slash'";
83 dol_syslog(
"'$filter' has unescaped '/'", LOG_ERR);
89 $excludefilter_ok =
true;
90 $exclude_array = ($excludefilter ===
null || $excludefilter ===
'') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
91 foreach ($exclude_array as $f) {
93 if ((
int) preg_match(
'/(?:^|[^\\\\])\//', $f) > 0) {
94 $excludefilter_ok =
false;
95 $error_info .=
" error='excludefilter_has_unescaped_slash'";
100 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);
102 if (!$filter_ok || !$excludefilter_ok) {
108 $exclude_array = ($excludefilter ===
null || $excludefilter ===
'') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
112 $excludefilterarray = array_merge(array(
'^\.'), $exclude_array);
114 $loaddate = ($mode == 1 || $mode == 2 || $nbsecondsold != 0 || $sortcriteria ==
'date');
115 $loadsize = ($mode == 1 || $mode == 3 || $sortcriteria ==
'size');
116 $loadperm = ($mode == 1 || $mode == 4 || $sortcriteria ==
'perm');
120 $file_list = array();
123 $utf8_path = preg_replace(
'/([\\/]+)$/',
'', $utf8_path);
125 if (preg_match(
'/\*/', $utf8_path)) {
126 $utf8_path_array = glob($utf8_path, GLOB_ONLYDIR);
129 $utf8_path_array = array($utf8_path);
132 foreach ($utf8_path_array as $utf8_path_cursor) {
134 if (!$nohook && $hookmanager instanceof
HookManager) {
135 $hookmanager->resArray = array();
137 $hookmanager->initHooks(array(
'fileslib'));
142 'recursive' => $recursive,
144 'excludefilter' => $exclude_array,
145 'sortcriteria' => $sortcriteria,
146 'sortorder' => $sortorder,
147 'loaddate' => $loaddate,
148 'loadsize' => $loadsize,
151 $reshook = $hookmanager->executeHooks(
'getDirList', $parameters,
$object);
155 if (empty($reshook)) {
156 if (!is_dir($os_path)) {
160 if (($dir = opendir($os_path)) ===
false) {
168 while (
false !== ($os_file = readdir($dir))) {
169 $os_fullpathfile = ($os_path ? $os_path.
'/' :
'').$os_file;
172 $utf8_file = mb_convert_encoding($os_file,
'UTF-8',
'ISO-8859-1');
174 $utf8_file = $os_file;
177 $utf8_fullpathfile = $utf8_path_cursor.
"/".$utf8_file;
181 foreach ($excludefilterarray as $filt) {
182 if (preg_match(
'/'.$filt.
'/i', $utf8_file) || preg_match(
'/'.$filt.
'/i', $utf8_fullpathfile)) {
190 $isdir = is_dir($os_fullpathfile);
194 if (($types ==
"directories") || ($types ==
"all")) {
195 if ($loaddate || $sortcriteria ==
'date') {
198 if ($loadsize || $sortcriteria ==
'size') {
201 if ($loadperm || $sortcriteria ==
'perm') {
205 $qualifiedforfilter = 0;
206 if (empty($filter)) {
207 $qualifiedforfilter = 1;
209 $testpregmatch =
false;
210 if (is_array($filter)) {
211 $chunks = array_chunk($filter, 500);
212 foreach ($chunks as $chunk) {
213 $testpregmatch = preg_match(
'/'.implode(
'|', $chunk).
'/i', $utf8_file);
214 if ($testpregmatch) {
219 $testpregmatch = preg_match(
'/'.$filter.
'/i', $utf8_file);
221 if ($testpregmatch) {
222 $qualifiedforfilter = 1;
226 if ($qualifiedforfilter) {
228 preg_match(
'/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
229 $level1name = (isset($reg[1]) ? $reg[1] :
'');
230 $file_list[] = array(
231 "name" => $utf8_file,
232 "path" => $utf8_path,
233 "level1name" => $level1name,
234 "relativename" => ($relativename ? $relativename.
'/' :
'').$utf8_file,
235 "fullname" => $utf8_fullpathfile,
245 if ($recursive > 0) {
246 if (empty($donotfollowsymlinks) || !is_link($os_fullpathfile)) {
248 $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));
251 } elseif (in_array($types, array(
"files",
"all"))) {
253 if ($loaddate || $sortcriteria ==
'date') {
256 if ($loadsize || $sortcriteria ==
'size') {
260 $qualifiedforfilter = 0;
261 if (empty($filter)) {
262 $qualifiedforfilter = 1;
264 $testpregmatch =
false;
265 if (is_array($filter)) {
266 $chunks = array_chunk($filter, 500);
267 foreach ($chunks as $chunk) {
268 $testpregmatch = preg_match(
'/'.implode(
'|', $chunk).
'/i', $utf8_file);
269 if ($testpregmatch) {
274 $testpregmatch = preg_match(
'/'.$filter.
'/i', $utf8_file);
276 if ($testpregmatch) {
277 $qualifiedforfilter = 1;
281 if ($qualifiedforfilter) {
282 if (empty($nbsecondsold) || $filedate <= ($now - $nbsecondsold)) {
283 preg_match(
'/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
284 $level1name = (isset($reg[1]) ? $reg[1] :
'');
285 $file_list[] = array(
286 "name" => $utf8_file,
287 "path" => $utf8_path,
288 "level1name" => $level1name,
289 "relativename" => ($relativename ? $relativename.
'/' :
'').$utf8_file,
290 "fullname" => $utf8_fullpathfile,
305 if (!empty($sortcriteria) && $sortorder) {
306 $file_list =
dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ?
'asc' :
'desc'));
309 if ($hookmanager instanceof
HookManager && is_array($hookmanager->resArray)) {
310 $file_list = array_merge($file_list, $hookmanager->resArray);
333function dol_dir_list_in_database($path, $filter =
"", $excludefilter =
null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0, $sqlfilters =
"",
$object =
null)
341 $sql =
"SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,";
342 $sql .=
" date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share";
344 $sql .=
", description";
346 $sql .=
" FROM ".MAIN_DB_PREFIX.
"ecm_files";
348 $sql .=
" WHERE entity = ".((int)
$object->entity);
350 $sql .=
" WHERE entity = ".((int)
$conf->entity);
352 if (preg_match(
'/%$/', $path)) {
353 $sql .=
" AND (filepath LIKE '".$db->escape($path).
"' OR filepath = '".
$db->escape(preg_replace(
'/\/%$/',
'', $path)).
"')";
355 $sql .=
" AND filepath = '".$db->escape($path).
"'";
366 $resql =
$db->query($sql);
368 $file_list = array();
369 $num =
$db->num_rows($resql);
372 $obj =
$db->fetch_object($resql);
375 preg_match(
'/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename, $reg);
376 $level1name = (isset($reg[1]) ? $reg[1] :
'');
377 $file_list[] = array(
378 "rowid" => $obj->rowid,
379 "label" => $obj->label,
380 "name" => $obj->filename,
381 "path" => DOL_DATA_ROOT.
'/'.$obj->filepath,
382 "level1name" => $level1name,
383 "fullname" => DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename,
384 "fullpath_orig" => $obj->fullpath_orig,
385 "date_c" =>
$db->jdate($obj->date_c),
386 "date_m" =>
$db->jdate($obj->date_m),
388 "keywords" => $obj->keywords,
389 "cover" => $obj->cover,
390 "position" => (
int) $obj->position,
392 "share" => $obj->share,
393 "description" => ($mode ? $obj->description :
'')
401 if (!empty($sortcriteria)) {
403 foreach ($file_list as $key => $row) {
404 $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] :
'');
408 array_multisort($myarray, $sortorder, SORT_REGULAR, $file_list);
443 if (in_array($modulepart, array(
'produit',
'product')) &&
getDolGlobalInt(
'PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
448 $upload_dirold =
$conf->product->multidir_output[
$object->entity ??
$conf->entity].
'/'.substr(substr(
"000".
$object->id, -2), 1, 1).
'/'.substr(substr(
"000".
$object->id, -2), 0, 1).
'/'.
$object->id.
"/photos";
450 $upload_dirold =
$conf->service->multidir_output[
$object->entity ??
$conf->entity].
'/'.substr(substr(
"000".
$object->id, -2), 1, 1).
'/'.substr(substr(
"000".
$object->id, -2), 0, 1).
'/'.
$object->id.
"/photos";
453 $relativedirold = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dirold);
454 $relativedirold = ltrim($relativedirold,
"/\\");
459 } elseif ($modulepart ==
'ticket') {
460 foreach ($filearray as $key => $val) {
461 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filearray[$key][
'path']);
462 $rel_dir = trim($rel_dir,
"/\\");
463 if ($rel_dir != $relativedir) {
464 $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';
515 $ecmfile->src_object_type =
$object->element;
516 $ecmfile->src_object_id =
$object->id;
518 $ecmfile->description =
'';
519 $ecmfile->keywords =
'';
524 $result = $ecmfile->create($user);
528 $filearray[$key][
'rowid'] = $result;
531 $filearray[$key][
'rowid'] = 0;
548 global $sortorder, $sortfield;
550 $sortorder = strtoupper($sortorder);
552 if ($sortorder ==
'ASC') {
560 if ($sortfield ==
'name') {
561 if ($a->name == $b->name) {
564 return ($a->name < $b->name) ? $retup : $retdown;
566 if ($sortfield ==
'date') {
567 if ($a->date == $b->date) {
570 return ($a->date < $b->date) ? $retup : $retdown;
572 if ($sortfield ==
'size') {
573 if ($a->size == $b->size) {
576 return ($a->size < $b->size) ? $retup : $retdown;
592 if (is_dir($newfolder)) {
607 if (!is_readable($dir)) {
610 return (count(scandir($dir)) == 2);
622 return is_file($newpathoffile);
634 return is_link($newpathoffile);
646 return is_writable($newfolderorfile);
659 $prots = array(
'file',
'http',
'https',
'ftp',
'zlib',
'data',
'ssh',
'ssh2',
'ogg',
'expect');
660 return false !== preg_match(
'/^('.implode(
'|', $prots).
'):/i', $uri);
672 if (is_dir($newfolder)) {
673 $handle = opendir($newfolder);
674 $folder_content =
'';
676 while ((gettype($name = readdir($handle)) !=
"boolean")) {
677 $name_array[] = $name;
679 foreach ($name_array as $temp) {
680 $folder_content .= $temp;
685 if ($folder_content ==
"...") {
708 $fp = fopen($newfile,
'r');
715 if ($line !==
false) {
738 return filesize($newpathoffile);
750 return @filemtime($newpathoffile);
762 return fileperms($newpathoffile);
777function dolReplaceInFile($srcfile, $arrayreplacement, $destfile =
'', $newmask =
'0', $indexdatabase = 0, $arrayreplacementisregex = 0)
779 dol_syslog(
"files.lib.php::dolReplaceInFile srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" indexdatabase=".$indexdatabase.
" arrayreplacementisregex=".$arrayreplacementisregex);
781 if (empty($srcfile)) {
784 if (empty($destfile)) {
785 $destfile = $srcfile;
789 $srcfile = preg_replace(
'/\.\.\/?/',
'', $srcfile);
790 $destfile = preg_replace(
'/\.\.\/?/',
'', $destfile);
793 if (($destfile != $srcfile) && $destexists) {
799 dol_syslog(
"files.lib.php::dolReplaceInFile failed to read src file", LOG_WARNING);
803 $tmpdestfile = $destfile.
'.tmp';
808 $newdirdestfile = dirname($newpathofdestfile);
810 if ($destexists && !is_writable($newpathofdestfile)) {
811 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
814 if (!is_writable($newdirdestfile)) {
815 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
822 $content = file_get_contents($newpathofsrcfile);
824 if (empty($arrayreplacementisregex)) {
827 foreach ($arrayreplacement as $key => $value) {
828 $content = preg_replace($key, (
string) $value, $content);
832 file_put_contents($newpathoftmpdestfile, $content);
833 dolChmod($newpathoftmpdestfile, $newmask);
836 $moreinfo = array(
'gen_or_uploaded' =>
'unknown');
837 $result =
dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase, $moreinfo);
839 dol_syslog(
"files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
845 if (empty($newmask)) {
846 dol_syslog(
"Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
850 dolChmod($newpathofdestfile, $newmask);
865 if (! file_exists($filePath)) {
866 dol_syslog(
"files.lib.php::removePatternFromFile: File $filePath does not exist", LOG_WARNING);
872 $content = file_get_contents($filePath);
873 if ($content ===
false) {
874 dol_syslog(
"files.lib.php::removePatternFromFile: Unable to read the file $filePath", LOG_WARNING);
880 $updatedContent = preg_replace($pattern,
'', $content);
881 if ($updatedContent ===
null) {
882 dol_syslog(
"files.lib.php::removePatternFromFile: Error while processing the file $filePath", LOG_WARNING);
888 $result = file_put_contents($filePath, $updatedContent);
889 if ($result ===
false) {
890 dol_syslog(
"files.lib.php::removePatternFromFile: Permission denied to overwrite the target file $filePath", LOG_WARNING);
895 dol_syslog(
"files.lib.php::removePatternFromFile: Content successfully removed in the file $filePath", LOG_INFO);
914function dol_copy($srcfile, $destfile, $newmask =
'0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 0)
918 dol_syslog(
"files.lib.php::dol_copy srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
920 if (empty($srcfile) || empty($destfile)) {
925 if (!$overwriteifexists && $destexists) {
931 $newdirdestfile = dirname($newpathofdestfile);
933 if ($destexists && !is_writable($newpathofdestfile)) {
934 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
937 if (!is_writable($newdirdestfile)) {
938 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
943 $testvirusarray = array();
946 if (count($testvirusarray)) {
947 dol_syslog(
"files.lib.php::dol_copy canceled because a virus was found into source file. we ignore the copy request.", LOG_WARNING);
953 $result = @copy($newpathofsrcfile, $newpathofdestfile);
956 dol_syslog(
"files.lib.php::dol_copy failed to copy", LOG_WARNING);
962 if (empty($newmask)) {
963 dol_syslog(
"Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
967 dolChmod($newpathofdestfile, $newmask);
969 if ($result && $indexdatabase) {
971 $rel_filetocopyafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $newpathofdestfile);
972 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetocopyafter)) {
973 $rel_filetocopyafter = preg_replace(
'/^[\\/]/',
'', $rel_filetocopyafter);
976 dol_syslog(
"Try to copy also entries in database for: ".$rel_filetocopyafter, LOG_DEBUG);
977 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
980 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetocopyafter);
981 if ($resultecmtarget > 0) {
982 dol_syslog(
"ECM dest file found, remove it", LOG_DEBUG);
983 $ecmfiletarget->delete($user);
985 dol_syslog(
"ECM dest file not found, create it", LOG_DEBUG);
989 $resultecm = $ecmSrcfile->fetch(0,
'', $srcfile);
993 dol_syslog(
"Fetch src file error", LOG_DEBUG);
997 $filename = basename($rel_filetocopyafter);
998 $rel_dir = dirname($rel_filetocopyafter);
999 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1000 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1002 $ecmfile->filepath = $rel_dir;
1003 $ecmfile->filename = $filename;
1005 $ecmfile->fullpath_orig = $srcfile;
1006 $ecmfile->gen_or_uploaded =
'copy';
1007 $ecmfile->description = $ecmSrcfile->description;
1008 $ecmfile->keywords = $ecmSrcfile->keywords;
1009 $resultecm = $ecmfile->create($user);
1010 if ($resultecm < 0) {
1014 dol_syslog(
"Create ECM file error", LOG_DEBUG);
1018 if ($resultecm > 0) {
1026 return (
int) $result;
1043function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement =
null, $excludesubdir = 0, $excludefileext =
null, $excludearchivefiles = 0)
1047 dol_syslog(
"files.lib.php::dolCopyDir srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
1049 if (empty($srcfile) || empty($destfile)) {
1060 $dirmaskdec = octdec($newmask);
1064 $dirmaskdec |= octdec(
'0200');
1066 $result =
dol_mkdir($destfile,
'', decoct($dirmaskdec));
1078 if (is_dir($ossrcfile)) {
1079 $dir_handle = opendir($ossrcfile);
1081 while ($file = readdir($dir_handle)) {
1082 if ($file !=
"." && $file !=
".." && !is_link($ossrcfile.
"/".$file)) {
1083 if (is_dir($ossrcfile.
"/".$file)) {
1084 if (empty($excludesubdir) || ($excludesubdir == 2 && strlen($file) == 2)) {
1087 if (is_array($arrayreplacement)) {
1088 foreach ($arrayreplacement as $key => $val) {
1089 $newfile = str_replace($key, $val, $newfile);
1093 $tmpresult =
dolCopyDir($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir, $excludefileext, $excludearchivefiles);
1098 if (is_array($excludefileext)) {
1099 $extension = pathinfo($file, PATHINFO_EXTENSION);
1100 if (in_array($extension, $excludefileext)) {
1106 if ($excludearchivefiles == 1) {
1107 $extension = pathinfo($file, PATHINFO_EXTENSION);
1108 if (preg_match(
'/^[v|d]\d+$/', $extension)) {
1114 if (is_array($arrayreplacement)) {
1115 foreach ($arrayreplacement as $key => $val) {
1116 $newfile = str_replace($key, $val, $newfile);
1119 $tmpresult =
dol_copy($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists);
1122 if ($result > 0 && $tmpresult >= 0) {
1125 $result = $tmpresult;
1132 closedir($dir_handle);
1138 return (
int) $result;
1160function dol_move($srcfile, $destfile, $newmask =
'0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1, $moreinfo = array(), $entity =
null)
1165 dol_syslog(
"files.lib.php::dol_move srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwritifexists=".$overwriteifexists);
1170 dol_syslog(
"files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
1174 if ($overwriteifexists || !$destexists) {
1179 $testvirusarray = array();
1182 $testvirusarray =
dolCheckVirus($newpathofsrcfile, $newpathofdestfile);
1183 if (count($testvirusarray)) {
1184 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1190 if (count($testvirusarray)) {
1191 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1196 global $dolibarr_main_restrict_os_commands;
1197 if (!empty($dolibarr_main_restrict_os_commands)) {
1198 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
1199 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
1200 if (in_array(basename($destfile), $arrayofallowedcommand)) {
1203 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);
1208 $result = @rename($newpathofsrcfile, $newpathofdestfile);
1211 dol_syslog(
"files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
1214 $result = @rename($newpathofsrcfile, $newpathofdestfile);
1216 dol_syslog(
"files.lib.php::dol_move Failed.", LOG_WARNING);
1221 if ($result && $indexdatabase) {
1223 $rel_filetorenamebefore = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $srcfile);
1224 $rel_filetorenameafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $destfile);
1225 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) {
1226 $rel_filetorenamebefore = preg_replace(
'/^[\\/]/',
'', $rel_filetorenamebefore);
1227 $rel_filetorenameafter = preg_replace(
'/^[\\/]/',
'', $rel_filetorenameafter);
1230 dol_syslog(
"Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore.
" after = ".$rel_filetorenameafter, LOG_DEBUG);
1231 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1234 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetorenameafter,
'',
'',
'', 0, $entity);
1235 if ($resultecmtarget > 0) {
1236 $ecmfiletarget->delete($user);
1240 $resultecm = $ecmfile->fetch(0,
'', $rel_filetorenamebefore,
'',
'',
'', 0, $entity);
1241 if ($resultecm > 0) {
1242 $filename = basename($rel_filetorenameafter);
1243 $rel_dir = dirname($rel_filetorenameafter);
1244 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1245 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1247 $ecmfile->filepath = $rel_dir;
1248 $ecmfile->filename = $filename;
1250 $resultecm = $ecmfile->update($user);
1251 } elseif ($resultecm == 0) {
1252 $filename = basename($rel_filetorenameafter);
1253 $rel_dir = dirname($rel_filetorenameafter);
1254 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1255 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1257 $ecmfile->filepath = $rel_dir;
1258 $ecmfile->filename = $filename;
1260 $ecmfile->fullpath_orig = basename($srcfile);
1261 if (!empty($moreinfo) && !empty($moreinfo[
'gen_or_uploaded'])) {
1262 $ecmfile->gen_or_uploaded = $moreinfo[
'gen_or_uploaded'];
1264 $ecmfile->gen_or_uploaded =
'unknown';
1266 if (!empty($moreinfo) && !empty($moreinfo[
'description'])) {
1267 $ecmfile->description = $moreinfo[
'description'];
1269 $ecmfile->description =
'';
1271 if (!empty($moreinfo) && !empty($moreinfo[
'keywords'])) {
1272 $ecmfile->keywords = $moreinfo[
'keywords'];
1274 $ecmfile->keywords =
'';
1276 if (!empty($moreinfo) && !empty($moreinfo[
'note_private'])) {
1277 $ecmfile->note_private = $moreinfo[
'note_private'];
1279 if (!empty($moreinfo) && !empty($moreinfo[
'note_public'])) {
1280 $ecmfile->note_public = $moreinfo[
'note_public'];
1282 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_type'])) {
1283 $ecmfile->src_object_type = $moreinfo[
'src_object_type'];
1285 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_id'])) {
1286 $ecmfile->src_object_id = $moreinfo[
'src_object_id'];
1288 if (!empty($moreinfo) && !empty($moreinfo[
'agenda_id'])) {
1289 $ecmfile->agenda_id = $moreinfo[
'agenda_id'];
1291 if (!empty($moreinfo) && !empty($moreinfo[
'position'])) {
1292 $ecmfile->position = $moreinfo[
'position'];
1294 if (!empty($moreinfo) && !empty($moreinfo[
'cover'])) {
1295 $ecmfile->cover = $moreinfo[
'cover'];
1297 if (!empty($moreinfo) && !empty($moreinfo[
'share'])) {
1298 $ecmfile->share = $moreinfo[
'share'];
1300 if (! empty($entity)) {
1301 $ecmfile->entity = $entity;
1304 $resultecm = $ecmfile->create($user);
1305 if ($resultecm < 0) {
1308 if (!empty($moreinfo) && !empty($moreinfo[
'array_options']) && is_array($moreinfo[
'array_options'])) {
1309 $ecmfile->array_options = $moreinfo[
'array_options'];
1310 $resultecm = $ecmfile->insertExtraFields();
1311 if ($resultecm < 0) {
1316 } elseif ($resultecm < 0) {
1320 if ($resultecm > 0) {
1328 if (empty($newmask)) {
1335 dolChmod($newpathofdestfile, $newmask);
1351function dol_move_dir($srcdir, $destdir, $overwriteifexists = 1, $indexdatabase = 1, $renamedircontent = 1)
1355 dol_syslog(
"files.lib.php::dol_move_dir srcdir=".$srcdir.
" destdir=".$destdir.
" overwritifexists=".$overwriteifexists.
" indexdatabase=".$indexdatabase.
" renamedircontent=".$renamedircontent);
1357 $srcbasename = basename($srcdir);
1361 dol_syslog(
"files.lib.php::dol_move_dir srcdir does not exists. Move fails");
1365 if ($overwriteifexists || !$destexists) {
1372 if ($overwriteifexists) {
1373 if (strtoupper(substr(PHP_OS, 0, 3)) ===
'WIN') {
1374 if (is_dir($newpathofdestdir)) {
1375 @rmdir($newpathofdestdir);
1380 $result = @rename($newpathofsrcdir, $newpathofdestdir);
1383 if ($result && $renamedircontent) {
1384 if (file_exists($newpathofdestdir)) {
1385 $destbasename = basename($newpathofdestdir);
1387 if (!empty($files) && is_array($files)) {
1388 foreach ($files as $key => $file) {
1389 if (!file_exists($file[
"fullname"])) {
1392 $filepath = $file[
"path"];
1393 $oldname = $file[
"name"];
1395 $newname = str_replace($srcbasename, $destbasename, $oldname);
1396 if (!empty($newname) && $newname !== $oldname) {
1397 if ($file[
"type"] ==
"dir") {
1398 $res =
dol_move_dir($filepath.
'/'.$oldname, $filepath.
'/'.$newname, $overwriteifexists, $indexdatabase, $renamedircontent);
1400 $moreinfo = array(
'gen_or_uploaded' =>
'unknown');
1401 $res =
dol_move($filepath.
'/'.$oldname, $filepath.
'/'.$newname,
'0', $overwriteifexists, 0, $indexdatabase, $moreinfo);
1428 return trim(basename($filename),
".\x00..\x20");
1444 if (!empty($reterrors)) {
1449 if (!class_exists(
'AntiVir')) {
1450 require_once DOL_DOCUMENT_ROOT.
'/core/class/antivir.class.php';
1453 $result = $antivir->dol_avscan_file($src_file);
1455 $reterrors = $antivir->errors;
1471 if (preg_match(
'/\.pdf$/i', $dest_file)) {
1473 dol_syslog(
"dolCheckOnFileName Check that pdf does not contains js code");
1475 $tmp = file_get_contents(trim($src_file));
1476 if (preg_match(
'/[\n\s]+\/JavaScript[\n\s]+/m', $tmp)) {
1477 return array(
'File is a PDF with javascript inside');
1480 dol_syslog(
"dolCheckOnFileName Check js into pdf disabled");
1509function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $keyforsourcefile =
'addedfile', $upload_dir =
'', $mode = 0)
1515 $file_name = $dest_file;
1518 if (empty($nohook)) {
1519 $reshook = $hookmanager->initHooks(array(
'fileslib'));
1521 $parameters = array(
'dest_file' => $dest_file,
'src_file' => $src_file,
'file_name' => $file_name,
'varfiles' => $keyforsourcefile,
'allowoverwrite' => $allowoverwrite);
1522 $reshook = $hookmanager->executeHooks(
'moveUploadedFile', $parameters,
$object);
1525 if (empty($reshook)) {
1527 if ($uploaderrorcode) {
1528 switch ($uploaderrorcode) {
1529 case UPLOAD_ERR_INI_SIZE:
1530 return 'ErrorFileSizeTooLarge';
1531 case UPLOAD_ERR_FORM_SIZE:
1532 return 'ErrorFileSizeTooLarge';
1533 case UPLOAD_ERR_PARTIAL:
1534 return 'ErrorPartialFile';
1535 case UPLOAD_ERR_NO_TMP_DIR:
1536 return 'ErrorNoTmpDir';
1537 case UPLOAD_ERR_CANT_WRITE:
1538 return 'ErrorFailedToWriteInDir';
1539 case UPLOAD_ERR_EXTENSION:
1540 return 'ErrorUploadBlockedByAddon';
1548 if (empty($disablevirusscan) && file_exists($src_file)) {
1550 if (count($checkvirusarray)) {
1551 dol_syslog(
'Files.lib::dol_move_uploaded_file File "'.$src_file.
'" (target name "'.$dest_file.
'") KO with antivirus: errors='.implode(
',', $checkvirusarray), LOG_WARNING);
1552 return 'ErrorFileIsInfectedWithAVirus: '.implode(
',', $checkvirusarray);
1561 $publicmediasdirwithslash =
$conf->medias->multidir_output[
$conf->entity];
1562 if (!preg_match(
'/\/$/', $publicmediasdirwithslash)) {
1563 $publicmediasdirwithslash .=
'/';
1566 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0 || !
getDolGlobalInt(
"MAIN_DOCUMENT_DISABLE_NOEXE_IN_MEDIAS_DIR")) {
1567 $file_name .=
'.noexe';
1574 if (preg_match(
'/^\./', basename($src_file)) || preg_match(
'/\.\./', $src_file) || preg_match(
'/[<>|]/', $src_file)) {
1575 dol_syslog(
"Refused to deliver file ".$src_file, LOG_WARNING);
1581 if (preg_match(
'/^\./', basename($dest_file)) || preg_match(
'/\.\./', $dest_file) || preg_match(
'/[<>|]/', $dest_file)) {
1582 dol_syslog(
"Refused to deliver file ".$dest_file, LOG_WARNING);
1588 $errmsg = implode(
',', $hookmanager->errors);
1589 if (empty($errmsg)) {
1590 $errmsg =
'ErrorReturnedBySomeHooks';
1593 } elseif (empty($reshook)) {
1599 if (!is_writable(dirname($file_name_osencoded))) {
1600 dol_syslog(
"Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded).
" is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1601 return 'ErrorDirNotWritable';
1605 if (!$allowoverwrite) {
1606 if (file_exists($file_name_osencoded)) {
1607 dol_syslog(
"Files.lib::dol_move_uploaded_file File ".$file_name.
" already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1608 return 'ErrorFileAlreadyExists';
1611 if (is_dir($file_name_osencoded)) {
1612 dol_syslog(
"Files.lib::dol_move_uploaded_file A directory with name ".$file_name.
" already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
1613 return 'ErrorDirWithFileNameAlreadyExists';
1619 $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1621 $return = rename($src_file_osencoded, $file_name_osencoded);
1626 dol_syslog(
"Files.lib::dol_move_uploaded_file Success to move ".$src_file.
" to ".$file_name.
" - Umask=" .
getDolGlobalString(
'MAIN_UMASK'), LOG_DEBUG);
1627 return $successcode;
1629 dol_syslog(
"Files.lib::dol_move_uploaded_file Failed to move ".$src_file.
" to ".$file_name, LOG_ERR);
1634 return $successcode;
1652function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0,
$object =
null, $allowdotdot =
false, $indexdatabase = 1, $nolog = 0)
1655 global $hookmanager;
1657 if (empty($nolog)) {
1658 dol_syslog(
"dol_delete_file file=".$file.
" disableglob=".$disableglob.
" nophperrors=".$nophperrors.
" nohook=".$nohook);
1663 if ((!$allowdotdot && preg_match(
'/\.\./', $file)) || preg_match(
'/[<>|]/', $file)) {
1664 dol_syslog(
"Refused to delete file ".$file, LOG_WARNING);
1669 if (empty($nohook) && !empty($hookmanager)) {
1670 $hookmanager->initHooks(array(
'fileslib'));
1672 $parameters = array(
1674 'disableglob' => $disableglob,
1675 'nophperrors' => $nophperrors
1677 $reshook = $hookmanager->executeHooks(
'deleteFile', $parameters,
$object);
1680 if (empty($nohook) && $reshook != 0) {
1688 if (empty($disableglob) && !empty($file_osencoded)) {
1690 $globencoded = str_replace(
'[',
'\[', $file_osencoded);
1691 $globencoded = str_replace(
']',
'\]', $globencoded);
1692 $listoffiles = glob($globencoded);
1694 if (!empty($listoffiles) && is_array($listoffiles)) {
1695 foreach ($listoffiles as $filename) {
1697 $ok = @unlink($filename);
1699 $ok = unlink($filename);
1703 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1704 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);
1705 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1708 $ok = @unlink($filename);
1710 $ok = unlink($filename);
1715 if (empty($nolog)) {
1716 dol_syslog(
"Removed file ".$filename, LOG_DEBUG);
1720 $rel_filetodelete = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filename);
1721 if (!preg_match(
'/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) {
1722 if (is_object(
$db) && $indexdatabase) {
1723 $rel_filetodelete = preg_replace(
'/^[\\/]/',
'', $rel_filetodelete);
1724 $rel_filetodelete = preg_replace(
'/\.noexe$/',
'', $rel_filetodelete);
1726 dol_syslog(
"Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1727 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1730 $result = $ecmfile->fetch(0,
'', $rel_filetodelete,
'',
'',
'', 0, $entity);
1731 if ($result >= 0 && $ecmfile->id > 0) {
1732 $result = $ecmfile->delete($user);
1740 dol_syslog(
"Failed to remove file ".$filename, LOG_WARNING);
1747 dol_syslog(
"No files to delete found", LOG_DEBUG);
1752 $ok = @unlink($file_osencoded);
1754 $ok = unlink($file_osencoded);
1757 $filename = $file_osencoded;
1760 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1761 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);
1762 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1765 $ok = @unlink($filename);
1767 $ok = unlink($filename);
1772 if (empty($nolog)) {
1773 dol_syslog(
"Removed file ".$filename, LOG_DEBUG);
1777 $rel_filetodelete = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filename);
1778 if (!preg_match(
'/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) {
1779 if (is_object(
$db) && $indexdatabase) {
1780 $rel_filetodelete = preg_replace(
'/^[\\/]/',
'', $rel_filetodelete);
1781 $rel_filetodelete = preg_replace(
'/\.noexe$/',
'', $rel_filetodelete);
1783 dol_syslog(
"Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1784 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1787 $result = $ecmfile->fetch(0,
'', $rel_filetodelete,
'',
'',
'', 0, $entity);
1788 if ($result >= 0 && $ecmfile->id > 0) {
1789 $result = $ecmfile->delete($user);
1797 dol_syslog(
"Failed to remove file ".$filename, LOG_WARNING);
1818 if (preg_match(
'/\.\./', $dir) || preg_match(
'/[<>|]/', $dir)) {
1819 dol_syslog(
"Refused to delete dir ".$dir.
' (contains invalid char sequence)', LOG_WARNING);
1824 return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1840function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0, $indexdatabase = 1, $nolog = 0, $level = 0)
1842 if (empty($nolog) || empty($level)) {
1843 dol_syslog(
"functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1845 if ($level > 1000) {
1846 dol_syslog(
"functions.lib:dol_delete_dir_recursive too many depth", LOG_WARNING);
1851 if ($handle = opendir(
"$dir_osencoded")) {
1852 while (
false !== ($item = readdir($handle))) {
1854 $item = mb_convert_encoding($item,
'UTF-8',
'ISO-8859-1');
1857 if ($item !=
"." && $item !=
"..") {
1859 $count =
dol_delete_dir_recursive(
"$dir/$item", $count, $nophperrors, 0, $countdeleted, $indexdatabase, $nolog, ($level + 1));
1864 $result =
dol_delete_file(
"$dir/$item", 1, $nophperrors, 0,
null,
false, $indexdatabase, $nolog);
1876 if (empty($onlysub)) {
1901 global $langs,
$conf;
1906 if (
$object->element ==
'order_supplier') {
1907 $dir =
$conf->fournisseur->commande->dir_output;
1908 } elseif (
$object->element ==
'invoice_supplier') {
1909 $dir =
$conf->fournisseur->facture->dir_output;
1910 } elseif (
$object->element ==
'project') {
1911 $dir =
$conf->project->dir_output;
1912 } elseif (
$object->element ==
'shipping') {
1913 $dir =
$conf->expedition->dir_output.
'/sending';
1914 } elseif (
$object->element ==
'delivery') {
1915 $dir =
$conf->expedition->dir_output.
'/receipt';
1916 } elseif (
$object->element ==
'fichinter') {
1917 $dir =
$conf->ficheinter->dir_output;
1919 $dir = empty(
$conf->$element->dir_output) ?
'' :
$conf->$element->dir_output;
1923 $object->error = $langs->trans(
'ErrorObjectNoSupportedByFunction');
1928 $dir = $dir.
"/".$refsan;
1929 $filepreviewnew = $dir.
"/".$refsan.
".pdf_preview.png";
1930 $filepreviewnewbis = $dir.
"/".$refsan.
".pdf_preview-0.png";
1931 $filepreviewold = $dir.
"/".$refsan.
".pdf.png";
1934 if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
1936 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnew);
1940 if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
1942 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnewbis);
1947 if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
1949 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewold);
1953 $multiple = $filepreviewold.
".";
1954 for ($i = 0; $i < 20; $i++) {
1955 $preview = $multiple.$i;
1957 if (file_exists($preview) && is_writable($preview)) {
1959 $object->error = $langs->trans(
"ErrorFailedToOpenFile", $preview);
1989 if (
$object->element ==
'order_supplier') {
1990 $dir =
$conf->fournisseur->dir_output.
'/commande';
1991 } elseif (
$object->element ==
'invoice_supplier') {
1992 $dir =
$conf->fournisseur->dir_output.
'/facture';
1993 } elseif (
$object->element ==
'project') {
1994 $dir =
$conf->project->dir_output;
1995 } elseif (
$object->element ==
'shipping') {
1996 $dir =
$conf->expedition->dir_output.
'/sending';
1997 } elseif (
$object->element ==
'delivery') {
1998 $dir =
$conf->expedition->dir_output.
'/receipt';
1999 } elseif (
$object->element ==
'fichinter') {
2000 $dir =
$conf->ficheinter->dir_output;
2002 $dir = empty(
$conf->$element->dir_output) ?
'' :
$conf->$element->dir_output;
2009 $dir = $dir.
"/".$objectref;
2010 $file = $dir.
"/".$objectref.
".meta";
2012 if (!is_dir($dir)) {
2019 $nblines = count(
$object->lines);
2024 $meta =
"REFERENCE=\"".$object->ref.
"\"
2026 NB_ITEMS=\"" . $nblines.
"\"
2027 CLIENT=\"" . $client.
"\"
2028 AMOUNT_EXCL_TAX=\"" .
$object->total_ht.
"\"
2029 AMOUNT=\"" .
$object->total_ttc.
"\"\n";
2031 for ($i = 0; $i < $nblines; $i++) {
2033 $meta .=
"ITEM_".$i.
"_QUANTITY=\"".
$object->lines[$i]->qty.
"\"
2034 ITEM_" . $i.
"_AMOUNT_WO_TAX=\"".
$object->lines[$i]->total_ht.
"\"
2035 ITEM_" . $i.
"_VAT=\"".
$object->lines[$i]->tva_tx.
"\"
2036 ITEM_" . $i.
"_DESCRIPTION=\"".str_replace(
"\r\n",
"", nl2br(
$object->lines[$i]->desc)).
"\"
2041 $fp = fopen($file,
"w");
2049 dol_syslog(
'FailedToDetectDirInDolMetaCreateFor'.
$object->element, LOG_WARNING);
2067 $listofpaths = array();
2068 $listofnames = array();
2069 $listofmimes = array();
2073 foreach ($listoffiles as $key => $val) {
2074 $listofpaths[] = $val[
'fullname'];
2075 $listofnames[] = $val[
'name'];
2079 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
2080 $_SESSION[
"listofpaths".$keytoavoidconflict] = implode(
';', $listofpaths);
2081 $_SESSION[
"listofnames".$keytoavoidconflict] = implode(
';', $listofnames);
2082 $_SESSION[
"listofmimes".$keytoavoidconflict] = implode(
';', $listofmimes);
2106function dol_add_file_process($upload_dir, $allowoverwrite = 0, $updatesessionordb = 0, $keyforsourcefile =
'addedfile', $savingdocmask =
'', $link =
null, $trackid =
'', $generatethumbs = 1,
$object =
null, $forceFullTextIndexation =
'', $mode = 0)
2114 $_FILES = array($keyforsourcefile => array());
2115 $_FILES[$keyforsourcefile][
'tmp_name'] = $keyforsourcefile;
2116 $_FILES[$keyforsourcefile][
'name'] = $keyforsourcefile;
2120 if (!empty($_FILES[$keyforsourcefile])) {
2121 dol_syslog(
'dol_add_file_process varfiles = '.$keyforsourcefile.
' upload_dir='.$upload_dir.
' allowoverwrite='.$allowoverwrite.
' updatesessionordb='.$updatesessionordb.
' savingdocmask='.$savingdocmask, LOG_DEBUG);
2122 $maxfilesinform =
getDolGlobalInt(
"MAIN_SECURITY_MAX_ATTACHMENT_ON_FORMS", 10);
2123 if (is_array($_FILES[$keyforsourcefile][
"name"]) && count($_FILES[$keyforsourcefile][
"name"]) > $maxfilesinform) {
2124 $langs->load(
"errors");
2125 setEventMessages($langs->trans(
"ErrorTooMuchFileInForm", $maxfilesinform),
null,
"errors");
2133 $TFile = $_FILES[$keyforsourcefile];
2135 if (!is_array($TFile[
'name'])) {
2136 foreach ($TFile as $key => &$val) {
2141 $nbfile = count($TFile[
'name']);
2143 for ($i = 0; $i < $nbfile; $i++) {
2144 if (empty($TFile[
'name'][$i])) {
2149 $destfile = trim($TFile[
'name'][$i]);
2150 $destfull = $upload_dir.
"/".$destfile;
2151 $destfilewithoutext = preg_replace(
'/\.[^\.]+$/',
'', $destfile);
2153 if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
2154 $destfile = trim(preg_replace(
'/__file__/', $TFile[
'name'][$i], $savingdocmask));
2155 $destfull = $upload_dir.
"/".$destfile;
2158 $filenameto = basename($destfile);
2159 if (preg_match(
'/^\./', $filenameto)) {
2160 $langs->load(
"errors");
2161 setEventMessages($langs->trans(
"ErrorFilenameCantStartWithDot", $filenameto),
null,
'errors');
2165 $info = pathinfo($destfull);
2166 $destfull = $info[
'dirname'].
'/'.
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
2167 $info = pathinfo($destfile);
2168 $destfile =
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
2171 $defaultexecutableextensions = function_exists(
'getExecutableContent') ? implode(
',',
getExecutableContent()) :
'htm,html,shtml,js,phar,php,php3,php4,php5,phtml,pht,pl,py,cgi,ksh,sh,bash,bat,cmd,wpk,exe';
2172 $fileextensionrestriction =
getDolGlobalString(
"MAIN_FILE_EXTENSION_UPLOAD_RESTRICTION", $defaultexecutableextensions);
2173 if (!empty($fileextensionrestriction)) {
2174 $arrayofregexextension = explode(
",", $fileextensionrestriction);
2176 foreach ($arrayofregexextension as $fileextension) {
2177 if (preg_match(
'/\.'.preg_quote(trim($fileextension),
'/').
'$/i', $destfull)) {
2178 $langs->load(
"errors");
2179 setEventMessages($langs->trans(
"ErrorFilenameExtensionNotAllowed", $filenameto),
null,
'errors');
2191 global $dolibarr_main_restrict_os_commands;
2192 if (!empty($dolibarr_main_restrict_os_commands)) {
2193 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
2194 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
2195 if (in_array($destfile, $arrayofallowedcommand)) {
2196 $langs->load(
"errors");
2197 setEventMessages($langs->trans(
"ErrorFilenameReserved", $destfile),
null,
'errors');
2203 $resupload =
dol_move_uploaded_file($TFile[
'tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile[
'error'][$i], 0, $keyforsourcefile, $upload_dir, $mode);
2205 if (is_numeric($resupload) && $resupload > 0) {
2206 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
2209 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
2210 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
2211 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
2212 $maxheightmini = $tmparraysize[
'maxheightmini'];
2217 if ($generatethumbs) {
2223 $imgThumbSmall =
vignette($destfull, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
2226 $imgThumbMini =
vignette($destfull, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
2231 if (empty($updatesessionordb)) {
2232 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2234 $formmail->trackid = $trackid;
2235 $formmail->add_attached_files($destfull, $destfile, $TFile[
'type'][$i]);
2239 if ($updatesessionordb == 1) {
2241 if ($TFile[
'type'][$i] ==
'application/pdf' && strpos($_SERVER[
"REQUEST_URI"],
'product') !==
false &&
getDolGlobalString(
'PRODUCT_ALLOW_EXTERNAL_DOWNLOAD')) {
2246 if ($allowoverwrite) {
2250 $result =
addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ?
'.noexe' :
''), $TFile[
'name'][$i],
'uploaded', $sharefile,
$object, $forceFullTextIndexation);
2252 if ($allowoverwrite) {
2255 setEventMessages(
'WarningFailedToAddFileIntoDatabaseIndex',
null,
'warnings');
2262 $langs->load(
"errors");
2263 if (is_numeric($resupload) && $resupload < 0) {
2265 } elseif (preg_match(
'/ErrorFileIsInfectedWithAVirus/', $resupload)) {
2266 if (preg_match(
'/File is a PDF with javascript inside/', $resupload)) {
2267 setEventMessages($langs->trans(
"ErrorFileIsAnInfectedPDFWithJSInside"),
null,
'errors');
2281 setEventMessages($langs->trans(
"ErrorFailedToCreateDir", $upload_dir),
null,
'errors');
2284 require_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
2286 $linkObject->entity =
$conf->entity;
2287 $linkObject->url = $link;
2288 $linkObject->objecttype =
GETPOST(
'objecttype',
'alpha');
2289 $linkObject->objectid =
GETPOSTINT(
'objectid');
2290 $linkObject->label =
GETPOST(
'label',
'alpha');
2291 $res = $linkObject->create($user);
2299 $langs->load(
"errors");
2300 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"File")),
null,
'errors');
2322 $keytodelete = $filenb;
2325 $listofpaths = array();
2326 $listofnames = array();
2327 $listofmimes = array();
2328 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
2329 if (!empty($_SESSION[
"listofpaths".$keytoavoidconflict])) {
2330 $listofpaths = explode(
';', $_SESSION[
"listofpaths".$keytoavoidconflict]);
2332 if (!empty($_SESSION[
"listofnames".$keytoavoidconflict])) {
2333 $listofnames = explode(
';', $_SESSION[
"listofnames".$keytoavoidconflict]);
2335 if (!empty($_SESSION[
"listofmimes".$keytoavoidconflict])) {
2336 $listofmimes = explode(
';', $_SESSION[
"listofmimes".$keytoavoidconflict]);
2339 if ($keytodelete >= 0) {
2340 $pathtodelete = $listofpaths[$keytodelete];
2341 $filetodelete = $listofnames[$keytodelete];
2342 if (empty($donotdeletefile)) {
2348 if (empty($donotdeletefile)) {
2349 $langs->load(
"other");
2350 setEventMessages($langs->trans(
"FileWasRemoved", $filetodelete),
null,
'mesgs');
2352 if (empty($donotupdatesession)) {
2353 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2355 $formmail->trackid = $trackid;
2356 $formmail->remove_attached_files($keytodelete);
2384 dol_syslog(
"addFileIntoDatabaseIndex dir=".$dir.
" file=".$file, LOG_DEBUG);
2386 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2388 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
2389 $filename = basename(preg_replace(
'/\.noexe$/',
'', $file));
2390 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2391 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2393 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
2395 $ecmfile->filepath = $rel_dir;
2396 $ecmfile->filename = $filename;
2397 $ecmfile->label = md5_file(
dol_osencode($dir.
'/'.$file));
2398 $ecmfile->fullpath_orig = $fullpathorig;
2399 $ecmfile->gen_or_uploaded = $mode;
2400 $ecmfile->description =
'';
2401 $ecmfile->keywords =
'';
2404 $ecmfile->src_object_id =
$object->id;
2405 if (isset(
$object->table_element)) {
2406 $ecmfile->src_object_type =
$object->table_element;
2408 dol_syslog(
'Error: object ' . get_class(
$object) .
' has no table_element attribute.');
2411 if (isset(
$object->src_object_description)) {
2412 $ecmfile->description =
$object->src_object_description;
2414 if (isset(
$object->src_object_keywords)) {
2415 $ecmfile->keywords =
$object->src_object_keywords;
2418 $ecmfile->entity =
$object->entity;
2427 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
2433 if (empty($useFullTextIndexation) && $forceFullTextIndexation ==
'1') {
2435 $useFullTextIndexation =
'pdftotext';
2437 $useFullTextIndexation =
'docling';
2442 if ($useFullTextIndexation) {
2443 $ecmfile->filepath = $rel_dir;
2444 $ecmfile->filename = $filename;
2446 $filetoprocess = $dir.
'/'.$ecmfile->filename;
2448 $textforfulltextindex =
'';
2451 if (preg_match(
'/\.pdf/i', $filename)) {
2455 if (empty($result[
'error'])) {
2456 $textforfulltextindex = $result[
'content'];
2457 $filetoprocess = $result[
'keywords'];
2458 $cmd = $result[
'cmd'];
2465 $ecmfile->description =
'File content generated by '.$cmd;
2467 $ecmfile->content = $textforfulltextindex;
2468 $ecmfile->keywords = $keywords;
2472 $result = $ecmfile->create($user);
2498 dol_syslog(
"deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
2502 dol_syslog(
"deleteFilesIntoDatabaseIndex dir=".$dir.
" file=".$file, LOG_DEBUG);
2506 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2508 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
2510 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2511 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2514 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'ecm_files';
2516 $sql .=
' WHERE entity = ' . ((int)
$object->entity);
2518 $sql .=
' WHERE entity = ' . ((int)
$conf->entity);
2520 $sql .=
" AND filepath = '".$db->escape($rel_dir).
"'";
2522 $sql .=
" AND filename = '".$db->escape($file).
"'";
2525 $sql .=
" AND gen_or_uploaded = '".$db->escape($mode).
"'";
2528 $resql =
$db->query($sql);
2555 if (!is_file($filePath) || !is_readable($filePath)) {
2560 $handle = fopen($filePath,
'rb');
2564 $header = fread($handle, 5);
2567 if ($header !==
'%PDF-') {
2597 if (class_exists(
'Imagick')) {
2598 $image =
new Imagick();
2604 dol_syslog(
"We try to convert a PDF file with name ".$fileinput.
" but it is not a real PDF file (hack attempt ?).", LOG_WARNING);
2608 $filetoconvert = $fileinput.(($page !=
'') ?
'['.$page.
']' :
'');
2610 $ret = $image->readImage($filetoconvert);
2612 $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
2613 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);
2618 $ret = $image->setImageFormat($ext);
2620 if (empty($fileoutput)) {
2621 $fileoutput = $fileinput.
".".$ext;
2624 $count = $image->getNumberImages();
2626 if (!
dol_is_file($fileoutput) || is_writable($fileoutput)) {
2628 $ret = $image->writeImages($fileoutput,
true);
2633 dol_syslog(
"Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
2663function dol_compress_file($inputfile, $outputfile, $mode =
"gz", &$errorstring =
null)
2669 dol_syslog(
"dol_compress_file mode=".$mode.
" inputfile=".$inputfile.
" outputfile=".$outputfile);
2672 $compressdata =
null;
2673 if ($mode ==
'gz' && function_exists(
'gzencode')) {
2675 $compressdata = gzencode($data, 9);
2676 } elseif ($mode ==
'bz' && function_exists(
'bzcompress')) {
2678 $compressdata = bzcompress($data, 9);
2679 } elseif ($mode ==
'zstd' && function_exists(
'zstd_compress')) {
2681 $compressdata = zstd_compress($data, 9);
2682 } elseif ($mode ==
'zip') {
2683 if (class_exists(
'ZipArchive') &&
getDolGlobalString(
'MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS')) {
2686 $rootPath = realpath($inputfile);
2688 dol_syslog(
"Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.
' rootPath='.$rootPath);
2689 $zip =
new ZipArchive();
2691 if ($zip->open($outputfile, ZipArchive::CREATE) !==
true) {
2692 $errorstring =
"dol_compress_file failure - Failed to open file ".$outputfile.
"\n";
2696 $errormsg = $errorstring;
2703 $files =
new RecursiveIteratorIterator(
2704 new RecursiveDirectoryIterator($rootPath, FilesystemIterator::UNIX_PATHS),
2705 RecursiveIteratorIterator::LEAVES_ONLY
2707 '@phan-var-force SplFileInfo[] $files';
2709 foreach ($files as $name => $file) {
2711 if (!$file->isDir()) {
2713 $filePath = $file->getPath();
2714 $fileName = $file->getFilename();
2715 $fileFullRealPath = $file->getRealPath();
2718 $relativePath = substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($rootPath) + 1);
2721 $zip->addFile($fileFullRealPath, $relativePath);
2728 dol_syslog(
"dol_compress_file success - ".$zip->numFiles.
" files");
2732 if (defined(
'ODTPHP_PATHTOPCLZIP')) {
2735 include_once ODTPHP_PATHTOPCLZIP.
'pclzip.lib.php';
2736 $archive =
new PclZip($outputfile);
2738 $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2740 if ($result === 0) {
2742 $errormsg = $archive->errorInfo(
true);
2744 if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
2745 $errorstring =
"PCLZIP_ERR_WRITE_OPEN_FAIL";
2746 dol_syslog(
"dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
2750 $errorstring =
"dol_compress_file error archive->errorCode = ".$archive->errorCode().
" errormsg=".$errormsg;
2751 dol_syslog(
"dol_compress_file failure - ".$errormsg, LOG_ERR);
2754 dol_syslog(
"dol_compress_file success - ".count($result).
" files");
2760 if ($foundhandler && is_string($compressdata)) {
2761 $fp = fopen($outputfile,
"w");
2762 fwrite($fp, $compressdata);
2766 $errorstring =
"Try to zip with format ".$mode.
" with no handler for this format";
2770 $errormsg = $errorstring;
2774 global $langs, $errormsg;
2775 $langs->load(
"errors");
2776 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
2778 $errorstring =
"Failed to open file ".$outputfile;
2796 $fileinfo = pathinfo($inputfile);
2797 $fileinfo[
"extension"] = strtolower($fileinfo[
"extension"]);
2799 if ($fileinfo[
"extension"] ==
"zip") {
2800 if (defined(
'ODTPHP_PATHTOPCLZIP') && !
getDolGlobalString(
'MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS')) {
2801 dol_syslog(
"Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.
", so we use Pclzip to unzip into ".$outputdir);
2802 include_once ODTPHP_PATHTOPCLZIP.
'pclzip.lib.php';
2803 $archive =
new PclZip($inputfile);
2810 $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG,
'/^((?!\.\.).)*$/');
2812 return array(
'error' => $e->getMessage());
2815 if (!is_array($result) && $result <= 0) {
2816 return array(
'error' => $archive->errorInfo(
true));
2821 foreach ($result as $key => $val) {
2822 if ($val[
'status'] ==
'path_creation_fail') {
2823 $langs->load(
"errors");
2825 $errmsg = $langs->trans(
"ErrorFailToCreateDir", $val[
'filename']);
2828 if ($val[
'status'] ==
'write_protected') {
2829 $langs->load(
"errors");
2831 $errmsg = $langs->trans(
"ErrorFailToCreateFile", $val[
'filename']);
2839 return array(
'error' => $errmsg);
2844 if (class_exists(
'ZipArchive')) {
2845 dol_syslog(
"Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
2846 $zip =
new ZipArchive();
2847 $res = $zip->open($inputfile);
2848 if ($res ===
true) {
2854 for ($i = 0; $i < $zip->numFiles; $i++) {
2855 if (preg_match(
'/\.\./', $zip->getNameIndex($i))) {
2856 dol_syslog(
"Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
2859 $zip->extractTo($outputdir.
'/', array($zip->getNameIndex($i)));
2865 return array(
'error' =>
'ErrUnzipFails');
2869 return array(
'error' =>
'ErrNoZipEngine');
2870 } elseif (in_array($fileinfo[
"extension"], array(
'gz',
'bz2',
'zst'))) {
2871 include_once DOL_DOCUMENT_ROOT.
"/core/class/utils.class.php";
2879 $extension = strtolower(pathinfo($fileinfo[
"filename"], PATHINFO_EXTENSION));
2880 if ($extension ==
"tar") {
2883 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0, $outputfilename.
'.err', 0);
2884 if ($resarray[
"result"] != 0) {
2885 $resarray[
"error"] .= file_get_contents($outputfilename.
'.err');
2889 if ($fileinfo[
"extension"] ==
"gz") {
2891 } elseif ($fileinfo[
"extension"] ==
"bz2") {
2893 } elseif ($fileinfo[
"extension"] ==
"zst") {
2896 return array(
'error' =>
'ErrorBadFileExtension');
2899 $cmd .=
' > '.$outputfilename;
2901 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0,
null, 1, $outputfilename.
'.err');
2902 if ($resarray[
"result"] != 0) {
2903 $errfilecontent = @file_get_contents($outputfilename.
'.err');
2904 if ($errfilecontent) {
2905 $resarray[
"error"] .=
" - ".$errfilecontent;
2909 return $resarray[
"result"] != 0 ? array(
'error' => $resarray[
"error"]) : array();
2912 return array(
'error' =>
'ErrorBadFileExtension');
2928function dol_compress_dir($inputdir, $outputfile, $mode =
"zip", $excludefiles =
'', $rootdirinzip =
'', $newmask =
'0')
2932 dol_syslog(
"Try to zip dir ".$inputdir.
" into ".$outputfile.
" mode=".$mode);
2934 if (!
dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
2935 global $langs, $errormsg;
2936 $langs->load(
"errors");
2937 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir", $outputfile);
2942 if ($mode ==
'gz') {
2944 } elseif ($mode ==
'bz') {
2946 } elseif ($mode ==
'zip') {
2960 if (class_exists(
'ZipArchive')) {
2964 $zip =
new ZipArchive();
2965 $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2966 if ($result !==
true) {
2967 global $langs, $errormsg;
2968 $langs->load(
"errors");
2969 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile);
2976 $files =
new RecursiveIteratorIterator(
2977 new RecursiveDirectoryIterator($inputdir, FilesystemIterator::UNIX_PATHS),
2978 RecursiveIteratorIterator::LEAVES_ONLY
2980 '@phan-var-force SplFileInfo[] $files';
2983 foreach ($files as $name => $file) {
2985 if (!$file->isDir()) {
2987 $filePath = $file->getPath();
2988 $fileName = $file->getFilename();
2989 $fileFullRealPath = $file->getRealPath();
2992 $relativePath = ($rootdirinzip ? $rootdirinzip.
'/' :
'').substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($inputdir) + 1);
2995 if (empty($excludefiles) || !preg_match($excludefiles, $fileFullRealPath)) {
2997 $zip->addFile($fileFullRealPath, $relativePath);
3008 if (empty($newmask)) {
3009 dol_syslog(
"Warning: dol_compress_dir called with empty value for newmask and no default value defined", LOG_WARNING);
3019 if (!$foundhandler) {
3020 dol_syslog(
"Try to zip with format ".$mode.
" with no handler for this format", LOG_ERR);
3026 global $langs, $errormsg;
3027 $langs->load(
"errors");
3028 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
3030 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile).
' - '.$e->getMessage();
3047function dol_most_recent_file($dir, $regexfilter =
'', $excludefilter = array(
'(\.meta|_preview.*\.png)$',
'^\.'), $nohook = 0, $mode = 0)
3049 $tmparray =
dol_dir_list($dir,
'files', 0, $regexfilter, $excludefilter,
'date', SORT_DESC, $mode, $nohook);
3050 return isset($tmparray[0]) ? $tmparray[0] :
null;
3068 global
$conf,
$db, $user, $hookmanager;
3069 global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
3072 if (!is_object($fuser)) {
3076 if (empty($modulepart)) {
3077 return 'ErrorBadParameter';
3079 if (empty($entity)) {
3090 if ($modulepart ==
'facture') {
3091 $modulepart =
'invoice';
3092 } elseif ($modulepart ==
'users') {
3093 $modulepart =
'user';
3094 } elseif ($modulepart ==
'tva') {
3095 $modulepart =
'tax-vat';
3096 } elseif ($modulepart ==
'expedition' && strpos($original_file,
'receipt/') === 0) {
3098 $modulepart =
'delivery';
3099 } elseif ($modulepart ==
'propale') {
3100 $modulepart =
'propal';
3104 dol_syslog(
'dol_check_secure_access_document modulepart='.$modulepart.
' original_file='.$original_file.
' entity='.$entity);
3108 $sqlprotectagainstexternals =
'';
3110 $checksecureaccesshook =
false;
3113 if (empty($refname)) {
3114 $refname = basename(dirname($original_file).
"/");
3115 if ($refname ==
'thumbs' || $refname ==
'temp') {
3117 $refname = basename(dirname(dirname($original_file)).
"/");
3124 $download =
'download';
3125 if ($mode ==
'write') {
3128 $download =
'upload';
3132 if ($modulepart ==
'common') {
3135 $original_file = DOL_DOCUMENT_ROOT.
'/public/theme/common/'.$original_file;
3136 } elseif ($modulepart ==
'medias' && !empty($dolibarr_main_data_root)) {
3138 if (empty($entity)) {
3142 if ($mode ==
'write') {
3143 if ($fuser->hasRight(
'website',
'write')) {
3149 $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;
3150 } elseif ($modulepart ==
'logs' && !empty($dolibarr_main_data_root)) {
3152 $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match(
'/^dolibarr.*\.(log|json)$/', basename($original_file)));
3153 $original_file = $dolibarr_main_data_root.
'/'.$original_file;
3154 } elseif ($modulepart ==
'doctemplates' && !empty($dolibarr_main_data_root)) {
3155 $accessallowed = $user->admin;
3156 $relative_file = $original_file;
3157 $ent = ($entity > 0 ? $entity :
$conf->entity);
3158 $path_with_entity = $dolibarr_main_data_root .
'/' . $ent .
'/doctemplates/' . $relative_file;
3159 if ($ent > 1 && file_exists(
dol_osencode($path_with_entity))) {
3160 $original_file = $path_with_entity;
3162 $original_file = $dolibarr_main_data_root .
'/doctemplates/' . $relative_file;
3164 } elseif ($modulepart ==
'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
3166 $accessallowed = ($fuser->hasRight(
'website',
'write') && preg_match(
'/\.jpg$/i', basename($original_file)));
3167 $original_file = $dolibarr_main_data_root.
'/doctemplates/websites/'.$original_file;
3168 } elseif ($modulepart ==
'packages' && !empty($dolibarr_main_data_root)) {
3171 $tmp = explode(
',', $dolibarr_main_document_root_alt);
3174 $accessallowed = ($user->admin && preg_match(
'/^module_.*\.zip$/', basename($original_file)));
3175 $original_file = $dirins.
'/'.$original_file;
3176 } elseif ($modulepart ==
'mycompany' && !empty(
$conf->mycompany->dir_output)) {
3179 $original_file =
$conf->mycompany->dir_output.
'/'.$original_file;
3180 } elseif ($modulepart ==
'userphoto' && !empty(
$conf->user->dir_output)) {
3183 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
3187 if ($mode !=
'read' && empty($fuser->admin) && !$fuser->hasRight(
'user',
'user', $lire) && !((
int) $original_file == $fuser->id && $fuser->hasRight(
'user',
'self', $lire))) {
3190 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3191 } elseif ($modulepart ==
'userphotopublic' && !empty(
$conf->user->dir_output)) {
3196 if (preg_match(
'/^(\d+)\/photos\//', $original_file, $reg)) {
3197 if ((
int) $reg[1]) {
3199 $tmpobject->fetch((
int) $reg[1],
'',
'', 1);
3201 $securekey =
GETPOST(
'securekey',
'alpha', 1);
3203 global $dolibarr_main_cookie_cryptkey, $dolibarr_main_instance_unique_id;
3204 $valuetouse = $dolibarr_main_instance_unique_id ? $dolibarr_main_instance_unique_id : $dolibarr_main_cookie_cryptkey;
3205 $encodedsecurekey =
dol_hash($valuetouse.
'uservirtualcard'.$tmpobject->id.
'-'.$tmpobject->login,
'md5');
3206 if (hash_equals($encodedsecurekey, (
string) $securekey)) {
3215 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3216 } elseif (($modulepart ==
'companylogo') && !empty(
$conf->mycompany->dir_output)) {
3219 $original_file =
$conf->mycompany->dir_output.
'/logos/'.$original_file;
3220 } elseif ($modulepart ==
'memberphoto' && !empty(
$conf->member->dir_output)) {
3224 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
3228 if (preg_match(
'/^MEM\d\d\d\d-\d\d\d\d\/photos\//', $original_file)) {
3231 $original_file =
$conf->member->dir_output.
'/'.$original_file;
3232 } elseif ($modulepart ==
'apercufacture' && !empty(
$conf->invoice->multidir_output[$entity])) {
3234 if ($fuser->hasRight(
'facture', $lire)) {
3237 $original_file =
$conf->invoice->multidir_output[$entity].
'/'.$original_file;
3238 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'invoice').
")";
3239 } elseif ($modulepart ==
'apercupropal' && !empty(
$conf->propal->multidir_output[$entity])) {
3241 if ($fuser->hasRight(
'propal', $lire)) {
3244 $original_file =
$conf->propal->multidir_output[$entity].
'/'.$original_file;
3245 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"propal WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'propal').
")";
3246 } elseif ($modulepart ==
'apercucommande' && !empty(
$conf->order->multidir_output[$entity])) {
3248 if ($fuser->hasRight(
'commande', $lire)) {
3251 $original_file =
$conf->order->multidir_output[$entity].
'/'.$original_file;
3252 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'order').
")";
3253 } elseif (($modulepart ==
'apercufichinter' || $modulepart ==
'apercuficheinter') && !empty(
$conf->ficheinter->multidir_output[$entity])) {
3255 if ($fuser->hasRight(
'ficheinter', $lire)) {
3258 $original_file =
$conf->ficheinter->multidir_output[$entity].
'/'.$original_file;
3259 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"fichinter WHERE ref='".
$db->escape($refname).
"' AND entity=".((int) $entity);
3260 } elseif (($modulepart ==
'apercucontract') && !empty(
$conf->contract->multidir_output[$entity])) {
3262 if ($fuser->hasRight(
'contrat', $lire)) {
3265 $original_file =
$conf->contract->multidir_output[$entity].
'/'.$original_file;
3266 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"contrat WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'contract').
")";
3267 } elseif (($modulepart ==
'apercusupplier_proposal') && !empty(
$conf->supplier_proposal->dir_output)) {
3269 if ($fuser->hasRight(
'supplier_proposal', $lire)) {
3272 $original_file =
$conf->supplier_proposal->dir_output.
'/'.$original_file;
3273 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"supplier_proposal WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'supplier_proposal').
")";
3274 } elseif (($modulepart ==
'apercusupplier_order') && !empty(
$conf->fournisseur->commande->dir_output)) {
3276 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
3279 $original_file =
$conf->fournisseur->commande->dir_output.
'/'.$original_file;
3280 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande_fournisseur WHERE ref='".
$db->escape($refname).
"' AND entity = ".((int)
$conf->entity);
3281 } elseif (($modulepart ==
'apercusupplier_invoice') && !empty(
$conf->fournisseur->facture->dir_output)) {
3283 if ($fuser->hasRight(
'fournisseur', $lire)) {
3286 $original_file =
$conf->fournisseur->facture->dir_output.
'/'.$original_file;
3287 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture_fourn WHERE ref='".
$db->escape($refname).
"' AND entity=".((int)
$conf->entity);
3288 } elseif (($modulepart ==
'holiday') && !empty(
$conf->holiday->dir_output)) {
3289 if ($fuser->hasRight(
'holiday', $read) || ($mode ==
'read' && $fuser->hasRight(
'holiday',
'readall')) || preg_match(
'/^specimen/i', $original_file)) {
3292 if ($refname && !$fuser->hasRight(
'holiday',
'readall') && !preg_match(
'/^specimen/i', $original_file)) {
3293 include_once DOL_DOCUMENT_ROOT.
'/holiday/class/holiday.class.php';
3295 $tmpholiday->fetch(0, $refname);
3296 $accessallowed =
checkUserAccessToObject($user, array(
'holiday'), $tmpholiday,
'holiday',
'',
'',
'rowid',
'');
3299 $original_file =
$conf->holiday->dir_output.
'/'.$original_file;
3300 } elseif (($modulepart ==
'salaries') && !empty(
$conf->salaries->dir_output)) {
3302 if ($fuser->hasRight(
'salaries', $read) || ($mode ==
'read' && $fuser->hasRight(
'salaries',
'readall')) || preg_match(
'/^specimen/i', $original_file)) {
3308 if ($refname && !$fuser->hasRight(
'salaries',
'readall') && !preg_match(
'/^specimen/i', $original_file)) {
3309 include_once DOL_DOCUMENT_ROOT.
'/salaries/class/salary.class.php';
3311 $tmpsalary->fetch((
int) $refname);
3316 $accessallowed = ($tmpsalary->fk_user > 0 && in_array($tmpsalary->fk_user, $fuser->getAllChildIds(1))) ? 1 : 0;
3319 $original_file =
$conf->salaries->dir_output.
'/'.$original_file;
3320 } elseif (($modulepart ==
'expensereport') && !empty(
$conf->expensereport->dir_output)) {
3321 if ($fuser->hasRight(
'expensereport', $lire) || ($mode ==
'read' && $fuser->hasRight(
'expensereport',
'readall')) || preg_match(
'/^specimen/i', $original_file)) {
3324 if ($refname && !$fuser->hasRight(
'expensereport',
'readall') && !preg_match(
'/^specimen/i', $original_file)) {
3325 include_once DOL_DOCUMENT_ROOT.
'/expensereport/class/expensereport.class.php';
3327 $tmpexpensereport->fetch(0, $refname);
3328 $accessallowed =
checkUserAccessToObject($user, array(
'expensereport'), $tmpexpensereport,
'expensereport',
'',
'',
'rowid',
'');
3331 $original_file =
$conf->expensereport->dir_output.
'/'.$original_file;
3332 } elseif (($modulepart ==
'apercuexpensereport') && !empty(
$conf->expensereport->dir_output)) {
3334 if ($fuser->hasRight(
'expensereport', $lire)) {
3337 if ($fuser->socid > 0) {
3341 $original_file =
$conf->expensereport->dir_output.
'/'.$original_file;
3342 } elseif ($modulepart ==
'propalstats' && !empty(
$conf->propal->multidir_temp[$entity])) {
3344 if ($fuser->hasRight(
'propal', $lire)) {
3347 $original_file =
$conf->propal->multidir_temp[$entity].
'/'.$original_file;
3348 } elseif ($modulepart ==
'orderstats' && !empty(
$conf->order->dir_temp)) {
3350 if ($fuser->hasRight(
'commande', $lire)) {
3353 $original_file =
$conf->order->dir_temp.
'/'.$original_file;
3354 } elseif ($modulepart ==
'orderstatssupplier' && !empty(
$conf->fournisseur->dir_output)) {
3355 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
3358 $original_file =
$conf->fournisseur->commande->dir_temp.
'/'.$original_file;
3359 } elseif ($modulepart ==
'billstats' && !empty(
$conf->invoice->dir_temp)) {
3361 if ($fuser->hasRight(
'facture', $lire)) {
3364 $original_file =
$conf->invoice->dir_temp.
'/'.$original_file;
3365 } elseif ($modulepart ==
'billstatssupplier' && !empty(
$conf->fournisseur->dir_output)) {
3366 if ($fuser->hasRight(
'fournisseur',
'facture', $lire)) {
3369 $original_file =
$conf->fournisseur->facture->dir_temp.
'/'.$original_file;
3370 } elseif ($modulepart ==
'expeditionstats' && !empty(
$conf->expedition->dir_temp)) {
3372 if ($fuser->hasRight(
'expedition', $lire)) {
3375 $original_file =
$conf->expedition->dir_temp.
'/'.$original_file;
3376 } elseif ($modulepart ==
'tripsexpensesstats' && !empty(
$conf->deplacement->dir_temp)) {
3378 if ($fuser->hasRight(
'deplacement', $lire)) {
3381 $original_file =
$conf->deplacement->dir_temp.
'/'.$original_file;
3382 } elseif ($modulepart ==
'memberstats' && !empty(
$conf->member->dir_temp)) {
3384 if ($fuser->hasRight(
'adherent', $lire)) {
3387 $original_file =
$conf->member->dir_temp.
'/'.$original_file;
3388 } elseif (preg_match(
'/^productstats_/i', $modulepart) && !empty(
$conf->product->dir_temp)) {
3390 if ($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) {
3393 $original_file = (!empty(
$conf->product->multidir_temp[$entity]) ?
$conf->product->multidir_temp[$entity] :
$conf->service->multidir_temp[$entity]).
'/'.$original_file;
3394 } elseif (in_array($modulepart, array(
'tax',
'tax-vat',
'tva')) && !empty(
$conf->tax->dir_output)) {
3396 if ($fuser->hasRight(
'tax',
'charges', $lire)) {
3399 $modulepartsuffix = str_replace(
'tax-',
'', $modulepart);
3400 $original_file =
$conf->tax->dir_output.
'/'.($modulepartsuffix !=
'tax' ? $modulepartsuffix.
'/' :
'').$original_file;
3401 } elseif (($modulepart ==
'actions' || $modulepart ==
'actioncomm') && !empty(
$conf->agenda->dir_output)) {
3403 if ($fuser->hasRight(
'agenda',
'allactions', $read)) {
3405 } elseif ($fuser->hasRight(
'agenda',
'myactions', $read)) {
3408 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3409 include_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
3411 $tmpobject->fetch((
int) $refname);
3412 $accessallowed =
checkUserAccessToObject($user, array(
'agenda'), $tmpobject->id,
'actioncomm&societe',
'myactions|allactions',
'fk_soc',
'id',
'');
3413 if ($user->socid && $tmpobject->socid) {
3418 $original_file =
$conf->agenda->dir_output.
'/'.$original_file;
3419 } elseif ($modulepart ==
'category' && !empty(
$conf->categorie->multidir_output[$entity])) {
3421 if (empty($entity) || empty(
$conf->categorie->multidir_output[$entity])) {
3422 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3424 if ($fuser->hasRight(
"categorie", $lire) || ($mode ==
'read' && $fuser->hasRight(
"takepos",
"run"))) {
3427 $original_file =
$conf->categorie->multidir_output[$entity].
'/'.$original_file;
3428 } elseif ($modulepart ==
'prelevement' && !empty(
$conf->prelevement->dir_output)) {
3430 if ($fuser->hasRight(
'prelevement',
'bons', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3433 $original_file =
$conf->prelevement->dir_output.
'/'.$original_file;
3434 } elseif ($modulepart ==
'graph_stock' && !empty(
$conf->stock->dir_temp)) {
3437 $original_file =
$conf->stock->dir_temp.
'/'.$original_file;
3438 } elseif ($modulepart ==
'graph_fourn' && !empty(
$conf->fournisseur->dir_temp)) {
3441 $original_file =
$conf->fournisseur->dir_temp.
'/'.$original_file;
3442 } elseif ($modulepart ==
'graph_product' && !empty(
$conf->product->dir_temp)) {
3445 $original_file =
$conf->product->multidir_temp[$entity].
'/'.$original_file;
3446 } elseif ($modulepart ==
'barcode') {
3451 $original_file =
'';
3452 } elseif ($modulepart ==
'iconmailing' && !empty(
$conf->mailing->dir_temp)) {
3455 $original_file =
$conf->mailing->dir_temp.
'/'.$original_file;
3456 } elseif ($modulepart ==
'scanner_user_temp' && !empty(
$conf->scanner->dir_temp)) {
3459 $original_file =
$conf->scanner->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3460 } elseif ($modulepart ==
'fckeditor' && !empty(
$conf->fckeditor->dir_output)) {
3463 $original_file =
$conf->fckeditor->dir_output.
'/'.$original_file;
3464 } elseif ($modulepart ==
'user' && !empty(
$conf->user->dir_output)) {
3466 $canreaduser = (!empty($fuser->admin) || $fuser->hasRight(
'user',
'user', $lire));
3467 if ($fuser->id == (
int) $refname) {
3470 if ($canreaduser || preg_match(
'/^specimen/i', $original_file)) {
3473 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3474 } elseif (($modulepart ==
'company' || $modulepart ==
'societe' || $modulepart ==
'thirdparty') && !empty(
$conf->societe->multidir_output[$entity])) {
3476 if (empty($entity) || empty(
$conf->societe->multidir_output[$entity])) {
3477 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3479 if ($fuser->hasRight(
'societe', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3482 $original_file =
$conf->societe->multidir_output[$entity].
'/'.$original_file;
3483 $sqlprotectagainstexternals =
"SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX.
"societe WHERE rowid = ".((int) $refname).
" AND entity IN (".
getEntity(
'societe').
")";
3484 } elseif (($modulepart ==
'contact' || $modulepart ==
'socpeople') && !empty(
$conf->societe->multidir_output[$entity])) {
3486 $checksecureaccesshook =
true;
3487 if (empty($entity) || empty(
$conf->societe->multidir_output[$entity])) {
3488 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3490 if ($fuser->hasRight(
'societe',
'contact', $lire)) {
3493 $original_file =
$conf->societe->multidir_output[$entity].
'/contact/'.$original_file;
3494 $sqlprotectagainstexternals =
"SELECT fk_soc FROM ".MAIN_DB_PREFIX.
"socpeople WHERE rowid = ".((int) $refname).
" AND entity IN (".
getEntity(
'contact').
")";
3495 } elseif (($modulepart ==
'facture' || $modulepart ==
'invoice') && !empty(
$conf->invoice->multidir_output[$entity])) {
3497 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3500 $original_file =
$conf->invoice->multidir_output[$entity].
'/'.$original_file;
3501 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'invoice').
")";
3502 } elseif ($modulepart ==
'massfilesarea_proposals' && !empty(
$conf->propal->multidir_output[$entity])) {
3504 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3507 $original_file =
$conf->propal->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3508 } elseif ($modulepart ==
'massfilesarea_orders') {
3509 if ($fuser->hasRight(
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3512 $original_file =
$conf->order->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3513 } elseif ($modulepart ==
'massfilesarea_sendings') {
3514 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3517 $original_file =
$conf->expedition->dir_output.
'/sending/temp/massgeneration/'.$user->id.
'/'.$original_file;
3518 } elseif ($modulepart ==
'massfilesarea_receipts') {
3519 if ($fuser->hasRight(
'reception', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3522 $original_file =
$conf->reception->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3523 } elseif ($modulepart ==
'massfilesarea_invoices') {
3524 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3527 $original_file =
$conf->invoice->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3528 } elseif ($modulepart ==
'massfilesarea_expensereport') {
3529 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3532 $original_file =
$conf->expensereport->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3533 } elseif ($modulepart ==
'massfilesarea_interventions') {
3534 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3537 $original_file =
$conf->ficheinter->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3538 } elseif ($modulepart ==
'massfilesarea_supplier_proposal' && !empty(
$conf->supplier_proposal->dir_output)) {
3539 if ($fuser->hasRight(
'supplier_proposal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3542 $original_file =
$conf->supplier_proposal->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3543 } elseif ($modulepart ==
'massfilesarea_supplier_order') {
3544 if ($fuser->hasRight(
'fournisseur',
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3547 $original_file =
$conf->fournisseur->commande->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3548 } elseif ($modulepart ==
'massfilesarea_supplier_invoice') {
3549 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3552 $original_file =
$conf->fournisseur->facture->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3553 } elseif ($modulepart ==
'massfilesarea_contract' && !empty(
$conf->contract->dir_output)) {
3554 if ($fuser->hasRight(
'contrat', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3557 $original_file =
$conf->contract->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3558 } elseif ($modulepart ==
'massfilesarea_stock' && !empty(
$conf->stock->dir_output)) {
3559 if ($fuser->hasRight(
'stock', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3562 $original_file =
$conf->stock->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3563 } elseif (($modulepart ==
'fichinter' || $modulepart ==
'ficheinter') && !empty(
$conf->ficheinter->multidir_output[$entity])) {
3565 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3568 $original_file =
$conf->ficheinter->multidir_output[$entity].
'/'.$original_file;
3569 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"fichinter WHERE ref='".
$db->escape($refname).
"' AND entity=".((int)
$conf->entity);
3570 } elseif ($modulepart ==
'deplacement' && !empty(
$conf->deplacement->dir_output)) {
3572 if ($fuser->hasRight(
'deplacement', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3575 $original_file =
$conf->deplacement->dir_output.
'/'.$original_file;
3577 } elseif (($modulepart ==
'propal' || $modulepart ==
'propale') && isset(
$conf->propal->multidir_output[$entity])) {
3579 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3582 $original_file =
$conf->propal->multidir_output[$entity].
'/'.$original_file;
3583 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"propal WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'propal').
")";
3584 } elseif (($modulepart ==
'commande' || $modulepart ==
'order') && !empty(
$conf->order->multidir_output[$entity])) {
3586 if ($fuser->hasRight(
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3589 $original_file =
$conf->order->multidir_output[$entity].
'/'.$original_file;
3590 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'order').
")";
3591 } elseif ($modulepart ==
'project' && !empty(
$conf->project->multidir_output[$entity])) {
3593 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3596 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3597 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
3599 $tmpproject->fetch(0, $refname);
3600 $accessallowed =
checkUserAccessToObject($user, array(
'projet'), $tmpproject->id,
'projet&project',
'',
'',
'rowid',
'');
3603 $original_file =
$conf->project->multidir_output[$entity].
'/'.$original_file;
3604 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3605 } elseif ($modulepart ==
'project_task' && !empty(
$conf->project->multidir_output[$entity])) {
3606 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3609 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3610 include_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
3612 $tmptask->fetch(0, $refname);
3613 $accessallowed =
checkUserAccessToObject($user, array(
'projet_task'), $tmptask->id,
'projet_task&project',
'',
'',
'rowid',
'');
3616 $original_file =
$conf->project->multidir_output[$entity].
'/'.$original_file;
3617 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3618 } elseif (($modulepart ==
'commande_fournisseur' || $modulepart ==
'order_supplier' || $modulepart ==
'supplier_order') && !empty(
$conf->fournisseur->commande->dir_output)) {
3620 if ($fuser->hasRight(
'fournisseur',
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3623 $original_file = (!empty(
$conf->fournisseur->commande->multidir_output[$entity]) ?
$conf->fournisseur->commande->multidir_output[$entity] :
$conf->fournisseur->commande->dir_output).
'/'.$original_file;
3624 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande_fournisseur WHERE ref='".
$db->escape($refname).
"' AND entity = ".((int)
$conf->entity);
3625 } elseif (($modulepart ==
'facture_fournisseur' || $modulepart ==
'invoice_supplier' || $modulepart ==
'supplier_invoice') && !empty(
$conf->fournisseur->facture->dir_output)) {
3627 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3630 $original_file = (!empty(
$conf->fournisseur->facture->multidir_output[$entity]) ?
$conf->fournisseur->facture->multidir_output[$entity] :
$conf->fournisseur->facture->dir_output).
'/'.$original_file;
3631 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture_fourn WHERE ref='".
$db->escape($refname).
"' AND entity=".((int)
$conf->entity);
3632 } elseif ($modulepart ==
'supplier_payment') {
3634 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3637 $original_file = preg_replace(
"/payment\//",
"", $original_file);
3638 $original_file =
$conf->fournisseur->payment->dir_output.
'/'.$original_file;
3639 $sqlprotectagainstexternals =
"SELECT f.fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"paiementfourn as p";
3640 $sqlprotectagainstexternals .=
" INNER JOIN ".MAIN_DB_PREFIX.
"paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid";
3641 $sqlprotectagainstexternals .=
" INNER JOIN ".MAIN_DB_PREFIX.
"facture_fourn as f ON pf.fk_facturefourn = p.rowid";
3642 $sqlprotectagainstexternals .=
" WHERE p.ref = '".$db->escape($refname).
"' AND p.entity=".((int)
$conf->entity);
3643 } elseif ($modulepart ==
'payment') {
3645 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3648 $original_file =
$conf->compta->payment->dir_output.
'/'.$original_file;
3649 } elseif ($modulepart ==
'facture_paiement' && !empty(
$conf->invoice->dir_output)) {
3651 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3654 if ($fuser->socid > 0) {
3655 $original_file =
$conf->invoice->dir_output.
'/payments/private/'.$fuser->id.
'/'.$original_file;
3657 $original_file =
$conf->invoice->dir_output.
'/payments/'.$original_file;
3664 } elseif ($modulepart ==
'accounting' && !empty(
$conf->accounting->dir_output)) {
3666 if ($fuser->hasRight(
'accounting',
'bind',
'write') || $fuser->hasRight(
'accounting',
'mouvements',
'export') || preg_match(
'/^specimen/i', $original_file)) {
3669 $original_file =
$conf->accounting->dir_output.
'/'.$original_file;
3670 } elseif (($modulepart ==
'expedition' || $modulepart ==
'shipment' || $modulepart ==
'shipping') && !empty(
$conf->expedition->dir_output)) {
3672 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3675 $original_file =
$conf->expedition->dir_output.
"/".(strpos($original_file,
'sending/') === 0 ?
'' :
'sending/').$original_file;
3677 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"expedition WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'expedition').
")";
3678 } elseif (($modulepart ==
'livraison' || $modulepart ==
'delivery') && !empty(
$conf->expedition->dir_output)) {
3680 if ($fuser->hasRight(
'expedition',
'delivery', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3683 $original_file =
$conf->expedition->dir_output.
"/".(strpos($original_file,
'receipt/') === 0 ?
'' :
'receipt/').$original_file;
3684 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"delivery WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'delivery').
")";
3685 } elseif ($modulepart ==
'actionsreport' && !empty(
$conf->agenda->dir_temp)) {
3687 if ($fuser->hasRight(
'agenda',
'allactions', $read) || preg_match(
'/^specimen/i', $original_file)) {
3690 $original_file =
$conf->agenda->dir_temp.
"/".$original_file;
3691 } elseif ($modulepart ==
'product' || $modulepart ==
'produit' || $modulepart ==
'service' || $modulepart ==
'produit|service') {
3693 $checksecureaccesshook =
true;
3694 if (empty($entity) || (empty(
$conf->product->multidir_output[$entity]) && empty(
$conf->service->multidir_output[$entity]))) {
3695 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3697 if (($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3701 $original_file =
$conf->product->multidir_output[$entity].
'/'.$original_file;
3703 $original_file =
$conf->service->multidir_output[$entity].
'/'.$original_file;
3705 } elseif ($modulepart ==
'product_batch' || $modulepart ==
'produitlot') {
3707 if (empty($entity) || (empty(
$conf->productbatch->multidir_output[$entity]))) {
3708 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3710 if (($fuser->hasRight(
'produit', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3714 $original_file =
$conf->productbatch->multidir_output[$entity].
'/'.$original_file;
3716 } elseif ($modulepart ==
'movement' || $modulepart ==
'mouvement') {
3718 if (empty($entity) || empty(
$conf->stock->multidir_output[$entity])) {
3719 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3721 if (($fuser->hasRight(
'stock', $lire) || $fuser->hasRight(
'stock',
'movement', $lire) || $fuser->hasRight(
'stock',
'mouvement', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3725 $original_file =
$conf->stock->multidir_output[$entity].
'/movement/'.$original_file;
3727 } elseif ($modulepart ==
'entrepot') {
3729 if (empty($entity) || empty(
$conf->stock->multidir_output[$entity])) {
3730 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3732 if (($fuser->hasRight(
'stock', $lire) || $fuser->hasRight(
'stock',
'movement', $lire) || $fuser->hasRight(
'stock',
'mouvement', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3736 $original_file =
$conf->stock->multidir_output[$entity].
'/'.$original_file;
3738 } elseif ($modulepart ==
'contract' && !empty(
$conf->contract->multidir_output[$entity])) {
3740 if ($fuser->hasRight(
'contrat', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3743 $original_file =
$conf->contract->multidir_output[$entity].
'/'.$original_file;
3744 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"contrat WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'contract').
")";
3745 } elseif ($modulepart ==
'donation' && !empty(
$conf->don->dir_output)) {
3747 if ($fuser->hasRight(
'don', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3750 $original_file =
$conf->don->dir_output.
'/'.$original_file;
3751 } elseif ($modulepart ==
'dolresource' && !empty(
$conf->resource->dir_output)) {
3753 if ($fuser->hasRight(
'resource', $read) || preg_match(
'/^specimen/i', $original_file)) {
3756 $original_file =
$conf->resource->dir_output.
'/'.$original_file;
3757 } elseif (($modulepart ==
'remisecheque' || $modulepart ==
'chequereceipt') && !empty(
$conf->bank->dir_output)) {
3759 if ($fuser->hasRight(
'banque', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3762 $original_file =
$conf->bank->dir_output.
'/checkdeposits/'.$original_file;
3763 } elseif (($modulepart ==
'banque' || $modulepart ==
'bank') && !empty(
$conf->bank->dir_output)) {
3766 if ($fuser->hasRight(
'banque', ($mode ==
'read' ?
'lire' :
'modifier'))) {
3769 $original_file =
$conf->bank->dir_output.
'/'.$original_file;
3770 } elseif ($modulepart ==
'export' && !empty(
$conf->export->dir_temp)) {
3773 $accessallowed = $fuser->hasRight(
'export', $lire);
3774 $original_file =
$conf->export->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3775 } elseif ($modulepart ==
'import' && !empty(
$conf->import->dir_temp)) {
3777 $accessallowed = $user->hasRight(
'import',
'run');
3778 $original_file =
$conf->import->dir_temp.
'/'.$original_file;
3779 } elseif ($modulepart ==
'recruitment' && !empty(
$conf->recruitment->dir_output)) {
3781 $accessallowed = $fuser->hasRight(
'recruitment',
'recruitmentjobposition', $read);
3782 $original_file =
$conf->recruitment->dir_output.
'/'.$original_file;
3783 } elseif ($modulepart ==
'hrm' && !empty(
$conf->hrm->dir_output)) {
3785 $accessallowed = $fuser->hasRight(
'hrm',
'all', $read);
3786 $original_file =
$conf->hrm->dir_output.
'/'.$original_file;
3787 } elseif ($modulepart ==
'editor' && !empty(
$conf->fckeditor->dir_output)) {
3790 $original_file =
$conf->fckeditor->dir_output.
'/'.$original_file;
3791 } elseif ($modulepart ==
'systemtools' && !empty(
$conf->admin->dir_output)) {
3793 if ($fuser->admin) {
3796 $original_file =
$conf->admin->dir_output.
'/'.$original_file;
3797 } elseif ($modulepart ==
'admin_temp' && !empty(
$conf->admin->dir_temp)) {
3799 if ($fuser->admin) {
3802 $original_file =
$conf->admin->dir_temp.
'/'.$original_file;
3803 } elseif ($modulepart ==
'bittorrent' && !empty(
$conf->bittorrent->dir_output)) {
3807 if (
dol_mimetype($original_file) ==
'application/x-bittorrent') {
3810 $original_file =
$conf->bittorrent->dir_output.
'/'.$dir.
'/'.$original_file;
3811 } elseif ($modulepart ==
'member' && !empty(
$conf->member->dir_output)) {
3813 if ($fuser->hasRight(
'adherent', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3816 $original_file =
$conf->member->dir_output.
'/'.$original_file;
3817 } elseif ($modulepart ==
'ticket' && !empty(
$conf->ticket->multidir_output[$entity])) {
3819 if ($fuser->hasRight(
'ticket', $read)) {
3822 if (!isset($_SESSION[
'email_customer'])) {
3824 $sqlprotectagainstexternals =
"SELECT fk_soc FROM ".MAIN_DB_PREFIX.
"ticket WHERE ref='".
$db->escape($refname).
"' AND entity=".((int)
$conf->entity);
3826 $email_split = explode(
'@', $_SESSION[
'email_customer']);
3828 $sqlprotectagainstexternals =
'SELECT t.rowid, t.fk_soc FROM '.MAIN_DB_PREFIX.
'ticket t';
3829 $sqlprotectagainstexternals .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'element_contact ec ON ec.element_id = t.rowid';
3830 $sqlprotectagainstexternals .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'socpeople c ON c.rowid = ec.fk_socpeople';
3831 $sqlprotectagainstexternals .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_type_contact tc ON tc.element = "ticket" AND tc.rowid = ec.fk_c_type_contact';
3832 $sqlprotectagainstexternals .=
" WHERE t.ref LIKE '".$db->escape($refname).
"'";
3833 $sqlprotectagainstexternals .=
' AND (';
3834 $sqlprotectagainstexternals .=
' (';
3835 $sqlprotectagainstexternals .=
' tc.rowid IS NOT NULL';
3836 $sqlprotectagainstexternals .=
" AND c.email = '".$db->escape($email_split[0]).
'@'.
$db->sanitize($email_split[1]).
"'";
3837 $sqlprotectagainstexternals .=
' )';
3838 $sqlprotectagainstexternals .=
" OR t.origin_email = '".$db->escape($email_split[0]).
'@'.
$db->sanitize($email_split[1]).
"'";
3839 $sqlprotectagainstexternals .=
' )';
3841 $original_file =
$conf->ticket->multidir_output[$entity].
'/'.$original_file;
3849 $checksecureaccesshook =
true;
3852 if (preg_match(
'/^specimen/i', $original_file)) {
3855 if ($fuser->admin) {
3859 $tmpmodulepart = explode(
'-', $modulepart);
3860 if (!empty($tmpmodulepart[1])) {
3861 $modulepart = $tmpmodulepart[0];
3862 $original_file = $tmpmodulepart[1].
'/'.$original_file;
3867 if (preg_match(
'/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
3868 $tmpmodule = $reg[1];
3869 if (empty(
$conf->$tmpmodule->dir_temp)) {
3870 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3873 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3876 $original_file =
$conf->{$reg[1]}->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3877 } elseif (preg_match(
'/^([a-z]+)_temp$/i', $modulepart, $reg)) {
3878 $tmpmodule = $reg[1];
3879 if (empty(
$conf->$tmpmodule->dir_temp)) {
3880 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3883 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3886 $original_file =
$conf->$tmpmodule->dir_temp.
'/'.$original_file;
3887 } elseif (preg_match(
'/^([a-z]+)_user$/i', $modulepart, $reg)) {
3888 $tmpmodule = $reg[1];
3889 if (empty(
$conf->$tmpmodule->dir_output)) {
3890 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3893 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3896 $original_file =
$conf->$tmpmodule->dir_output.
'/'.$fuser->id.
'/'.$original_file;
3897 } elseif (preg_match(
'/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
3898 $tmpmodule = $reg[1];
3899 if (empty(
$conf->$tmpmodule->dir_output)) {
3900 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3905 $partsofdirinoriginalfile = explode(
'/', $original_file);
3906 if (!empty($partsofdirinoriginalfile[1])) {
3907 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3908 if (($partofdirinoriginalfile && $fuser->hasRight($tmpmodule, $partofdirinoriginalfile,
'read')) || preg_match(
'/^specimen/i', $original_file)) {
3912 if ($fuser->hasRight($tmpmodule, $read) || preg_match(
'/^specimen/i', $original_file)) {
3915 $original_file =
$conf->$tmpmodule->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3917 if (empty(
$conf->$modulepart->dir_output)) {
3918 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.');
3923 $partsofdirinoriginalfile = explode(
'/', $original_file);
3924 if (!empty($partsofdirinoriginalfile[1])) {
3925 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3926 if ($partofdirinoriginalfile && ($fuser->hasRight($modulepart, $partofdirinoriginalfile, $lire) || $fuser->hasRight($modulepart, $partofdirinoriginalfile, $read))) {
3930 if (($fuser->hasRight($modulepart, $lire) || $fuser->hasRight($modulepart, $read)) || ($fuser->hasRight($modulepart,
'all', $lire) || $fuser->hasRight($modulepart,
'all', $read))) {
3934 if (is_array(
$conf->$modulepart->multidir_output) && !empty(
$conf->$modulepart->multidir_output[$entity])) {
3935 $original_file =
$conf->$modulepart->multidir_output[$entity].
'/'.$original_file;
3937 $original_file =
$conf->$modulepart->dir_output.
'/'.$original_file;
3943 if ($checksecureaccesshook) {
3944 $parameters = array(
3945 'modulepart' => $modulepart,
3946 'original_file' => $original_file,
3947 'entity' => $entity,
3952 $reshook = $hookmanager->executeHooks(
'checkSecureAccess', $parameters,
$object);
3955 } elseif ($reshook > 0) {
3956 if (!empty($hookmanager->resArray[
'original_file'])) {
3957 $original_file = $hookmanager->resArray[
'original_file'];
3959 if (array_key_exists(
'accessallowed', $hookmanager->resArray)) {
3960 $accessallowed = $hookmanager->resArray[
'accessallowed'];
3962 if (!empty($hookmanager->resArray[
'sqlprotectagainstexternals'])) {
3963 $sqlprotectagainstexternals = $hookmanager->resArray[
'sqlprotectagainstexternals'];
3971 if ($mode !=
'read' && empty($fuser->admin)) {
3972 if (in_array($modulepart, array(
'mycompany',
'companylogo',
'graph_stock',
'graph_fourn',
'graph_product',
'barcode',
'iconmailing',
'fckeditor',
'editor',
'bittorrent'))) {
3975 if ($modulepart ==
'memberphoto' && !$fuser->hasRight(
'adherent', $lire)) {
3981 'accessallowed' => ($accessallowed ? 1 : 0),
3982 'sqlprotectagainstexternals' => $sqlprotectagainstexternals,
3983 'original_file' => $original_file
4002 dol_syslog(
"Failed to create the cache directory ".$directory, LOG_WARNING);
4005 $cachefile = $directory.$filename;
4007 file_put_contents($cachefile, json_encode(
$object), LOCK_EX);
4022 $cachefile = $directory.$filename;
4023 $refresh = !file_exists($cachefile) || ($now - $cachetime) >
dol_filemtime($cachefile);
4036 $cachefile = $directory.$filename;
4037 $object = json_decode(file_get_contents($cachefile));
4049 return preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\//',
'', $pathfile);
4064function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path =
'', $pathref =
'', &$checksumconcat = array())
4072 if (!empty($dir->md5file)) {
4073 $entry = $dir->md5file;
4075 } elseif (!empty($dir->sha256file)) {
4076 $entry = $dir->sha256file;
4080 foreach ($entry as $file) {
4081 $filename = $path.$file[
'name'];
4082 $file_list[
'insignature'][] = $filename;
4083 $expectedsize = (empty($file[
'size']) ?
'' : $file[
'size']);
4084 $expectedhash = (
string) $file;
4086 if (!file_exists($pathref.
'/'.$filename)) {
4087 $file_list[
'missing'][] = array(
'filename' => $filename,
'expectedhash' => $expectedhash,
'expectedsize' => $expectedsize,
'algo' => (
string) $algo);
4089 $hash_local = hash_file($algo, $pathref.
'/'.$filename);
4091 if (
$conffile ==
'/etc/dolibarr/conf.php' && $filename ==
'/filefunc.inc.php') {
4092 $checksumconcat[] = $expectedhash;
4094 if ($hash_local != $expectedhash) {
4095 $file_list[
'updated'][] = array(
'filename' => $filename,
'expectedhash' => $expectedhash,
'expectedsize' => $expectedsize,
'hash' => (
string) $hash_local,
'algo' => (
string) $algo);
4097 $checksumconcat[] = $hash_local;
4102 foreach ($dir->dir as $subdir) {
4103 getFilesUpdated($file_list, $subdir, $path.$subdir[
'name'].
'/', $pathref, $checksumconcat);
4121 $out .=
'<div id="'.$htmlname.
'Message" class="dragDropAreaMessage hidden"><span>'.
img_picto(
"",
'download').
'<br>'.$langs->trans(
"DropFileToAddItToObject").
'</span></div>';
4122 $out .=
"\n<!-- JS CODE TO ENABLE DRAG AND DROP OF FILE -->\n";
4125 jQuery(document).ready(function() {
4126 var enterTargetDragDrop = null;
4128 $("#'.$htmlname.
'").addClass("cssDragDropArea");
4130 $(".cssDragDropArea").on("dragenter", function(ev, ui) {
4131 var dataTransfer = ev.originalEvent.dataTransfer;
4132 var dataTypes = dataTransfer.types;
4133 //console.log(dataTransfer);
4134 //console.log(dataTypes);
4136 if (!dataTypes || ($.inArray(\'Files\', dataTypes) === -1)) {
4137 // The element dragged is not a file, so we avoid the "dragenter"
4138 ev.preventDefault();
4142 // Entering drop area. Highlight area
4143 console.log("dragAndDropFileUpload: We add class highlightDragDropArea")
4144 enterTargetDragDrop = ev.target;
4145 $(this).addClass("highlightDragDropArea");
4146 $("#'.$htmlname.
'Message").removeClass("hidden");
4147 ev.preventDefault();
4150 $(".cssDragDropArea").on("dragleave", function(ev) {
4151 // Going out of drop area. Remove Highlight
4152 if (enterTargetDragDrop == ev.target){
4153 console.log("dragAndDropFileUpload: We remove class highlightDragDropArea")
4154 $("#'.$htmlname.
'Message").addClass("hidden");
4155 $(this).removeClass("highlightDragDropArea");
4159 $(".cssDragDropArea").on("dragover", function(ev) {
4160 ev.preventDefault();
4164 $(".cssDragDropArea").on("drop", function(e) {
4167 fd = new FormData();
4171 fd.append("action", "linkit");
4173 var dataTransfer = e.originalEvent.dataTransfer;
4175 if (dataTransfer.files && dataTransfer.files.length){
4176 var droppedFiles = e.originalEvent.dataTransfer.files;
4177 $.each(droppedFiles, function(index,file){
4178 fd.append("files[]", file,file.name)
4181 $(".cssDragDropArea").removeClass("highlightDragDropArea");
4182 counterdragdrop = 0;
4184 url: "'.DOL_URL_ROOT.
'/core/ajax/fileupload.php",
4189 success:function() {
4190 console.log("Uploaded.", arguments);
4191 /* arguments[0] is the json string of files */
4192 /* arguments[1] is the value for variable "success", can be 0 or 1 */
4193 let listoffiles = JSON.parse(arguments[0]);
4194 console.log(listoffiles);
4196 for (let i = 0; i < listoffiles.length; i++) {
4197 console.log(listoffiles[i].error);
4198 if (listoffiles[i].error) {
4202 console.log(nboferror);
4203 if (nboferror > 0) {
4204 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=ErrorOnAtLeastOneFileUpload:warnings";
4206 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=UploadFileDragDropSuccess:mesgs";
4210 console.log("Error Uploading.", arguments)
4211 if (arguments[0].status == 403) {
4212 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=ErrorUploadPermissionDenied:errors";
4214 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js((
string)
$object->id).
'&seteventmessages=ErrorUploadFileDragDropPermissionDenied:errors";
4220 $out .=
"</script>\n";
4234function archiveOrBackupFile($srcfile, $max_versions = 5, $archivedir =
'', $suffix =
"v", $moveorcopy =
'move')
4236 $base_file_pattern = ($archivedir ? $archivedir : dirname($srcfile)).
'/'.basename($srcfile).
".".$suffix;
4237 $files_in_directory = glob($base_file_pattern .
"*");
4240 $files_with_timestamps = [];
4241 foreach ($files_in_directory as $file) {
4242 $files_with_timestamps[] = [
4244 'timestamp' => filemtime($file)
4250 while (count($files_with_timestamps) > 0) {
4251 $latest_file =
null;
4252 $latest_index =
null;
4255 foreach ($files_with_timestamps as $index => $file_info) {
4256 if ($latest_file ===
null || (is_array($latest_file) && $file_info[
'timestamp'] > $latest_file[
'timestamp'])) {
4257 $latest_file = $file_info;
4258 $latest_index = $index;
4263 if ($latest_file !==
null) {
4264 $sorted_files[] = $latest_file[
'file'];
4265 unset($files_with_timestamps[$latest_index]);
4270 if (count($sorted_files) >= $max_versions) {
4271 $oldest_files = array_slice($sorted_files, $max_versions - 1);
4272 foreach ($oldest_files as $oldest_file) {
4278 $new_backup = $srcfile .
".v" . $timestamp;
4281 if ($moveorcopy ==
'move') {
4282 $result =
dol_move($srcfile, $new_backup,
'0', 1, 0, 0);
4284 $result =
dol_copy($srcfile, $new_backup,
'0', 1, 0, 0);
4300function dolDocToText($filetoprocess, $useFullTextIndexation =
'pdftotext', $options =
'html')
4305 $keywords = array();
4306 $textforfulltextindex =
'';
4309 if (empty($useFullTextIndexation)) {
4310 $useFullTextIndexation =
'pdftotext';
4317 if (preg_match(
'/pdftotext/i', $useFullTextIndexation)) {
4318 include_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
4320 $outputfile =
$conf->admin->dir_temp.
'/tmppdftotext.'.$user->id.
'.out';
4324 if ($options ==
'fulltext') {
4325 $params =
'-nodiag -layout';
4327 $params =
'-htmlmeta';
4333 $resultexec = $utils->executeCLI($cmd, $outputfile, 0,
null, 1);
4335 if (empty($resultexec[
'error'])) {
4337 if ($options ==
'fulltext') {
4338 $textforfulltextindex = $resultexec[
'output'];
4340 if ($options ==
'html') {
4341 $txt = $resultexec[
'output'];
4342 if (preg_match(
'/<meta name="keywords" content="([^\/]+)"\s*\/>/i', $txt, $matches)) {
4343 $keywords = $matches[1];
4345 if (preg_match(
'/<pre>(.*)<\/pre>/si', $txt, $matches)) {
4357 if (preg_match(
'/docling/i', $useFullTextIndexation)) {
4358 include_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
4360 $outputfile =
$conf->admin->dir_temp.
'/tmpdocling.'.$user->id.
'.out';
4366 $resultexec = $utils->executeCLI($cmd, $outputfile, 0,
null, 1);
4368 if (!$resultexec[
'error']) {
4369 $txt = $resultexec[
'output'];
4377 $textforfulltextindex = $txt;
4384 return array(
'error' => $error,
'keywords' => $keywords,
'content' => $textforfulltextindex,
'cmd' => $cmd);
4396 $fp = fopen($fullpath,
"r");
4397 fseek($fp, -1, SEEK_END);
4400 while ($char ===
"\n" || $char ===
"\r") {
4401 fseek($fp, $pos--, SEEK_END);
4404 while ($char !==
"\n" && $char !==
false) {
4405 fseek($fp, $pos--, SEEK_END);
4414 $truncatePos = ftell($fp);
4417 $fp = fopen($fullpath,
"c+");
4418 ftruncate($fp, $truncatePos);
if(! $sortfield) if(! $sortorder) $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 salary payments.
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_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
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.
removePatternFromFile(string $filePath, string $pattern)
Removes content from a file that matches a given pattern.
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_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)
isRealPdf(string $filePath)
Check if a file is a real PDF file by checking its signature and its MIME type.
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 a PDF file into another image format.
removeLastLine($fullpath)
Remove the last line of a text file.
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.
dolDocToText($filetoprocess, $useFullTextIndexation='pdftotext', $options='html')
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.
dol_now($mode='gmt')
Return date for now.
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.
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'.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
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...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_string_nounprintableascii($str, $removetabcrlf=1)
Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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_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.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
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.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.