39 return preg_replace(
'/^.*\/([^\/]+)$/',
'$1', rtrim($pathfile,
'/'));
62 function dol_dir_list($path, $types =
"all", $recursive = 0, $filter =
"", $excludefilter =
null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename =
"", $donotfollowsymlinks = 0, $nbsecondsold = 0)
64 global $db, $hookmanager;
67 if ($recursive <= 1) {
68 dol_syslog(
"files.lib.php::dol_dir_list path=".$path.
" types=".$types.
" recursive=".$recursive.
" filter=".$filter.
" excludefilter=".json_encode($excludefilter));
72 $loaddate = ($mode == 1 || $mode == 2 || $nbsecondsold) ?
true :
false;
73 $loadsize = ($mode == 1 || $mode == 3) ?
true :
false;
74 $loadperm = ($mode == 1 || $mode == 4) ?
true :
false;
77 $path = preg_replace(
'/([\\/]+)$/i',
'', $path);
84 if (is_object($hookmanager) && !$nohook) {
85 $hookmanager->resArray = array();
87 $hookmanager->initHooks(array(
'fileslib'));
92 'recursive' => $recursive,
94 'excludefilter' => $excludefilter,
95 'sortcriteria' => $sortcriteria,
96 'sortorder' => $sortorder,
97 'loaddate' => $loaddate,
98 'loadsize' => $loadsize,
101 $reshook = $hookmanager->executeHooks(
'getDirList', $parameters, $object);
105 if (empty($reshook)) {
106 if (!is_dir($newpath)) {
110 if ($dir = opendir($newpath)) {
114 while (
false !== ($file = readdir($dir))) {
116 $file = utf8_encode($file);
118 $fullpathfile = ($newpath ? $newpath.
'/' :
'').$file;
123 $excludefilterarray = array(
'^\.');
124 if (is_array($excludefilter)) {
125 $excludefilterarray = array_merge($excludefilterarray, $excludefilter);
126 } elseif ($excludefilter) {
127 $excludefilterarray[] = $excludefilter;
130 foreach ($excludefilterarray as $filt) {
131 if (preg_match(
'/'.$filt.
'/i', $file) || preg_match(
'/'.$filt.
'/i', $fullpathfile)) {
141 if ($isdir && (($types ==
"directories") || ($types ==
"all") || $recursive > 0)) {
143 if (($types ==
"directories") || ($types ==
"all")) {
144 if ($loaddate || $sortcriteria ==
'date') {
147 if ($loadsize || $sortcriteria ==
'size') {
150 if ($loadperm || $sortcriteria ==
'perm') {
154 if (!$filter || preg_match(
'/'.$filter.
'/i', $file)) {
156 preg_match(
'/([^\/]+)\/[^\/]+$/', $path.
'/'.$file, $reg);
157 $level1name = (isset($reg[1]) ? $reg[1] :
'');
158 $file_list[] = array(
161 "level1name" => $level1name,
162 "relativename" => ($relativename ? $relativename.
'/' :
'').$file,
163 "fullname" => $path.
'/'.$file,
173 if ($recursive > 0) {
174 if (empty($donotfollowsymlinks) || !is_link($path.
"/".$file)) {
176 $file_list = array_merge($file_list,
dol_dir_list($path.
"/".$file, $types, $recursive + 1, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename !=
'' ? $relativename.
'/' :
'').$file, $donotfollowsymlinks, $nbsecondsold));
179 } elseif (!$isdir && (($types ==
"files") || ($types ==
"all"))) {
181 if ($loaddate || $sortcriteria ==
'date') {
184 if ($loadsize || $sortcriteria ==
'size') {
188 if (!$filter || preg_match(
'/'.$filter.
'/i', $file)) {
189 if (empty($nbsecondsold) || $filedate <= ($now - $nbsecondsold)) {
190 preg_match(
'/([^\/]+)\/[^\/]+$/', $path.
'/'.$file, $reg);
191 $level1name = (isset($reg[1]) ? $reg[1] :
'');
192 $file_list[] = array(
195 "level1name" => $level1name,
196 "relativename" => ($relativename ? $relativename.
'/' :
'').$file,
197 "fullname" => $path.
'/'.$file,
210 if (!empty($sortcriteria) && $sortorder) {
211 $file_list =
dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ?
'asc' :
'desc'));
216 if (is_object($hookmanager) && is_array($hookmanager->resArray)) {
217 $file_list = array_merge($file_list, $hookmanager->resArray);
237 function dol_dir_list_in_database($path, $filter =
"", $excludefilter =
null, $sortcriteria =
"name", $sortorder = SORT_ASC, $mode = 0)
241 $sql =
" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,";
242 $sql .=
" date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share";
244 $sql .=
", description";
246 $sql .=
" FROM ".MAIN_DB_PREFIX.
"ecm_files";
247 $sql .=
" WHERE entity = ".$conf->entity;
248 if (preg_match(
'/%$/', $path)) {
249 $sql .=
" AND filepath LIKE '".$db->escape($path).
"'";
251 $sql .=
" AND filepath = '".$db->escape($path).
"'";
254 $resql = $db->query(
$sql);
256 $file_list = array();
257 $num = $db->num_rows($resql);
260 $obj = $db->fetch_object($resql);
263 preg_match(
'/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename, $reg);
264 $level1name = (isset($reg[1]) ? $reg[1] :
'');
265 $file_list[] = array(
266 "rowid" => $obj->rowid,
267 "label" => $obj->label,
268 "name" => $obj->filename,
269 "path" => DOL_DATA_ROOT.
'/'.$obj->filepath,
270 "level1name" => $level1name,
271 "fullname" => DOL_DATA_ROOT.
'/'.$obj->filepath.
'/'.$obj->filename,
272 "fullpath_orig" => $obj->fullpath_orig,
273 "date_c" => $db->jdate($obj->date_c),
274 "date_m" => $db->jdate($obj->date_m),
276 "keywords" => $obj->keywords,
277 "cover" => $obj->cover,
278 "position" => (
int) $obj->position,
280 "share" => $obj->share,
281 "description" => ($mode ? $obj->description :
'')
288 if (!empty($sortcriteria)) {
290 foreach ($file_list as $key => $row) {
291 $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] :
'');
295 array_multisort($myarray, $sortorder, $file_list);
317 global $conf, $db, $user;
323 if ($modulepart ==
'produit' &&
getDolGlobalInt(
'PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
325 if (!empty($object->id)) {
327 $upload_dirold = $conf->product->multidir_output[$object->entity].
'/'.substr(substr(
"000".$object->id, -2), 1, 1).
'/'.substr(substr(
"000".$object->id, -2), 0, 1).
'/'.$object->id.
"/photos";
329 $upload_dirold = $conf->service->multidir_output[$object->entity].
'/'.substr(substr(
"000".$object->id, -2), 1, 1).
'/'.substr(substr(
"000".$object->id, -2), 0, 1).
'/'.$object->id.
"/photos";
332 $relativedirold = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dirold);
333 $relativedirold = preg_replace(
'/^[\\/]/',
'', $relativedirold);
335 $filearrayindatabase = array_merge($filearrayindatabase,
dol_dir_list_in_database($relativedirold,
'',
null,
'name', SORT_ASC));
344 foreach ($filearray as $key => $val) {
345 $tmpfilename = preg_replace(
'/\.noexe$/',
'', $filearray[$key][
'name']);
348 foreach ($filearrayindatabase as $key2 => $val2) {
349 if (($filearrayindatabase[$key2][
'path'] == $filearray[$key][
'path']) && ($filearrayindatabase[$key2][
'name'] == $tmpfilename)) {
350 $filearray[$key][
'position_name'] = ($filearrayindatabase[$key2][
'position'] ? $filearrayindatabase[$key2][
'position'] :
'0').
'_'.$filearrayindatabase[$key2][
'name'];
351 $filearray[$key][
'position'] = $filearrayindatabase[$key2][
'position'];
352 $filearray[$key][
'cover'] = $filearrayindatabase[$key2][
'cover'];
353 $filearray[$key][
'keywords'] = $filearrayindatabase[$key2][
'keywords'];
354 $filearray[$key][
'acl'] = $filearrayindatabase[$key2][
'acl'];
355 $filearray[$key][
'rowid'] = $filearrayindatabase[$key2][
'rowid'];
356 $filearray[$key][
'label'] = $filearrayindatabase[$key2][
'label'];
357 $filearray[$key][
'share'] = $filearrayindatabase[$key2][
'share'];
364 $filearray[$key][
'position'] =
'999999';
365 $filearray[$key][
'cover'] = 0;
366 $filearray[$key][
'acl'] =
'';
368 $rel_filename = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filearray[$key][
'fullname']);
370 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filename)) {
371 dol_syslog(
"list_of_documents We found a file called '".$filearray[$key][
'name'].
"' not indexed into database. We add it");
372 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
376 $filename = basename($rel_filename);
377 $rel_dir = dirname($rel_filename);
378 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
379 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
381 $ecmfile->filepath = $rel_dir;
382 $ecmfile->filename = $filename;
383 $ecmfile->label = md5_file(
dol_osencode($filearray[$key][
'fullname']));
384 $ecmfile->fullpath_orig = $filearray[$key][
'fullname'];
385 $ecmfile->gen_or_uploaded =
'unknown';
386 $ecmfile->description =
'';
387 $ecmfile->keywords =
'';
388 $result = $ecmfile->create($user);
392 $filearray[$key][
'rowid'] = $result;
395 $filearray[$key][
'rowid'] = 0;
412 global $sortorder, $sortfield;
414 $sortorder = strtoupper($sortorder);
416 if ($sortorder ==
'ASC') {
424 if ($sortfield ==
'name') {
425 if ($a->name == $b->name) {
428 return ($a->name < $b->name) ? $retup : $retdown;
430 if ($sortfield ==
'date') {
431 if ($a->date == $b->date) {
434 return ($a->date < $b->date) ? $retup : $retdown;
436 if ($sortfield ==
'size') {
437 if ($a->size == $b->size) {
440 return ($a->size < $b->size) ? $retup : $retdown;
456 if (is_dir($newfolder)) {
471 if (!is_readable($dir)) {
474 return (count(scandir($dir)) == 2);
486 return is_file($newpathoffile);
498 return is_link($newpathoffile);
509 $tmpprot = array(
'file',
'http',
'https',
'ftp',
'zlib',
'data',
'ssh',
'ssh2',
'ogg',
'expect');
510 foreach ($tmpprot as $prot) {
511 if (preg_match(
'/^'.$prot.
':/i', $url)) {
527 if (is_dir($newfolder)) {
528 $handle = opendir($newfolder);
529 $folder_content =
'';
530 while ((gettype($name = readdir($handle)) !=
"boolean")) {
531 $name_array[] = $name;
533 foreach ($name_array as $temp) {
534 $folder_content .= $temp;
539 if ($folder_content ==
"...") {
562 $fp = fopen($newfile,
'r');
567 if (!$line ===
false) {
590 return filesize($newpathoffile);
602 return @filemtime($newpathoffile);
614 return fileperms($newpathoffile);
629 function dolReplaceInFile($srcfile, $arrayreplacement, $destfile =
'', $newmask = 0, $indexdatabase = 0, $arrayreplacementisregex = 0)
633 dol_syslog(
"files.lib.php::dolReplaceInFile srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" indexdatabase=".$indexdatabase.
" arrayreplacementisregex=".$arrayreplacementisregex);
635 if (empty($srcfile)) {
638 if (empty($destfile)) {
639 $destfile = $srcfile;
643 if (($destfile != $srcfile) && $destexists) {
649 dol_syslog(
"files.lib.php::dolReplaceInFile failed to read src file", LOG_WARNING);
653 $tmpdestfile = $destfile.
'.tmp';
658 $newdirdestfile = dirname($newpathofdestfile);
660 if ($destexists && !is_writable($newpathofdestfile)) {
661 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
664 if (!is_writable($newdirdestfile)) {
665 dol_syslog(
"files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
672 $content = file_get_contents($newpathofsrcfile,
'r');
674 if (empty($arrayreplacementisregex)) {
677 foreach ($arrayreplacement as $key => $value) {
678 $content = preg_replace($key, $value, $content);
682 file_put_contents($newpathoftmpdestfile, $content);
683 dolChmod($newpathoftmpdestfile, $newmask);
686 $result =
dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase);
688 dol_syslog(
"files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
691 if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
692 $newmask = $conf->global->MAIN_UMASK;
694 if (empty($newmask)) {
695 dol_syslog(
"Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
699 dolChmod($newpathofdestfile, $newmask);
717 function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 0)
719 global $conf, $db, $user;
721 dol_syslog(
"files.lib.php::dol_copy srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
723 if (empty($srcfile) || empty($destfile)) {
728 if (!$overwriteifexists && $destexists) {
734 $newdirdestfile = dirname($newpathofdestfile);
736 if ($destexists && !is_writable($newpathofdestfile)) {
737 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
740 if (!is_writable($newdirdestfile)) {
741 dol_syslog(
"files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
746 $testvirusarray = array();
749 if (count($testvirusarray)) {
750 dol_syslog(
"files.lib.php::dol_copy canceled because a virus was found into source file. we ignore the copy request.", LOG_WARNING);
756 $result = @copy($newpathofsrcfile, $newpathofdestfile);
759 dol_syslog(
"files.lib.php::dol_copy failed to copy", LOG_WARNING);
762 if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
763 $newmask = $conf->global->MAIN_UMASK;
765 if (empty($newmask)) {
766 dol_syslog(
"Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
770 dolChmod($newpathofdestfile, $newmask);
772 if ($result && $indexdatabase) {
774 $rel_filetocopyafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $newpathofdestfile);
775 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetocopyafter)) {
776 $rel_filetocopyafter = preg_replace(
'/^[\\/]/',
'', $rel_filetocopyafter);
779 dol_syslog(
"Try to copy also entries in database for: ".$rel_filetocopyafter, LOG_DEBUG);
780 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
783 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetocopyafter);
784 if ($resultecmtarget > 0) {
785 dol_syslog(
"ECM dest file found, remove it", LOG_DEBUG);
786 $ecmfiletarget->delete($user);
788 dol_syslog(
"ECM dest file not found, create it", LOG_DEBUG);
792 $resultecm = $ecmSrcfile->fetch(0,
'', $srcfile);
796 dol_syslog(
"Fetch src file error", LOG_DEBUG);
800 $filename = basename($rel_filetocopyafter);
801 $rel_dir = dirname($rel_filetocopyafter);
802 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
803 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
805 $ecmfile->filepath = $rel_dir;
806 $ecmfile->filename = $filename;
808 $ecmfile->fullpath_orig = $srcfile;
809 $ecmfile->gen_or_uploaded =
'copy';
810 $ecmfile->description = $ecmSrcfile->description;
811 $ecmfile->keywords = $ecmSrcfile->keywords;
812 $resultecm = $ecmfile->create($user);
813 if ($resultecm < 0) {
817 dol_syslog(
"Create ECM file error", LOG_DEBUG);
821 if ($resultecm > 0) {
845 function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement =
null, $excludesubdir = 0, $excludefileext =
null)
851 dol_syslog(
"files.lib.php::dolCopyDir srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwriteifexists=".$overwriteifexists);
853 if (empty($srcfile) || empty($destfile)) {
863 $dirmaskdec = octdec($newmask);
864 if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
865 $dirmaskdec = octdec($conf->global->MAIN_UMASK);
867 $dirmaskdec |= octdec(
'0200');
868 dol_mkdir($destfile,
'', decoct($dirmaskdec));
875 if (is_dir($ossrcfile)) {
876 $dir_handle = opendir($ossrcfile);
877 while ($file = readdir($dir_handle)) {
878 if ($file !=
"." && $file !=
".." && !is_link($ossrcfile.
"/".$file)) {
879 if (is_dir($ossrcfile.
"/".$file)) {
880 if (empty($excludesubdir) || ($excludesubdir == 2 && strlen($file) == 2)) {
883 if (is_array($arrayreplacement)) {
884 foreach ($arrayreplacement as $key => $val) {
885 $newfile = str_replace($key, $val, $newfile);
889 $tmpresult =
dolCopyDir($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir, $excludefileext);
894 if (is_array($excludefileext)) {
895 $extension = pathinfo($file, PATHINFO_EXTENSION);
896 if (in_array($extension, $excludefileext)) {
903 if (is_array($arrayreplacement)) {
904 foreach ($arrayreplacement as $key => $val) {
905 $newfile = str_replace($key, $val, $newfile);
908 $tmpresult =
dol_copy($srcfile.
"/".$file, $destfile.
"/".$newfile, $newmask, $overwriteifexists);
911 if ($result > 0 && $tmpresult >= 0) {
914 $result = $tmpresult;
921 closedir($dir_handle);
948 function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1, $moreinfo = array())
950 global $user, $db, $conf;
953 dol_syslog(
"files.lib.php::dol_move srcfile=".$srcfile.
" destfile=".$destfile.
" newmask=".$newmask.
" overwritifexists=".$overwriteifexists);
958 dol_syslog(
"files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
962 if ($overwriteifexists || !$destexists) {
967 $testvirusarray = array();
970 if (count($testvirusarray)) {
971 dol_syslog(
"files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING);
976 global $dolibarr_main_restrict_os_commands;
977 if (!empty($dolibarr_main_restrict_os_commands)) {
978 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
979 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
980 if (in_array(basename($destfile), $arrayofallowedcommand)) {
983 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);
988 $result = @rename($newpathofsrcfile, $newpathofdestfile);
991 dol_syslog(
"files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
994 $result = @rename($newpathofsrcfile, $newpathofdestfile);
996 dol_syslog(
"files.lib.php::dol_move Failed.", LOG_WARNING);
1001 if ($result && $indexdatabase) {
1003 $rel_filetorenamebefore = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $srcfile);
1004 $rel_filetorenameafter = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $destfile);
1005 if (!preg_match(
'/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) {
1006 $rel_filetorenamebefore = preg_replace(
'/^[\\/]/',
'', $rel_filetorenamebefore);
1007 $rel_filetorenameafter = preg_replace(
'/^[\\/]/',
'', $rel_filetorenameafter);
1010 dol_syslog(
"Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore.
" after = ".$rel_filetorenameafter, LOG_DEBUG);
1011 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1013 $ecmfiletarget =
new EcmFiles($db);
1014 $resultecmtarget = $ecmfiletarget->fetch(0,
'', $rel_filetorenameafter);
1015 if ($resultecmtarget > 0) {
1016 $ecmfiletarget->delete($user);
1020 $resultecm = $ecmfile->fetch(0,
'', $rel_filetorenamebefore);
1021 if ($resultecm > 0) {
1022 $filename = basename($rel_filetorenameafter);
1023 $rel_dir = dirname($rel_filetorenameafter);
1024 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1025 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1027 $ecmfile->filepath = $rel_dir;
1028 $ecmfile->filename = $filename;
1030 $resultecm = $ecmfile->update($user);
1031 } elseif ($resultecm == 0) {
1032 $filename = basename($rel_filetorenameafter);
1033 $rel_dir = dirname($rel_filetorenameafter);
1034 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
1035 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
1037 $ecmfile->filepath = $rel_dir;
1038 $ecmfile->filename = $filename;
1040 $ecmfile->fullpath_orig = $srcfile;
1041 $ecmfile->gen_or_uploaded =
'uploaded';
1042 if (!empty($moreinfo) && !empty($moreinfo[
'description'])) {
1043 $ecmfile->description = $moreinfo[
'description'];
1045 $ecmfile->description =
'';
1047 if (!empty($moreinfo) && !empty($moreinfo[
'keywords'])) {
1048 $ecmfile->keywords = $moreinfo[
'keywords'];
1050 $ecmfile->keywords =
'';
1052 if (!empty($moreinfo) && !empty($moreinfo[
'note_private'])) {
1053 $ecmfile->note_private = $moreinfo[
'note_private'];
1055 if (!empty($moreinfo) && !empty($moreinfo[
'note_public'])) {
1056 $ecmfile->note_public = $moreinfo[
'note_public'];
1058 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_type'])) {
1059 $ecmfile->src_object_type = $moreinfo[
'src_object_type'];
1061 if (!empty($moreinfo) && !empty($moreinfo[
'src_object_id'])) {
1062 $ecmfile->src_object_id = $moreinfo[
'src_object_id'];
1065 $resultecm = $ecmfile->create($user);
1066 if ($resultecm < 0) {
1069 } elseif ($resultecm < 0) {
1073 if ($resultecm > 0) {
1081 if (empty($newmask)) {
1082 $newmask = empty($conf->global->MAIN_UMASK) ?
'0755' : $conf->global->MAIN_UMASK;
1088 dolChmod($newpathofdestfile, $newmask);
1105 function dol_move_dir($srcdir, $destdir, $overwriteifexists = 1, $indexdatabase = 1, $renamedircontent = 1)
1108 global $user, $db, $conf;
1111 dol_syslog(
"files.lib.php::dol_move_dir srcdir=".$srcdir.
" destdir=".$destdir.
" overwritifexists=".$overwriteifexists.
" indexdatabase=".$indexdatabase.
" renamedircontent=".$renamedircontent);
1113 $srcbasename = basename($srcdir);
1117 dol_syslog(
"files.lib.php::dol_move_dir srcdir does not exists. we ignore the move request.");
1121 if ($overwriteifexists || !$destexists) {
1125 $result = @rename($newpathofsrcdir, $newpathofdestdir);
1127 if ($result && $renamedircontent) {
1128 if (file_exists($newpathofdestdir)) {
1129 $destbasename = basename($newpathofdestdir);
1131 if (!empty($files) && is_array($files)) {
1132 foreach ($files as $key => $file) {
1133 if (!file_exists($file[
"fullname"]))
continue;
1134 $filepath = $file[
"path"];
1135 $oldname = $file[
"name"];
1137 $newname = str_replace($srcbasename, $destbasename, $oldname);
1138 if (!empty($newname) && $newname !== $oldname) {
1139 if ($file[
"type"] ==
"dir") {
1140 $res =
dol_move_dir($filepath.
'/'.$oldname, $filepath.
'/'.$newname, $overwriteifexists, $indexdatabase, $renamedircontent);
1142 $res =
dol_move($filepath.
'/'.$oldname, $filepath.
'/'.$newname, 0, $overwriteifexists, 0, $indexdatabase);
1169 return trim(basename($filename),
".\x00..\x20");
1183 if (!empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) {
1184 if (!class_exists(
'AntiVir')) {
1185 require_once DOL_DOCUMENT_ROOT.
'/core/class/antivir.class.php';
1188 $result = $antivir->dol_avscan_file($src_file);
1190 $reterrors = $antivir->errors;
1218 function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $varfiles =
'addedfile', $upload_dir =
'')
1220 global $conf, $db, $user, $langs;
1221 global $object, $hookmanager;
1224 $file_name = $dest_file;
1227 if (empty($nohook)) {
1228 $reshook = $hookmanager->initHooks(array(
'fileslib'));
1230 $parameters = array(
'dest_file' => $dest_file,
'src_file' => $src_file,
'file_name' => $file_name,
'varfiles' => $varfiles,
'allowoverwrite' => $allowoverwrite);
1231 $reshook = $hookmanager->executeHooks(
'moveUploadedFile', $parameters, $object);
1234 if (empty($reshook)) {
1236 if ($uploaderrorcode) {
1237 switch ($uploaderrorcode) {
1238 case UPLOAD_ERR_INI_SIZE:
1239 return 'ErrorFileSizeTooLarge';
1240 case UPLOAD_ERR_FORM_SIZE:
1241 return 'ErrorFileSizeTooLarge';
1242 case UPLOAD_ERR_PARTIAL:
1243 return 'ErrorPartialFile';
1244 case UPLOAD_ERR_NO_TMP_DIR:
1245 return 'ErrorNoTmpDir';
1246 case UPLOAD_ERR_CANT_WRITE:
1247 return 'ErrorFailedToWriteInDir';
1248 case UPLOAD_ERR_EXTENSION:
1249 return 'ErrorUploadBlockedByAddon';
1257 if (empty($disablevirusscan) && file_exists($src_file)) {
1259 if (count($checkvirusarray)) {
1260 dol_syslog(
'Files.lib::dol_move_uploaded_file File "'.$src_file.
'" (target name "'.$dest_file.
'") KO with antivirus: errors='.join(
',', $checkvirusarray), LOG_WARNING);
1261 return 'ErrorFileIsInfectedWithAVirus: '.join(
',', $checkvirusarray);
1270 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
1271 if (!preg_match(
'/\/$/', $publicmediasdirwithslash)) {
1272 $publicmediasdirwithslash .=
'/';
1275 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0 || !
getDolGlobalInt(
"MAIN_DOCUMENT_DISABLE_NOEXE_IN_MEDIAS_DIR")) {
1276 $file_name .=
'.noexe';
1283 if (preg_match(
'/^\./', basename($src_file)) || preg_match(
'/\.\./', $src_file) || preg_match(
'/[<>|]/', $src_file)) {
1284 dol_syslog(
"Refused to deliver file ".$src_file, LOG_WARNING);
1290 if (preg_match(
'/^\./', basename($dest_file)) || preg_match(
'/\.\./', $dest_file) || preg_match(
'/[<>|]/', $dest_file)) {
1291 dol_syslog(
"Refused to deliver file ".$dest_file, LOG_WARNING);
1297 $errmsg = join(
',', $hookmanager->errors);
1298 if (empty($errmsg)) {
1299 $errmsg =
'ErrorReturnedBySomeHooks';
1302 } elseif (empty($reshook)) {
1308 if (!is_writable(dirname($file_name_osencoded))) {
1309 dol_syslog(
"Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded).
" is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1310 return 'ErrorDirNotWritable';
1314 if (!$allowoverwrite) {
1315 if (file_exists($file_name_osencoded)) {
1316 dol_syslog(
"Files.lib::dol_move_uploaded_file File ".$file_name.
" already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1317 return 'ErrorFileAlreadyExists';
1320 if (is_dir($file_name_osencoded)) {
1321 dol_syslog(
"Files.lib::dol_move_uploaded_file A directory with name ".$file_name.
" already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
1322 return 'ErrorDirWithFileNameAlreadyExists';
1327 $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1330 dol_syslog(
"Files.lib::dol_move_uploaded_file Success to move ".$src_file.
" to ".$file_name.
" - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
1331 return $successcode;
1333 dol_syslog(
"Files.lib::dol_move_uploaded_file Failed to move ".$src_file.
" to ".$file_name, LOG_ERR);
1338 return $successcode;
1356 function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, $object =
null, $allowdotdot =
false, $indexdatabase = 1, $nolog = 0)
1358 global $db, $conf, $user, $langs;
1359 global $hookmanager;
1362 $langs->loadLangs(array(
'other',
'errors'));
1364 if (empty($nolog)) {
1365 dol_syslog(
"dol_delete_file file=".$file.
" disableglob=".$disableglob.
" nophperrors=".$nophperrors.
" nohook=".$nohook);
1370 if ((!$allowdotdot && preg_match(
'/\.\./', $file)) || preg_match(
'/[<>|]/', $file)) {
1371 dol_syslog(
"Refused to delete file ".$file, LOG_WARNING);
1376 if (empty($nohook)) {
1377 $hookmanager->initHooks(array(
'fileslib'));
1379 $parameters = array(
1381 'disableglob'=> $disableglob,
1382 'nophperrors' => $nophperrors
1384 $reshook = $hookmanager->executeHooks(
'deleteFile', $parameters, $object);
1387 if (empty($nohook) && $reshook != 0) {
1395 if (empty($disableglob) && !empty($file_osencoded)) {
1397 $globencoded = str_replace(
'[',
'\[', $file_osencoded);
1398 $globencoded = str_replace(
']',
'\]', $globencoded);
1399 $listofdir = glob($globencoded);
1400 if (!empty($listofdir) && is_array($listofdir)) {
1401 foreach ($listofdir as $filename) {
1403 $ok = @unlink($filename);
1405 $ok = unlink($filename);
1409 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1410 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);
1411 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1414 $ok = @unlink($filename);
1416 $ok = unlink($filename);
1421 if (empty($nolog)) {
1422 dol_syslog(
"Removed file ".$filename, LOG_DEBUG);
1426 $rel_filetodelete = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $filename);
1427 if (!preg_match(
'/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) {
1428 if (is_object($db) && $indexdatabase) {
1429 $rel_filetodelete = preg_replace(
'/^[\\/]/',
'', $rel_filetodelete);
1430 $rel_filetodelete = preg_replace(
'/\.noexe$/',
'', $rel_filetodelete);
1432 dol_syslog(
"Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1433 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1435 $result = $ecmfile->fetch(0,
'', $rel_filetodelete);
1436 if ($result >= 0 && $ecmfile->id > 0) {
1437 $result = $ecmfile->delete($user);
1445 dol_syslog(
"Failed to remove file ".$filename, LOG_WARNING);
1451 dol_syslog(
"No files to delete found", LOG_DEBUG);
1456 $ok = @unlink($file_osencoded);
1458 $ok = unlink($file_osencoded);
1461 if (empty($nolog)) {
1462 dol_syslog(
"Removed file ".$file_osencoded, LOG_DEBUG);
1465 dol_syslog(
"Failed to remove file ".$file_osencoded, LOG_WARNING);
1486 if (preg_match(
'/\.\./', $dir) || preg_match(
'/[<>|]/', $dir)) {
1487 dol_syslog(
"Refused to delete dir ".$dir.
' (contains invalid char sequence)', LOG_WARNING);
1492 return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1507 function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0, $indexdatabase = 1, $nolog = 0)
1509 if (empty($nolog)) {
1510 dol_syslog(
"functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1514 if ($handle = opendir(
"$dir_osencoded")) {
1515 while (
false !== ($item = readdir($handle))) {
1517 $item = utf8_encode($item);
1520 if ($item !=
"." && $item !=
"..") {
1524 $result =
dol_delete_file(
"$dir/$item", 1, $nophperrors, 0,
null,
false, $indexdatabase, $nolog);
1536 if (empty($onlysub)) {
1561 global $langs, $conf;
1564 $element = $object->element;
1566 if ($object->element ==
'order_supplier') {
1567 $dir = $conf->fournisseur->commande->dir_output;
1568 } elseif ($object->element ==
'invoice_supplier') {
1569 $dir = $conf->fournisseur->facture->dir_output;
1570 } elseif ($object->element ==
'project') {
1571 $dir = $conf->project->dir_output;
1572 } elseif ($object->element ==
'shipping') {
1573 $dir = $conf->expedition->dir_output.
'/sending';
1574 } elseif ($object->element ==
'delivery') {
1575 $dir = $conf->expedition->dir_output.
'/receipt';
1576 } elseif ($object->element ==
'fichinter') {
1577 $dir = $conf->ficheinter->dir_output;
1579 $dir = empty($conf->$element->dir_output) ?
'' : $conf->$element->dir_output;
1583 return 'ErrorObjectNoSupportedByFunction';
1587 $dir = $dir.
"/".$refsan;
1588 $filepreviewnew = $dir.
"/".$refsan.
".pdf_preview.png";
1589 $filepreviewnewbis = $dir.
"/".$refsan.
".pdf_preview-0.png";
1590 $filepreviewold = $dir.
"/".$refsan.
".pdf.png";
1593 if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
1595 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnew);
1599 if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
1601 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewnewbis);
1606 if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
1608 $object->error = $langs->trans(
"ErrorFailedToDeleteFile", $filepreviewold);
1612 $multiple = $filepreviewold.
".";
1613 for ($i = 0; $i < 20; $i++) {
1614 $preview = $multiple.$i;
1616 if (file_exists($preview) && is_writable($preview)) {
1618 $object->error = $langs->trans(
"ErrorFailedToOpenFile", $preview);
1641 if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) {
1646 $element = $object->element;
1648 if ($object->element ==
'order_supplier') {
1649 $dir = $conf->fournisseur->dir_output.
'/commande';
1650 } elseif ($object->element ==
'invoice_supplier') {
1651 $dir = $conf->fournisseur->dir_output.
'/facture';
1652 } elseif ($object->element ==
'project') {
1653 $dir = $conf->project->dir_output;
1654 } elseif ($object->element ==
'shipping') {
1655 $dir = $conf->expedition->dir_output.
'/sending';
1656 } elseif ($object->element ==
'delivery') {
1657 $dir = $conf->expedition->dir_output.
'/receipt';
1658 } elseif ($object->element ==
'fichinter') {
1659 $dir = $conf->ficheinter->dir_output;
1661 $dir = empty($conf->$element->dir_output) ?
'' : $conf->$element->dir_output;
1665 $object->fetch_thirdparty();
1668 $dir = $dir.
"/".$objectref;
1669 $file = $dir.
"/".$objectref.
".meta";
1671 if (!is_dir($dir)) {
1676 if (is_countable($object->lines) && count($object->lines) > 0) {
1677 $nblines = count($object->lines);
1679 $client = $object->thirdparty->name.
" ".$object->thirdparty->address.
" ".$object->thirdparty->zip.
" ".$object->thirdparty->town;
1680 $meta =
"REFERENCE=\"".$object->ref.
"\"
1682 NB_ITEMS=\"" . $nblines.
"\"
1683 CLIENT=\"" . $client.
"\"
1684 AMOUNT_EXCL_TAX=\"" . $object->total_ht.
"\"
1685 AMOUNT=\"" . $object->total_ttc.
"\"\n";
1687 for ($i = 0; $i < $nblines; $i++) {
1689 $meta .=
"ITEM_".$i.
"_QUANTITY=\"".$object->lines[$i]->qty.
"\"
1690 ITEM_" . $i.
"_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht.
"\"
1691 ITEM_" . $i.
"_VAT=\"".$object->lines[$i]->tva_tx.
"\"
1692 ITEM_" . $i.
"_DESCRIPTION=\"".str_replace(
"\r\n",
"", nl2br($object->lines[$i]->desc)).
"\"
1697 $fp = fopen($file,
"w");
1705 dol_syslog(
'FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
1723 $listofpaths = array();
1724 $listofnames = array();
1725 $listofmimes = array();
1729 foreach ($listoffiles as $key => $val) {
1730 $listofpaths[] = $val[
'fullname'];
1731 $listofnames[] = $val[
'name'];
1735 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
1736 $_SESSION[
"listofpaths".$keytoavoidconflict] = join(
';', $listofpaths);
1737 $_SESSION[
"listofnames".$keytoavoidconflict] = join(
';', $listofnames);
1738 $_SESSION[
"listofmimes".$keytoavoidconflict] = join(
';', $listofmimes);
1759 function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles =
'addedfile', $savingdocmask =
'', $link =
null, $trackid =
'', $generatethumbs = 1, $object =
null)
1762 global $db, $user, $conf, $langs;
1766 if (!empty($_FILES[$varfiles])) {
1767 dol_syslog(
'dol_add_file_process upload_dir='.$upload_dir.
' allowoverwrite='.$allowoverwrite.
' donotupdatesession='.$donotupdatesession.
' savingdocmask='.$savingdocmask, LOG_DEBUG);
1768 $maxfilesinform =
getDolGlobalInt(
"MAIN_SECURITY_MAX_ATTACHMENT_ON_FORMS", 10);
1769 if (is_array($_FILES[$varfiles][
"name"]) && count($_FILES[$varfiles][
"name"]) > $maxfilesinform) {
1770 $langs->load(
"errors");
1771 setEventMessages($langs->trans(
"ErrorTooMuchFileInForm", $maxfilesinform),
null,
"errors");
1777 $TFile = $_FILES[$varfiles];
1778 if (!is_array($TFile[
'name'])) {
1779 foreach ($TFile as $key => &$val) {
1784 $nbfile = count($TFile[
'name']);
1786 for ($i = 0; $i < $nbfile; $i++) {
1787 if (empty($TFile[
'name'][$i])) {
1792 $destfull = $upload_dir.
"/".$TFile[
'name'][$i];
1793 $destfile = $TFile[
'name'][$i];
1794 $destfilewithoutext = preg_replace(
'/\.[^\.]+$/',
'', $destfile);
1796 if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
1797 $destfull = $upload_dir.
"/".preg_replace(
'/__file__/', $TFile[
'name'][$i], $savingdocmask);
1798 $destfile = preg_replace(
'/__file__/', $TFile[
'name'][$i], $savingdocmask);
1801 $filenameto = basename($destfile);
1802 if (preg_match(
'/^\./', $filenameto)) {
1803 $langs->load(
"errors");
1804 setEventMessages($langs->trans(
"ErrorFilenameCantStartWithDot", $filenameto),
null,
'errors');
1809 $info = pathinfo($destfull);
1810 $destfull = $info[
'dirname'].
'/'.
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
1811 $info = pathinfo($destfile);
1812 $destfile =
dol_sanitizeFileName($info[
'filename'].($info[
'extension'] !=
'' ? (
'.'.strtolower($info[
'extension'])) :
''));
1820 global $dolibarr_main_restrict_os_commands;
1821 if (!empty($dolibarr_main_restrict_os_commands)) {
1822 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
1823 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
1824 if (in_array($destfile, $arrayofallowedcommand)) {
1825 $langs->load(
"errors");
1826 setEventMessages($langs->trans(
"ErrorFilenameReserved", $destfile),
null,
'errors');
1832 $resupload =
dol_move_uploaded_file($TFile[
'tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile[
'error'][$i], 0, $varfiles, $upload_dir);
1834 if (is_numeric($resupload) && $resupload > 0) {
1835 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
1838 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
1839 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
1840 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
1841 $maxheightmini = $tmparraysize[
'maxheightmini'];
1846 if ($generatethumbs) {
1852 $imgThumbSmall =
vignette($destfull, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
1855 $imgThumbMini =
vignette($destfull, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
1860 if (empty($donotupdatesession)) {
1861 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
1863 $formmail->trackid = $trackid;
1864 $formmail->add_attached_files($destfull, $destfile, $TFile[
'type'][$i]);
1868 if ($donotupdatesession == 1) {
1870 if ($TFile[
'type'][$i] ==
'application/pdf' && strpos($_SERVER[
"REQUEST_URI"],
'product') !==
false && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) $sharefile = 1;
1871 $result =
addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ?
'.noexe' :
''), $TFile[
'name'][$i],
'uploaded', $sharefile, $object);
1873 if ($allowoverwrite) {
1876 setEventMessages(
'WarningFailedToAddFileIntoDatabaseIndex',
null,
'warnings');
1883 $langs->load(
"errors");
1884 if ($resupload < 0) {
1886 } elseif (preg_match(
'/ErrorFileIsInfectedWithAVirus/', $resupload)) {
1887 setEventMessages($langs->trans(
"ErrorFileIsInfectedWithAVirus"),
null,
'errors');
1899 setEventMessages($langs->trans(
"ErrorFailedToCreateDir", $upload_dir),
null,
'errors');
1902 require_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
1903 $linkObject =
new Link($db);
1904 $linkObject->entity = $conf->entity;
1905 $linkObject->url = $link;
1906 $linkObject->objecttype =
GETPOST(
'objecttype',
'alpha');
1907 $linkObject->objectid =
GETPOST(
'objectid',
'int');
1908 $linkObject->label =
GETPOST(
'label',
'alpha');
1909 $res = $linkObject->create($user);
1910 $langs->load(
'link');
1917 $langs->load(
"errors");
1918 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"File")),
null,
'errors');
1938 global $db, $user, $conf, $langs, $_FILES;
1940 $keytodelete = $filenb;
1943 $listofpaths = array();
1944 $listofnames = array();
1945 $listofmimes = array();
1946 $keytoavoidconflict = empty($trackid) ?
'' :
'-'.$trackid;
1947 if (!empty($_SESSION[
"listofpaths".$keytoavoidconflict])) {
1948 $listofpaths = explode(
';', $_SESSION[
"listofpaths".$keytoavoidconflict]);
1950 if (!empty($_SESSION[
"listofnames".$keytoavoidconflict])) {
1951 $listofnames = explode(
';', $_SESSION[
"listofnames".$keytoavoidconflict]);
1953 if (!empty($_SESSION[
"listofmimes".$keytoavoidconflict])) {
1954 $listofmimes = explode(
';', $_SESSION[
"listofmimes".$keytoavoidconflict]);
1957 if ($keytodelete >= 0) {
1958 $pathtodelete = $listofpaths[$keytodelete];
1959 $filetodelete = $listofnames[$keytodelete];
1960 if (empty($donotdeletefile)) {
1966 if (empty($donotdeletefile)) {
1967 $langs->load(
"other");
1968 setEventMessages($langs->trans(
"FileWasRemoved", $filetodelete),
null,
'mesgs');
1970 if (empty($donotupdatesession)) {
1971 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
1973 $formmail->trackid = $trackid;
1974 $formmail->remove_attached_files($keytodelete);
1996 global $db, $user, $conf;
2000 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2002 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
2003 $filename = basename(preg_replace(
'/\.noexe$/',
'', $file));
2004 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2005 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2007 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
2009 $ecmfile->filepath = $rel_dir;
2010 $ecmfile->filename = $filename;
2011 $ecmfile->label = md5_file(
dol_osencode($dir.
'/'.$file));
2012 $ecmfile->fullpath_orig = $fullpathorig;
2013 $ecmfile->gen_or_uploaded = $mode;
2014 $ecmfile->description =
'';
2015 $ecmfile->keywords =
'';
2017 if (is_object($object) && $object->id > 0) {
2018 $ecmfile->src_object_id = $object->id;
2019 if (isset($object->table_element)) {
2020 $ecmfile->src_object_type = $object->table_element;
2022 dol_syslog(
'Error: object ' . get_class($object) .
' has no table_element attribute.');
2025 if (isset($object->src_object_description)) $ecmfile->description = $object->src_object_description;
2026 if (isset($object->src_object_keywords)) $ecmfile->keywords = $object->src_object_keywords;
2029 if (!empty($conf->global->MAIN_FORCE_SHARING_ON_ANY_UPLOADED_FILE)) {
2034 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
2038 $result = $ecmfile->create($user);
2057 global $conf, $db, $user;
2062 dol_syslog(
"deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
2068 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
2070 $filename = basename($file);
2071 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
2072 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
2075 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'ecm_files';
2076 $sql .=
' WHERE entity = '.$conf->entity;
2077 $sql .=
" AND filepath = '".$db->escape($rel_dir).
"'";
2079 $sql .=
" AND filename = '".$db->escape($file).
"'";
2082 $sql .=
" AND gen_or_uploaded = '".$db->escape($mode).
"'";
2085 $resql = $db->query(
$sql);
2088 dol_syslog(__METHOD__.
' '.$db->lasterror(), LOG_ERR);
2116 if (class_exists(
'Imagick')) {
2117 $image =
new Imagick();
2119 $filetoconvert = $fileinput.(($page !=
'') ?
'['.$page.
']' :
'');
2121 $ret = $image->readImage($filetoconvert);
2123 $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
2124 dol_syslog(
"Failed to read image using Imagick (Try to install package 'apt-get install php-imagick ghostscript' and check there is no policy to disable ".$ext.
" convertion in /etc/ImageMagick*/policy.xml): ".$e->getMessage(), LOG_WARNING);
2128 $ret = $image->setImageFormat($ext);
2130 if (empty($fileoutput)) {
2131 $fileoutput = $fileinput.
".".$ext;
2134 $count = $image->getNumberImages();
2136 if (!
dol_is_file($fileoutput) || is_writeable($fileoutput)) {
2138 $ret = $image->writeImages($fileoutput,
true);
2143 dol_syslog(
"Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
2173 function dol_compress_file($inputfile, $outputfile, $mode =
"gz", &$errorstring =
null)
2180 dol_syslog(
"dol_compress_file mode=".$mode.
" inputfile=".$inputfile.
" outputfile=".$outputfile);
2183 if ($mode ==
'gz' && function_exists(
'gzencode')) {
2185 $compressdata = gzencode($data, 9);
2186 } elseif ($mode ==
'bz' && function_exists(
'bzcompress')) {
2188 $compressdata = bzcompress($data, 9);
2189 } elseif ($mode ==
'zstd' && function_exists(
'zstd_compress')) {
2191 $compressdata = zstd_compress($data, 9);
2192 } elseif ($mode ==
'zip') {
2193 if (class_exists(
'ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) {
2196 $rootPath = realpath($inputfile);
2198 dol_syslog(
"Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.
' rootPath='.$rootPath);
2199 $zip =
new ZipArchive;
2201 if ($zip->open($outputfile, ZipArchive::CREATE) !==
true) {
2202 $errorstring =
"dol_compress_file failure - Failed to open file ".$outputfile.
"\n";
2206 $errormsg = $errorstring;
2213 $files =
new RecursiveIteratorIterator(
2214 new RecursiveDirectoryIterator($rootPath),
2215 RecursiveIteratorIterator::LEAVES_ONLY
2218 foreach ($files as $name => $file) {
2220 if (!$file->isDir()) {
2222 $filePath = $file->getPath();
2223 $fileName = $file->getFilename();
2224 $fileFullRealPath = $file->getRealPath();
2227 $relativePath = substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($rootPath) + 1);
2230 $zip->addFile($fileFullRealPath, $relativePath);
2237 dol_syslog(
"dol_compress_file success - ".count($zip->numFiles).
" files");
2241 if (defined(
'ODTPHP_PATHTOPCLZIP')) {
2244 include_once ODTPHP_PATHTOPCLZIP.
'/pclzip.lib.php';
2245 $archive =
new PclZip($outputfile);
2246 $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2248 if ($result === 0) {
2250 $errormsg = $archive->errorInfo(
true);
2252 if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
2253 $errorstring =
"PCLZIP_ERR_WRITE_OPEN_FAIL";
2254 dol_syslog(
"dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
2258 $errorstring =
"dol_compress_file error archive->errorCode = ".$archive->errorCode().
" errormsg=".$errormsg;
2259 dol_syslog(
"dol_compress_file failure - ".$errormsg, LOG_ERR);
2262 dol_syslog(
"dol_compress_file success - ".count($result).
" files");
2268 if ($foundhandler) {
2269 $fp = fopen($outputfile,
"w");
2270 fwrite($fp, $compressdata);
2274 $errorstring =
"Try to zip with format ".$mode.
" with no handler for this format";
2278 $errormsg = $errorstring;
2282 global $langs, $errormsg;
2283 $langs->load(
"errors");
2284 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
2286 $errorstring =
"Failed to open file ".$outputfile;
2302 global $conf, $langs, $db;
2304 $fileinfo = pathinfo($inputfile);
2305 $fileinfo[
"extension"] = strtolower($fileinfo[
"extension"]);
2307 if ($fileinfo[
"extension"] ==
"zip") {
2308 if (defined(
'ODTPHP_PATHTOPCLZIP') && empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS)) {
2309 dol_syslog(
"Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.
", so we use Pclzip to unzip into ".$outputdir);
2310 include_once ODTPHP_PATHTOPCLZIP.
'/pclzip.lib.php';
2311 $archive =
new PclZip($inputfile);
2317 $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG,
'/^((?!\.\.).)*$/');
2319 if (!is_array($result) && $result <= 0) {
2320 return array(
'error'=>$archive->errorInfo(
true));
2325 foreach ($result as $key => $val) {
2326 if ($val[
'status'] ==
'path_creation_fail') {
2327 $langs->load(
"errors");
2329 $errmsg = $langs->trans(
"ErrorFailToCreateDir", $val[
'filename']);
2337 return array(
'error'=>$errmsg);
2342 if (class_exists(
'ZipArchive')) {
2343 dol_syslog(
"Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
2344 $zip =
new ZipArchive;
2345 $res = $zip->open($inputfile);
2346 if ($res ===
true) {
2352 for ($i = 0; $i < $zip->numFiles; $i++) {
2353 if (preg_match(
'/\.\./', $zip->getNameIndex($i))) {
2354 dol_syslog(
"Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
2357 $zip->extractTo($outputdir.
'/', array($zip->getNameIndex($i)));
2363 return array(
'error'=>
'ErrUnzipFails');
2367 return array(
'error'=>
'ErrNoZipEngine');
2368 } elseif (in_array($fileinfo[
"extension"], array(
'gz',
'bz2',
'zst'))) {
2369 include_once DOL_DOCUMENT_ROOT.
"/core/class/utils.class.php";
2370 $utils =
new Utils($db);
2377 $extension = strtolower(pathinfo($fileinfo[
"filename"], PATHINFO_EXTENSION));
2378 if ($extension ==
"tar") {
2381 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0, $outputfilename.
'.err', 0);
2382 if ($resarray[
"result"] != 0) {
2383 $resarray[
"error"] .= file_get_contents($outputfilename.
'.err');
2387 if ($fileinfo[
"extension"] ==
"gz") {
2389 } elseif ($fileinfo[
"extension"] ==
"bz2") {
2391 } elseif ($fileinfo[
"extension"] ==
"zst") {
2394 return array(
'error'=>
'ErrorBadFileExtension');
2397 $cmd .=
' > '.$outputfilename;
2399 $resarray = $utils->executeCLI($cmd, $outputfilename.
'.tmp', 0,
null, 1, $outputfilename.
'.err');
2400 if ($resarray[
"result"] != 0) {
2401 $errfilecontent = @file_get_contents($outputfilename.
'.err');
2402 if ($errfilecontent) {
2403 $resarray[
"error"] .=
" - ".$errfilecontent;
2407 return $resarray[
"result"] != 0 ? array(
'error' => $resarray[
"error"]) : array();
2410 return array(
'error'=>
'ErrorBadFileExtension');
2426 function dol_compress_dir($inputdir, $outputfile, $mode =
"zip", $excludefiles =
'', $rootdirinzip =
'', $newmask = 0)
2432 dol_syslog(
"Try to zip dir ".$inputdir.
" into ".$outputfile.
" mode=".$mode);
2434 if (!
dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
2435 global $langs, $errormsg;
2436 $langs->load(
"errors");
2437 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir", $outputfile);
2442 if ($mode ==
'gz') {
2444 } elseif ($mode ==
'bz') {
2446 } elseif ($mode ==
'zip') {
2460 if (class_exists(
'ZipArchive')) {
2464 $zip =
new ZipArchive();
2465 $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2466 if ($result !==
true) {
2467 global $langs, $errormsg;
2468 $langs->load(
"errors");
2469 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile);
2476 $files =
new RecursiveIteratorIterator(
2477 new RecursiveDirectoryIterator($inputdir),
2478 RecursiveIteratorIterator::LEAVES_ONLY
2482 foreach ($files as $name => $file) {
2484 if (!$file->isDir()) {
2486 $filePath = $file->getPath();
2487 $fileName = $file->getFilename();
2488 $fileFullRealPath = $file->getRealPath();
2491 $relativePath = ($rootdirinzip ? $rootdirinzip.
'/' :
'').substr(($filePath ? $filePath.
'/' :
'').$fileName, strlen($inputdir) + 1);
2494 if (empty($excludefiles) || !preg_match($excludefiles, $fileFullRealPath)) {
2496 $zip->addFile($fileFullRealPath, $relativePath);
2504 if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
2505 $newmask = $conf->global->MAIN_UMASK;
2507 if (empty($newmask)) {
2508 dol_syslog(
"Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
2518 if (!$foundhandler) {
2519 dol_syslog(
"Try to zip with format ".$mode.
" with no handler for this format", LOG_ERR);
2525 global $langs, $errormsg;
2526 $langs->load(
"errors");
2527 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
2529 $errormsg = $langs->trans(
"ErrorFailedToBuildArchive", $outputfile).
' - '.$e->getMessage();
2546 function dol_most_recent_file($dir, $regexfilter =
'', $excludefilter = array(
'(\.meta|_preview.*\.png)$',
'^\.'), $nohook =
false, $mode =
'')
2548 $tmparray =
dol_dir_list($dir,
'files', 0, $regexfilter, $excludefilter,
'date', SORT_DESC, $mode, $nohook);
2549 return isset($tmparray[0])?$tmparray[0]:
null;
2567 global $conf, $db, $user, $hookmanager;
2568 global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2571 if (!is_object($fuser)) {
2575 if (empty($modulepart)) {
2576 return 'ErrorBadParameter';
2578 if (empty($entity)) {
2586 if ($modulepart ==
'users') {
2587 $modulepart =
'user';
2589 if ($modulepart ==
'tva') {
2590 $modulepart =
'tax-vat';
2593 if ($modulepart ==
'expedition' && strpos($original_file,
'receipt/') === 0) {
2594 $modulepart =
'delivery';
2598 dol_syslog(
'dol_check_secure_access_document modulepart='.$modulepart.
' original_file='.$original_file.
' entity='.$entity);
2602 $sqlprotectagainstexternals =
'';
2606 if (empty($refname)) {
2607 $refname = basename(dirname($original_file).
"/");
2608 if ($refname ==
'thumbs' || $refname ==
'temp') {
2610 $refname = basename(dirname(dirname($original_file)).
"/");
2617 $download =
'download';
2618 if ($mode ==
'write') {
2621 $download =
'upload';
2625 if ($modulepart ==
'medias' && !empty($dolibarr_main_data_root)) {
2626 if (empty($entity) || empty($conf->medias->multidir_output[$entity])) {
2627 return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2630 $original_file = $conf->medias->multidir_output[$entity].
'/'.$original_file;
2631 } elseif ($modulepart ==
'logs' && !empty($dolibarr_main_data_root)) {
2633 $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match(
'/^dolibarr.*\.(log|json)$/', basename($original_file)));
2634 $original_file = $dolibarr_main_data_root.
'/'.$original_file;
2635 } elseif ($modulepart ==
'doctemplates' && !empty($dolibarr_main_data_root)) {
2637 $accessallowed = $user->admin;
2638 $original_file = $dolibarr_main_data_root.
'/doctemplates/'.$original_file;
2639 } elseif ($modulepart ==
'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
2641 $accessallowed = ($fuser->rights->website->write && preg_match(
'/\.jpg$/i', basename($original_file)));
2642 $original_file = $dolibarr_main_data_root.
'/doctemplates/websites/'.$original_file;
2643 } elseif ($modulepart ==
'packages' && !empty($dolibarr_main_data_root)) {
2646 $tmp = explode(
',', $dolibarr_main_document_root_alt);
2649 $accessallowed = ($user->admin && preg_match(
'/^module_.*\.zip$/', basename($original_file)));
2650 $original_file = $dirins.
'/'.$original_file;
2651 } elseif ($modulepart ==
'mycompany' && !empty($conf->mycompany->dir_output)) {
2654 $original_file = $conf->mycompany->dir_output.
'/'.$original_file;
2655 } elseif ($modulepart ==
'userphoto' && !empty($conf->user->dir_output)) {
2658 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
2661 $original_file = $conf->user->dir_output.
'/'.$original_file;
2662 } elseif ($modulepart ==
'userphotopublic' && !empty($conf->user->dir_output)) {
2666 if (preg_match(
'/^(\d+)\/photos\//', $original_file, $reg)) {
2668 $tmpobject =
new User($db);
2669 $tmpobject->fetch($reg[1],
'',
'', 1);
2671 $securekey =
GETPOST(
'securekey',
'alpha', 1);
2673 global $dolibarr_main_cookie_cryptkey, $dolibarr_main_instance_unique_id;
2674 $valuetouse = $dolibarr_main_instance_unique_id ? $dolibarr_main_instance_unique_id : $dolibarr_main_cookie_cryptkey;
2675 $encodedsecurekey =
dol_hash($valuetouse.
'uservirtualcard'.$tmpobject->id.
'-'.$tmpobject->login,
'md5');
2676 if ($encodedsecurekey == $securekey) {
2685 $original_file = $conf->user->dir_output.
'/'.$original_file;
2686 } elseif (($modulepart ==
'companylogo') && !empty($conf->mycompany->dir_output)) {
2689 $original_file = $conf->mycompany->dir_output.
'/logos/'.$original_file;
2690 } elseif ($modulepart ==
'memberphoto' && !empty($conf->adherent->dir_output)) {
2693 if (preg_match(
'/^\d+\/photos\//', $original_file)) {
2696 $original_file = $conf->adherent->dir_output.
'/'.$original_file;
2697 } elseif ($modulepart ==
'apercufacture' && !empty($conf->facture->multidir_output[$entity])) {
2699 if ($fuser->hasRight(
'facture', $lire)) {
2702 $original_file = $conf->facture->multidir_output[$entity].
'/'.$original_file;
2703 } elseif ($modulepart ==
'apercupropal' && !empty($conf->propal->multidir_output[$entity])) {
2705 if ($fuser->hasRight(
'propal', $lire)) {
2708 $original_file = $conf->propal->multidir_output[$entity].
'/'.$original_file;
2709 } elseif ($modulepart ==
'apercucommande' && !empty($conf->commande->multidir_output[$entity])) {
2711 if ($fuser->hasRight(
'commande', $lire)) {
2714 $original_file = $conf->commande->multidir_output[$entity].
'/'.$original_file;
2715 } elseif (($modulepart ==
'apercufichinter' || $modulepart ==
'apercuficheinter') && !empty($conf->ficheinter->dir_output)) {
2717 if ($fuser->hasRight(
'ficheinter', $lire)) {
2720 $original_file = $conf->ficheinter->dir_output.
'/'.$original_file;
2721 } elseif (($modulepart ==
'apercucontract') && !empty($conf->contrat->multidir_output[$entity])) {
2723 if ($fuser->hasRight(
'contrat', $lire)) {
2726 $original_file = $conf->contrat->multidir_output[$entity].
'/'.$original_file;
2727 } elseif (($modulepart ==
'apercusupplier_proposal' || $modulepart ==
'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) {
2729 if ($fuser->hasRight(
'supplier_proposal', $lire)) {
2732 $original_file = $conf->supplier_proposal->dir_output.
'/'.$original_file;
2733 } elseif (($modulepart ==
'apercusupplier_order' || $modulepart ==
'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) {
2735 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
2738 $original_file = $conf->fournisseur->commande->dir_output.
'/'.$original_file;
2739 } elseif (($modulepart ==
'apercusupplier_invoice' || $modulepart ==
'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) {
2741 if ($fuser->hasRight(
'fournisseur', $lire)) {
2744 $original_file = $conf->fournisseur->facture->dir_output.
'/'.$original_file;
2745 } elseif (($modulepart ==
'holiday') && !empty($conf->holiday->dir_output)) {
2746 if ($fuser->hasRight(
'holiday', $read) || !empty($fuser->rights->holiday->readall) || preg_match(
'/^specimen/i', $original_file)) {
2749 if ($refname && empty($fuser->rights->holiday->readall) && !preg_match(
'/^specimen/i', $original_file)) {
2750 include_once DOL_DOCUMENT_ROOT.
'/holiday/class/holiday.class.php';
2751 $tmpholiday =
new Holiday($db);
2752 $tmpholiday->fetch(
'', $refname);
2753 $accessallowed =
checkUserAccessToObject($user, array(
'holiday'), $tmpholiday,
'holiday',
'',
'',
'rowid',
'');
2756 $original_file = $conf->holiday->dir_output.
'/'.$original_file;
2757 } elseif (($modulepart ==
'expensereport') && !empty($conf->expensereport->dir_output)) {
2758 if ($fuser->hasRight(
'expensereport', $lire) || !empty($fuser->rights->expensereport->readall) || preg_match(
'/^specimen/i', $original_file)) {
2761 if ($refname && empty($fuser->rights->expensereport->readall) && !preg_match(
'/^specimen/i', $original_file)) {
2762 include_once DOL_DOCUMENT_ROOT.
'/expensereport/class/expensereport.class.php';
2764 $tmpexpensereport->fetch(
'', $refname);
2765 $accessallowed =
checkUserAccessToObject($user, array(
'expensereport'), $tmpexpensereport,
'expensereport',
'',
'',
'rowid',
'');
2768 $original_file = $conf->expensereport->dir_output.
'/'.$original_file;
2769 } elseif (($modulepart ==
'apercuexpensereport') && !empty($conf->expensereport->dir_output)) {
2771 if ($fuser->hasRight(
'expensereport', $lire)) {
2774 $original_file = $conf->expensereport->dir_output.
'/'.$original_file;
2775 } elseif ($modulepart ==
'propalstats' && !empty($conf->propal->multidir_temp[$entity])) {
2777 if ($fuser->hasRight(
'propal', $lire)) {
2780 $original_file = $conf->propal->multidir_temp[$entity].
'/'.$original_file;
2781 } elseif ($modulepart ==
'orderstats' && !empty($conf->commande->dir_temp)) {
2783 if ($fuser->hasRight(
'commande', $lire)) {
2786 $original_file = $conf->commande->dir_temp.
'/'.$original_file;
2787 } elseif ($modulepart ==
'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) {
2788 if ($fuser->hasRight(
'fournisseur',
'commande', $lire)) {
2791 $original_file = $conf->fournisseur->commande->dir_temp.
'/'.$original_file;
2792 } elseif ($modulepart ==
'billstats' && !empty($conf->facture->dir_temp)) {
2794 if ($fuser->hasRight(
'facture', $lire)) {
2797 $original_file = $conf->facture->dir_temp.
'/'.$original_file;
2798 } elseif ($modulepart ==
'billstatssupplier' && !empty($conf->fournisseur->dir_output)) {
2799 if ($fuser->hasRight(
'fournisseur',
'facture', $lire)) {
2802 $original_file = $conf->fournisseur->facture->dir_temp.
'/'.$original_file;
2803 } elseif ($modulepart ==
'expeditionstats' && !empty($conf->expedition->dir_temp)) {
2805 if ($fuser->hasRight(
'expedition', $lire)) {
2808 $original_file = $conf->expedition->dir_temp.
'/'.$original_file;
2809 } elseif ($modulepart ==
'tripsexpensesstats' && !empty($conf->deplacement->dir_temp)) {
2811 if ($fuser->hasRight(
'deplacement', $lire)) {
2814 $original_file = $conf->deplacement->dir_temp.
'/'.$original_file;
2815 } elseif ($modulepart ==
'memberstats' && !empty($conf->adherent->dir_temp)) {
2817 if ($fuser->hasRight(
'adherent', $lire)) {
2820 $original_file = $conf->adherent->dir_temp.
'/'.$original_file;
2821 } elseif (preg_match(
'/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp)) {
2823 if ($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) {
2826 $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).
'/'.$original_file;
2827 } elseif (in_array($modulepart, array(
'tax',
'tax-vat',
'tva')) && !empty($conf->tax->dir_output)) {
2829 if ($fuser->hasRight(
'tax',
'charges', $lire)) {
2832 $modulepartsuffix = str_replace(
'tax-',
'', $modulepart);
2833 $original_file = $conf->tax->dir_output.
'/'.($modulepartsuffix !=
'tax' ? $modulepartsuffix.
'/' :
'').$original_file;
2834 } elseif ($modulepart ==
'actions' && !empty($conf->agenda->dir_output)) {
2836 if ($fuser->hasRight(
'agenda',
'myactions', $read)) {
2839 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
2840 include_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
2842 $tmpobject->fetch((
int) $refname);
2843 $accessallowed =
checkUserAccessToObject($user, array(
'agenda'), $tmpobject->id,
'actioncomm&societe',
'myactions|allactions',
'fk_soc',
'id',
'');
2844 if ($user->socid && $tmpobject->socid) {
2849 $original_file = $conf->agenda->dir_output.
'/'.$original_file;
2850 } elseif ($modulepart ==
'category' && !empty($conf->categorie->multidir_output[$entity])) {
2852 if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) {
2853 return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2855 if ($fuser->hasRight(
"categorie", $lire) || $fuser->hasRight(
"takepos",
"run")) {
2858 $original_file = $conf->categorie->multidir_output[$entity].
'/'.$original_file;
2859 } elseif ($modulepart ==
'prelevement' && !empty($conf->prelevement->dir_output)) {
2861 if ($fuser->rights->prelevement->bons->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
2864 $original_file = $conf->prelevement->dir_output.
'/'.$original_file;
2865 } elseif ($modulepart ==
'graph_stock' && !empty($conf->stock->dir_temp)) {
2868 $original_file = $conf->stock->dir_temp.
'/'.$original_file;
2869 } elseif ($modulepart ==
'graph_fourn' && !empty($conf->fournisseur->dir_temp)) {
2872 $original_file = $conf->fournisseur->dir_temp.
'/'.$original_file;
2873 } elseif ($modulepart ==
'graph_product' && !empty($conf->product->dir_temp)) {
2876 $original_file = $conf->product->multidir_temp[$entity].
'/'.$original_file;
2877 } elseif ($modulepart ==
'barcode') {
2882 $original_file =
'';
2883 } elseif ($modulepart ==
'iconmailing' && !empty($conf->mailing->dir_temp)) {
2886 $original_file = $conf->mailing->dir_temp.
'/'.$original_file;
2887 } elseif ($modulepart ==
'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
2890 $original_file = $conf->scanner->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
2891 } elseif ($modulepart ==
'fckeditor' && !empty($conf->fckeditor->dir_output)) {
2894 $original_file = $conf->fckeditor->dir_output.
'/'.$original_file;
2895 } elseif ($modulepart ==
'user' && !empty($conf->user->dir_output)) {
2897 $canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire});
2898 if ($fuser->id == (
int) $refname) {
2901 if ($canreaduser || preg_match(
'/^specimen/i', $original_file)) {
2904 $original_file = $conf->user->dir_output.
'/'.$original_file;
2905 } elseif (($modulepart ==
'company' || $modulepart ==
'societe' || $modulepart ==
'thirdparty') && !empty($conf->societe->multidir_output[$entity])) {
2907 if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
2908 return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2910 if ($fuser->rights->societe->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
2913 $original_file = $conf->societe->multidir_output[$entity].
'/'.$original_file;
2914 $sqlprotectagainstexternals =
"SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX.
"societe WHERE rowid='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'societe').
")";
2915 } elseif ($modulepart ==
'contact' && !empty($conf->societe->multidir_output[$entity])) {
2917 if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
2918 return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
2920 if ($fuser->hasRight(
'societe', $lire)) {
2923 $original_file = $conf->societe->multidir_output[$entity].
'/contact/'.$original_file;
2924 } elseif (($modulepart ==
'facture' || $modulepart ==
'invoice') && !empty($conf->facture->multidir_output[$entity])) {
2926 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2929 $original_file = $conf->facture->multidir_output[$entity].
'/'.$original_file;
2930 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'invoice').
")";
2931 } elseif ($modulepart ==
'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity])) {
2933 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2936 $original_file = $conf->propal->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2937 } elseif ($modulepart ==
'massfilesarea_orders') {
2938 if ($fuser->hasRight(
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2941 $original_file = $conf->commande->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2942 } elseif ($modulepart ==
'massfilesarea_sendings') {
2943 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2946 $original_file = $conf->expedition->dir_output.
'/sending/temp/massgeneration/'.$user->id.
'/'.$original_file;
2947 } elseif ($modulepart ==
'massfilesarea_invoices') {
2948 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2951 $original_file = $conf->facture->multidir_output[$entity].
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2952 } elseif ($modulepart ==
'massfilesarea_expensereport') {
2953 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2956 $original_file = $conf->expensereport->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2957 } elseif ($modulepart ==
'massfilesarea_interventions') {
2958 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2961 $original_file = $conf->ficheinter->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2962 } elseif ($modulepart ==
'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) {
2963 if ($fuser->hasRight(
'supplier_proposal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2966 $original_file = $conf->supplier_proposal->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2967 } elseif ($modulepart ==
'massfilesarea_supplier_order') {
2968 if ($fuser->hasRight(
'fournisseur',
'commande', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2971 $original_file = $conf->fournisseur->commande->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2972 } elseif ($modulepart ==
'massfilesarea_supplier_invoice') {
2973 if ($fuser->hasRight(
'fournisseur',
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2976 $original_file = $conf->fournisseur->facture->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2977 } elseif ($modulepart ==
'massfilesarea_contract' && !empty($conf->contrat->dir_output)) {
2978 if ($fuser->hasRight(
'contrat', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2981 $original_file = $conf->contrat->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
2982 } elseif (($modulepart ==
'fichinter' || $modulepart ==
'ficheinter') && !empty($conf->ficheinter->dir_output)) {
2984 if ($fuser->hasRight(
'ficheinter', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2987 $original_file = $conf->ficheinter->dir_output.
'/'.$original_file;
2988 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"fichinter WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
2989 } elseif ($modulepart ==
'deplacement' && !empty($conf->deplacement->dir_output)) {
2991 if ($fuser->hasRight(
'deplacement', $lire) || preg_match(
'/^specimen/i', $original_file)) {
2994 $original_file = $conf->deplacement->dir_output.
'/'.$original_file;
2996 } elseif (($modulepart ==
'propal' || $modulepart ==
'propale') && isset($conf->propal->multidir_output[$entity])) {
2998 if ($fuser->hasRight(
'propal', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3001 $original_file = $conf->propal->multidir_output[$entity].
'/'.$original_file;
3002 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"propal WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'propal').
")";
3003 } elseif (($modulepart ==
'commande' || $modulepart ==
'order') && !empty($conf->commande->multidir_output[$entity])) {
3005 if ($fuser->rights->commande->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
3008 $original_file = $conf->commande->multidir_output[$entity].
'/'.$original_file;
3009 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'order').
")";
3010 } elseif ($modulepart ==
'project' && !empty($conf->project->multidir_output[$entity])) {
3012 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3015 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3016 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
3017 $tmpproject =
new Project($db);
3018 $tmpproject->fetch(
'', $refname);
3019 $accessallowed =
checkUserAccessToObject($user, array(
'projet'), $tmpproject->id,
'projet&project',
'',
'',
'rowid',
'');
3022 $original_file = $conf->project->multidir_output[$entity].
'/'.$original_file;
3023 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3024 } elseif ($modulepart ==
'project_task' && !empty($conf->project->multidir_output[$entity])) {
3025 if ($fuser->hasRight(
'projet', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3028 if ($refname && !preg_match(
'/^specimen/i', $original_file)) {
3029 include_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
3030 $tmptask =
new Task($db);
3031 $tmptask->fetch(
'', $refname);
3032 $accessallowed =
checkUserAccessToObject($user, array(
'projet_task'), $tmptask->id,
'projet_task&project',
'',
'',
'rowid',
'');
3035 $original_file = $conf->project->multidir_output[$entity].
'/'.$original_file;
3036 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"projet WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'project').
")";
3037 } elseif (($modulepart ==
'commande_fournisseur' || $modulepart ==
'order_supplier') && !empty($conf->fournisseur->commande->dir_output)) {
3039 if ($fuser->rights->fournisseur->commande->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
3042 $original_file = $conf->fournisseur->commande->dir_output.
'/'.$original_file;
3043 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"commande_fournisseur WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
3044 } elseif (($modulepart ==
'facture_fournisseur' || $modulepart ==
'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output)) {
3046 if ($fuser->rights->fournisseur->facture->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
3049 $original_file = $conf->fournisseur->facture->dir_output.
'/'.$original_file;
3050 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"facture_fourn WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
3051 } elseif ($modulepart ==
'supplier_payment') {
3053 if ($fuser->rights->fournisseur->facture->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
3056 $original_file = $conf->fournisseur->payment->dir_output.
'/'.$original_file;
3057 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"paiementfournisseur WHERE ref='".$db->escape($refname).
"' AND entity=".$conf->entity;
3058 } elseif ($modulepart ==
'facture_paiement' && !empty($conf->facture->dir_output)) {
3060 if ($fuser->hasRight(
'facture', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3063 if ($fuser->socid > 0) {
3064 $original_file = $conf->facture->dir_output.
'/payments/private/'.$fuser->id.
'/'.$original_file;
3066 $original_file = $conf->facture->dir_output.
'/payments/'.$original_file;
3068 } elseif ($modulepart ==
'export_compta' && !empty($conf->accounting->dir_output)) {
3070 if ($fuser->rights->accounting->bind->write || preg_match(
'/^specimen/i', $original_file)) {
3073 $original_file = $conf->accounting->dir_output.
'/'.$original_file;
3074 } elseif (($modulepart ==
'expedition' || $modulepart ==
'shipment') && !empty($conf->expedition->dir_output)) {
3076 if ($fuser->hasRight(
'expedition', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3079 $original_file = $conf->expedition->dir_output.
"/".(strpos($original_file,
'sending/') === 0 ?
'' :
'sending/').$original_file;
3081 } elseif (($modulepart ==
'livraison' || $modulepart ==
'delivery') && !empty($conf->expedition->dir_output)) {
3083 if ($fuser->hasRight(
'expedition',
'delivery', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3086 $original_file = $conf->expedition->dir_output.
"/".(strpos($original_file,
'receipt/') === 0 ?
'' :
'receipt/').$original_file;
3087 } elseif ($modulepart ==
'actions' && !empty($conf->agenda->dir_output)) {
3089 if ($fuser->hasRight(
'agenda',
'myactions', $read) || preg_match(
'/^specimen/i', $original_file)) {
3092 $original_file = $conf->agenda->dir_output.
'/'.$original_file;
3093 } elseif ($modulepart ==
'actionsreport' && !empty($conf->agenda->dir_temp)) {
3095 if ($fuser->hasRight(
'agenda',
'allactions', $read) || preg_match(
'/^specimen/i', $original_file)) {
3098 $original_file = $conf->agenda->dir_temp.
"/".$original_file;
3099 } elseif ($modulepart ==
'product' || $modulepart ==
'produit' || $modulepart ==
'service' || $modulepart ==
'produit|service') {
3101 if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) {
3102 return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
3104 if (($fuser->hasRight(
'produit', $lire) || $fuser->hasRight(
'service', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3108 $original_file = $conf->product->multidir_output[$entity].
'/'.$original_file;
3110 $original_file = $conf->service->multidir_output[$entity].
'/'.$original_file;
3112 } elseif ($modulepart ==
'product_batch' || $modulepart ==
'produitlot') {
3114 if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) {
3115 return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
3117 if (($fuser->hasRight(
'produit', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3121 $original_file = $conf->productbatch->multidir_output[$entity].
'/'.$original_file;
3123 } elseif ($modulepart ==
'movement' || $modulepart ==
'mouvement') {
3125 if (empty($entity) || empty($conf->stock->multidir_output[$entity])) {
3126 return array(
'accessallowed'=>0,
'error'=>
'Value entity must be provided');
3128 if (($fuser->hasRight(
'stock', $lire) || $fuser->hasRight(
'stock',
'movement', $lire) || $fuser->hasRight(
'stock',
'mouvement', $lire)) || preg_match(
'/^specimen/i', $original_file)) {
3132 $original_file = $conf->stock->multidir_output[$entity].
'/movement/'.$original_file;
3134 } elseif ($modulepart ==
'contract' && !empty($conf->contrat->multidir_output[$entity])) {
3136 if ($fuser->rights->contrat->{$lire} || preg_match(
'/^specimen/i', $original_file)) {
3139 $original_file = $conf->contrat->multidir_output[$entity].
'/'.$original_file;
3140 $sqlprotectagainstexternals =
"SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX.
"contrat WHERE ref='".$db->escape($refname).
"' AND entity IN (".
getEntity(
'contract').
")";
3141 } elseif ($modulepart ==
'donation' && !empty($conf->don->dir_output)) {
3143 if ($fuser->hasRight(
'don', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3146 $original_file = $conf->don->dir_output.
'/'.$original_file;
3147 } elseif ($modulepart ==
'dolresource' && !empty($conf->resource->dir_output)) {
3149 if ($fuser->hasRight(
'resource', $read) || preg_match(
'/^specimen/i', $original_file)) {
3152 $original_file = $conf->resource->dir_output.
'/'.$original_file;
3153 } elseif (($modulepart ==
'remisecheque' || $modulepart ==
'chequereceipt') && !empty($conf->bank->dir_output)) {
3155 if ($fuser->hasRight(
'banque', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3159 $original_file = $conf->bank->dir_output.
'/checkdeposits/'.$original_file;
3160 } elseif (($modulepart ==
'banque' || $modulepart ==
'bank') && !empty($conf->bank->dir_output)) {
3162 if ($fuser->hasRight(
'banque', $lire)) {
3165 $original_file = $conf->bank->dir_output.
'/'.$original_file;
3166 } elseif ($modulepart ==
'export' && !empty($conf->export->dir_temp)) {
3169 $accessallowed = $user->rights->export->lire;
3170 $original_file = $conf->export->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3171 } elseif ($modulepart ==
'import' && !empty($conf->import->dir_temp)) {
3173 $accessallowed = $user->rights->import->run;
3174 $original_file = $conf->import->dir_temp.
'/'.$original_file;
3175 } elseif ($modulepart ==
'recruitment' && !empty($conf->recruitment->dir_output)) {
3177 $accessallowed = $user->hasRight(
'recruitment',
'recruitmentjobposition',
'read');
3178 $original_file = $conf->recruitment->dir_output.
'/'.$original_file;
3179 } elseif ($modulepart ==
'editor' && !empty($conf->fckeditor->dir_output)) {
3182 $original_file = $conf->fckeditor->dir_output.
'/'.$original_file;
3183 } elseif ($modulepart ==
'systemtools' && !empty($conf->admin->dir_output)) {
3185 if ($fuser->admin) {
3188 $original_file = $conf->admin->dir_output.
'/'.$original_file;
3189 } elseif ($modulepart ==
'admin_temp' && !empty($conf->admin->dir_temp)) {
3191 if ($fuser->admin) {
3194 $original_file = $conf->admin->dir_temp.
'/'.$original_file;
3195 } elseif ($modulepart ==
'bittorrent' && !empty($conf->bittorrent->dir_output)) {
3199 if (
dol_mimetype($original_file) ==
'application/x-bittorrent') {
3202 $original_file = $conf->bittorrent->dir_output.
'/'.$dir.
'/'.$original_file;
3203 } elseif ($modulepart ==
'member' && !empty($conf->adherent->dir_output)) {
3205 if ($fuser->hasRight(
'adherent', $lire) || preg_match(
'/^specimen/i', $original_file)) {
3208 $original_file = $conf->adherent->dir_output.
'/'.$original_file;
3209 } elseif ($modulepart ==
'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
3212 $original_file = $conf->scanner->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3222 if (preg_match(
'/^specimen/i', $original_file)) {
3225 if ($fuser->admin) {
3229 $tmpmodulepart = explode(
'-', $modulepart);
3230 if (!empty($tmpmodulepart[1])) {
3231 $modulepart = $tmpmodulepart[0];
3232 $original_file = $tmpmodulepart[1].
'/'.$original_file;
3237 if (preg_match(
'/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
3238 $tmpmodule = $reg[1];
3239 if (empty($conf->$tmpmodule->dir_temp)) {
3240 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3243 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3246 $original_file = $conf->{$reg[1]}->dir_temp.
'/'.$fuser->id.
'/'.$original_file;
3247 } elseif (preg_match(
'/^([a-z]+)_temp$/i', $modulepart, $reg)) {
3248 $tmpmodule = $reg[1];
3249 if (empty($conf->$tmpmodule->dir_temp)) {
3250 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3253 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3256 $original_file = $conf->$tmpmodule->dir_temp.
'/'.$original_file;
3257 } elseif (preg_match(
'/^([a-z]+)_user$/i', $modulepart, $reg)) {
3258 $tmpmodule = $reg[1];
3259 if (empty($conf->$tmpmodule->dir_output)) {
3260 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3263 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3266 $original_file = $conf->$tmpmodule->dir_output.
'/'.$fuser->id.
'/'.$original_file;
3267 } elseif (preg_match(
'/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
3268 $tmpmodule = $reg[1];
3269 if (empty($conf->$tmpmodule->dir_output)) {
3270 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
')');
3273 if ($fuser->hasRight($tmpmodule, $lire) || preg_match(
'/^specimen/i', $original_file)) {
3276 $original_file = $conf->$tmpmodule->dir_output.
'/temp/massgeneration/'.$user->id.
'/'.$original_file;
3278 if (empty($conf->$modulepart->dir_output)) {
3279 dol_print_error(
'',
'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.
'). The module for this modulepart value may not be activated.');
3284 $partsofdirinoriginalfile = explode(
'/', $original_file);
3285 if (!empty($partsofdirinoriginalfile[1])) {
3286 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3287 if ($partofdirinoriginalfile && ($fuser->hasRight($modulepart, $partofdirinoriginalfile,
'lire') || $fuser->hasRight($modulepart, $partofdirinoriginalfile,
'read'))) {
3291 if ($fuser->hasRight($modulepart, $lire) || $fuser->hasRight($modulepart, $read)) {
3295 if (is_array($conf->$modulepart->multidir_output) && !empty($conf->$modulepart->multidir_output[$entity])) {
3296 $original_file = $conf->$modulepart->multidir_output[$entity].
'/'.$original_file;
3298 $original_file = $conf->$modulepart->dir_output.
'/'.$original_file;
3302 $parameters = array(
3303 'modulepart' => $modulepart,
3304 'original_file' => $original_file,
3305 'entity' => $entity,
3310 $reshook = $hookmanager->executeHooks(
'checkSecureAccess', $parameters, $object);
3312 if (!empty($hookmanager->resArray[
'original_file'])) {
3313 $original_file = $hookmanager->resArray[
'original_file'];
3315 if (!empty($hookmanager->resArray[
'accessallowed'])) {
3316 $accessallowed = $hookmanager->resArray[
'accessallowed'];
3318 if (!empty($hookmanager->resArray[
'sqlprotectagainstexternals'])) {
3319 $sqlprotectagainstexternals = $hookmanager->resArray[
'sqlprotectagainstexternals'];
3325 'accessallowed' => ($accessallowed ? 1 : 0),
3326 'sqlprotectagainstexternals' => $sqlprotectagainstexternals,
3327 'original_file' => $original_file
3346 $cachefile = $directory.$filename;
3347 file_put_contents($cachefile, serialize($object), LOCK_EX);
3362 $cachefile = $directory.$filename;
3363 $refresh = !file_exists($cachefile) || ($now - $cachetime) >
dol_filemtime($cachefile);
3376 $cachefile = $directory.$filename;
3377 $object = unserialize(file_get_contents($cachefile));
3389 return preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\//',
'', $pathfile);
3404 function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path =
'', $pathref =
'', &$checksumconcat = array())
3408 $exclude =
'install';
3410 foreach ($dir->md5file as $file) {
3411 $filename = $path.$file[
'name'];
3412 $file_list[
'insignature'][] = $filename;
3413 $expectedsize = (empty($file[
'size']) ?
'' : $file[
'size']);
3414 $expectedmd5 = (string) $file;
3418 if (!file_exists($pathref.
'/'.$filename)) {
3419 $file_list[
'missing'][] = array(
'filename'=>$filename,
'expectedmd5'=>$expectedmd5,
'expectedsize'=>$expectedsize);
3421 $md5_local = md5_file($pathref.
'/'.$filename);
3423 if ($conffile ==
'/etc/dolibarr/conf.php' && $filename ==
'/filefunc.inc.php') {
3424 $checksumconcat[] = $expectedmd5;
3426 if ($md5_local != $expectedmd5) {
3427 $file_list[
'updated'][] = array(
'filename'=>$filename,
'expectedmd5'=>$expectedmd5,
'expectedsize'=>$expectedsize,
'md5'=>(
string) $md5_local);
3429 $checksumconcat[] = $md5_local;
3434 foreach ($dir->dir as $subdir) {
3435 getFilesUpdated($file_list, $subdir, $path.$subdir[
'name'].
'/', $pathref, $checksumconcat);
3450 global $object, $langs;
3453 $out .=
'<div id="'.$htmlname.
'Message" class="dragDropAreaMessage hidden"><span>'.
img_picto(
"",
'download').
'<br>'.$langs->trans(
"DropFileToAddItToObject").
'</span></div>';
3454 $out .=
"\n<!-- JS CODE TO ENABLE DRAG AND DROP OF FILE -->\n";
3457 jQuery(document).ready(function() {
3458 var enterTargetDragDrop = null;
3460 $("#'.$htmlname.
'").addClass("cssDragDropArea");
3462 $(".cssDragDropArea").on("dragenter", function(ev, ui) {
3463 var dataTransfer = ev.originalEvent.dataTransfer;
3464 var dataTypes = dataTransfer.types;
3465 //console.log(dataTransfer);
3466 //console.log(dataTypes);
3468 if (!dataTypes || ($.inArray(\'Files\', dataTypes) === -1)) {
3469 // The element dragged is not a file, so we avoid the "dragenter"
3470 ev.preventDefault();
3474 // Entering drop area. Highlight area
3475 console.log("dragAndDropFileUpload: We add class highlightDragDropArea")
3476 enterTargetDragDrop = ev.target;
3477 $(this).addClass("highlightDragDropArea");
3478 $("#'.$htmlname.
'Message").removeClass("hidden");
3479 ev.preventDefault();
3482 $(".cssDragDropArea").on("dragleave", function(ev) {
3483 // Going out of drop area. Remove Highlight
3484 if (enterTargetDragDrop == ev.target){
3485 console.log("dragAndDropFileUpload: We remove class highlightDragDropArea")
3486 $("#'.$htmlname.
'Message").addClass("hidden");
3487 $(this).removeClass("highlightDragDropArea");
3491 $(".cssDragDropArea").on("dragover", function(ev) {
3492 ev.preventDefault();
3496 $(".cssDragDropArea").on("drop", function(e) {
3497 console.log("Trigger event file dropped. fk_element='.
dol_escape_js($object->id).
' element='.
dol_escape_js($object->element).
'");
3499 fd = new FormData();
3501 fd.append("element", "'.
dol_escape_js($object->element).
'");
3503 fd.append("action", "linkit");
3505 var dataTransfer = e.originalEvent.dataTransfer;
3507 if (dataTransfer.files && dataTransfer.files.length){
3508 var droppedFiles = e.originalEvent.dataTransfer.files;
3509 $.each(droppedFiles, function(index,file){
3510 fd.append("files[]", file,file.name)
3513 $(".cssDragDropArea").removeClass("highlightDragDropArea");
3514 counterdragdrop = 0;
3516 url: "'.DOL_URL_ROOT.
'/core/ajax/fileupload.php",
3521 success:function() {
3522 console.log("Uploaded.", arguments);
3523 /* arguments[0] is the json string of files */
3524 /* arguments[1] is the value for variable "success", can be 0 or 1 */
3525 let listoffiles = JSON.parse(arguments[0]);
3526 console.log(listoffiles);
3528 for (let i = 0; i < listoffiles.length; i++) {
3529 console.log(listoffiles[i].error);
3530 if (listoffiles[i].error) {
3534 console.log(nboferror);
3535 if (nboferror > 0) {
3536 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js($object->id).
'&seteventmessages=ErrorOnAtLeastOneFileUpload:warnings";
3538 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js($object->id).
'&seteventmessages=UploadFileDragDropSuccess:mesgs";
3542 console.log("Error Uploading.", arguments)
3543 if (arguments[0].status == 403) {
3544 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js($object->id).
'&seteventmessages=ErrorUploadPermissionDenied:errors";
3546 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?id='.
dol_escape_js($object->id).
'&seteventmessages=ErrorUploadFileDragDropPermissionDenied:errors";
3552 $out .=
"</script>\n";
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.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
dirbasename($pathfile)
Return the relative dirname (relative to DOL_DATA_ROOT) of a full path string.
dol_is_link($pathoffile)
Return if path is a symbolic link.
dol_compare_file($a, $b)
Fast compare of 2 files identified by their properties ->name, ->date and ->size.
dol_meta_create($object)
Create a meta file with document file into same directory.
dolCheckVirus($src_file)
Check virus into a file.
dol_basename($pathfile)
Make a basename working with all page code (default PHP basenamed fails with cyrillic).
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
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_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile', $upload_dir='')
Make control on an uploaded file from an GUI page and move it to final destination.
dol_move_dir($srcdir, $destdir, $overwriteifexists=1, $indexdatabase=1, $renamedircontent=1)
Move a directory into another name.
dol_fileperm($pathoffile)
Return permissions of a file.
dol_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser='', $refname='', $mode='read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices to g...
dol_uncompress($inputfile, $outputdir)
Uncompress a file.
dol_init_file_process($pathtoscan='', $trackid='')
Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
addFileIntoDatabaseIndex($dir, $file, $fullpathorig='', $mode='uploaded', $setsharekey=0, $object=null)
Add a file into database index.
dol_convert_file($fileinput, $ext='png', $fileoutput='', $page='')
Convert an image file or a PDF into another image format.
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png)$', '^\.'), $nohook=false, $mode='')
Return file(s) into a directory (by default most recent)
dol_is_url($url)
Return if path is an URL.
dol_filecache($directory, $filename, $object)
Store object in file.
dol_dir_list_in_database($path, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0)
Scan a directory and return a list of files/directories.
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.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_unescapefile($filename)
Unescape a file submitted by upload.
dol_dir_list($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_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).
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0, $excludefileext=null)
Copy a dir to another dir.
deleteFilesIntoDatabaseIndex($dir, $file, $mode='uploaded')
Delete files into database index using search criterias.
dol_readcachefile($directory, $filename)
Read object from cachefile.
dol_is_dir($folder)
Test if filename is a directory.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null)
Get and save an upload file (for example after submitting a new file a mail form).
dol_cache_refresh($directory, $filename, $cachetime)
Test if Refresh needed.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_is_dir_empty($dir)
Return if path is empty.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
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.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
currentToken()
Return the value of token currently saved into session with name 'token'.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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 second index function, which produces ascending (default) or descending output...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
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_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
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.
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')
Returns a hash (non reversible encryption) of a string.