42 return preg_replace(
'/^.*\/([^\/]+)$/',
'$1', rtrim($pathfile,
'/'));
65function 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)
70 if ($recursive <= 1) {
75 if (!empty($filter) && !is_array($filter)) {
76 if (strlen($filter) > 25000) {
77 dol_syslog(
"Value for filter is too large", LOG_ERR);
81 if ((
int) preg_match(
'/(?:^|[^\\\\])\//', $filter) > 0) {
82 $excludefilter_ok =
false;
83 $error_info .=
" error='filter_has_unescaped_slash'";
84 dol_syslog(
"'$filter' has unescaped '/'", LOG_ERR);
90 $excludefilter_ok =
true;
91 $exclude_array = ($excludefilter ===
null || $excludefilter ===
'') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
92 foreach ($exclude_array as $f) {
94 if ((
int) preg_match(
'/(?:^|[^\\\\])\//', $f) > 0) {
95 $excludefilter_ok =
false;
96 $error_info .=
" error='excludefilter_has_unescaped_slash'";
101 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);
103 if (!$filter_ok || !$excludefilter_ok) {
109 $exclude_array = ($excludefilter ===
null || $excludefilter ===
'') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
113 $excludefilterarray = array_merge(array(
'^\.'), $exclude_array);
115 $loaddate = ($mode == 1 || $mode == 2 || $nbsecondsold != 0 || $sortcriteria ==
'date');
116 $loadsize = ($mode == 1 || $mode == 3 || $sortcriteria ==
'size');
117 $loadperm = ($mode == 1 || $mode == 4 || $sortcriteria ==
'perm');
121 $file_list = array();
124 $utf8_path = preg_replace(
'/([\\/]+)$/',
'', $utf8_path);
126 if (preg_match(
'/\*/', $utf8_path)) {
127 $utf8_path_array = glob($utf8_path, GLOB_ONLYDIR);
130 $utf8_path_array = array($utf8_path);
133 foreach ($utf8_path_array as $utf8_path_cursor) {
135 if (!$nohook && $hookmanager instanceof
HookManager) {
136 $hookmanager->resArray = array();
138 $hookmanager->initHooks(array(
'fileslib'));
143 'recursive' => $recursive,
145 'excludefilter' => $exclude_array,
146 'sortcriteria' => $sortcriteria,
147 'sortorder' => $sortorder,
148 'loaddate' => $loaddate,
149 'loadsize' => $loadsize,
152 $reshook = $hookmanager->executeHooks(
'getDirList', $parameters,
$object);
156 if (empty($reshook)) {
157 if (!is_dir($os_path)) {
161 if (($dir = opendir($os_path)) ===
false) {
169 while (
false !== ($os_file = readdir($dir))) {
170 $os_fullpathfile = ($os_path ? $os_path.
'/' :
'').$os_file;
173 $utf8_file = mb_convert_encoding($os_file,
'UTF-8',
'ISO-8859-1');
175 $utf8_file = $os_file;
178 $utf8_fullpathfile = $utf8_path_cursor.
"/".$utf8_file;
182 foreach ($excludefilterarray as $filt) {
183 if (preg_match(
'/'.$filt.
'/i', $utf8_file) || preg_match(
'/'.$filt.
'/i', $utf8_fullpathfile)) {
191 $isdir = is_dir($os_fullpathfile);
195 if (($types ==
"directories") || ($types ==
"all")) {
196 if ($loaddate || $sortcriteria ==
'date') {
199 if ($loadsize || $sortcriteria ==
'size') {
202 if ($loadperm || $sortcriteria ==
'perm') {
206 $qualifiedforfilter = 0;
207 if (empty($filter)) {
208 $qualifiedforfilter = 1;
210 $testpregmatch =
false;
211 if (is_array($filter)) {
212 $chunks = array_chunk($filter, 500);
213 foreach ($chunks as $chunk) {
214 $testpregmatch = preg_match(
'/'.implode(
'|', $chunk).
'/i', $utf8_file);
215 if ($testpregmatch) {
220 $testpregmatch = preg_match(
'/'.$filter.
'/i', $utf8_file);
222 if ($testpregmatch) {
223 $qualifiedforfilter = 1;
227 if ($qualifiedforfilter) {
229 preg_match(
'/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
230 $level1name = (isset($reg[1]) ? $reg[1] :
'');
231 $file_list[] = array(
232 "name" => $utf8_file,
233 "path" => $utf8_path,
234 "level1name" => $level1name,
235 "relativename" => ($relativename ? $relativename.
'/' :
'').$utf8_file,
236 "fullname" => $utf8_fullpathfile,
246 if ($recursive > 0) {
247 if (empty($donotfollowsymlinks) || !is_link($os_fullpathfile)) {
249 $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));
252 } elseif (in_array($types, array(
"files",
"all"))) {
254 if ($loaddate || $sortcriteria ==
'date') {
257 if ($loadsize || $sortcriteria ==
'size') {
261 $qualifiedforfilter = 0;
262 if (empty($filter)) {
263 $qualifiedforfilter = 1;
265 $testpregmatch =
false;
266 if (is_array($filter)) {
267 $chunks = array_chunk($filter, 500);
268 foreach ($chunks as $chunk) {
269 $testpregmatch = preg_match(
'/'.implode(
'|', $chunk).
'/i', $utf8_file);
270 if ($testpregmatch) {
275 $testpregmatch = preg_match(
'/'.$filter.
'/i', $utf8_file);
277 if ($testpregmatch) {
278 $qualifiedforfilter = 1;
282 if ($qualifiedforfilter) {
283 if (empty($nbsecondsold) || $filedate <= ($now - $nbsecondsold)) {
284 preg_match(
'/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
285 $level1name = (isset($reg[1]) ? $reg[1] :
'');
286 $file_list[] = array(
287 "name" => $utf8_file,
288 "path" => $utf8_path,
289 "level1name" => $level1name,
290 "relativename" => ($relativename ? $relativename.
'/' :
'').$utf8_file,
291 "fullname" => $utf8_fullpathfile,
306 if (!empty($sortcriteria) && $sortorder) {
307 $file_list =
dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ?
'asc' :
'desc'));
310 if ($hookmanager instanceof
HookManager && is_array($hookmanager->resArray)) {
311 $file_list = array_merge($file_list, $hookmanager->resArray);
334function dol_dir_list_in_database($path, $filter =
"", $excludefilter =
null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0, $sqlfilters =
"",
$object =
null)
342 $sql =
"SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,";
343 $sql .=
" date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share";
345 $sql .=
", description";
347 $sql .=
" FROM ".MAIN_DB_PREFIX.
"ecm_files";
349 $sql .=
" WHERE entity = ".((int)
$object->entity);
351 $sql .=
" WHERE entity = ".((int)
$conf->entity);
353 if (preg_match(
'/%$/', $path)) {
354 $sql .=
" AND (filepath LIKE '".$db->escape($path).
"' OR filepath = '".
$db->escape(preg_replace(
'/\/%$/',
'', $path)).
"')";
356 $sql .=
" AND filepath = '".$db->escape($path).
"'";
367 $resql =
$db->query($sql);
369 $file_list = array();
370 $num =
$db->num_rows($resql);
373 $obj =
$db->fetch_object($resql);
376 preg_match(
'/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename, $reg);
377 $level1name = (isset($reg[1]) ? $reg[1] :
'');
378 $file_list[] = array(
379 "rowid" => $obj->rowid,
380 "label" => $obj->label,
381 "name" => $obj->filename,
382 "path" => DOL_DATA_ROOT.
'/'.$obj->filepath,
383 "level1name" => $level1name,
384 "fullname" => DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename,
385 "fullpath_orig" => $obj->fullpath_orig,
386 "date_c" =>
$db->jdate($obj->date_c),
387 "date_m" =>
$db->jdate($obj->date_m),
389 "keywords" => $obj->keywords,
390 "cover" => $obj->cover,
391 "position" => (
int) $obj->position,
393 "share" => $obj->share,
394 "description" => ($mode ? $obj->description :
'')
402 if (!empty($sortcriteria)) {
404 foreach ($file_list as $key => $row) {
405 $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] :
'');
409 array_multisort($myarray, $sortorder, SORT_REGULAR, $file_list);
444 if (in_array($modulepart, array(
'produit',
'product')) &&
getDolGlobalInt(
'PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
449 $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";
451 $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";
454 $relativedirold = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dirold);
455 $relativedirold = ltrim($relativedirold,
"/\\");
460 } elseif ($modulepart ==
'ticket') {
461 foreach ($filearray as $key => $val) {
462 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filearray[$key][
'path']);
463 $rel_dir = trim($rel_dir,
"/\\");
464 if ($rel_dir != $relativedir) {
465 $filearrayindatabase = array_merge($filearrayindatabase,
dol_dir_list_in_database($rel_dir,
'',
null,
'name', SORT_ASC));
471 foreach ($filearray as $key => $val) {
472 $tmpfilename = preg_replace(
'/\.noexe$/',
'', $filearray[$key][
'name']);
475 foreach ($filearrayindatabase as $key2 => $val2) {
476 if (($filearrayindatabase[$key2][
'path'] == $filearray[$key][
'path']) && ($filearrayindatabase[$key2][
'name'] == $tmpfilename)) {
477 $filearray[$key][
'position_name'] = ($filearrayindatabase[$key2][
'position'] ? $filearrayindatabase[$key2][
'position'] :
'0').
'_'.$filearrayindatabase[$key2][
'name'];
478 $filearray[$key][
'position'] = $filearrayindatabase[$key2][
'position'];
479 $filearray[$key][
'cover'] = $filearrayindatabase[$key2][
'cover'];
480 $filearray[$key][
'keywords'] = $filearrayindatabase[$key2][
'keywords'];
481 $filearray[$key][
'acl'] = $filearrayindatabase[$key2][
'acl'];
482 $filearray[$key][
'rowid'] = $filearrayindatabase[$key2][
'rowid'];
483 $filearray[$key][
'label'] = $filearrayindatabase[$key2][
'label'];
484 $filearray[$key][
'share'] = $filearrayindatabase[$key2][
'share'];
491 $filearray[$key][
'position'] =
'999999';
492 $filearray[$key][
'cover'] = 0;
493 $filearray[$key][
'acl'] =
'';
494 $filearray[$key][
'share'] = 0;
496 $rel_filename = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filearray[$key][
'fullname']);
498 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filename)) {
499 dol_syslog(
"list_of_documents We found a file called '".$filearray[$key][
'name'].
"' not indexed into database. We add it");
501 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
505 $filename = basename($rel_filename);
506 $rel_dir = dirname($rel_filename);
507 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
508 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
510 $ecmfile->filepath = $rel_dir;
511 $ecmfile->filename = $filename;
512 $ecmfile->label = md5_file(
dol_osencode($filearray[$key][
'fullname']));
513 $ecmfile->fullpath_orig = $filearray[$key][
'fullname'];
514 $ecmfile->gen_or_uploaded =
'unknown';
516 $ecmfile->src_object_type =
$object->element;
517 $ecmfile->src_object_id =
$object->id;
519 $ecmfile->description =
'';
520 $ecmfile->keywords =
'';
525 $result = $ecmfile->create($user);
529 $filearray[$key][
'rowid'] = $result;
532 $filearray[$key][
'rowid'] = 0;
549 global $sortorder, $sortfield;
551 $sortorder = strtoupper($sortorder);
553 if ($sortorder ==
'ASC') {
561 if ($sortfield ==
'name') {
562 if ($a->name == $b->name) {
565 return ($a->name < $b->name) ? $retup : $retdown;
567 if ($sortfield ==
'date') {
568 if ($a->date == $b->date) {
571 return ($a->date < $b->date) ? $retup : $retdown;
573 if ($sortfield ==
'size') {
574 if ($a->size == $b->size) {
577 return ($a->size < $b->size) ? $retup : $retdown;
593 if (is_dir($newfolder)) {
608 if (!is_readable($dir)) {
611 return (count(scandir($dir)) == 2);
623 return is_file($newpathoffile);
635 return is_link($newpathoffile);
647 return is_writable($newfolderorfile);
660 $prots = array(
'file',
'http',
'https',
'ftp',
'zlib',
'data',
'ssh',
'ssh2',
'ogg',
'expect');
661 return false !== preg_match(
'/^('.implode(
'|', $prots).
'):/i', $uri);
673 if (is_dir($newfolder)) {
674 $handle = opendir($newfolder);
675 $folder_content =
'';
677 while ((gettype($name = readdir($handle)) !=
"boolean")) {
678 $name_array[] = $name;
680 foreach ($name_array as $temp) {
681 $folder_content .= $temp;
686 if ($folder_content ==
"...") {
709 $fp = fopen($newfile,
'r');
716 if ($line !==
false) {
739 return filesize($newpathoffile);
751 return @filemtime($newpathoffile);
763 return fileperms($newpathoffile);
778function dolReplaceInFile($srcfile, $arrayreplacement, $destfile =
'', $newmask =
'0', $indexdatabase = 0, $arrayreplacementisregex = 0)
780 dol_syslog(
"files.lib.php::dolReplaceInFile srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" indexdatabase=".$indexdatabase.
" arrayreplacementisregex=".$arrayreplacementisregex);
782 if (empty($srcfile)) {
785 if (empty($destfile)) {
786 $destfile = $srcfile;
790 $srcfile = preg_replace(
'/\.\.\/?/',
'', $srcfile);
791 $destfile = preg_replace(
'/\.\.\/?/',
'', $destfile);
794 if (($destfile != $srcfile) && $destexists) {
800 dol_syslog(
"files.lib.php::dolReplaceInFile failed to read src file", LOG_WARNING);
804 $tmpdestfile = $destfile.
'.tmp';
809 $newdirdestfile = dirname($newpathofdestfile);
811 if ($destexists && !is_writable($newpathofdestfile)) {
812 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
815 if (!is_writable($newdirdestfile)) {
816 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
823 $content = file_get_contents($newpathofsrcfile);
825 if (empty($arrayreplacementisregex)) {
828 foreach ($arrayreplacement as $key => $value) {
829 $content = preg_replace($key, (
string) $value, $content);
833 file_put_contents($newpathoftmpdestfile, $content);
834 dolChmod($newpathoftmpdestfile, $newmask);
837 $moreinfo = array(
'gen_or_uploaded' =>
'unknown');
838 $result =
dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase, $moreinfo);
840 dol_syslog(
"files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
846 if (empty($newmask)) {
847 dol_syslog(
"Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
851 dolChmod($newpathofdestfile, $newmask);
866 if (! file_exists($filePath)) {
867 dol_syslog(
"files.lib.php::removePatternFromFile: File $filePath does not exist", LOG_WARNING);
873 $content = file_get_contents($filePath);
874 if ($content ===
false) {
875 dol_syslog(
"files.lib.php::removePatternFromFile: Unable to read the file $filePath", LOG_WARNING);
881 $updatedContent = preg_replace($pattern,
'', $content);
882 if ($updatedContent ===
null) {
883 dol_syslog(
"files.lib.php::removePatternFromFile: Error while processing the file $filePath", LOG_WARNING);
889 $result = file_put_contents($filePath, $updatedContent);
890 if ($result ===
false) {
891 dol_syslog(
"files.lib.php::removePatternFromFile: Permission denied to overwrite the target file $filePath", LOG_WARNING);
896 dol_syslog(
"files.lib.php::removePatternFromFile: Content successfully removed in the file $filePath", LOG_INFO);
915function dol_copy($srcfile, $destfile, $newmask =
'0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 0)
919 dol_syslog(
"files.lib.php::dol_copy srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
921 if (empty($srcfile) || empty($destfile)) {
926 if (!$overwriteifexists && $destexists) {
932 $newdirdestfile = dirname($newpathofdestfile);
934 if ($destexists && !is_writable($newpathofdestfile)) {
935 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
938 if (!is_writable($newdirdestfile)) {
939 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
944 $testvirusarray = array();
947 if (count($testvirusarray)) {
948 dol_syslog(
"files.lib.php::dol_copy canceled because a virus was found into source file. we ignore the copy request.", LOG_WARNING);
954 $result = @copy($newpathofsrcfile, $newpathofdestfile);
957 dol_syslog(
"files.lib.php::dol_copy failed to copy", LOG_WARNING);
963 if (empty($newmask)) {
964 dol_syslog(
"Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
968 dolChmod($newpathofdestfile, $newmask);
970 if ($result && $indexdatabase) {
972 $rel_filetocopyafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $newpathofdestfile);
973 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetocopyafter)) {
974 $rel_filetocopyafter = preg_replace(
'/^[\\/]/',
'', $rel_filetocopyafter);
977 dol_syslog(
"Try to copy also entries in database for: ".$rel_filetocopyafter, LOG_DEBUG);
978 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
981 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetocopyafter);
982 if ($resultecmtarget > 0) {
983 dol_syslog(
"ECM dest file found, remove it", LOG_DEBUG);
984 $ecmfiletarget->delete($user);
986 dol_syslog(
"ECM dest file not found, create it", LOG_DEBUG);
990 $resultecm = $ecmSrcfile->fetch(0,
'', $srcfile);
994 dol_syslog(
"Fetch src file error", LOG_DEBUG);
998 $filename = basename($rel_filetocopyafter);
999 $rel_dir = dirname($rel_filetocopyafter);
1000 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1001 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1003 $ecmfile->filepath = $rel_dir;
1004 $ecmfile->filename = $filename;
1006 $ecmfile->fullpath_orig = $srcfile;
1007 $ecmfile->gen_or_uploaded =
'copy';
1008 $ecmfile->description = $ecmSrcfile->description;
1009 $ecmfile->keywords = $ecmSrcfile->keywords;
1010 $resultecm = $ecmfile->create($user);
1011 if ($resultecm < 0) {
1015 dol_syslog(
"Create ECM file error", LOG_DEBUG);
1019 if ($resultecm > 0) {
1027 return (
int) $result;
1044function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement =
null, $excludesubdir = 0, $excludefileext =
null, $excludearchivefiles = 0)
1048 dol_syslog(
"files.lib.php::dolCopyDir srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
1050 if (empty($srcfile) || empty($destfile)) {
1061 $dirmaskdec = octdec($newmask);
1065 $dirmaskdec |= octdec(
'0200');
1067 $result =
dol_mkdir($destfile,
'', decoct($dirmaskdec));
1079 if (is_dir($ossrcfile)) {
1080 $dir_handle = opendir($ossrcfile);
1082 while ($file = readdir($dir_handle)) {
1083 if ($file !=
"." && $file !=
".." && !is_link($ossrcfile.
"/".$file)) {
1084 if (is_dir($ossrcfile.
"/".$file)) {
1085 if (empty($excludesubdir) || ($excludesubdir == 2 && strlen($file) == 2)) {
1088 if (is_array($arrayreplacement)) {
1089 foreach ($arrayreplacement as $key => $val) {
1090 $newfile = str_replace($key, $val, $newfile);
1094 $tmpresult =
dolCopyDir($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir, $excludefileext, $excludearchivefiles);
1099 if (is_array($excludefileext)) {
1100 $extension = pathinfo($file, PATHINFO_EXTENSION);
1101 if (in_array($extension, $excludefileext)) {
1107 if ($excludearchivefiles == 1) {
1108 $extension = pathinfo($file, PATHINFO_EXTENSION);
1109 if (preg_match(
'/^[v|d]\d+$/', $extension)) {
1115 if (is_array($arrayreplacement)) {
1116 foreach ($arrayreplacement as $key => $val) {
1117 $newfile = str_replace($key, $val, $newfile);
1120 $tmpresult =
dol_copy($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists);
1123 if ($result > 0 && $tmpresult >= 0) {
1126 $result = $tmpresult;
1133 closedir($dir_handle);
1139 return (
int) $result;
1161function dol_move($srcfile, $destfile, $newmask =
'0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1, $moreinfo = array(), $entity =
null)
1166 dol_syslog(
"files.lib.php::dol_move srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwritifexists=".$overwriteifexists);
1171 dol_syslog(
"files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
1175 if ($overwriteifexists || !$destexists) {
1180 $testvirusarray = array();
1183 $testvirusarray =
dolCheckVirus($newpathofsrcfile, $newpathofdestfile);
1184 if (count($testvirusarray)) {
1185 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1191 if (count($testvirusarray)) {
1192 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1197 global $dolibarr_main_restrict_os_commands;
1198 if (!empty($dolibarr_main_restrict_os_commands)) {
1199 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
1200 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
1201 if (in_array(basename($destfile), $arrayofallowedcommand)) {
1204 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);
1209 $result = @rename($newpathofsrcfile, $newpathofdestfile);
1212 dol_syslog(
"files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
1215 $result = @rename($newpathofsrcfile, $newpathofdestfile);
1217 dol_syslog(
"files.lib.php::dol_move Failed.", LOG_WARNING);
1222 if ($result && $indexdatabase) {
1224 $rel_filetorenamebefore = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $srcfile);
1225 $rel_filetorenameafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $destfile);
1226 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) {
1227 $rel_filetorenamebefore = preg_replace(
'/^[\\/]/',
'', $rel_filetorenamebefore);
1228 $rel_filetorenameafter = preg_replace(
'/^[\\/]/',
'', $rel_filetorenameafter);
1231 dol_syslog(
"Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore.
" after = ".$rel_filetorenameafter, LOG_DEBUG);
1232 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1235 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetorenameafter,
'',
'',
'', 0, $entity);
1236 if ($resultecmtarget > 0) {
1237 $ecmfiletarget->delete($user);
1241 $resultecm = $ecmfile->fetch(0,
'', $rel_filetorenamebefore,
'',
'',
'', 0, $entity);
1242 if ($resultecm > 0) {
1243 $filename = basename($rel_filetorenameafter);
1244 $rel_dir = dirname($rel_filetorenameafter);
1245 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1246 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1248 $ecmfile->filepath = $rel_dir;
1249 $ecmfile->filename = $filename;
1251 $resultecm = $ecmfile->update($user);
1252 } elseif ($resultecm == 0) {
1253 $filename = basename($rel_filetorenameafter);
1254 $rel_dir = dirname($rel_filetorenameafter);
1255 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1256 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1258 $ecmfile->filepath = $rel_dir;
1259 $ecmfile->filename = $filename;
1261 $ecmfile->fullpath_orig = basename($srcfile);
1262 if (!empty($moreinfo) && !empty($moreinfo[
'gen_or_uploaded'])) {
1263 $ecmfile->gen_or_uploaded = $moreinfo[
'gen_or_uploaded'];
1265 $ecmfile->gen_or_uploaded =
'unknown';
1267 if (!empty($moreinfo) && !empty($moreinfo[
'description'])) {
1268 $ecmfile->description = $moreinfo[
'description'];
1270 $ecmfile->description =
'';
1272 if (!empty($moreinfo) && !empty($moreinfo[
'keywords'])) {
1273 $ecmfile->keywords = $moreinfo[
'keywords'];
1275 $ecmfile->keywords =
'';
1277 if (!empty($moreinfo) && !empty($moreinfo[
'note_private'])) {
1278 $ecmfile->note_private = $moreinfo[
'note_private'];
1280 if (!empty($moreinfo) && !empty($moreinfo[
'note_public'])) {
1281 $ecmfile->note_public = $moreinfo[
'note_public'];
1283 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_type'])) {
1284 $ecmfile->src_object_type = $moreinfo[
'src_object_type'];
1286 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_id'])) {
1287 $ecmfile->src_object_id = $moreinfo[
'src_object_id'];
1289 if (!empty($moreinfo) && !empty($moreinfo[
'position'])) {
1290 $ecmfile->position = $moreinfo[
'position'];
1292 if (!empty($moreinfo) && !empty($moreinfo[
'cover'])) {
1293 $ecmfile->cover = $moreinfo[
'cover'];
1295 if (! empty($entity)) {
1296 $ecmfile->entity = $entity;
1299 $resultecm = $ecmfile->create($user);
1300 if ($resultecm < 0) {
1303 if (!empty($moreinfo) && !empty($moreinfo[
'array_options']) && is_array($moreinfo[
'array_options'])) {
1304 $ecmfile->array_options = $moreinfo[
'array_options'];
1305 $resultecm = $ecmfile->insertExtraFields();
1306 if ($resultecm < 0) {
1311 } elseif ($resultecm < 0) {
1315 if ($resultecm > 0) {
1323 if (empty($newmask)) {
1330 dolChmod($newpathofdestfile, $newmask);
1346function dol_move_dir($srcdir, $destdir, $overwriteifexists = 1, $indexdatabase = 1, $renamedircontent = 1)
1350 dol_syslog(
"files.lib.php::dol_move_dir srcdir=".$srcdir.
" destdir=".$destdir.
" overwritifexists=".$overwriteifexists.
" indexdatabase=".$indexdatabase.
" renamedircontent=".$renamedircontent);
1352 $srcbasename = basename($srcdir);
1356 dol_syslog(
"files.lib.php::dol_move_dir srcdir does not exists. Move fails");
1360 if ($overwriteifexists || !$destexists) {
1367 if ($overwriteifexists) {
1368 if (strtoupper(substr(PHP_OS, 0, 3)) ===
'WIN') {
1369 if (is_dir($newpathofdestdir)) {
1370 @rmdir($newpathofdestdir);
1375 $result = @rename($newpathofsrcdir, $newpathofdestdir);
1378 if ($result && $renamedircontent) {
1379 if (file_exists($newpathofdestdir)) {
1380 $destbasename = basename($newpathofdestdir);
1382 if (!empty($files) && is_array($files)) {
1383 foreach ($files as $key => $file) {
1384 if (!file_exists($file[
"fullname"])) {
1387 $filepath = $file[
"path"];
1388 $oldname = $file[
"name"];
1390 $newname = str_replace($srcbasename, $destbasename, $oldname);
1391 if (!empty($newname) && $newname !== $oldname) {
1392 if ($file[
"type"] ==
"dir") {
1393 $res =
dol_move_dir($filepath.
'/'.$oldname, $filepath.
'/'.$newname, $overwriteifexists, $indexdatabase, $renamedircontent);
1395 $moreinfo = array(
'gen_or_uploaded' =>
'unknown');
1396 $res =
dol_move($filepath.
'/'.$oldname, $filepath.
'/'.$newname,
'0', $overwriteifexists, 0, $indexdatabase, $moreinfo);
1423 return trim(basename($filename),
".\x00..\x20");
1439 if (!empty($reterrors)) {
1444 if (!class_exists(
'AntiVir')) {
1445 require_once DOL_DOCUMENT_ROOT.
'/core/class/antivir.class.php';
1448 $result = $antivir->dol_avscan_file($src_file);
1450 $reterrors = $antivir->errors;
1466 if (preg_match(
'/\.pdf$/i', $dest_file)) {
1468 dol_syslog(
"dolCheckOnFileName Check that pdf does not contains js code");
1470 $tmp = file_get_contents(trim($src_file));
1471 if (preg_match(
'/[\n\s]+\/JavaScript[\n\s]+/m', $tmp)) {
1472 return array(
'File is a PDF with javascript inside');
1475 dol_syslog(
"dolCheckOnFileName Check js into pdf disabled");
1504function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $keyforsourcefile =
'addedfile', $upload_dir =
'', $mode = 0)
1510 $file_name = $dest_file;
1513 if (empty($nohook)) {
1514 $reshook = $hookmanager->initHooks(array(
'fileslib'));
1516 $parameters = array(
'dest_file' => $dest_file,
'src_file' => $src_file,
'file_name' => $file_name,
'varfiles' => $keyforsourcefile,
'allowoverwrite' => $allowoverwrite);
1517 $reshook = $hookmanager->executeHooks(
'moveUploadedFile', $parameters,
$object);
1520 if (empty($reshook)) {
1522 if ($uploaderrorcode) {
1523 switch ($uploaderrorcode) {
1524 case UPLOAD_ERR_INI_SIZE:
1525 return 'ErrorFileSizeTooLarge';
1526 case UPLOAD_ERR_FORM_SIZE:
1527 return 'ErrorFileSizeTooLarge';
1528 case UPLOAD_ERR_PARTIAL:
1529 return 'ErrorPartialFile';
1530 case UPLOAD_ERR_NO_TMP_DIR:
1531 return 'ErrorNoTmpDir';
1532 case UPLOAD_ERR_CANT_WRITE:
1533 return 'ErrorFailedToWriteInDir';
1534 case UPLOAD_ERR_EXTENSION:
1535 return 'ErrorUploadBlockedByAddon';
1543 if (empty($disablevirusscan) && file_exists($src_file)) {
1545 if (count($checkvirusarray)) {
1546 dol_syslog(
'Files.lib::dol_move_uploaded_file File "'.$src_file.
'" (target name "'.$dest_file.
'") KO with antivirus: errors='.implode(
',', $checkvirusarray), LOG_WARNING);
1547 return 'ErrorFileIsInfectedWithAVirus: '.implode(
',', $checkvirusarray);
1556 $publicmediasdirwithslash =
$conf->medias->multidir_output[
$conf->entity];
1557 if (!preg_match(
'/\/$/', $publicmediasdirwithslash)) {
1558 $publicmediasdirwithslash .=
'/';
1561 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0 || !
getDolGlobalInt(
"MAIN_DOCUMENT_DISABLE_NOEXE_IN_MEDIAS_DIR")) {
1562 $file_name .=
'.noexe';
1569 if (preg_match(
'/^\./', basename($src_file)) || preg_match(
'/\.\./', $src_file) || preg_match(
'/[<>|]/', $src_file)) {
1570 dol_syslog(
"Refused to deliver file ".$src_file, LOG_WARNING);
1576 if (preg_match(
'/^\./', basename($dest_file)) || preg_match(
'/\.\./', $dest_file) || preg_match(
'/[<>|]/', $dest_file)) {
1577 dol_syslog(
"Refused to deliver file ".$dest_file, LOG_WARNING);
1583 $errmsg = implode(
',', $hookmanager->errors);
1584 if (empty($errmsg)) {
1585 $errmsg =
'ErrorReturnedBySomeHooks';
1588 } elseif (empty($reshook)) {
1594 if (!is_writable(dirname($file_name_osencoded))) {
1595 dol_syslog(
"Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded).
" is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1596 return 'ErrorDirNotWritable';
1600 if (!$allowoverwrite) {
1601 if (file_exists($file_name_osencoded)) {
1602 dol_syslog(
"Files.lib::dol_move_uploaded_file File ".$file_name.
" already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1603 return 'ErrorFileAlreadyExists';
1606 if (is_dir($file_name_osencoded)) {
1607 dol_syslog(
"Files.lib::dol_move_uploaded_file A directory with name ".$file_name.
" already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
1608 return 'ErrorDirWithFileNameAlreadyExists';
1614 $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1616 $return = rename($src_file_osencoded, $file_name_osencoded);
1621 dol_syslog(
"Files.lib::dol_move_uploaded_file Success to move ".$src_file.
" to ".$file_name.
" - Umask=" .
getDolGlobalString(
'MAIN_UMASK'), LOG_DEBUG);
1622 return $successcode;
1624 dol_syslog(
"Files.lib::dol_move_uploaded_file Failed to move ".$src_file.
" to ".$file_name, LOG_ERR);
1629 return $successcode;
1647function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0,
$object =
null, $allowdotdot =
false, $indexdatabase = 1, $nolog = 0)
1650 global $hookmanager;
1652 if (empty($nolog)) {
1653 dol_syslog(
"dol_delete_file file=".$file.
" disableglob=".$disableglob.
" nophperrors=".$nophperrors.
" nohook=".$nohook);
1658 if ((!$allowdotdot && preg_match(
'/\.\./', $file)) || preg_match(
'/[<>|]/', $file)) {
1659 dol_syslog(
"Refused to delete file ".$file, LOG_WARNING);
1664 if (empty($nohook) && !empty($hookmanager)) {
1665 $hookmanager->initHooks(array(
'fileslib'));
1667 $parameters = array(
1669 'disableglob' => $disableglob,
1670 'nophperrors' => $nophperrors
1672 $reshook = $hookmanager->executeHooks(
'deleteFile', $parameters,
$object);
1675 if (empty($nohook) && $reshook != 0) {
1683 if (empty($disableglob) && !empty($file_osencoded)) {
1685 $globencoded = str_replace(
'[',
'\[', $file_osencoded);
1686 $globencoded = str_replace(
']',
'\]', $globencoded);
1687 $listoffiles = glob($globencoded);
1689 if (!empty($listoffiles) && is_array($listoffiles)) {
1690 foreach ($listoffiles as $filename) {
1692 $ok = @unlink($filename);
1694 $ok = unlink($filename);
1698 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1699 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);
1700 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1703 $ok = @unlink($filename);
1705 $ok = unlink($filename);
1710 if (empty($nolog)) {
1711 dol_syslog(
"Removed file ".$filename, LOG_DEBUG);
1715 $rel_filetodelete = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filename);
1716 if (!preg_match(
'/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) {
1717 if (is_object(
$db) && $indexdatabase) {
1718 $rel_filetodelete = preg_replace(
'/^[\\/]/',
'', $rel_filetodelete);
1719 $rel_filetodelete = preg_replace(
'/\.noexe$/',
'', $rel_filetodelete);
1721 dol_syslog(
"Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1722 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1725 $result = $ecmfile->fetch(0,
'', $rel_filetodelete,
'',
'',
'', 0, $entity);
1726 if ($result >= 0 && $ecmfile->id > 0) {
1727 $result = $ecmfile->delete($user);
1735 dol_syslog(
"Failed to remove file ".$filename, LOG_WARNING);
1742 dol_syslog(
"No files to delete found", LOG_DEBUG);
1747 $ok = @unlink($file_osencoded);
1749 $ok = unlink($file_osencoded);
1752 $filename = $file_osencoded;
1755 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1756 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);
1757 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1760 $ok = @unlink($filename);
1762 $ok = unlink($filename);
1767 if (empty($nolog)) {
1768 dol_syslog(
"Removed file ".$filename, LOG_DEBUG);
1772 $rel_filetodelete = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filename);
1773 if (!preg_match(
'/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) {
1774 if (is_object(
$db) && $indexdatabase) {
1775 $rel_filetodelete = preg_replace(
'/^[\\/]/',
'', $rel_filetodelete);
1776 $rel_filetodelete = preg_replace(
'/\.noexe$/',
'', $rel_filetodelete);
1778 dol_syslog(
"Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1779 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1782 $result = $ecmfile->fetch(0,
'', $rel_filetodelete,
'',
'',
'', 0, $entity);
1783 if ($result >= 0 && $ecmfile->id > 0) {
1784 $result = $ecmfile->delete($user);
1792 dol_syslog(
"Failed to remove file ".$filename, LOG_WARNING);
1813 if (preg_match(
'/\.\./', $dir) || preg_match(
'/[<>|]/', $dir)) {
1814 dol_syslog(
"Refused to delete dir ".$dir.
' (contains invalid char sequence)', LOG_WARNING);
1819 return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1835function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0, $indexdatabase = 1, $nolog = 0, $level = 0)
1837 if (empty($nolog) || empty($level)) {
1838 dol_syslog(
"functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1840 if ($level > 1000) {
1841 dol_syslog(
"functions.lib:dol_delete_dir_recursive too many depth", LOG_WARNING);
1846 if ($handle = opendir(
"$dir_osencoded")) {
1847 while (
false !== ($item = readdir($handle))) {
1849 $item = mb_convert_encoding($item,
'UTF-8',
'ISO-8859-1');
1852 if ($item !=
"." && $item !=
"..") {
1854 $count =
dol_delete_dir_recursive(
"$dir/$item", $count, $nophperrors, 0, $countdeleted, $indexdatabase, $nolog, ($level + 1));
1857 $result =
dol_delete_file(
"$dir/$item", 1, $nophperrors, 0,
null,
false, $indexdatabase, $nolog);
1869 if (empty($onlysub)) {
1894 global $langs,
$conf;
1899 if (
$object->element ==
'order_supplier') {
1900 $dir =
$conf->fournisseur->commande->dir_output;
1901 } elseif (
$object->element ==
'invoice_supplier') {
1902 $dir =
$conf->fournisseur->facture->dir_output;
1903 } elseif (
$object->element ==
'project') {
1904 $dir =
$conf->project->dir_output;
1905 } elseif (
$object->element ==
'shipping') {
1906 $dir =
$conf->expedition->dir_output.
'/sending';
1907 } elseif (
$object->element ==
'delivery') {
1908 $dir =
$conf->expedition->dir_output.
'/receipt';
1909 } elseif (
$object->element ==
'fichinter') {
1910 $dir =
$conf->ficheinter->dir_output;
1912 $dir = empty(
$conf->$element->dir_output) ?
'' :
$conf->$element->dir_output;
1916 $object->error = $langs->trans(
'ErrorObjectNoSupportedByFunction');
1921 $dir = $dir.
"/".$refsan;
1922 $filepreviewnew = $dir.
"/".$refsan.
".pdf_preview.png";
1923 $filepreviewnewbis = $dir.
"/".$refsan.
".pdf_preview-0.png";
1924 $filepreviewold = $dir.
"/".$refsan.
".pdf.png";
1927 if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
1929 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnew);
1933 if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
1935 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnewbis);
1940 if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
1942 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewold);
1946 $multiple = $filepreviewold.
".";
1947 for ($i = 0; $i < 20; $i++) {
1948 $preview = $multiple.$i;
1950 if (file_exists($preview) && is_writable($preview)) {
1952 $object->error = $langs->trans(
"ErrorFailedToOpenFile", $preview);
1982 if (
$object->element ==
'order_supplier') {
1983 $dir =
$conf->fournisseur->dir_output.
'/commande';
1984 } elseif (
$object->element ==
'invoice_supplier') {
1985 $dir =
$conf->fournisseur->dir_output.
'/facture';
1986 } elseif (
$object->element ==
'project') {
1987 $dir =
$conf->project->dir_output;
1988 } elseif (
$object->element ==
'shipping') {
1989 $dir =
$conf->expedition->dir_output.
'/sending';
1990 } elseif (
$object->element ==
'delivery') {
1991 $dir =
$conf->expedition->dir_output.
'/receipt';
1992 } elseif (
$object->element ==
'fichinter') {
1993 $dir =
$conf->ficheinter->dir_output;
1995 $dir = empty(
$conf->$element->dir_output) ?
'' :
$conf->$element->dir_output;
2002 $dir = $dir.
"/".$objectref;
2003 $file = $dir.
"/".$objectref.
".meta";
2005 if (!is_dir($dir)) {
2012 $nblines = count(
$object->lines);
2017 $meta =
"REFERENCE=\"".$object->ref.
"\"
2019 NB_ITEMS=\"" . $nblines.
"\"
2020 CLIENT=\"" . $client.
"\"
2021 AMOUNT_EXCL_TAX=\"" .
$object->total_ht.
"\"
2022 AMOUNT=\"" .
$object->total_ttc.
"\"\n";
2024 for ($i = 0; $i < $nblines; $i++) {
2026 $meta .=
"ITEM_".$i.
"_QUANTITY=\"".
$object->lines[$i]->qty.
"\"
2027 ITEM_" . $i.
"_AMOUNT_WO_TAX=\"".
$object->lines[$i]->total_ht.
"\"
2028 ITEM_" . $i.
"_VAT=\"".
$object->lines[$i]->tva_tx.
"\"
2029 ITEM_" . $i.
"_DESCRIPTION=\"".str_replace(
"\r\n",
"", nl2br(
$object->lines[$i]->desc)).
"\"
2034 $fp = fopen($file,
"w");
2042 dol_syslog(
'FailedToDetectDirInDolMetaCreateFor'.
$object->element, LOG_WARNING);
2060 $listofpaths = array();
2061 $listofnames = array();
2062 $listofmimes = array();
2066 foreach ($listoffiles as $key => $val) {
2067 $listofpaths[] = $val[
'fullname'];
2068 $listofnames[] = $val[
'name'];
2072 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
2073 $_SESSION[
"listofpaths".$keytoavoidconflict] = implode(
';', $listofpaths);
2074 $_SESSION[
"listofnames".$keytoavoidconflict] = implode(
';', $listofnames);
2075 $_SESSION[
"listofmimes".$keytoavoidconflict] = implode(
';', $listofmimes);
2099function dol_add_file_process($upload_dir, $allowoverwrite = 0, $updatesessionordb = 0, $keyforsourcefile =
'addedfile', $savingdocmask =
'', $link =
null, $trackid =
'', $generatethumbs = 1,
$object =
null, $forceFullTextIndexation =
'', $mode = 0)
2107 $_FILES = array($keyforsourcefile => array());
2108 $_FILES[$keyforsourcefile][
'tmp_name'] = $keyforsourcefile;
2109 $_FILES[$keyforsourcefile][
'name'] = $keyforsourcefile;
2113 if (!empty($_FILES[$keyforsourcefile])) {
2114 dol_syslog(
'dol_add_file_process varfiles = '.$keyforsourcefile.
' upload_dir='.$upload_dir.
' allowoverwrite='.$allowoverwrite.
' updatesessionordb='.$updatesessionordb.
' savingdocmask='.$savingdocmask, LOG_DEBUG);
2115 $maxfilesinform =
getDolGlobalInt(
"MAIN_SECURITY_MAX_ATTACHMENT_ON_FORMS", 10);
2116 if (is_array($_FILES[$keyforsourcefile][
"name"]) && count($_FILES[$keyforsourcefile][
"name"]) > $maxfilesinform) {
2117 $langs->load(
"errors");
2118 setEventMessages($langs->trans(
"ErrorTooMuchFileInForm", $maxfilesinform),
null,
"errors");
2126 $TFile = $_FILES[$keyforsourcefile];
2128 if (!is_array($TFile[
'name'])) {
2129 foreach ($TFile as $key => &$val) {
2134 $nbfile = count($TFile[
'name']);
2136 for ($i = 0; $i < $nbfile; $i++) {
2137 if (empty($TFile[
'name'][$i])) {
2142 $destfile = trim($TFile[
'name'][$i]);
2143 $destfull = $upload_dir.
"/".$destfile;
2144 $destfilewithoutext = preg_replace(
'/\.[^\.]+$/',
'', $destfile);
2146 if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
2147 $destfile = trim(preg_replace(
'/__file__/', $TFile[
'name'][$i], $savingdocmask));
2148 $destfull = $upload_dir.
"/".$destfile;
2151 $filenameto = basename($destfile);
2152 if (preg_match(
'/^\./', $filenameto)) {
2153 $langs->load(
"errors");
2154 setEventMessages($langs->trans(
"ErrorFilenameCantStartWithDot", $filenameto),
null,
'errors');
2158 $info = pathinfo($destfull);
2159 $destfull = $info[
'dirname'].
'/'.
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
2160 $info = pathinfo($destfile);
2161 $destfile =
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
2164 $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';
2165 $fileextensionrestriction =
getDolGlobalString(
"MAIN_FILE_EXTENSION_UPLOAD_RESTRICTION", $defaultexecutableextensions);
2166 if (!empty($fileextensionrestriction)) {
2167 $arrayofregexextension = explode(
",", $fileextensionrestriction);
2169 foreach ($arrayofregexextension as $fileextension) {
2170 if (preg_match(
'/\.'.preg_quote(trim($fileextension),
'/').
'$/i', $destfull)) {
2171 $langs->load(
"errors");
2172 setEventMessages($langs->trans(
"ErrorFilenameExtensionNotAllowed", $filenameto),
null,
'errors');
2184 global $dolibarr_main_restrict_os_commands;
2185 if (!empty($dolibarr_main_restrict_os_commands)) {
2186 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
2187 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
2188 if (in_array($destfile, $arrayofallowedcommand)) {
2189 $langs->load(
"errors");
2190 setEventMessages($langs->trans(
"ErrorFilenameReserved", $destfile),
null,
'errors');
2196 $resupload =
dol_move_uploaded_file($TFile[
'tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile[
'error'][$i], 0, $keyforsourcefile, $upload_dir, $mode);
2198 if (is_numeric($resupload) && $resupload > 0) {
2199 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
2202 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
2203 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
2204 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
2205 $maxheightmini = $tmparraysize[
'maxheightmini'];
2210 if ($generatethumbs) {
2216 $imgThumbSmall =
vignette($destfull, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
2219 $imgThumbMini =
vignette($destfull, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
2224 if (empty($updatesessionordb)) {
2225 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2227 $formmail->trackid = $trackid;
2228 $formmail->add_attached_files($destfull, $destfile, $TFile[
'type'][$i]);
2232 if ($updatesessionordb == 1) {
2234 if ($TFile[
'type'][$i] ==
'application/pdf' && strpos($_SERVER[
"REQUEST_URI"],
'product') !==
false &&
getDolGlobalString(
'PRODUCT_ALLOW_EXTERNAL_DOWNLOAD')) {
2239 if ($allowoverwrite) {
2243 $result =
addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ?
'.noexe' :
''), $TFile[
'name'][$i],
'uploaded', $sharefile,
$object, $forceFullTextIndexation);
2245 if ($allowoverwrite) {
2248 setEventMessages(
'WarningFailedToAddFileIntoDatabaseIndex',
null,
'warnings');
2255 $langs->load(
"errors");
2256 if (is_numeric($resupload) && $resupload < 0) {
2258 } elseif (preg_match(
'/ErrorFileIsInfectedWithAVirus/', $resupload)) {
2259 if (preg_match(
'/File is a PDF with javascript inside/', $resupload)) {
2260 setEventMessages($langs->trans(
"ErrorFileIsAnInfectedPDFWithJSInside"),
null,
'errors');
2274 setEventMessages($langs->trans(
"ErrorFailedToCreateDir", $upload_dir),
null,
'errors');
2277 require_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
2279 $linkObject->entity =
$conf->entity;
2280 $linkObject->url = $link;
2281 $linkObject->objecttype =
GETPOST(
'objecttype',
'alpha');
2282 $linkObject->objectid =
GETPOSTINT(
'objectid');
2283 $linkObject->label =
GETPOST(
'label',
'alpha');
2284 $res = $linkObject->create($user);
2292 $langs->load(
"errors");
2293 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"File")),
null,
'errors');
2315 $keytodelete = $filenb;
2318 $listofpaths = array();
2319 $listofnames = array();
2320 $listofmimes = array();
2321 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
2322 if (!empty($_SESSION[
"listofpaths".$keytoavoidconflict])) {
2323 $listofpaths = explode(
';', $_SESSION[
"listofpaths".$keytoavoidconflict]);
2325 if (!empty($_SESSION[
"listofnames".$keytoavoidconflict])) {
2326 $listofnames = explode(
';', $_SESSION[
"listofnames".$keytoavoidconflict]);
2328 if (!empty($_SESSION[
"listofmimes".$keytoavoidconflict])) {
2329 $listofmimes = explode(
';', $_SESSION[
"listofmimes".$keytoavoidconflict]);
2332 if ($keytodelete >= 0) {
2333 $pathtodelete = $listofpaths[$keytodelete];
2334 $filetodelete = $listofnames[$keytodelete];
2335 if (empty($donotdeletefile)) {
2341 if (empty($donotdeletefile)) {
2342 $langs->load(
"other");
2343 setEventMessages($langs->trans(
"FileWasRemoved", $filetodelete),
null,
'mesgs');
2345 if (empty($donotupdatesession)) {
2346 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
2348 $formmail->trackid = $trackid;
2349 $formmail->remove_attached_files($keytodelete);
2377 dol_syslog(
"addFileIntoDatabaseIndex dir=".$dir.
" file=".$file, LOG_DEBUG);
2379 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2381 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
2382 $filename = basename(preg_replace(
'/\.noexe$/',
'', $file));
2383 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2384 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2386 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
2388 $ecmfile->filepath = $rel_dir;
2389 $ecmfile->filename = $filename;
2390 $ecmfile->label = md5_file(
dol_osencode($dir.
'/'.$file));
2391 $ecmfile->fullpath_orig = $fullpathorig;
2392 $ecmfile->gen_or_uploaded = $mode;
2393 $ecmfile->description =
'';
2394 $ecmfile->keywords =
'';
2397 $ecmfile->src_object_id =
$object->id;
2398 if (isset(
$object->table_element)) {
2399 $ecmfile->src_object_type =
$object->table_element;
2401 dol_syslog(
'Error: object ' . get_class(
$object) .
' has no table_element attribute.');
2404 if (isset(
$object->src_object_description)) {
2405 $ecmfile->description =
$object->src_object_description;
2407 if (isset(
$object->src_object_keywords)) {
2408 $ecmfile->keywords =
$object->src_object_keywords;
2411 $ecmfile->entity =
$object->entity;
2420 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
2426 if (empty($useFullTextIndexation) && $forceFullTextIndexation ==
'1') {
2428 $useFullTextIndexation =
'pdftotext';
2430 $useFullTextIndexation =
'docling';
2435 if ($useFullTextIndexation) {
2436 $ecmfile->filepath = $rel_dir;
2437 $ecmfile->filename = $filename;
2439 $filetoprocess = $dir.
'/'.$ecmfile->filename;
2441 $textforfulltextindex =
'';
2444 if (preg_match(
'/\.pdf/i', $filename)) {
2448 if (empty($result[
'error'])) {
2449 $textforfulltextindex = $result[
'content'];
2450 $filetoprocess = $result[
'keywords'];
2451 $cmd = $result[
'cmd'];
2458 $ecmfile->description =
'File content generated by '.$cmd;
2460 $ecmfile->content = $textforfulltextindex;
2461 $ecmfile->keywords = $keywords;
2465 $result = $ecmfile->create($user);
2491 dol_syslog(
"deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
2495 dol_syslog(
"deleteFilesIntoDatabaseIndex dir=".$dir.
" file=".$file, LOG_DEBUG);
2499 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2501 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
2503 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2504 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2507 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'ecm_files';
2509 $sql .=
' WHERE entity = ' . ((int)
$object->entity);
2511 $sql .=
' WHERE entity = ' . ((int)
$conf->entity);
2513 $sql .=
" AND filepath = '".$db->escape($rel_dir).
"'";
2515 $sql .=
" AND filename = '".$db->escape($file).
"'";
2518 $sql .=
" AND gen_or_uploaded = '".$db->escape($mode).
"'";
2521 $resql =
$db->query($sql);
2548 if (!is_file($filePath) || !is_readable($filePath)) {
2553 $handle = fopen($filePath,
'rb');
2557 $header = fread($handle, 5);
2560 if ($header !==
'%PDF-') {
2590 if (class_exists(
'Imagick')) {
2591 $image =
new Imagick();
2597 dol_syslog(
"We try to convert a PDF file with name ".$fileinput.
" but it is not a real PDF file (hack attempt ?).", LOG_WARNING);
2601 $filetoconvert = $fileinput.(($page !=
'') ?
'['.$page.
']' :
'');
2603 $ret = $image->readImage($filetoconvert);
2605 $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
2606 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);
2611 $ret = $image->setImageFormat($ext);
2613 if (empty($fileoutput)) {
2614 $fileoutput = $fileinput.
".".$ext;
2617 $count = $image->getNumberImages();
2619 if (!
dol_is_file($fileoutput) || is_writable($fileoutput)) {
2621 $ret = $image->writeImages($fileoutput,
true);
2626 dol_syslog(
"Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
2656function dol_compress_file($inputfile, $outputfile, $mode =
"gz", &$errorstring =
null)
2662 dol_syslog(
"dol_compress_file mode=".$mode.
" inputfile=".$inputfile.
" outputfile=".$outputfile);
2665 $compressdata =
null;
2666 if ($mode ==
'gz' && function_exists(
'gzencode')) {
2668 $compressdata = gzencode($data, 9);
2669 } elseif ($mode ==
'bz' && function_exists(
'bzcompress')) {
2671 $compressdata = bzcompress($data, 9);
2672 } elseif ($mode ==
'zstd' && function_exists(
'zstd_compress')) {
2674 $compressdata = zstd_compress($data, 9);
2675 } elseif ($mode ==
'zip') {
2676 if (class_exists(
'ZipArchive') &&
getDolGlobalString(
'MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS')) {
2679 $rootPath = realpath($inputfile);
2681 dol_syslog(
"Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.
' rootPath='.$rootPath);
2682 $zip =
new ZipArchive();
2684 if ($zip->open($outputfile, ZipArchive::CREATE) !==
true) {
2685 $errorstring =
"dol_compress_file failure - Failed to open file ".$outputfile.
"\n";
2689 $errormsg = $errorstring;
2696 $files =
new RecursiveIteratorIterator(
2697 new RecursiveDirectoryIterator($rootPath, FilesystemIterator::UNIX_PATHS),
2698 RecursiveIteratorIterator::LEAVES_ONLY
2700 '@phan-var-force SplFileInfo[] $files';
2702 foreach ($files as $name => $file) {
2704 if (!$file->isDir()) {
2706 $filePath = $file->getPath();
2707 $fileName = $file->getFilename();
2708 $fileFullRealPath = $file->getRealPath();
2711 $relativePath = substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($rootPath) + 1);
2714 $zip->addFile($fileFullRealPath, $relativePath);
2721 dol_syslog(
"dol_compress_file success - ".$zip->numFiles.
" files");
2725 if (defined(
'ODTPHP_PATHTOPCLZIP')) {
2728 include_once ODTPHP_PATHTOPCLZIP.
'pclzip.lib.php';
2729 $archive =
new PclZip($outputfile);
2731 $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2733 if ($result === 0) {
2735 $errormsg = $archive->errorInfo(
true);
2737 if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
2738 $errorstring =
"PCLZIP_ERR_WRITE_OPEN_FAIL";
2739 dol_syslog(
"dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
2743 $errorstring =
"dol_compress_file error archive->errorCode = ".$archive->errorCode().
" errormsg=".$errormsg;
2744 dol_syslog(
"dol_compress_file failure - ".$errormsg, LOG_ERR);
2747 dol_syslog(
"dol_compress_file success - ".count($result).
" files");
2753 if ($foundhandler && is_string($compressdata)) {
2754 $fp = fopen($outputfile,
"w");
2755 fwrite($fp, $compressdata);
2759 $errorstring =
"Try to zip with format ".$mode.
" with no handler for this format";
2763 $errormsg = $errorstring;
2767 global $langs, $errormsg;
2768 $langs->load(
"errors");
2769 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
2771 $errorstring =
"Failed to open file ".$outputfile;
2789 $fileinfo = pathinfo($inputfile);
2790 $fileinfo[
"extension"] = strtolower($fileinfo[
"extension"]);
2792 if ($fileinfo[
"extension"] ==
"zip") {
2793 if (defined(
'ODTPHP_PATHTOPCLZIP') && !
getDolGlobalString(
'MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS')) {
2794 dol_syslog(
"Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.
", so we use Pclzip to unzip into ".$outputdir);
2795 include_once ODTPHP_PATHTOPCLZIP.
'pclzip.lib.php';
2796 $archive =
new PclZip($inputfile);
2803 $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG,
'/^((?!\.\.).)*$/');
2805 return array(
'error' => $e->getMessage());
2808 if (!is_array($result) && $result <= 0) {
2809 return array(
'error' => $archive->errorInfo(
true));
2814 foreach ($result as $key => $val) {
2815 if ($val[
'status'] ==
'path_creation_fail') {
2816 $langs->load(
"errors");
2818 $errmsg = $langs->trans(
"ErrorFailToCreateDir", $val[
'filename']);
2821 if ($val[
'status'] ==
'write_protected') {
2822 $langs->load(
"errors");
2824 $errmsg = $langs->trans(
"ErrorFailToCreateFile", $val[
'filename']);
2832 return array(
'error' => $errmsg);
2837 if (class_exists(
'ZipArchive')) {
2838 dol_syslog(
"Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
2839 $zip =
new ZipArchive();
2840 $res = $zip->open($inputfile);
2841 if ($res ===
true) {
2847 for ($i = 0; $i < $zip->numFiles; $i++) {
2848 if (preg_match(
'/\.\./', $zip->getNameIndex($i))) {
2849 dol_syslog(
"Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
2852 $zip->extractTo($outputdir.
'/', array($zip->getNameIndex($i)));
2858 return array(
'error' =>
'ErrUnzipFails');
2862 return array(
'error' =>
'ErrNoZipEngine');
2863 } elseif (in_array($fileinfo[
"extension"], array(
'gz',
'bz2',
'zst'))) {
2864 include_once DOL_DOCUMENT_ROOT.
"/core/class/utils.class.php";
2872 $extension = strtolower(pathinfo($fileinfo[
"filename"], PATHINFO_EXTENSION));
2873 if ($extension ==
"tar") {
2876 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0, $outputfilename.
'.err', 0);
2877 if ($resarray[
"result"] != 0) {
2878 $resarray[
"error"] .= file_get_contents($outputfilename.
'.err');
2882 if ($fileinfo[
"extension"] ==
"gz") {
2884 } elseif ($fileinfo[
"extension"] ==
"bz2") {
2886 } elseif ($fileinfo[
"extension"] ==
"zst") {
2889 return array(
'error' =>
'ErrorBadFileExtension');
2892 $cmd .=
' > '.$outputfilename;
2894 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0,
null, 1, $outputfilename.
'.err');
2895 if ($resarray[
"result"] != 0) {
2896 $errfilecontent = @file_get_contents($outputfilename.
'.err');
2897 if ($errfilecontent) {
2898 $resarray[
"error"] .=
" - ".$errfilecontent;
2902 return $resarray[
"result"] != 0 ? array(
'error' => $resarray[
"error"]) : array();
2905 return array(
'error' =>
'ErrorBadFileExtension');
2921function dol_compress_dir($inputdir, $outputfile, $mode =
"zip", $excludefiles =
'', $rootdirinzip =
'', $newmask =
'0')
2925 dol_syslog(
"Try to zip dir ".$inputdir.
" into ".$outputfile.
" mode=".$mode);
2927 if (!
dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
2928 global $langs, $errormsg;
2929 $langs->load(
"errors");
2930 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir", $outputfile);
2935 if ($mode ==
'gz') {
2937 } elseif ($mode ==
'bz') {
2939 } elseif ($mode ==
'zip') {
2953 if (class_exists(
'ZipArchive')) {
2957 $zip =
new ZipArchive();
2958 $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2959 if ($result !==
true) {
2960 global $langs, $errormsg;
2961 $langs->load(
"errors");
2962 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile);
2969 $files =
new RecursiveIteratorIterator(
2970 new RecursiveDirectoryIterator($inputdir, FilesystemIterator::UNIX_PATHS),
2971 RecursiveIteratorIterator::LEAVES_ONLY
2973 '@phan-var-force SplFileInfo[] $files';
2976 foreach ($files as $name => $file) {
2978 if (!$file->isDir()) {
2980 $filePath = $file->getPath();
2981 $fileName = $file->getFilename();
2982 $fileFullRealPath = $file->getRealPath();
2985 $relativePath = ($rootdirinzip ? $rootdirinzip.
'/' :
'').substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($inputdir) + 1);
2988 if (empty($excludefiles) || !preg_match($excludefiles, $fileFullRealPath)) {
2990 $zip->addFile($fileFullRealPath, $relativePath);
3001 if (empty($newmask)) {
3002 dol_syslog(
"Warning: dol_compress_dir called with empty value for newmask and no default value defined", LOG_WARNING);
3012 if (!$foundhandler) {
3013 dol_syslog(
"Try to zip with format ".$mode.
" with no handler for this format", LOG_ERR);
3019 global $langs, $errormsg;
3020 $langs->load(
"errors");
3021 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
3023 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile).
' - '.$e->getMessage();
3040function dol_most_recent_file($dir, $regexfilter =
'', $excludefilter = array(
'(\.meta|_preview.*\.png)$',
'^\.'), $nohook = 0, $mode = 0)
3042 $tmparray =
dol_dir_list($dir,
'files', 0, $regexfilter, $excludefilter,
'date', SORT_DESC, $mode, $nohook);
3043 return isset($tmparray[0]) ? $tmparray[0] :
null;
3061 global
$conf,
$db, $user, $hookmanager;
3062 global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
3065 if (!is_object($fuser)) {
3069 if (empty($modulepart)) {
3070 return 'ErrorBadParameter';
3072 if (empty($entity)) {
3083 if ($modulepart ==
'facture') {
3084 $modulepart =
'invoice';
3085 } elseif ($modulepart ==
'users') {
3086 $modulepart =
'user';
3087 } elseif ($modulepart ==
'tva') {
3088 $modulepart =
'tax-vat';
3089 } elseif ($modulepart ==
'expedition' && strpos($original_file,
'receipt/') === 0) {
3091 $modulepart =
'delivery';
3092 } elseif ($modulepart ==
'propale') {
3093 $modulepart =
'propal';
3097 dol_syslog(
'dol_check_secure_access_document modulepart='.$modulepart.
' original_file='.$original_file.
' entity='.$entity);
3101 $sqlprotectagainstexternals =
'';
3105 if (empty($refname)) {
3106 $refname = basename(dirname($original_file).
"/");
3107 if ($refname ==
'thumbs' || $refname ==
'temp') {
3109 $refname = basename(dirname(dirname($original_file)).
"/");
3116 $download =
'download';
3117 if ($mode ==
'write') {
3120 $download =
'upload';
3124 if ($modulepart ==
'common') {
3127 $original_file = DOL_DOCUMENT_ROOT.
'/public/theme/common/'.$original_file;
3128 } elseif ($modulepart ==
'medias' && !empty($dolibarr_main_data_root)) {
3130 if (empty($entity)) {
3134 if ($mode ==
'write') {
3135 if ($fuser->hasRight(
'website',
'write')) {
3141 $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;
3142 } elseif ($modulepart ==
'logs' && !empty($dolibarr_main_data_root)) {
3144 $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match(
'/^dolibarr.*\.(log|json)$/', basename($original_file)));
3145 $original_file = $dolibarr_main_data_root.
'/'.$original_file;
3146 } elseif ($modulepart ==
'doctemplates' && !empty($dolibarr_main_data_root)) {
3147 $accessallowed = $user->admin;
3148 $relative_file = $original_file;
3149 $ent = ($entity > 0 ? $entity :
$conf->entity);
3150 $path_with_entity = $dolibarr_main_data_root .
'/' . $ent .
'/doctemplates/' . $relative_file;
3151 if ($ent > 1 && file_exists(
dol_osencode($path_with_entity))) {
3152 $original_file = $path_with_entity;
3154 $original_file = $dolibarr_main_data_root .
'/doctemplates/' . $relative_file;
3156 } elseif ($modulepart ==
'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
3158 $accessallowed = ($fuser->hasRight(
'website',
'write') && preg_match(
'/\.jpg$/i', basename($original_file)));
3159 $original_file = $dolibarr_main_data_root.
'/doctemplates/websites/'.$original_file;
3160 } elseif ($modulepart ==
'packages' && !empty($dolibarr_main_data_root)) {
3163 $tmp = explode(
',', $dolibarr_main_document_root_alt);
3166 $accessallowed = ($user->admin && preg_match(
'/^module_.*\.zip$/', basename($original_file)));
3167 $original_file = $dirins.
'/'.$original_file;
3168 } elseif ($modulepart ==
'mycompany' && !empty(
$conf->mycompany->dir_output)) {
3171 $original_file =
$conf->mycompany->dir_output.
'/'.$original_file;
3172 } elseif ($modulepart ==
'userphoto' && !empty(
$conf->user->dir_output)) {
3175 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
3178 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3179 } elseif ($modulepart ==
'userphotopublic' && !empty(
$conf->user->dir_output)) {
3184 if (preg_match(
'/^(\d+)\/photos\//', $original_file, $reg)) {
3185 if ((
int) $reg[1]) {
3187 $tmpobject->fetch((
int) $reg[1],
'',
'', 1);
3189 $securekey =
GETPOST(
'securekey',
'alpha', 1);
3191 global $dolibarr_main_cookie_cryptkey, $dolibarr_main_instance_unique_id;
3192 $valuetouse = $dolibarr_main_instance_unique_id ? $dolibarr_main_instance_unique_id : $dolibarr_main_cookie_cryptkey;
3193 $encodedsecurekey =
dol_hash($valuetouse.
'uservirtualcard'.$tmpobject->id.
'-'.$tmpobject->login,
'md5');
3194 if ($encodedsecurekey == $securekey) {
3203 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3204 } elseif (($modulepart ==
'companylogo') && !empty(
$conf->mycompany->dir_output)) {
3207 $original_file =
$conf->mycompany->dir_output.
'/logos/'.$original_file;
3208 } elseif ($modulepart ==
'memberphoto' && !empty(
$conf->member->dir_output)) {
3212 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
3216 if (preg_match(
'/^MEM\d\d\d\d-\d\d\d\d\/photos\//', $original_file)) {
3219 $original_file =
$conf->member->dir_output.
'/'.$original_file;
3220 } elseif ($modulepart ==
'apercufacture' && !empty(
$conf->invoice->multidir_output[$entity])) {
3222 if ($fuser->hasRight(
'facture', $lire)) {
3225 $original_file =
$conf->invoice->multidir_output[$entity].
'/'.$original_file;
3226 } elseif ($modulepart ==
'apercupropal' && !empty(
$conf->propal->multidir_output[$entity])) {
3228 if ($fuser->hasRight(
'propal', $lire)) {
3231 $original_file =
$conf->propal->multidir_output[$entity].
'/'.$original_file;
3232 } elseif ($modulepart ==
'apercucommande' && !empty(
$conf->order->multidir_output[$entity])) {
3234 if ($fuser->hasRight(
'commande', $lire)) {
3237 $original_file =
$conf->order->multidir_output[$entity].
'/'.$original_file;
3238 } elseif (($modulepart ==
'apercufichinter' || $modulepart ==
'apercuficheinter') && !empty(
$conf->ficheinter->multidir_output[$entity])) {
3240 if ($fuser->hasRight(
'ficheinter', $lire)) {
3243 $original_file =
$conf->ficheinter->multidir_output[$entity].
'/'.$original_file;
3244 } elseif (($modulepart ==
'apercucontract') && !empty(
$conf->contract->multidir_output[$entity])) {
3246 if ($fuser->hasRight(
'contrat', $lire)) {
3249 $original_file =
$conf->contract->multidir_output[$entity].
'/'.$original_file;
3250 } elseif (($modulepart ==
'apercusupplier_proposal') && !empty(
$conf->supplier_proposal->dir_output)) {
3252 if ($fuser->hasRight(
'supplier_proposal', $lire)) {
3255 $original_file =
$conf->supplier_proposal->dir_output.
'/'.$original_file;
3256 } elseif (($modulepart ==
'apercusupplier_order') && !empty(
$conf->fournisseur->commande->dir_output)) {
3258 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
3261 $original_file =
$conf->fournisseur->commande->dir_output.
'/'.$original_file;
3262 } elseif (($modulepart ==
'apercusupplier_invoice') && !empty(
$conf->fournisseur->facture->dir_output)) {
3264 if ($fuser->hasRight(
'fournisseur', $lire)) {
3267 $original_file =
$conf->fournisseur->facture->dir_output.
'/'.$original_file;
3268 } elseif (($modulepart ==
'holiday') && !empty(
$conf->holiday->dir_output)) {
3269 if ($fuser->hasRight(
'holiday', $read) || $fuser->hasRight(
'holiday',
'readall') || preg_match(
'/^specimen/i', $original_file)) {
3272 if ($refname && !$fuser->hasRight(
'holiday',
'readall') && !preg_match(
'/^specimen/i', $original_file)) {
3273 include_once DOL_DOCUMENT_ROOT.
'/holiday/class/holiday.class.php';
3275 $tmpholiday->fetch(0, $refname);
3276 $accessallowed =
checkUserAccessToObject($user, array(
'holiday'), $tmpholiday,
'holiday',
'',
'',
'rowid',
'');
3279 $original_file =
$conf->holiday->dir_output.
'/'.$original_file;
3280 } elseif (($modulepart ==
'expensereport') && !empty(
$conf->expensereport->dir_output)) {
3281 if ($fuser->hasRight(
'expensereport', $lire) || $fuser->hasRight(
'expensereport',
'readall') || preg_match(
'/^specimen/i', $original_file)) {
3284 if ($refname && !$fuser->hasRight(
'expensereport',
'readall') && !preg_match(
'/^specimen/i', $original_file)) {
3285 include_once DOL_DOCUMENT_ROOT.
'/expensereport/class/expensereport.class.php';
3287 $tmpexpensereport->fetch(0, $refname);
3288 $accessallowed =
checkUserAccessToObject($user, array(
'expensereport'), $tmpexpensereport,
'expensereport',
'',
'',
'rowid',
'');
3291 $original_file =
$conf->expensereport->dir_output.
'/'.$original_file;
3292 } elseif (($modulepart ==
'apercuexpensereport') && !empty(
$conf->expensereport->dir_output)) {
3294 if ($fuser->hasRight(
'expensereport', $lire)) {
3297 $original_file =
$conf->expensereport->dir_output.
'/'.$original_file;
3298 } elseif ($modulepart ==
'propalstats' && !empty(
$conf->propal->multidir_temp[$entity])) {
3300 if ($fuser->hasRight(
'propal', $lire)) {
3303 $original_file =
$conf->propal->multidir_temp[$entity].
'/'.$original_file;
3304 } elseif ($modulepart ==
'orderstats' && !empty(
$conf->order->dir_temp)) {
3306 if ($fuser->hasRight(
'commande', $lire)) {
3309 $original_file =
$conf->order->dir_temp.
'/'.$original_file;
3310 } elseif ($modulepart ==
'orderstatssupplier' && !empty(
$conf->fournisseur->dir_output)) {
3311 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
3314 $original_file =
$conf->fournisseur->commande->dir_temp.
'/'.$original_file;
3315 } elseif ($modulepart ==
'billstats' && !empty(
$conf->invoice->dir_temp)) {
3317 if ($fuser->hasRight(
'facture', $lire)) {
3320 $original_file =
$conf->invoice->dir_temp.
'/'.$original_file;
3321 } elseif ($modulepart ==
'billstatssupplier' && !empty(
$conf->fournisseur->dir_output)) {
3322 if ($fuser->hasRight(
'fournisseur',
'facture', $lire)) {
3325 $original_file =
$conf->fournisseur->facture->dir_temp.
'/'.$original_file;
3326 } elseif ($modulepart ==
'expeditionstats' && !empty(
$conf->expedition->dir_temp)) {
3328 if ($fuser->hasRight(
'expedition', $lire)) {
3331 $original_file =
$conf->expedition->dir_temp.
'/'.$original_file;
3332 } elseif ($modulepart ==
'tripsexpensesstats' && !empty(
$conf->deplacement->dir_temp)) {
3334 if ($fuser->hasRight(
'deplacement', $lire)) {
3337 $original_file =
$conf->deplacement->dir_temp.
'/'.$original_file;
3338 } elseif ($modulepart ==
'memberstats' && !empty(
$conf->member->dir_temp)) {
3340 if ($fuser->hasRight(
'adherent', $lire)) {
3343 $original_file =
$conf->member->dir_temp.
'/'.$original_file;
3344 } elseif (preg_match(
'/^productstats_/i', $modulepart) && !empty(
$conf->product->dir_temp)) {
3346 if ($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) {
3349 $original_file = (!empty(
$conf->product->multidir_temp[$entity]) ?
$conf->product->multidir_temp[$entity] :
$conf->service->multidir_temp[$entity]).
'/'.$original_file;
3350 } elseif (in_array($modulepart, array(
'tax',
'tax-vat',
'tva')) && !empty(
$conf->tax->dir_output)) {
3352 if ($fuser->hasRight(
'tax',
'charges', $lire)) {
3355 $modulepartsuffix = str_replace(
'tax-',
'', $modulepart);
3356 $original_file =
$conf->tax->dir_output.
'/'.($modulepartsuffix !=
'tax' ? $modulepartsuffix.
'/' :
'').$original_file;
3357 } elseif (($modulepart ==
'actions' || $modulepart ==
'actioncomm') && !empty(
$conf->agenda->dir_output)) {
3359 if ($fuser->hasRight(
'agenda',
'myactions', $read)) {
3362 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3363 include_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
3365 $tmpobject->fetch((
int) $refname);
3366 $accessallowed =
checkUserAccessToObject($user, array(
'agenda'), $tmpobject->id,
'actioncomm&societe',
'myactions|allactions',
'fk_soc',
'id',
'');
3367 if ($user->socid && $tmpobject->socid) {
3372 $original_file =
$conf->agenda->dir_output.
'/'.$original_file;
3373 } elseif ($modulepart ==
'category' && !empty(
$conf->categorie->multidir_output[$entity])) {
3375 if (empty($entity) || empty(
$conf->categorie->multidir_output[$entity])) {
3376 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3378 if ($fuser->hasRight(
"categorie", $lire) || $fuser->hasRight(
"takepos",
"run")) {
3381 $original_file =
$conf->categorie->multidir_output[$entity].
'/'.$original_file;
3382 } elseif ($modulepart ==
'prelevement' && !empty(
$conf->prelevement->dir_output)) {
3384 if ($fuser->hasRight(
'prelevement',
'bons', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3387 $original_file =
$conf->prelevement->dir_output.
'/'.$original_file;
3388 } elseif ($modulepart ==
'graph_stock' && !empty(
$conf->stock->dir_temp)) {
3391 $original_file =
$conf->stock->dir_temp.
'/'.$original_file;
3392 } elseif ($modulepart ==
'graph_fourn' && !empty(
$conf->fournisseur->dir_temp)) {
3395 $original_file =
$conf->fournisseur->dir_temp.
'/'.$original_file;
3396 } elseif ($modulepart ==
'graph_product' && !empty(
$conf->product->dir_temp)) {
3399 $original_file =
$conf->product->multidir_temp[$entity].
'/'.$original_file;
3400 } elseif ($modulepart ==
'barcode') {
3405 $original_file =
'';
3406 } elseif ($modulepart ==
'iconmailing' && !empty(
$conf->mailing->dir_temp)) {
3409 $original_file =
$conf->mailing->dir_temp.
'/'.$original_file;
3410 } elseif ($modulepart ==
'scanner_user_temp' && !empty(
$conf->scanner->dir_temp)) {
3413 $original_file =
$conf->scanner->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3414 } elseif ($modulepart ==
'fckeditor' && !empty(
$conf->fckeditor->dir_output)) {
3417 $original_file =
$conf->fckeditor->dir_output.
'/'.$original_file;
3418 } elseif ($modulepart ==
'user' && !empty(
$conf->user->dir_output)) {
3420 $canreaduser = (!empty($fuser->admin) || $fuser->hasRight(
'user',
'user', $lire));
3421 if ($fuser->id == (
int) $refname) {
3424 if ($canreaduser || preg_match(
'/^specimen/i', $original_file)) {
3427 $original_file =
$conf->user->dir_output.
'/'.$original_file;
3428 } elseif (($modulepart ==
'company' || $modulepart ==
'societe' || $modulepart ==
'thirdparty') && !empty(
$conf->societe->multidir_output[$entity])) {
3430 if (empty($entity) || empty(
$conf->societe->multidir_output[$entity])) {
3431 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3433 if ($fuser->hasRight(
'societe', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3436 $original_file =
$conf->societe->multidir_output[$entity].
'/'.$original_file;
3437 $sqlprotectagainstexternals =
"SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX.
"societe WHERE rowid = ".((int) $refname).
" AND entity IN (".
getEntity(
'societe').
")";
3438 } elseif (($modulepart ==
'contact' || $modulepart ==
'socpeople') && !empty(
$conf->societe->multidir_output[$entity])) {
3440 if (empty($entity) || empty(
$conf->societe->multidir_output[$entity])) {
3441 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3443 if ($fuser->hasRight(
'societe',
'contact', $lire)) {
3446 $original_file =
$conf->societe->multidir_output[$entity].
'/contact/'.$original_file;
3447 $sqlprotectagainstexternals =
"SELECT fk_soc FROM ".MAIN_DB_PREFIX.
"socpeople WHERE rowid = ".((int) $refname).
" AND entity IN (".
getEntity(
'contact').
")";
3448 } elseif (($modulepart ==
'facture' || $modulepart ==
'invoice') && !empty(
$conf->invoice->multidir_output[$entity])) {
3450 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3453 $original_file =
$conf->invoice->multidir_output[$entity].
'/'.$original_file;
3454 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'invoice').
")";
3455 } elseif ($modulepart ==
'massfilesarea_proposals' && !empty(
$conf->propal->multidir_output[$entity])) {
3457 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3460 $original_file =
$conf->propal->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3461 } elseif ($modulepart ==
'massfilesarea_orders') {
3462 if ($fuser->hasRight(
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3465 $original_file =
$conf->order->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3466 } elseif ($modulepart ==
'massfilesarea_sendings') {
3467 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3470 $original_file =
$conf->expedition->dir_output.
'/sending/temp/massgeneration/'.$user->id.
'/'.$original_file;
3471 } elseif ($modulepart ==
'massfilesarea_receipts') {
3472 if ($fuser->hasRight(
'reception', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3475 $original_file =
$conf->reception->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3476 } elseif ($modulepart ==
'massfilesarea_invoices') {
3477 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3480 $original_file =
$conf->invoice->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3481 } elseif ($modulepart ==
'massfilesarea_expensereport') {
3482 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3485 $original_file =
$conf->expensereport->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3486 } elseif ($modulepart ==
'massfilesarea_interventions') {
3487 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3490 $original_file =
$conf->ficheinter->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3491 } elseif ($modulepart ==
'massfilesarea_supplier_proposal' && !empty(
$conf->supplier_proposal->dir_output)) {
3492 if ($fuser->hasRight(
'supplier_proposal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3495 $original_file =
$conf->supplier_proposal->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3496 } elseif ($modulepart ==
'massfilesarea_supplier_order') {
3497 if ($fuser->hasRight(
'fournisseur',
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3500 $original_file =
$conf->fournisseur->commande->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3501 } elseif ($modulepart ==
'massfilesarea_supplier_invoice') {
3502 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3505 $original_file =
$conf->fournisseur->facture->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3506 } elseif ($modulepart ==
'massfilesarea_contract' && !empty(
$conf->contract->dir_output)) {
3507 if ($fuser->hasRight(
'contrat', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3510 $original_file =
$conf->contract->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3511 } elseif ($modulepart ==
'massfilesarea_stock' && !empty(
$conf->stock->dir_output)) {
3512 if ($fuser->hasRight(
'stock', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3515 $original_file =
$conf->stock->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3516 } elseif (($modulepart ==
'fichinter' || $modulepart ==
'ficheinter') && !empty(
$conf->ficheinter->multidir_output[$entity])) {
3518 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3521 $original_file =
$conf->ficheinter->multidir_output[$entity].
'/'.$original_file;
3522 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"fichinter WHERE ref='".
$db->escape($refname).
"' AND entity=".((int)
$conf->entity);
3523 } elseif ($modulepart ==
'deplacement' && !empty(
$conf->deplacement->dir_output)) {
3525 if ($fuser->hasRight(
'deplacement', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3528 $original_file =
$conf->deplacement->dir_output.
'/'.$original_file;
3530 } elseif (($modulepart ==
'propal' || $modulepart ==
'propale') && isset(
$conf->propal->multidir_output[$entity])) {
3532 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3535 $original_file =
$conf->propal->multidir_output[$entity].
'/'.$original_file;
3536 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"propal WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'propal').
")";
3537 } elseif (($modulepart ==
'commande' || $modulepart ==
'order') && !empty(
$conf->order->multidir_output[$entity])) {
3539 if ($fuser->hasRight(
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3542 $original_file =
$conf->order->multidir_output[$entity].
'/'.$original_file;
3543 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'order').
")";
3544 } elseif ($modulepart ==
'project' && !empty(
$conf->project->multidir_output[$entity])) {
3546 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3549 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3550 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
3552 $tmpproject->fetch(0, $refname);
3553 $accessallowed =
checkUserAccessToObject($user, array(
'projet'), $tmpproject->id,
'projet&project',
'',
'',
'rowid',
'');
3556 $original_file =
$conf->project->multidir_output[$entity].
'/'.$original_file;
3557 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3558 } elseif ($modulepart ==
'project_task' && !empty(
$conf->project->multidir_output[$entity])) {
3559 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3562 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3563 include_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
3565 $tmptask->fetch(0, $refname);
3566 $accessallowed =
checkUserAccessToObject($user, array(
'projet_task'), $tmptask->id,
'projet_task&project',
'',
'',
'rowid',
'');
3569 $original_file =
$conf->project->multidir_output[$entity].
'/'.$original_file;
3570 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3571 } elseif (($modulepart ==
'commande_fournisseur' || $modulepart ==
'order_supplier') && !empty(
$conf->fournisseur->commande->dir_output)) {
3573 if ($fuser->hasRight(
'fournisseur',
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3576 $original_file =
$conf->fournisseur->commande->dir_output.
'/'.$original_file;
3577 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande_fournisseur WHERE ref='".
$db->escape($refname).
"' AND entity=".((int)
$conf->entity);
3578 } elseif (($modulepart ==
'facture_fournisseur' || $modulepart ==
'invoice_supplier') && !empty(
$conf->fournisseur->facture->dir_output)) {
3580 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3583 $original_file =
$conf->fournisseur->facture->dir_output.
'/'.$original_file;
3584 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture_fourn WHERE ref='".
$db->escape($refname).
"' AND entity=".((int)
$conf->entity);
3585 } elseif ($modulepart ==
'supplier_payment') {
3587 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3590 $original_file = preg_replace(
"/payment\//",
"", $original_file);
3591 $original_file =
$conf->fournisseur->payment->dir_output.
'/'.$original_file;
3592 $sqlprotectagainstexternals =
"SELECT f.fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"paiementfourn as p";
3593 $sqlprotectagainstexternals .=
" INNER JOIN ".MAIN_DB_PREFIX.
"paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid";
3594 $sqlprotectagainstexternals .=
" INNER JOIN ".MAIN_DB_PREFIX.
"facture_fourn as f ON pf.fk_facturefourn = p.rowid";
3595 $sqlprotectagainstexternals .=
" WHERE p.ref = '".$db->escape($refname).
"' AND p.entity=".((int)
$conf->entity);
3596 } elseif ($modulepart ==
'payment') {
3598 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3601 $original_file =
$conf->compta->payment->dir_output.
'/'.$original_file;
3602 } elseif ($modulepart ==
'facture_paiement' && !empty(
$conf->invoice->dir_output)) {
3604 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3607 if ($fuser->socid > 0) {
3608 $original_file =
$conf->invoice->dir_output.
'/payments/private/'.$fuser->id.
'/'.$original_file;
3610 $original_file =
$conf->invoice->dir_output.
'/payments/'.$original_file;
3617 } elseif ($modulepart ==
'export_compta' && !empty(
$conf->accounting->dir_output)) {
3619 if ($fuser->hasRight(
'accounting',
'bind',
'write') || $fuser->hasRight(
'accounting',
'mouvements',
'export') || preg_match(
'/^specimen/i', $original_file)) {
3622 $original_file =
$conf->accounting->dir_output.
'/'.$original_file;
3623 } elseif (($modulepart ==
'expedition' || $modulepart ==
'shipment' || $modulepart ==
'shipping') && !empty(
$conf->expedition->dir_output)) {
3625 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3628 $original_file =
$conf->expedition->dir_output.
"/".(strpos($original_file,
'sending/') === 0 ?
'' :
'sending/').$original_file;
3630 } elseif (($modulepart ==
'livraison' || $modulepart ==
'delivery') && !empty(
$conf->expedition->dir_output)) {
3632 if ($fuser->hasRight(
'expedition',
'delivery', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3635 $original_file =
$conf->expedition->dir_output.
"/".(strpos($original_file,
'receipt/') === 0 ?
'' :
'receipt/').$original_file;
3636 } elseif ($modulepart ==
'actionsreport' && !empty(
$conf->agenda->dir_temp)) {
3638 if ($fuser->hasRight(
'agenda',
'allactions', $read) || preg_match(
'/^specimen/i', $original_file)) {
3641 $original_file =
$conf->agenda->dir_temp.
"/".$original_file;
3642 } elseif ($modulepart ==
'product' || $modulepart ==
'produit' || $modulepart ==
'service' || $modulepart ==
'produit|service') {
3644 if (empty($entity) || (empty(
$conf->product->multidir_output[$entity]) && empty(
$conf->service->multidir_output[$entity]))) {
3645 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3647 if (($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3651 $original_file =
$conf->product->multidir_output[$entity].
'/'.$original_file;
3653 $original_file =
$conf->service->multidir_output[$entity].
'/'.$original_file;
3655 } elseif ($modulepart ==
'product_batch' || $modulepart ==
'produitlot') {
3657 if (empty($entity) || (empty(
$conf->productbatch->multidir_output[$entity]))) {
3658 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3660 if (($fuser->hasRight(
'produit', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3664 $original_file =
$conf->productbatch->multidir_output[$entity].
'/'.$original_file;
3666 } elseif ($modulepart ==
'movement' || $modulepart ==
'mouvement') {
3668 if (empty($entity) || empty(
$conf->stock->multidir_output[$entity])) {
3669 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3671 if (($fuser->hasRight(
'stock', $lire) || $fuser->hasRight(
'stock',
'movement', $lire) || $fuser->hasRight(
'stock',
'mouvement', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3675 $original_file =
$conf->stock->multidir_output[$entity].
'/movement/'.$original_file;
3677 } elseif ($modulepart ==
'inventory') {
3679 if (empty($entity) || empty(
$conf->stock->multidir_output[$entity])) {
3680 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3682 if ($fuser->hasRight(
'stock', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3686 $original_file =
$conf->stock->multidir_output[$entity].
'/inventory/'.$original_file;
3688 } elseif ($modulepart ==
'entrepot') {
3690 if (empty($entity) || empty(
$conf->stock->multidir_output[$entity])) {
3691 return array(
'accessallowed' => 0,
'error' =>
'Value entity must be provided');
3693 if (($fuser->hasRight(
'stock', $lire) || $fuser->hasRight(
'stock',
'movement', $lire) || $fuser->hasRight(
'stock',
'mouvement', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3697 $original_file =
$conf->stock->multidir_output[$entity].
'/'.$original_file;
3699 } elseif ($modulepart ==
'contract' && !empty(
$conf->contract->multidir_output[$entity])) {
3701 if ($fuser->hasRight(
'contrat', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3704 $original_file =
$conf->contract->multidir_output[$entity].
'/'.$original_file;
3705 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"contrat WHERE ref='".
$db->escape($refname).
"' AND entity IN (".
getEntity(
'contract').
")";
3706 } elseif ($modulepart ==
'donation' && !empty(
$conf->don->dir_output)) {
3708 if ($fuser->hasRight(
'don', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3711 $original_file =
$conf->don->dir_output.
'/'.$original_file;
3712 } elseif ($modulepart ==
'dolresource' && !empty(
$conf->resource->dir_output)) {
3714 if ($fuser->hasRight(
'resource', $read) || preg_match(
'/^specimen/i', $original_file)) {
3717 $original_file =
$conf->resource->dir_output.
'/'.$original_file;
3718 } elseif (($modulepart ==
'remisecheque' || $modulepart ==
'chequereceipt') && !empty(
$conf->bank->dir_output)) {
3720 if ($fuser->hasRight(
'banque', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3723 $original_file =
$conf->bank->dir_output.
'/checkdeposits/'.$original_file;
3724 } elseif (($modulepart ==
'banque' || $modulepart ==
'bank') && !empty(
$conf->bank->dir_output)) {
3726 if ($fuser->hasRight(
'banque', $lire)) {
3729 $original_file =
$conf->bank->dir_output.
'/'.$original_file;
3730 } elseif ($modulepart ==
'export' && !empty(
$conf->export->dir_temp)) {
3733 $accessallowed = $user->hasRight(
'export',
'lire');
3734 $original_file =
$conf->export->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3735 } elseif ($modulepart ==
'import' && !empty(
$conf->import->dir_temp)) {
3737 $accessallowed = $user->hasRight(
'import',
'run');
3738 $original_file =
$conf->import->dir_temp.
'/'.$original_file;
3739 } elseif ($modulepart ==
'recruitment' && !empty(
$conf->recruitment->dir_output)) {
3741 $accessallowed = $user->hasRight(
'recruitment',
'recruitmentjobposition',
'read');
3742 $original_file =
$conf->recruitment->dir_output.
'/'.$original_file;
3743 } elseif ($modulepart ==
'hrm' && !empty(
$conf->hrm->dir_output)) {
3745 $accessallowed = $user->hasRight(
'hrm',
'all',
'read');
3746 $original_file =
$conf->hrm->dir_output.
'/'.$original_file;
3747 } elseif ($modulepart ==
'editor' && !empty(
$conf->fckeditor->dir_output)) {
3750 $original_file =
$conf->fckeditor->dir_output.
'/'.$original_file;
3751 } elseif ($modulepart ==
'systemtools' && !empty(
$conf->admin->dir_output)) {
3753 if ($fuser->admin) {
3756 $original_file =
$conf->admin->dir_output.
'/'.$original_file;
3757 } elseif ($modulepart ==
'admin_temp' && !empty(
$conf->admin->dir_temp)) {
3759 if ($fuser->admin) {
3762 $original_file =
$conf->admin->dir_temp.
'/'.$original_file;
3763 } elseif ($modulepart ==
'bittorrent' && !empty(
$conf->bittorrent->dir_output)) {
3767 if (
dol_mimetype($original_file) ==
'application/x-bittorrent') {
3770 $original_file =
$conf->bittorrent->dir_output.
'/'.$dir.
'/'.$original_file;
3771 } elseif ($modulepart ==
'member' && !empty(
$conf->member->dir_output)) {
3773 if ($fuser->hasRight(
'adherent', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3776 $original_file =
$conf->member->dir_output.
'/'.$original_file;
3777 } elseif ($modulepart ==
'ticket' && !empty(
$conf->ticket->multidir_output[$entity])) {
3779 if ($fuser->hasRight(
'ticket', $read)) {
3782 if (!isset($_SESSION[
'email_customer'])) {
3783 $sqlprotectagainstexternals =
'';
3785 $email_split = explode(
'@', $_SESSION[
'email_customer']);
3787 $sqlprotectagainstexternals =
'SELECT t.rowid, t.fk_soc FROM '.MAIN_DB_PREFIX.
'ticket t';
3788 $sqlprotectagainstexternals .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'element_contact ec ON ec.element_id = t.rowid';
3789 $sqlprotectagainstexternals .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'socpeople c ON c.rowid = ec.fk_socpeople';
3790 $sqlprotectagainstexternals .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_type_contact tc ON tc.element = "ticket" AND tc.rowid = ec.fk_c_type_contact';
3791 $sqlprotectagainstexternals .=
' WHERE t.ref LIKE "'.$db->sanitize($refname).
'"';
3792 $sqlprotectagainstexternals .=
' AND (';
3793 $sqlprotectagainstexternals .=
' (';
3794 $sqlprotectagainstexternals .=
' tc.rowid IS NOT NULL';
3795 $sqlprotectagainstexternals .=
' AND c.email = "'.$db->sanitize($email_split[0]).
'@'.
$db->sanitize($email_split[1]).
'"';
3796 $sqlprotectagainstexternals .=
' )';
3797 $sqlprotectagainstexternals .=
' OR t.origin_email = "'.$db->sanitize($email_split[0]).
'@'.
$db->sanitize($email_split[1]).
'"';
3798 $sqlprotectagainstexternals .=
' )';
3800 $original_file =
$conf->ticket->multidir_output[$entity].
'/'.$original_file;
3810 if (preg_match(
'/^specimen/i', $original_file)) {
3813 if ($fuser->admin) {
3817 $tmpmodulepart = explode(
'-', $modulepart);
3818 if (!empty($tmpmodulepart[1])) {
3819 $modulepart = $tmpmodulepart[0];
3820 $original_file = $tmpmodulepart[1].
'/'.$original_file;
3825 if (preg_match(
'/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
3826 $tmpmodule = $reg[1];
3827 if (empty(
$conf->$tmpmodule->dir_temp)) {
3828 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3831 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3834 $original_file =
$conf->{$reg[1]}->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3835 } elseif (preg_match(
'/^([a-z]+)_temp$/i', $modulepart, $reg)) {
3836 $tmpmodule = $reg[1];
3837 if (empty(
$conf->$tmpmodule->dir_temp)) {
3838 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3841 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3844 $original_file =
$conf->$tmpmodule->dir_temp.
'/'.$original_file;
3845 } elseif (preg_match(
'/^([a-z]+)_user$/i', $modulepart, $reg)) {
3846 $tmpmodule = $reg[1];
3847 if (empty(
$conf->$tmpmodule->dir_output)) {
3848 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3851 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3854 $original_file =
$conf->$tmpmodule->dir_output.
'/'.$fuser->id.
'/'.$original_file;
3855 } elseif (preg_match(
'/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
3856 $tmpmodule = $reg[1];
3857 if (empty(
$conf->$tmpmodule->dir_output)) {
3858 dol_print_error(
null,
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3863 $partsofdirinoriginalfile = explode(
'/', $original_file);
3864 if (!empty($partsofdirinoriginalfile[1])) {
3865 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3866 if (($partofdirinoriginalfile && $fuser->hasRight($tmpmodule, $partofdirinoriginalfile,
'read')) || preg_match(
'/^specimen/i', $original_file)) {
3870 if ($fuser->hasRight($tmpmodule, $read) || preg_match(
'/^specimen/i', $original_file)) {
3873 $original_file =
$conf->$tmpmodule->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3875 if (empty(
$conf->$modulepart->dir_output)) {
3876 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.');
3881 $partsofdirinoriginalfile = explode(
'/', $original_file);
3882 if (!empty($partsofdirinoriginalfile[1])) {
3883 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3884 if ($partofdirinoriginalfile && ($fuser->hasRight($modulepart, $partofdirinoriginalfile,
'lire') || $fuser->hasRight($modulepart, $partofdirinoriginalfile,
'read'))) {
3888 if (($fuser->hasRight($modulepart, $lire) || $fuser->hasRight($modulepart, $read)) || ($fuser->hasRight($modulepart,
'all', $lire) || $fuser->hasRight($modulepart,
'all', $read))) {
3892 if (is_array(
$conf->$modulepart->multidir_output) && !empty(
$conf->$modulepart->multidir_output[$entity])) {
3893 $original_file =
$conf->$modulepart->multidir_output[$entity].
'/'.$original_file;
3895 $original_file =
$conf->$modulepart->dir_output.
'/'.$original_file;
3899 $parameters = array(
3900 'modulepart' => $modulepart,
3901 'original_file' => $original_file,
3902 'entity' => $entity,
3907 $reshook = $hookmanager->executeHooks(
'checkSecureAccess', $parameters,
$object);
3909 if (!empty($hookmanager->resArray[
'original_file'])) {
3910 $original_file = $hookmanager->resArray[
'original_file'];
3912 if (!empty($hookmanager->resArray[
'accessallowed'])) {
3913 $accessallowed = $hookmanager->resArray[
'accessallowed'];
3915 if (!empty($hookmanager->resArray[
'sqlprotectagainstexternals'])) {
3916 $sqlprotectagainstexternals = $hookmanager->resArray[
'sqlprotectagainstexternals'];
3922 'accessallowed' => ($accessallowed ? 1 : 0),
3923 'sqlprotectagainstexternals' => $sqlprotectagainstexternals,
3924 'original_file' => $original_file
3943 dol_syslog(
"Failed to create the cache directory ".$directory, LOG_WARNING);
3946 $cachefile = $directory.$filename;
3948 file_put_contents($cachefile, json_encode(
$object), LOCK_EX);
3963 $cachefile = $directory.$filename;
3964 $refresh = !file_exists($cachefile) || ($now - $cachetime) >
dol_filemtime($cachefile);
3977 $cachefile = $directory.$filename;
3978 $object = json_decode(file_get_contents($cachefile));
3990 return preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\//',
'', $pathfile);
4005function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path =
'', $pathref =
'', &$checksumconcat = array())
4013 if (!empty($dir->md5file)) {
4014 $entry = $dir->md5file;
4016 } elseif (!empty($dir->sha256file)) {
4017 $entry = $dir->sha256file;
4021 foreach ($entry as $file) {
4022 $filename = $path.$file[
'name'];
4023 $file_list[
'insignature'][] = $filename;
4024 $expectedsize = (empty($file[
'size']) ?
'' : $file[
'size']);
4025 $expectedhash = (
string) $file;
4027 if (!file_exists($pathref.
'/'.$filename)) {
4028 $file_list[
'missing'][] = array(
'filename' => $filename,
'expectedhash' => $expectedhash,
'expectedsize' => $expectedsize,
'algo' => (
string) $algo);
4030 $hash_local = hash_file($algo, $pathref.
'/'.$filename);
4032 if (
$conffile ==
'/etc/dolibarr/conf.php' && $filename ==
'/filefunc.inc.php') {
4033 $checksumconcat[] = $expectedhash;
4035 if ($hash_local != $expectedhash) {
4036 $file_list[
'updated'][] = array(
'filename' => $filename,
'expectedhash' => $expectedhash,
'expectedsize' => $expectedsize,
'hash' => (
string) $hash_local,
'algo' => (
string) $algo);
4038 $checksumconcat[] = $hash_local;
4043 foreach ($dir->dir as $subdir) {
4044 getFilesUpdated($file_list, $subdir, $path.$subdir[
'name'].
'/', $pathref, $checksumconcat);
4067 $pageurl = str_replace(
'</',
'<\\/',
dol_escape_js($_SERVER[
"PHP_SELF"], 1));
4075 $ajaxUrl = DOL_URL_ROOT.
'/core/ajax/fileupload.php';
4078 $out .=
'<div id="'.$htmlname.
'Message" class="dragDropAreaMessage hidden"><span>'.
img_picto(
"",
'download').
'<br>'.$langs->trans(
"DropFileToAddItToObject").
'</span></div>';
4079 $out .=
"\n<!-- JS CODE TO ENABLE DRAG AND DROP OF FILE -->\n";
4081<script nonce=
"{$nonce}">
4082 jQuery(document).ready(
function() {
4083 var enterTargetDragDrop =
null;
4085 $(
'#{$htmlname}').addClass(
'cssDragDropArea');
4087 $(
".cssDragDropArea").on(
"dragenter",
function(ev, ui) {
4088 var dataTransfer = ev.originalEvent.dataTransfer;
4089 var dataTypes = dataTransfer.types;
4093 if (!dataTypes || ($.inArray(
'Files', dataTypes) === -1)) {
4095 ev.preventDefault();
4100 console.log(
"dragAndDropFileUpload: We add class highlightDragDropArea")
4101 enterTargetDragDrop = ev.target;
4102 $(
this).addClass(
"highlightDragDropArea");
4103 $(
'#{$htmlname}Message').removeClass(
'hidden');
4104 ev.preventDefault();
4107 $(
".cssDragDropArea").on(
"dragleave",
function(ev) {
4109 if (enterTargetDragDrop == ev.target){
4110 console.log(
"dragAndDropFileUpload: We remove class highlightDragDropArea")
4111 $(
'#{$htmlname}Message').addClass(
'hidden');
4112 $(this).removeClass(
"highlightDragDropArea");
4116 $(
".cssDragDropArea").on(
"dragover",
function(ev) {
4117 ev.preventDefault();
4121 $(
".cssDragDropArea").on(
"drop",
function(e) {
4122 console.log(
'Trigger event file dropped. fk_element={$fkElement} element={$elementType}');
4124 fd =
new FormData();
4125 fd.append(
'fk_element',
'{$fkElement}');
4126 fd.append(
'element',
'{$elementType}');
4127 fd.append(
'token',
'{$token}');
4128 fd.append(
"action",
"linkit");
4130 var dataTransfer = e.originalEvent.dataTransfer;
4132 if (dataTransfer.files && dataTransfer.files.length){
4133 var droppedFiles = e.originalEvent.dataTransfer.files;
4134 $.each(droppedFiles,
function(index,file){
4135 fd.append(
"files[]", file,file.name)
4138 $(
".cssDragDropArea").removeClass(
"highlightDragDropArea");
4139 counterdragdrop = 0;
4146 success:
function() {
4147 console.log(
"Uploaded.", arguments);
4150 let listoffiles = [];
4155 listoffiles = JSON.parse(arguments[0]);
4157 window.location.href =
'{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDrop:errors';
4160 console.log(listoffiles);
4162 for (let i = 0; i < listoffiles.length; i++) {
4163 console.log(listoffiles[i].error);
4164 if (listoffiles[i].error) {
4168 console.log(nboferror);
4171 if (listoffiles.length == 0) {
4172 window.location.href =
'{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDrop:errors';
4173 }
else if (nboferror > 0) {
4174 window.location.href =
'{$pageurl}?id={$fkElement}&seteventmessages=ErrorOnAtLeastOneFileUpload:warnings';
4176 window.location.href =
'{$pageurl}?id={$fkElement}&seteventmessages=UploadFileDragDropSuccess:mesgs';
4179 error:
function(jqXHR) {
4180 console.log(
"Error Uploading.", arguments)
4181 if (jqXHR.status == 403) {
4182 window.location.href =
'{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDropPermissionDenied:errors';
4184 window.location.href =
'{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDrop:errors';
4206function archiveOrBackupFile($srcfile, $max_versions = 5, $archivedir =
'', $suffix =
"v", $moveorcopy =
'move')
4208 $base_file_pattern = ($archivedir ? $archivedir : dirname($srcfile)).
'/'.basename($srcfile).
".".$suffix;
4209 $files_in_directory = glob($base_file_pattern .
"*");
4212 $files_with_timestamps = [];
4213 foreach ($files_in_directory as $file) {
4214 $files_with_timestamps[] = [
4216 'timestamp' => filemtime($file)
4222 while (count($files_with_timestamps) > 0) {
4223 $latest_file =
null;
4224 $latest_index =
null;
4227 foreach ($files_with_timestamps as $index => $file_info) {
4228 if ($latest_file ===
null || (is_array($latest_file) && $file_info[
'timestamp'] > $latest_file[
'timestamp'])) {
4229 $latest_file = $file_info;
4230 $latest_index = $index;
4235 if ($latest_file !==
null) {
4236 $sorted_files[] = $latest_file[
'file'];
4237 unset($files_with_timestamps[$latest_index]);
4242 if (count($sorted_files) >= $max_versions) {
4243 $oldest_files = array_slice($sorted_files, $max_versions - 1);
4244 foreach ($oldest_files as $oldest_file) {
4250 $new_backup = $srcfile .
".v" . $timestamp;
4253 if ($moveorcopy ==
'move') {
4254 $result =
dol_move($srcfile, $new_backup,
'0', 1, 0, 0);
4256 $result =
dol_copy($srcfile, $new_backup,
'0', 1, 0, 0);
4272function dolDocToText($filetoprocess, $useFullTextIndexation =
'pdftotext', $options =
'html')
4277 $keywords = array();
4278 $textforfulltextindex =
'';
4281 if (empty($useFullTextIndexation)) {
4282 $useFullTextIndexation =
'pdftotext';
4289 if (preg_match(
'/pdftotext/i', $useFullTextIndexation)) {
4290 include_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
4292 $outputfile =
$conf->admin->dir_temp.
'/tmppdftotext.'.$user->id.
'.out';
4296 if ($options ==
'fulltext') {
4297 $params =
'-nodiag -layout';
4299 $params =
'-htmlmeta';
4301 $cmd =
getDolGlobalString(
'MAIN_SAVE_FILE_CONTENT_AS_TEXT_PDFTOTEXT',
'pdftotext') .
" " . $params .
" '".escapeshellcmd($filetoprocess).
"' - ";
4302 $resultexec = $utils->executeCLI($cmd, $outputfile, 0,
null, 1);
4304 if (empty($resultexec[
'error'])) {
4306 if ($options ==
'fulltext') {
4307 $textforfulltextindex = $resultexec[
'output'];
4309 if ($options ==
'html') {
4310 $txt = $resultexec[
'output'];
4311 if (preg_match(
'/<meta name="keywords" content="([^\/]+)"\s*\/>/i', $txt, $matches)) {
4312 $keywords = $matches[1];
4314 if (preg_match(
'/<pre>(.*)<\/pre>/si', $txt, $matches)) {
4326 if (preg_match(
'/docling/i', $useFullTextIndexation)) {
4327 include_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
4329 $outputfile =
$conf->admin->dir_temp.
'/tmpdocling.'.$user->id.
'.out';
4333 $cmd =
getDolGlobalString(
'MAIN_SAVE_FILE_CONTENT_AS_TEXT_DOCLING',
'docling').
" --from pdf --to text '".escapeshellcmd($filetoprocess).
"'";
4334 $resultexec = $utils->executeCLI($cmd, $outputfile, 0,
null, 1);
4336 if (!$resultexec[
'error']) {
4337 $txt = $resultexec[
'output'];
4345 $textforfulltextindex = $txt;
4352 return array(
'error' => $error,
'keywords' => $keywords,
'content' => $textforfulltextindex,
'cmd' => $cmd);
4364 $fp = fopen($fullpath,
"r");
4365 fseek($fp, -1, SEEK_END);
4368 while ($char ===
"\n" || $char ===
"\r") {
4369 fseek($fp, $pos--, SEEK_END);
4372 while ($char !==
"\n" && $char !==
false) {
4373 fseek($fp, $pos--, SEEK_END);
4382 $truncatePos = ftell($fp);
4385 $fp = fopen($fullpath,
"c+");
4386 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 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.
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).
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
getNonce()
Return a random string to be used as a nonce value for js.
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)
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
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.