dolibarr  16.0.1
files.lib.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2008-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2012-2021 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2012-2016 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
6  * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
7  * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <https://www.gnu.org/licenses/>.
21  * or see https://www.gnu.org/
22  */
23 
36 function dol_basename($pathfile)
37 {
38  return preg_replace('/^.*\/([^\/]+)$/', '$1', rtrim($pathfile, '/'));
39 }
40 
60 function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename = "", $donotfollowsymlinks = 0)
61 {
62  global $db, $hookmanager;
63  global $object;
64 
65  if ($recursive <= 1) { // Avoid too verbose log
66  dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter));
67  //print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
68  }
69 
70  $loaddate = ($mode == 1 || $mode == 2) ?true:false;
71  $loadsize = ($mode == 1 || $mode == 3) ?true:false;
72  $loadperm = ($mode == 1 || $mode == 4) ?true:false;
73 
74  // Clean parameters
75  $path = preg_replace('/([\\/]+)$/i', '', $path);
76  $newpath = dol_osencode($path);
77 
78  $reshook = 0;
79  $file_list = array();
80 
81  if (is_object($hookmanager) && !$nohook) {
82  $hookmanager->resArray = array();
83 
84  $hookmanager->initHooks(array('fileslib'));
85 
86  $parameters = array(
87  'path' => $newpath,
88  'types'=> $types,
89  'recursive' => $recursive,
90  'filter' => $filter,
91  'excludefilter' => $excludefilter,
92  'sortcriteria' => $sortcriteria,
93  'sortorder' => $sortorder,
94  'loaddate' => $loaddate,
95  'loadsize' => $loadsize,
96  'mode' => $mode
97  );
98  $reshook = $hookmanager->executeHooks('getDirList', $parameters, $object);
99  }
100 
101  // $hookmanager->resArray may contain array stacked by other modules
102  if (empty($reshook)) {
103  if (!is_dir($newpath)) {
104  return array();
105  }
106 
107  if ($dir = opendir($newpath)) {
108  $filedate = '';
109  $filesize = '';
110  $fileperm = '';
111  while (false !== ($file = readdir($dir))) { // $file is always a basename (into directory $newpath)
112  if (!utf8_check($file)) {
113  $file = utf8_encode($file); // To be sure data is stored in utf8 in memory
114  }
115  $fullpathfile = ($newpath ? $newpath.'/' : '').$file;
116 
117  $qualified = 1;
118 
119  // Define excludefilterarray
120  $excludefilterarray = array('^\.');
121  if (is_array($excludefilter)) {
122  $excludefilterarray = array_merge($excludefilterarray, $excludefilter);
123  } elseif ($excludefilter) {
124  $excludefilterarray[] = $excludefilter;
125  }
126  // Check if file is qualified
127  foreach ($excludefilterarray as $filt) {
128  if (preg_match('/'.$filt.'/i', $file) || preg_match('/'.$filt.'/i', $fullpathfile)) {
129  $qualified = 0;
130  break;
131  }
132  }
133  //print $fullpathfile.' '.$file.' '.$qualified.'<br>';
134 
135  if ($qualified) {
136  $isdir = is_dir(dol_osencode($path."/".$file));
137  // Check whether this is a file or directory and whether we're interested in that type
138  if ($isdir && (($types == "directories") || ($types == "all") || $recursive > 0)) {
139  // Add entry into file_list array
140  if (($types == "directories") || ($types == "all")) {
141  if ($loaddate || $sortcriteria == 'date') {
142  $filedate = dol_filemtime($path."/".$file);
143  }
144  if ($loadsize || $sortcriteria == 'size') {
145  $filesize = dol_filesize($path."/".$file);
146  }
147  if ($loadperm || $sortcriteria == 'perm') {
148  $fileperm = dol_fileperm($path."/".$file);
149  }
150 
151  if (!$filter || preg_match('/'.$filter.'/i', $file)) { // We do not search key $filter into all $path, only into $file part
152  $reg = array();
153  preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg);
154  $level1name = (isset($reg[1]) ? $reg[1] : '');
155  $file_list[] = array(
156  "name" => $file,
157  "path" => $path,
158  "level1name" => $level1name,
159  "relativename" => ($relativename ? $relativename.'/' : '').$file,
160  "fullname" => $path.'/'.$file,
161  "date" => $filedate,
162  "size" => $filesize,
163  "perm" => $fileperm,
164  "type" => 'dir'
165  );
166  }
167  }
168 
169  // if we're in a directory and we want recursive behavior, call this function again
170  if ($recursive > 0) {
171  if (empty($donotfollowsymlinks) || !is_link($path."/".$file)) {
172  //var_dump('eee '. $path."/".$file. ' '.is_dir($path."/".$file).' '.is_link($path."/".$file));
173  $file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive + 1, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename != '' ? $relativename.'/' : '').$file, $donotfollowsymlinks));
174  }
175  }
176  } elseif (!$isdir && (($types == "files") || ($types == "all"))) {
177  // Add file into file_list array
178  if ($loaddate || $sortcriteria == 'date') {
179  $filedate = dol_filemtime($path."/".$file);
180  }
181  if ($loadsize || $sortcriteria == 'size') {
182  $filesize = dol_filesize($path."/".$file);
183  }
184 
185  if (!$filter || preg_match('/'.$filter.'/i', $file)) { // We do not search key $filter into $path, only into $file
186  preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg);
187  $level1name = (isset($reg[1]) ? $reg[1] : '');
188  $file_list[] = array(
189  "name" => $file,
190  "path" => $path,
191  "level1name" => $level1name,
192  "relativename" => ($relativename ? $relativename.'/' : '').$file,
193  "fullname" => $path.'/'.$file,
194  "date" => $filedate,
195  "size" => $filesize,
196  "type" => 'file'
197  );
198  }
199  }
200  }
201  }
202  closedir($dir);
203 
204  // Obtain a list of columns
205  if (!empty($sortcriteria) && $sortorder) {
206  $file_list = dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ? 'asc' : 'desc'));
207  }
208  }
209  }
210 
211  if (is_object($hookmanager) && is_array($hookmanager->resArray)) {
212  $file_list = array_merge($file_list, $hookmanager->resArray);
213  }
214 
215  return $file_list;
216 }
217 
218 
232 function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0)
233 {
234  global $conf, $db;
235 
236  $sql = " SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,";
237  $sql .= " date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share";
238  if ($mode) {
239  $sql .= ", description";
240  }
241  $sql .= " FROM ".MAIN_DB_PREFIX."ecm_files";
242  $sql .= " WHERE entity = ".$conf->entity;
243  if (preg_match('/%$/', $path)) {
244  $sql .= " AND filepath LIKE '".$db->escape($path)."'";
245  } else {
246  $sql .= " AND filepath = '".$db->escape($path)."'";
247  }
248 
249  $resql = $db->query($sql);
250  if ($resql) {
251  $file_list = array();
252  $num = $db->num_rows($resql);
253  $i = 0;
254  while ($i < $num) {
255  $obj = $db->fetch_object($resql);
256  if ($obj) {
257  $reg = array();
258  preg_match('/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, $reg);
259  $level1name = (isset($reg[1]) ? $reg[1] : '');
260  $file_list[] = array(
261  "rowid" => $obj->rowid,
262  "label" => $obj->label, // md5
263  "name" => $obj->filename,
264  "path" => DOL_DATA_ROOT.'/'.$obj->filepath,
265  "level1name" => $level1name,
266  "fullname" => DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,
267  "fullpath_orig" => $obj->fullpath_orig,
268  "date_c" => $db->jdate($obj->date_c),
269  "date_m" => $db->jdate($obj->date_m),
270  "type" => 'file',
271  "keywords" => $obj->keywords,
272  "cover" => $obj->cover,
273  "position" => (int) $obj->position,
274  "acl" => $obj->acl,
275  "share" => $obj->share,
276  "description" => ($mode ? $obj->description : '')
277  );
278  }
279  $i++;
280  }
281 
282  // Obtain a list of columns
283  if (!empty($sortcriteria)) {
284  $myarray = array();
285  foreach ($file_list as $key => $row) {
286  $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] : '');
287  }
288  // Sort the data
289  if ($sortorder) {
290  array_multisort($myarray, $sortorder, $file_list);
291  }
292  }
293 
294  return $file_list;
295  } else {
296  dol_print_error($db);
297  return array();
298  }
299 }
300 
301 
310 function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
311 {
312  global $conf, $db, $user;
313 
314  $filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC);
315 
316  // TODO Remove this when PRODUCT_USE_OLD_PATH_FOR_PHOTO will be removed
317  global $modulepart;
318  if ($modulepart == 'produit' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
319  global $object;
320  if (!empty($object->id)) {
321  if (!empty($conf->product->enabled)) {
322  $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";
323  } else {
324  $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";
325  }
326 
327  $relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dirold);
328  $relativedirold = preg_replace('/^[\\/]/', '', $relativedirold);
329 
330  $filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC));
331  }
332  }
333 
334  //var_dump($relativedir);
335  //var_dump($filearray);
336  //var_dump($filearrayindatabase);
337 
338  // Complete filearray with properties found into $filearrayindatabase
339  foreach ($filearray as $key => $val) {
340  $tmpfilename = preg_replace('/\.noexe$/', '', $filearray[$key]['name']);
341  $found = 0;
342  // Search if it exists into $filearrayindatabase
343  foreach ($filearrayindatabase as $key2 => $val2) {
344  if (($filearrayindatabase[$key2]['path'] == $filearray[$key]['path']) && ($filearrayindatabase[$key2]['name'] == $tmpfilename)) {
345  $filearray[$key]['position_name'] = ($filearrayindatabase[$key2]['position'] ? $filearrayindatabase[$key2]['position'] : '0').'_'.$filearrayindatabase[$key2]['name'];
346  $filearray[$key]['position'] = $filearrayindatabase[$key2]['position'];
347  $filearray[$key]['cover'] = $filearrayindatabase[$key2]['cover'];
348  $filearray[$key]['acl'] = $filearrayindatabase[$key2]['acl'];
349  $filearray[$key]['rowid'] = $filearrayindatabase[$key2]['rowid'];
350  $filearray[$key]['label'] = $filearrayindatabase[$key2]['label'];
351  $filearray[$key]['share'] = $filearrayindatabase[$key2]['share'];
352  $found = 1;
353  break;
354  }
355  }
356 
357  if (!$found) { // This happen in transition toward version 6, or if files were added manually into os dir.
358  $filearray[$key]['position'] = '999999'; // File not indexed are at end. So if we add a file, it will not replace an existing position
359  $filearray[$key]['cover'] = 0;
360  $filearray[$key]['acl'] = '';
361 
362  $rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filearray[$key]['fullname']);
363 
364  if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filename)) { // If not a tmp file
365  dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it");
366  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
367  $ecmfile = new EcmFiles($db);
368 
369  // Add entry into database
370  $filename = basename($rel_filename);
371  $rel_dir = dirname($rel_filename);
372  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
373  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
374 
375  $ecmfile->filepath = $rel_dir;
376  $ecmfile->filename = $filename;
377  $ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname'])); // $destfile is a full path to file
378  $ecmfile->fullpath_orig = $filearray[$key]['fullname'];
379  $ecmfile->gen_or_uploaded = 'unknown';
380  $ecmfile->description = ''; // indexed content
381  $ecmfile->keywords = ''; // keyword content
382  $result = $ecmfile->create($user);
383  if ($result < 0) {
384  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
385  } else {
386  $filearray[$key]['rowid'] = $result;
387  }
388  } else {
389  $filearray[$key]['rowid'] = 0; // Should not happened
390  }
391  }
392  }
393  //var_dump($filearray); var_dump($relativedir.' - tmpfilename='.$tmpfilename.' - found='.$found);
394 }
395 
396 
404 function dol_compare_file($a, $b)
405 {
406  global $sortorder;
407  global $sortfield;
408 
409  $sortorder = strtoupper($sortorder);
410 
411  if ($sortorder == 'ASC') {
412  $retup = -1;
413  $retdown = 1;
414  } else {
415  $retup = 1;
416  $retdown = -1;
417  }
418 
419  if ($sortfield == 'name') {
420  if ($a->name == $b->name) {
421  return 0;
422  }
423  return ($a->name < $b->name) ? $retup : $retdown;
424  }
425  if ($sortfield == 'date') {
426  if ($a->date == $b->date) {
427  return 0;
428  }
429  return ($a->date < $b->date) ? $retup : $retdown;
430  }
431  if ($sortfield == 'size') {
432  if ($a->size == $b->size) {
433  return 0;
434  }
435  return ($a->size < $b->size) ? $retup : $retdown;
436  }
437 }
438 
439 
446 function dol_is_dir($folder)
447 {
448  $newfolder = dol_osencode($folder);
449  if (is_dir($newfolder)) {
450  return true;
451  } else {
452  return false;
453  }
454 }
455 
462 function dol_is_dir_empty($dir)
463 {
464  if (!is_readable($dir)) {
465  return false;
466  }
467  return (count(scandir($dir)) == 2);
468 }
469 
476 function dol_is_file($pathoffile)
477 {
478  $newpathoffile = dol_osencode($pathoffile);
479  return is_file($newpathoffile);
480 }
481 
488 function dol_is_link($pathoffile)
489 {
490  $newpathoffile = dol_osencode($pathoffile);
491  return is_link($newpathoffile);
492 }
493 
500 function dol_is_url($url)
501 {
502  $tmpprot = array('file', 'http', 'https', 'ftp', 'zlib', 'data', 'ssh', 'ssh2', 'ogg', 'expect');
503  foreach ($tmpprot as $prot) {
504  if (preg_match('/^'.$prot.':/i', $url)) {
505  return true;
506  }
507  }
508  return false;
509 }
510 
517 function dol_dir_is_emtpy($folder)
518 {
519  $newfolder = dol_osencode($folder);
520  if (is_dir($newfolder)) {
521  $handle = opendir($newfolder);
522  $folder_content = '';
523  while ((gettype($name = readdir($handle)) != "boolean")) {
524  $name_array[] = $name;
525  }
526  foreach ($name_array as $temp) {
527  $folder_content .= $temp;
528  }
529 
530  closedir($handle);
531 
532  if ($folder_content == "...") {
533  return true;
534  } else {
535  return false;
536  }
537  } else {
538  return true; // Dir does not exists
539  }
540 }
541 
549 function dol_count_nb_of_line($file)
550 {
551  $nb = 0;
552 
553  $newfile = dol_osencode($file);
554  //print 'x'.$file;
555  $fp = fopen($newfile, 'r');
556  if ($fp) {
557  while (!feof($fp)) {
558  $line = fgets($fp);
559  // We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines.
560  if (!$line === false) {
561  $nb++;
562  }
563  }
564  fclose($fp);
565  } else {
566  $nb = -1;
567  }
568 
569  return $nb;
570 }
571 
572 
580 function dol_filesize($pathoffile)
581 {
582  $newpathoffile = dol_osencode($pathoffile);
583  return filesize($newpathoffile);
584 }
585 
592 function dol_filemtime($pathoffile)
593 {
594  $newpathoffile = dol_osencode($pathoffile);
595  return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
596 }
597 
604 function dol_fileperm($pathoffile)
605 {
606  $newpathoffile = dol_osencode($pathoffile);
607  return fileperms($newpathoffile);
608 }
609 
622 function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = 0, $indexdatabase = 0, $arrayreplacementisregex = 0)
623 {
624  global $conf;
625 
626  dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase." arrayreplacementisregex=".$arrayreplacementisregex);
627 
628  if (empty($srcfile)) {
629  return -1;
630  }
631  if (empty($destfile)) {
632  $destfile = $srcfile;
633  }
634 
635  $destexists = dol_is_file($destfile);
636  if (($destfile != $srcfile) && $destexists) {
637  return 0;
638  }
639 
640  $tmpdestfile = $destfile.'.tmp';
641 
642  $newpathofsrcfile = dol_osencode($srcfile);
643  $newpathoftmpdestfile = dol_osencode($tmpdestfile);
644  $newpathofdestfile = dol_osencode($destfile);
645  $newdirdestfile = dirname($newpathofdestfile);
646 
647  if ($destexists && !is_writable($newpathofdestfile)) {
648  dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
649  return -1;
650  }
651  if (!is_writable($newdirdestfile)) {
652  dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
653  return -2;
654  }
655 
656  dol_delete_file($tmpdestfile);
657 
658  // Create $newpathoftmpdestfile from $newpathofsrcfile
659  $content = file_get_contents($newpathofsrcfile, 'r');
660 
661  if (empty($arrayreplacementisregex)) {
662  $content = make_substitutions($content, $arrayreplacement, null);
663  } else {
664  foreach ($arrayreplacement as $key => $value) {
665  $content = preg_replace($key, $value, $content);
666  }
667  }
668 
669  file_put_contents($newpathoftmpdestfile, $content);
670  @chmod($newpathoftmpdestfile, octdec($newmask));
671 
672  // Rename
673  $result = dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase);
674  if (!$result) {
675  dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
676  return -3;
677  }
678  if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
679  $newmask = $conf->global->MAIN_UMASK;
680  }
681  if (empty($newmask)) { // This should no happen
682  dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
683  $newmask = '0664';
684  }
685 
686  @chmod($newpathofdestfile, octdec($newmask));
687 
688  return 1;
689 }
690 
691 
702 function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1)
703 {
704  global $conf;
705 
706  dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
707 
708  if (empty($srcfile) || empty($destfile)) {
709  return -1;
710  }
711 
712  $destexists = dol_is_file($destfile);
713  if (!$overwriteifexists && $destexists) {
714  return 0;
715  }
716 
717  $newpathofsrcfile = dol_osencode($srcfile);
718  $newpathofdestfile = dol_osencode($destfile);
719  $newdirdestfile = dirname($newpathofdestfile);
720 
721  if ($destexists && !is_writable($newpathofdestfile)) {
722  dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
723  return -1;
724  }
725  if (!is_writable($newdirdestfile)) {
726  dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
727  return -2;
728  }
729  // Copy with overwriting if exists
730  $result = @copy($newpathofsrcfile, $newpathofdestfile);
731  //$result=copy($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
732  if (!$result) {
733  dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
734  return -3;
735  }
736  if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
737  $newmask = $conf->global->MAIN_UMASK;
738  }
739  if (empty($newmask)) { // This should no happen
740  dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
741  $newmask = '0664';
742  }
743 
744  @chmod($newpathofdestfile, octdec($newmask));
745 
746  return 1;
747 }
748 
761 function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement = null, $excludesubdir = 0)
762 {
763  global $conf;
764 
765  $result = 0;
766 
767  dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
768 
769  if (empty($srcfile) || empty($destfile)) {
770  return -1;
771  }
772 
773  $destexists = dol_is_dir($destfile);
774  //if (! $overwriteifexists && $destexists) return 0; // The overwriteifexists is for files only, so propagated to dol_copy only.
775 
776  if (!$destexists) {
777  // We must set mask just before creating dir, becaause it can be set differently by dol_copy
778  umask(0);
779  $dirmaskdec = octdec($newmask);
780  if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
781  $dirmaskdec = octdec($conf->global->MAIN_UMASK);
782  }
783  $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
784  dol_mkdir($destfile, '', decoct($dirmaskdec));
785  }
786 
787  $ossrcfile = dol_osencode($srcfile);
788  $osdestfile = dol_osencode($destfile);
789 
790  // Recursive function to copy all subdirectories and contents:
791  if (is_dir($ossrcfile)) {
792  $dir_handle = opendir($ossrcfile);
793  while ($file = readdir($dir_handle)) {
794  if ($file != "." && $file != ".." && !is_link($ossrcfile."/".$file)) {
795  if (is_dir($ossrcfile."/".$file)) {
796  if (empty($excludesubdir) || ($excludesubdir == 2 && strlen($file) == 2)) {
797  $newfile = $file;
798  // Replace destination filename with a new one
799  if (is_array($arrayreplacement)) {
800  foreach ($arrayreplacement as $key => $val) {
801  $newfile = str_replace($key, $val, $newfile);
802  }
803  }
804  //var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists");
805  $tmpresult = dolCopyDir($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir);
806  }
807  } else {
808  $newfile = $file;
809  // Replace destination filename with a new one
810  if (is_array($arrayreplacement)) {
811  foreach ($arrayreplacement as $key => $val) {
812  $newfile = str_replace($key, $val, $newfile);
813  }
814  }
815  $tmpresult = dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists);
816  }
817  // Set result
818  if ($result > 0 && $tmpresult >= 0) {
819  // Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass
820  } else {
821  $result = $tmpresult;
822  }
823  if ($result < 0) {
824  break;
825  }
826  }
827  }
828  closedir($dir_handle);
829  } else {
830  // Source directory does not exists
831  $result = -2;
832  }
833 
834  return $result;
835 }
836 
837 
854 function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1)
855 {
856  global $user, $db, $conf;
857  $result = false;
858 
859  dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
860  $srcexists = dol_is_file($srcfile);
861  $destexists = dol_is_file($destfile);
862 
863  if (!$srcexists) {
864  dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
865  return false;
866  }
867 
868  if ($overwriteifexists || !$destexists) {
869  $newpathofsrcfile = dol_osencode($srcfile);
870  $newpathofdestfile = dol_osencode($destfile);
871 
872  // Check virus
873  $testvirusarray = array();
874  if ($testvirus) {
875  $testvirusarray = dolCheckVirus($newpathofsrcfile);
876  if (count($testvirusarray)) {
877  dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING);
878  return false;
879  }
880  }
881 
882  $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
883  if (!$result) {
884  if ($destexists) {
885  dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
886  // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
887  dol_delete_file($destfile);
888  $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
889  } else {
890  dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
891  }
892  }
893 
894  // Move ok
895  if ($result && $indexdatabase) {
896  // Rename entry into ecm database
897  $rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $srcfile);
898  $rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destfile);
899  if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) { // If not a tmp file
900  $rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
901  $rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
902  //var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter);exit;
903 
904  dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG);
905  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
906 
907  $ecmfiletarget = new EcmFiles($db);
908  $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter);
909  if ($resultecmtarget > 0) { // An entry for target name already exists for target, we delete it, a new one will be created.
910  $ecmfiletarget->delete($user);
911  }
912 
913  $ecmfile = new EcmFiles($db);
914  $resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore);
915  if ($resultecm > 0) { // If an entry was found for src file, we use it to move entry
916  $filename = basename($rel_filetorenameafter);
917  $rel_dir = dirname($rel_filetorenameafter);
918  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
919  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
920 
921  $ecmfile->filepath = $rel_dir;
922  $ecmfile->filename = $filename;
923 
924  $resultecm = $ecmfile->update($user);
925  } elseif ($resultecm == 0) { // If no entry were found for src files, create/update target file
926  $filename = basename($rel_filetorenameafter);
927  $rel_dir = dirname($rel_filetorenameafter);
928  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
929  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
930 
931  $ecmfile->filepath = $rel_dir;
932  $ecmfile->filename = $filename;
933  $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file
934  $ecmfile->fullpath_orig = $srcfile;
935  $ecmfile->gen_or_uploaded = 'unknown';
936  $ecmfile->description = ''; // indexed content
937  $ecmfile->keywords = ''; // keyword content
938  $resultecm = $ecmfile->create($user);
939  if ($resultecm < 0) {
940  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
941  }
942  } elseif ($resultecm < 0) {
943  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
944  }
945 
946  if ($resultecm > 0) {
947  $result = true;
948  } else {
949  $result = false;
950  }
951  }
952  }
953 
954  if (empty($newmask)) {
955  $newmask = empty($conf->global->MAIN_UMASK) ? '0755' : $conf->global->MAIN_UMASK;
956  }
957  $newmaskdec = octdec($newmask);
958  // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
959  // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
960  // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories
961  @chmod($newpathofdestfile, $newmaskdec);
962  }
963 
964  return $result;
965 }
966 
978 function dol_move_dir($srcdir, $destdir, $overwriteifexists = 1, $indexdatabase = 1, $renamedircontent = 1)
979 {
980 
981  global $user, $db, $conf;
982  $result = false;
983 
984  dol_syslog("files.lib.php::dol_move_dir srcdir=".$srcdir." destdir=".$destdir." overwritifexists=".$overwriteifexists." indexdatabase=".$indexdatabase." renamedircontent=".$renamedircontent);
985  $srcexists = dol_is_dir($srcdir);
986  $srcbasename = basename($srcdir);
987  $destexists = dol_is_dir($destdir);
988 
989  if (!$srcexists) {
990  dol_syslog("files.lib.php::dol_move_dir srcdir does not exists. we ignore the move request.");
991  return false;
992  }
993 
994  if ($overwriteifexists || !$destexists) {
995  $newpathofsrcdir = dol_osencode($srcdir);
996  $newpathofdestdir = dol_osencode($destdir);
997 
998  $result = @rename($newpathofsrcdir, $newpathofdestdir);
999 
1000  if ($result && $renamedircontent) {
1001  if (file_exists($newpathofdestdir)) {
1002  $destbasename = basename($newpathofdestdir);
1003  $files = dol_dir_list($newpathofdestdir);
1004  if (!empty($files) && is_array($files)) {
1005  foreach ($files as $key => $file) {
1006  if (!file_exists($file["fullname"])) continue;
1007  $filepath = $file["path"];
1008  $oldname = $file["name"];
1009 
1010  $newname = str_replace($srcbasename, $destbasename, $oldname);
1011  if (!empty($newname) && $newname !== $oldname) {
1012  if ($file["type"] == "dir") {
1013  $res = dol_move_dir($filepath.'/'.$oldname, $filepath.'/'.$newname, $overwriteifexists, $indexdatabase, $renamedircontent);
1014  } else {
1015  $res = dol_move($filepath.'/'.$oldname, $filepath.'/'.$newname);
1016  }
1017  if (!$res) {
1018  return $result;
1019  }
1020  }
1021  }
1022  $result = true;
1023  }
1024  }
1025  }
1026  }
1027  return $result;
1028 }
1029 
1037 function dol_unescapefile($filename)
1038 {
1039  // Remove path information and dots around the filename, to prevent uploading
1040  // into different directories or replacing hidden system files.
1041  // Also remove control characters and spaces (\x00..\x20) around the filename:
1042  return trim(basename($filename), ".\x00..\x20");
1043 }
1044 
1045 
1052 function dolCheckVirus($src_file)
1053 {
1054  global $conf, $db;
1055 
1056  if (!empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) {
1057  if (!class_exists('AntiVir')) {
1058  require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
1059  }
1060  $antivir = new AntiVir($db);
1061  $result = $antivir->dol_avscan_file($src_file);
1062  if ($result < 0) { // If virus or error, we stop here
1063  $reterrors = $antivir->errors;
1064  return $reterrors;
1065  }
1066  }
1067  return array();
1068 }
1069 
1070 
1091 function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $varfiles = 'addedfile', $upload_dir = '')
1092 {
1093  global $conf, $db, $user, $langs;
1094  global $object, $hookmanager;
1095 
1096  $reshook = 0;
1097  $file_name = $dest_file;
1098  $successcode = 1;
1099 
1100  if (empty($nohook)) {
1101  $reshook = $hookmanager->initHooks(array('fileslib'));
1102 
1103  $parameters = array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
1104  $reshook = $hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
1105  }
1106 
1107  if (empty($reshook)) {
1108  // If an upload error has been reported
1109  if ($uploaderrorcode) {
1110  switch ($uploaderrorcode) {
1111  case UPLOAD_ERR_INI_SIZE: // 1
1112  return 'ErrorFileSizeTooLarge';
1113  case UPLOAD_ERR_FORM_SIZE: // 2
1114  return 'ErrorFileSizeTooLarge';
1115  case UPLOAD_ERR_PARTIAL: // 3
1116  return 'ErrorPartialFile';
1117  case UPLOAD_ERR_NO_TMP_DIR: //
1118  return 'ErrorNoTmpDir';
1119  case UPLOAD_ERR_CANT_WRITE:
1120  return 'ErrorFailedToWriteInDir';
1121  case UPLOAD_ERR_EXTENSION:
1122  return 'ErrorUploadBlockedByAddon';
1123  default:
1124  break;
1125  }
1126  }
1127 
1128  // If we need to make a virus scan
1129  if (empty($disablevirusscan) && file_exists($src_file)) {
1130  $checkvirusarray = dolCheckVirus($src_file);
1131  if (count($checkvirusarray)) {
1132  dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: errors='.join(',', $checkvirusarray), LOG_WARNING);
1133  return 'ErrorFileIsInfectedWithAVirus: '.join(',', $checkvirusarray);
1134  }
1135  }
1136 
1137  // Security:
1138  // Disallow file with some extensions. We rename them.
1139  // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
1140  if (isAFileWithExecutableContent($dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) {
1141  // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
1142  $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
1143  if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
1144  $publicmediasdirwithslash .= '/';
1145  }
1146 
1147  if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
1148  $file_name .= '.noexe';
1149  $successcode = 2;
1150  }
1151  }
1152 
1153  // Security:
1154  // We refuse cache files/dirs, upload using .. and pipes into filenames.
1155  if (preg_match('/^\./', basename($src_file)) || preg_match('/\.\./', $src_file) || preg_match('/[<>|]/', $src_file)) {
1156  dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
1157  return -1;
1158  }
1159 
1160  // Security:
1161  // We refuse cache files/dirs, upload using .. and pipes into filenames.
1162  if (preg_match('/^\./', basename($dest_file)) || preg_match('/\.\./', $dest_file) || preg_match('/[<>|]/', $dest_file)) {
1163  dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
1164  return -2;
1165  }
1166  }
1167 
1168  if ($reshook < 0) { // At least one blocking error returned by one hook
1169  $errmsg = join(',', $hookmanager->errors);
1170  if (empty($errmsg)) {
1171  $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1172  }
1173  return $errmsg;
1174  } elseif (empty($reshook)) {
1175  // The file functions must be in OS filesystem encoding.
1176  $src_file_osencoded = dol_osencode($src_file);
1177  $file_name_osencoded = dol_osencode($file_name);
1178 
1179  // Check if destination dir is writable
1180  if (!is_writable(dirname($file_name_osencoded))) {
1181  dol_syslog("Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded)." is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1182  return 'ErrorDirNotWritable';
1183  }
1184 
1185  // Check if destination file already exists
1186  if (!$allowoverwrite) {
1187  if (file_exists($file_name_osencoded)) {
1188  dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1189  return 'ErrorFileAlreadyExists';
1190  }
1191  } else { // We are allowed to erase
1192  if (is_dir($file_name_osencoded)) { // If there is a directory with name of file to create
1193  dol_syslog("Files.lib::dol_move_uploaded_file A directory with name ".$file_name." already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
1194  return 'ErrorDirWithFileNameAlreadyExists';
1195  }
1196  }
1197 
1198  // Move file
1199  $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1200  if ($return) {
1201  if (!empty($conf->global->MAIN_UMASK)) {
1202  @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1203  }
1204  dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
1205  return $successcode; // Success
1206  } else {
1207  dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
1208  return -3; // Unknown error
1209  }
1210  }
1211 
1212  return $successcode; // Success
1213 }
1214 
1230 function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, $object = null, $allowdotdot = false, $indexdatabase = 1, $nolog = 0)
1231 {
1232  global $db, $conf, $user, $langs;
1233  global $hookmanager;
1234 
1235  // Load translation files required by the page
1236  $langs->loadLangs(array('other', 'errors'));
1237 
1238  if (empty($nolog)) {
1239  dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
1240  }
1241 
1242  // Security:
1243  // We refuse transversal using .. and pipes into filenames.
1244  if ((!$allowdotdot && preg_match('/\.\./', $file)) || preg_match('/[<>|]/', $file)) {
1245  dol_syslog("Refused to delete file ".$file, LOG_WARNING);
1246  return false;
1247  }
1248 
1249  $reshook = 0;
1250  if (empty($nohook)) {
1251  $hookmanager->initHooks(array('fileslib'));
1252 
1253  $parameters = array(
1254  'GET' => $_GET,
1255  'file' => $file,
1256  'disableglob'=> $disableglob,
1257  'nophperrors' => $nophperrors
1258  );
1259  $reshook = $hookmanager->executeHooks('deleteFile', $parameters, $object);
1260  }
1261 
1262  if (empty($nohook) && $reshook != 0) { // reshook = 0 to do standard actions, 1 = ok and replace, -1 = ko
1263  dol_syslog("reshook=".$reshook);
1264  if ($reshook < 0) {
1265  return false;
1266  }
1267  return true;
1268  } else {
1269  $file_osencoded = dol_osencode($file); // New filename encoded in OS filesystem encoding charset
1270  if (empty($disableglob) && !empty($file_osencoded)) {
1271  $ok = true;
1272  $globencoded = str_replace('[', '\[', $file_osencoded);
1273  $globencoded = str_replace(']', '\]', $globencoded);
1274  $listofdir = glob($globencoded);
1275  if (!empty($listofdir) && is_array($listofdir)) {
1276  foreach ($listofdir as $filename) {
1277  if ($nophperrors) {
1278  $ok = @unlink($filename);
1279  } else {
1280  $ok = unlink($filename);
1281  }
1282 
1283  // If it fails and it is because of the missing write permission on parent dir
1284  if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1285  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);
1286  @chmod(dirname($filename), fileperms(dirname($filename)) | 0200);
1287  // Now we retry deletion
1288  if ($nophperrors) {
1289  $ok = @unlink($filename);
1290  } else {
1291  $ok = unlink($filename);
1292  }
1293  }
1294 
1295  if ($ok) {
1296  if (empty($nolog)) {
1297  dol_syslog("Removed file ".$filename, LOG_DEBUG);
1298  }
1299 
1300  // Delete entry into ecm database
1301  $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filename);
1302  if (!preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) { // If not a tmp file
1303  if (is_object($db) && $indexdatabase) { // $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
1304  $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
1305  $rel_filetodelete = preg_replace('/\.noexe$/', '', $rel_filetodelete);
1306 
1307  dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1308  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1309  $ecmfile = new EcmFiles($db);
1310  $result = $ecmfile->fetch(0, '', $rel_filetodelete);
1311  if ($result >= 0 && $ecmfile->id > 0) {
1312  $result = $ecmfile->delete($user);
1313  }
1314  if ($result < 0) {
1315  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1316  }
1317  }
1318  }
1319  } else {
1320  dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
1321  // TODO Failure to remove can be because file was already removed or because of permission
1322  // If error because it does not exists, we should return true, and we should return false if this is a permission problem
1323  }
1324  }
1325  } else {
1326  dol_syslog("No files to delete found", LOG_DEBUG);
1327  }
1328  } else {
1329  $ok = false;
1330  if ($nophperrors) {
1331  $ok = @unlink($file_osencoded);
1332  } else {
1333  $ok = unlink($file_osencoded);
1334  }
1335  if ($ok) {
1336  if (empty($nolog)) {
1337  dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
1338  }
1339  } else {
1340  dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
1341  }
1342  }
1343 
1344  return $ok;
1345  }
1346 }
1347 
1357 function dol_delete_dir($dir, $nophperrors = 0)
1358 {
1359  // Security:
1360  // We refuse transversal using .. and pipes into filenames.
1361  if (preg_match('/\.\./', $dir) || preg_match('/[<>|]/', $dir)) {
1362  dol_syslog("Refused to delete dir ".$dir, LOG_WARNING);
1363  return false;
1364  }
1365 
1366  $dir_osencoded = dol_osencode($dir);
1367  return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1368 }
1369 
1382 function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0, $indexdatabase = 1, $nolog = 0)
1383 {
1384  if (empty($nolog)) {
1385  dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1386  }
1387  if (dol_is_dir($dir)) {
1388  $dir_osencoded = dol_osencode($dir);
1389  if ($handle = opendir("$dir_osencoded")) {
1390  while (false !== ($item = readdir($handle))) {
1391  if (!utf8_check($item)) {
1392  $item = utf8_encode($item); // should be useless
1393  }
1394 
1395  if ($item != "." && $item != "..") {
1396  if (is_dir(dol_osencode("$dir/$item")) && !is_link(dol_osencode("$dir/$item"))) {
1397  $count = dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted, $indexdatabase, $nolog);
1398  } else {
1399  $result = dol_delete_file("$dir/$item", 1, $nophperrors, 0, null, false, $indexdatabase, $nolog);
1400  $count++;
1401  if ($result) {
1402  $countdeleted++;
1403  }
1404  //else print 'Error on '.$item."\n";
1405  }
1406  }
1407  }
1408  closedir($handle);
1409 
1410  // Delete also the main directory
1411  if (empty($onlysub)) {
1412  $result = dol_delete_dir($dir, $nophperrors);
1413  $count++;
1414  if ($result) {
1415  $countdeleted++;
1416  }
1417  //else print 'Error on '.$dir."\n";
1418  }
1419  }
1420  }
1421 
1422  return $count;
1423 }
1424 
1425 
1434 function dol_delete_preview($object)
1435 {
1436  global $langs, $conf;
1437 
1438  // Define parent dir of elements
1439  $element = $object->element;
1440 
1441  if ($object->element == 'order_supplier') {
1442  $dir = $conf->fournisseur->commande->dir_output;
1443  } elseif ($object->element == 'invoice_supplier') {
1444  $dir = $conf->fournisseur->facture->dir_output;
1445  } elseif ($object->element == 'project') {
1446  $dir = $conf->project->dir_output;
1447  } elseif ($object->element == 'shipping') {
1448  $dir = $conf->expedition->dir_output.'/sending';
1449  } elseif ($object->element == 'delivery') {
1450  $dir = $conf->expedition->dir_output.'/receipt';
1451  } elseif ($object->element == 'fichinter') {
1452  $dir = $conf->ficheinter->dir_output;
1453  } else {
1454  $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
1455  }
1456 
1457  if (empty($dir)) {
1458  return 'ErrorObjectNoSupportedByFunction';
1459  }
1460 
1461  $refsan = dol_sanitizeFileName($object->ref);
1462  $dir = $dir."/".$refsan;
1463  $filepreviewnew = $dir."/".$refsan.".pdf_preview.png";
1464  $filepreviewnewbis = $dir."/".$refsan.".pdf_preview-0.png";
1465  $filepreviewold = $dir."/".$refsan.".pdf.png";
1466 
1467  // For new preview files
1468  if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
1469  if (!dol_delete_file($filepreviewnew, 1)) {
1470  $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnew);
1471  return 0;
1472  }
1473  }
1474  if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
1475  if (!dol_delete_file($filepreviewnewbis, 1)) {
1476  $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnewbis);
1477  return 0;
1478  }
1479  }
1480  // For old preview files
1481  if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
1482  if (!dol_delete_file($filepreviewold, 1)) {
1483  $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewold);
1484  return 0;
1485  }
1486  } else {
1487  $multiple = $filepreviewold.".";
1488  for ($i = 0; $i < 20; $i++) {
1489  $preview = $multiple.$i;
1490 
1491  if (file_exists($preview) && is_writable($preview)) {
1492  if (!dol_delete_file($preview, 1)) {
1493  $object->error = $langs->trans("ErrorFailedToOpenFile", $preview);
1494  return 0;
1495  }
1496  }
1497  }
1498  }
1499 
1500  return 1;
1501 }
1502 
1511 function dol_meta_create($object)
1512 {
1513  global $conf;
1514 
1515  // Create meta file
1516  if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) {
1517  return 0; // By default, no metafile.
1518  }
1519 
1520  // Define parent dir of elements
1521  $element = $object->element;
1522 
1523  if ($object->element == 'order_supplier') {
1524  $dir = $conf->fournisseur->dir_output.'/commande';
1525  } elseif ($object->element == 'invoice_supplier') {
1526  $dir = $conf->fournisseur->dir_output.'/facture';
1527  } elseif ($object->element == 'project') {
1528  $dir = $conf->project->dir_output;
1529  } elseif ($object->element == 'shipping') {
1530  $dir = $conf->expedition->dir_output.'/sending';
1531  } elseif ($object->element == 'delivery') {
1532  $dir = $conf->expedition->dir_output.'/receipt';
1533  } elseif ($object->element == 'fichinter') {
1534  $dir = $conf->ficheinter->dir_output;
1535  } else {
1536  $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
1537  }
1538 
1539  if ($dir) {
1540  $object->fetch_thirdparty();
1541 
1542  $objectref = dol_sanitizeFileName($object->ref);
1543  $dir = $dir."/".$objectref;
1544  $file = $dir."/".$objectref.".meta";
1545 
1546  if (!is_dir($dir)) {
1547  dol_mkdir($dir);
1548  }
1549 
1550  if (is_dir($dir)) {
1551  $nblines = count($object->lines);
1552  $client = $object->thirdparty->name." ".$object->thirdparty->address." ".$object->thirdparty->zip." ".$object->thirdparty->town;
1553  $meta = "REFERENCE=\"".$object->ref."\"
1554  DATE=\"" . dol_print_date($object->date, '')."\"
1555  NB_ITEMS=\"" . $nblines."\"
1556  CLIENT=\"" . $client."\"
1557  AMOUNT_EXCL_TAX=\"" . $object->total_ht."\"
1558  AMOUNT=\"" . $object->total_ttc."\"\n";
1559 
1560  for ($i = 0; $i < $nblines; $i++) {
1561  //Pour les articles
1562  $meta .= "ITEM_".$i."_QUANTITY=\"".$object->lines[$i]->qty."\"
1563  ITEM_" . $i."_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht."\"
1564  ITEM_" . $i."_VAT=\"".$object->lines[$i]->tva_tx."\"
1565  ITEM_" . $i."_DESCRIPTION=\"".str_replace("\r\n", "", nl2br($object->lines[$i]->desc))."\"
1566  ";
1567  }
1568  }
1569 
1570  $fp = fopen($file, "w");
1571  fputs($fp, $meta);
1572  fclose($fp);
1573  if (!empty($conf->global->MAIN_UMASK)) {
1574  @chmod($file, octdec($conf->global->MAIN_UMASK));
1575  }
1576 
1577  return 1;
1578  } else {
1579  dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
1580  }
1581 
1582  return 0;
1583 }
1584 
1585 
1586 
1595 function dol_init_file_process($pathtoscan = '', $trackid = '')
1596 {
1597  $listofpaths = array();
1598  $listofnames = array();
1599  $listofmimes = array();
1600 
1601  if ($pathtoscan) {
1602  $listoffiles = dol_dir_list($pathtoscan, 'files');
1603  foreach ($listoffiles as $key => $val) {
1604  $listofpaths[] = $val['fullname'];
1605  $listofnames[] = $val['name'];
1606  $listofmimes[] = dol_mimetype($val['name']);
1607  }
1608  }
1609  $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
1610  $_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
1611  $_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
1612  $_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
1613 }
1614 
1615 
1633 function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1, $object = null)
1634 {
1635  global $db, $user, $conf, $langs;
1636 
1637  $res = 0;
1638 
1639  if (!empty($_FILES[$varfiles])) { // For view $_FILES[$varfiles]['error']
1640  dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
1641 
1642  $result = dol_mkdir($upload_dir);
1643  // var_dump($result);exit;
1644  if ($result >= 0) {
1645  $TFile = $_FILES[$varfiles];
1646  if (!is_array($TFile['name'])) {
1647  foreach ($TFile as $key => &$val) {
1648  $val = array($val);
1649  }
1650  }
1651 
1652  $nbfile = count($TFile['name']);
1653  $nbok = 0;
1654  for ($i = 0; $i < $nbfile; $i++) {
1655  if (empty($TFile['name'][$i])) {
1656  continue; // For example, when submitting a form with no file name
1657  }
1658 
1659  // Define $destfull (path to file including filename) and $destfile (only filename)
1660  $destfull = $upload_dir."/".$TFile['name'][$i];
1661  $destfile = $TFile['name'][$i];
1662  $destfilewithoutext = preg_replace('/\.[^\.]+$/', '', $destfile);
1663 
1664  if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
1665  $destfull = $upload_dir."/".preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
1666  $destfile = preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
1667  }
1668 
1669  $filenameto = basename($destfile);
1670  if (preg_match('/^\./', $filenameto)) {
1671  $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
1672  setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
1673  break;
1674  }
1675 
1676  // dol_sanitizeFileName the file name and lowercase extension
1677  $info = pathinfo($destfull);
1678  $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
1679  $info = pathinfo($destfile);
1680 
1681  $destfile = dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
1682 
1683  // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
1684  // this function is also applied when we rename and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
1685  $destfile = dol_string_nohtmltag($destfile);
1686  $destfull = dol_string_nohtmltag($destfull);
1687 
1688  // Move file from temp directory to final directory. A .noexe may also be appended on file name.
1689  $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles, $upload_dir);
1690 
1691  if (is_numeric($resupload) && $resupload > 0) { // $resupload can be 'ErrorFileAlreadyExists'
1692  global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
1693 
1694  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1695 
1696  // Generate thumbs.
1697  if ($generatethumbs) {
1698  if (image_format_supported($destfull) == 1) {
1699  // Create thumbs
1700  // We can't use $object->addThumbs here because there is no $object known
1701 
1702  // Used on logon for example
1703  $imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
1704  // Create mini thumbs for image (Ratio is near 16/9)
1705  // Used on menu or for setup page for example
1706  $imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
1707  }
1708  }
1709 
1710  // Update session
1711  if (empty($donotupdatesession)) {
1712  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1713  $formmail = new FormMail($db);
1714  $formmail->trackid = $trackid;
1715  $formmail->add_attached_files($destfull, $destfile, $TFile['type'][$i]);
1716  }
1717 
1718  // Update index table of files (llx_ecm_files)
1719  if ($donotupdatesession == 1) {
1720  $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', 0, $object);
1721  if ($result < 0) {
1722  if ($allowoverwrite) {
1723  // Do not show error message. We can have an error due to DB_ERROR_RECORD_ALREADY_EXISTS
1724  } else {
1725  setEventMessages('WarningFailedToAddFileIntoDatabaseIndex', '', 'warnings');
1726  }
1727  }
1728  }
1729 
1730  $nbok++;
1731  } else {
1732  $langs->load("errors");
1733  if ($resupload < 0) { // Unknown error
1734  setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
1735  } elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) { // Files infected by a virus
1736  setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
1737  } else // Known error
1738  {
1739  setEventMessages($langs->trans($resupload), null, 'errors');
1740  }
1741  }
1742  }
1743  if ($nbok > 0) {
1744  $res = 1;
1745  setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
1746  }
1747  } else {
1748  setEventMessages($langs->trans("ErrorFailedToCreateDir", $upload_dir), null, 'errors');
1749  }
1750  } elseif ($link) {
1751  require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
1752  $linkObject = new Link($db);
1753  $linkObject->entity = $conf->entity;
1754  $linkObject->url = $link;
1755  $linkObject->objecttype = GETPOST('objecttype', 'alpha');
1756  $linkObject->objectid = GETPOST('objectid', 'int');
1757  $linkObject->label = GETPOST('label', 'alpha');
1758  $res = $linkObject->create($user);
1759  $langs->load('link');
1760  if ($res > 0) {
1761  setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
1762  } else {
1763  setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
1764  }
1765  } else {
1766  $langs->load("errors");
1767  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
1768  }
1769 
1770  return $res;
1771 }
1772 
1773 
1785 function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletefile = 1, $trackid = '')
1786 {
1787  global $db, $user, $conf, $langs, $_FILES;
1788 
1789  $keytodelete = $filenb;
1790  $keytodelete--;
1791 
1792  $listofpaths = array();
1793  $listofnames = array();
1794  $listofmimes = array();
1795  $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
1796  if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
1797  $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
1798  }
1799  if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
1800  $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
1801  }
1802  if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
1803  $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
1804  }
1805 
1806  if ($keytodelete >= 0) {
1807  $pathtodelete = $listofpaths[$keytodelete];
1808  $filetodelete = $listofnames[$keytodelete];
1809  if (empty($donotdeletefile)) {
1810  $result = dol_delete_file($pathtodelete, 1); // The delete of ecm database is inside the function dol_delete_file
1811  } else {
1812  $result = 0;
1813  }
1814  if ($result >= 0) {
1815  if (empty($donotdeletefile)) {
1816  $langs->load("other");
1817  setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
1818  }
1819  if (empty($donotupdatesession)) {
1820  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1821  $formmail = new FormMail($db);
1822  $formmail->trackid = $trackid;
1823  $formmail->remove_attached_files($keytodelete);
1824  }
1825  }
1826  }
1827 }
1828 
1829 
1843 function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0, $object = null)
1844 {
1845  global $db, $user, $conf;
1846 
1847  $result = 0;
1848 
1849  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
1850 
1851  if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
1852  $filename = basename(preg_replace('/\.noexe$/', '', $file));
1853  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1854  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1855 
1856  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1857  $ecmfile = new EcmFiles($db);
1858  $ecmfile->filepath = $rel_dir;
1859  $ecmfile->filename = $filename;
1860  $ecmfile->label = md5_file(dol_osencode($dir.'/'.$file)); // MD5 of file content
1861  $ecmfile->fullpath_orig = $fullpathorig;
1862  $ecmfile->gen_or_uploaded = $mode;
1863  $ecmfile->description = ''; // indexed content
1864  $ecmfile->keywords = ''; // keyword content
1865 
1866  if (is_object($object) && $object->id > 0) {
1867  $ecmfile->src_object_id = $object->id;
1868  if (isset($object->table_element)) {
1869  $ecmfile->src_object_type = $object->table_element;
1870  } else {
1871  dol_syslog('Error: object ' . get_class($object) . ' has no table_element attribute.');
1872  return -1;
1873  }
1874  if (isset($object->src_object_description)) $ecmfile->description = $object->src_object_description;
1875  if (isset($object->src_object_keywords)) $ecmfile->keywords = $object->src_object_keywords;
1876  }
1877 
1878  if (!empty($conf->global->MAIN_FORCE_SHARING_ON_ANY_UPLOADED_FILE)) {
1879  $setsharekey = 1;
1880  }
1881 
1882  if ($setsharekey) {
1883  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1884  $ecmfile->share = getRandomPassword(true);
1885  }
1886 
1887  $result = $ecmfile->create($user);
1888  if ($result < 0) {
1889  dol_syslog($ecmfile->error);
1890  }
1891  }
1892 
1893  return $result;
1894 }
1895 
1904 function deleteFilesIntoDatabaseIndex($dir, $file, $mode = 'uploaded')
1905 {
1906  global $conf, $db, $user;
1907 
1908  $error = 0;
1909 
1910  if (empty($dir)) {
1911  dol_syslog("deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
1912  return -1;
1913  }
1914 
1915  $db->begin();
1916 
1917  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
1918 
1919  $filename = basename($file);
1920  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1921  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1922 
1923  if (!$error) {
1924  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'ecm_files';
1925  $sql .= ' WHERE entity = '.$conf->entity;
1926  $sql .= " AND filepath = '".$db->escape($rel_dir)."'";
1927  if ($file) {
1928  $sql .= " AND filename = '".$db->escape($file)."'";
1929  }
1930  if ($mode) {
1931  $sql .= " AND gen_or_uploaded = '".$db->escape($mode)."'";
1932  }
1933 
1934  $resql = $db->query($sql);
1935  if (!$resql) {
1936  $error++;
1937  dol_syslog(__METHOD__.' '.$db->lasterror(), LOG_ERR);
1938  }
1939  }
1940 
1941  // Commit or rollback
1942  if ($error) {
1943  $db->rollback();
1944  return -1 * $error;
1945  } else {
1946  $db->commit();
1947  return 1;
1948  }
1949 }
1950 
1951 
1963 function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '', $page = '')
1964 {
1965  global $langs;
1966  if (class_exists('Imagick')) {
1967  $image = new Imagick();
1968  try {
1969  $filetoconvert = $fileinput.(($page != '') ? '['.$page.']' : '');
1970  //var_dump($filetoconvert);
1971  $ret = $image->readImage($filetoconvert);
1972  } catch (Exception $e) {
1973  $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
1974  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);
1975  return 0;
1976  }
1977  if ($ret) {
1978  $ret = $image->setImageFormat($ext);
1979  if ($ret) {
1980  if (empty($fileoutput)) {
1981  $fileoutput = $fileinput.".".$ext;
1982  }
1983 
1984  $count = $image->getNumberImages();
1985 
1986  if (!dol_is_file($fileoutput) || is_writeable($fileoutput)) {
1987  try {
1988  $ret = $image->writeImages($fileoutput, true);
1989  } catch (Exception $e) {
1990  dol_syslog($e->getMessage(), LOG_WARNING);
1991  }
1992  } else {
1993  dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
1994  }
1995  if ($ret) {
1996  return $count;
1997  } else {
1998  return -3;
1999  }
2000  } else {
2001  return -2;
2002  }
2003  } else {
2004  return -1;
2005  }
2006  } else {
2007  return 0;
2008  }
2009 }
2010 
2011 
2022 function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring = null)
2023 {
2024  global $conf;
2025 
2026  $foundhandler = 0;
2027 
2028  try {
2029  dol_syslog("dol_compress_file mode=".$mode." inputfile=".$inputfile." outputfile=".$outputfile);
2030 
2031  $data = implode("", file(dol_osencode($inputfile)));
2032  if ($mode == 'gz') {
2033  $foundhandler = 1;
2034  $compressdata = gzencode($data, 9);
2035  } elseif ($mode == 'bz') {
2036  $foundhandler = 1;
2037  $compressdata = bzcompress($data, 9);
2038  } elseif ($mode == 'zstd') {
2039  $foundhandler = 1;
2040  $compressdata = zstd_compress($data, 9);
2041  } elseif ($mode == 'zip') {
2042  if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) {
2043  $foundhandler = 1;
2044 
2045  $rootPath = realpath($inputfile);
2046 
2047  dol_syslog("Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.' rootPath='.$rootPath);
2048  $zip = new ZipArchive;
2049 
2050  if ($zip->open($outputfile, ZipArchive::CREATE) !== true) {
2051  $errorstring = "dol_compress_file failure - Failed to open file ".$outputfile."\n";
2052  dol_syslog($errorstring, LOG_ERR);
2053 
2054  global $errormsg;
2055  $errormsg = $errorstring;
2056 
2057  return -6;
2058  }
2059 
2060  // Create recursive directory iterator
2062  $files = new RecursiveIteratorIterator(
2063  new RecursiveDirectoryIterator($rootPath),
2064  RecursiveIteratorIterator::LEAVES_ONLY
2065  );
2066 
2067  foreach ($files as $name => $file) {
2068  // Skip directories (they would be added automatically)
2069  if (!$file->isDir()) {
2070  // Get real and relative path for current file
2071  $filePath = $file->getPath(); // the full path with filename using the $inputdir root.
2072  $fileName = $file->getFilename();
2073  $fileFullRealPath = $file->getRealPath(); // the full path with name and transformed to use real path directory.
2074 
2075  //$relativePath = substr($fileFullRealPath, strlen($rootPath) + 1);
2076  $relativePath = substr(($filePath ? $filePath.'/' : '').$fileName, strlen($rootPath) + 1);
2077 
2078  // Add current file to archive
2079  $zip->addFile($fileFullRealPath, $relativePath);
2080  }
2081  }
2082 
2083  // Zip archive will be created only after closing object
2084  $zip->close();
2085 
2086  dol_syslog("dol_compress_file success - ".count($zip->numFiles)." files");
2087  return 1;
2088  }
2089 
2090  if (defined('ODTPHP_PATHTOPCLZIP')) {
2091  $foundhandler = 1;
2092 
2093  include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
2094  $archive = new PclZip($outputfile);
2095  $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2096 
2097  if ($result === 0) {
2098  global $errormsg;
2099  $errormsg = $archive->errorInfo(true);
2100 
2101  if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
2102  $errorstring = "PCLZIP_ERR_WRITE_OPEN_FAIL";
2103  dol_syslog("dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
2104  return -4;
2105  }
2106 
2107  $errorstring = "dol_compress_file error archive->errorCode = ".$archive->errorCode()." errormsg=".$errormsg;
2108  dol_syslog("dol_compress_file failure - ".$errormsg, LOG_ERR);
2109  return -3;
2110  } else {
2111  dol_syslog("dol_compress_file success - ".count($result)." files");
2112  return 1;
2113  }
2114  }
2115  }
2116 
2117  if ($foundhandler) {
2118  $fp = fopen($outputfile, "w");
2119  fwrite($fp, $compressdata);
2120  fclose($fp);
2121  return 1;
2122  } else {
2123  $errorstring = "Try to zip with format ".$mode." with no handler for this format";
2124  dol_syslog($errorstring, LOG_ERR);
2125 
2126  global $errormsg;
2127  $errormsg = $errorstring;
2128  return -2;
2129  }
2130  } catch (Exception $e) {
2131  global $langs, $errormsg;
2132  $langs->load("errors");
2133  $errormsg = $langs->trans("ErrorFailedToWriteInDir");
2134 
2135  $errorstring = "Failed to open file ".$outputfile;
2136  dol_syslog($errorstring, LOG_ERR);
2137  return -1;
2138  }
2139 }
2140 
2148 function dol_uncompress($inputfile, $outputdir)
2149 {
2150  global $conf, $langs, $db;
2151 
2152  $fileinfo = pathinfo($inputfile);
2153  $fileinfo["extension"] = strtolower($fileinfo["extension"]);
2154 
2155  if ($fileinfo["extension"] == "zip") {
2156  if (defined('ODTPHP_PATHTOPCLZIP') && empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS)) {
2157  dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
2158  include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
2159  $archive = new PclZip($inputfile);
2160 
2161  // We create output dir manually, so it uses the correct permission (When created by the archive->extract, dir is rwx for everybody).
2162  dol_mkdir(dol_sanitizePathName($outputdir));
2163 
2164  // Extract into outputdir, but only files that match the regex '/^((?!\.\.).)*$/' that means "does not include .."
2165  $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG, '/^((?!\.\.).)*$/');
2166 
2167  if (!is_array($result) && $result <= 0) {
2168  return array('error'=>$archive->errorInfo(true));
2169  } else {
2170  $ok = 1;
2171  $errmsg = '';
2172  // Loop on each file to check result for unzipping file
2173  foreach ($result as $key => $val) {
2174  if ($val['status'] == 'path_creation_fail') {
2175  $langs->load("errors");
2176  $ok = 0;
2177  $errmsg = $langs->trans("ErrorFailToCreateDir", $val['filename']);
2178  break;
2179  }
2180  }
2181 
2182  if ($ok) {
2183  return array();
2184  } else {
2185  return array('error'=>$errmsg);
2186  }
2187  }
2188  }
2189 
2190  if (class_exists('ZipArchive')) { // Must install php-zip to have it
2191  dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
2192  $zip = new ZipArchive;
2193  $res = $zip->open($inputfile);
2194  if ($res === true) {
2195  //$zip->extractTo($outputdir.'/');
2196  // We must extract one file at time so we can check that file name does not contains '..' to avoid transversal path of zip built for example using
2197  // python3 path_traversal_archiver.py <Created_file_name> test.zip -l 10 -p tmp/
2198  // with -l is the range of dot to go back in path.
2199  // and path_traversal_archiver.py found at https://github.com/Alamot/code-snippets/blob/master/path_traversal/path_traversal_archiver.py
2200  for ($i = 0; $i < $zip->numFiles; $i++) {
2201  if (preg_match('/\.\./', $zip->getNameIndex($i))) {
2202  dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
2203  continue; // Discard the file
2204  }
2205  $zip->extractTo($outputdir.'/', array($zip->getNameIndex($i)));
2206  }
2207 
2208  $zip->close();
2209  return array();
2210  } else {
2211  return array('error'=>'ErrUnzipFails');
2212  }
2213  }
2214 
2215  return array('error'=>'ErrNoZipEngine');
2216  } elseif (in_array($fileinfo["extension"], array('gz', 'bz2', 'zst'))) {
2217  include_once DOL_DOCUMENT_ROOT."/core/class/utils.class.php";
2218  $utils = new Utils($db);
2219 
2220  dol_mkdir(dol_sanitizePathName($outputdir));
2221  $outputfilename = escapeshellcmd(dol_sanitizePathName($outputdir).'/'.dol_sanitizeFileName($fileinfo["filename"]));
2222  dol_delete_file($outputfilename.'.tmp');
2223  dol_delete_file($outputfilename.'.err');
2224 
2225  $extension = strtolower(pathinfo($fileinfo["filename"], PATHINFO_EXTENSION));
2226  if ($extension == "tar") {
2227  $cmd = 'tar -C '.escapeshellcmd(dol_sanitizePathName($outputdir)).' -xvf '.escapeshellcmd(dol_sanitizePathName($fileinfo["dirname"]).'/'.dol_sanitizeFileName($fileinfo["basename"]));
2228 
2229  $resarray = $utils->executeCLI($cmd, $outputfilename.'.tmp', 0, $outputfilename.'.err', 0);
2230  if ($resarray["result"] != 0) {
2231  $resarray["error"] .= file_get_contents($outputfilename.'.err');
2232  }
2233  } else {
2234  $program = "";
2235  if ($fileinfo["extension"] == "gz") {
2236  $program = 'gzip';
2237  } elseif ($fileinfo["extension"] == "bz2") {
2238  $program = 'bzip2';
2239  } elseif ($fileinfo["extension"] == "zst") {
2240  $program = 'zstd';
2241  } else {
2242  return array('error'=>'ErrorBadFileExtension');
2243  }
2244  $cmd = $program.' -dc '.escapeshellcmd(dol_sanitizePathName($fileinfo["dirname"]).'/'.dol_sanitizeFileName($fileinfo["basename"]));
2245  $cmd .= ' > '.$outputfilename;
2246 
2247  $resarray = $utils->executeCLI($cmd, $outputfilename.'.tmp', 0, null, 1, $outputfilename.'.err');
2248  if ($resarray["result"] != 0) {
2249  $errfilecontent = @file_get_contents($outputfilename.'.err');
2250  if ($errfilecontent) {
2251  $resarray["error"] .= " - ".$errfilecontent;
2252  }
2253  }
2254  }
2255  return $resarray["result"] != 0 ? array('error' => $resarray["error"]) : array();
2256  }
2257 
2258  return array('error'=>'ErrorBadFileExtension');
2259 }
2260 
2261 
2272 function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '')
2273 {
2274  $foundhandler = 0;
2275 
2276  dol_syslog("Try to zip dir ".$inputdir." into ".$outputfile." mode=".$mode);
2277 
2278  if (!dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
2279  global $langs, $errormsg;
2280  $langs->load("errors");
2281  $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
2282  return -3;
2283  }
2284 
2285  try {
2286  if ($mode == 'gz') {
2287  $foundhandler = 0;
2288  } elseif ($mode == 'bz') {
2289  $foundhandler = 0;
2290  } elseif ($mode == 'zip') {
2291  /*if (defined('ODTPHP_PATHTOPCLZIP'))
2292  {
2293  $foundhandler=0; // TODO implement this
2294 
2295  include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
2296  $archive = new PclZip($outputfile);
2297  $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2298  //$archive->add($inputfile);
2299  return 1;
2300  }
2301  else*/
2302  //if (class_exists('ZipArchive') && ! empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS))
2303  if (class_exists('ZipArchive')) {
2304  $foundhandler = 1;
2305 
2306  // Initialize archive object
2307  $zip = new ZipArchive();
2308  $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2309  if (!$result) {
2310  global $langs, $errormsg;
2311  $langs->load("errors");
2312  $errormsg = $langs->trans("ErrorFailedToWriteInFile", $outputfile);
2313  return -4;
2314  }
2315 
2316  // Create recursive directory iterator
2317  // This does not return symbolic links
2319  $files = new RecursiveIteratorIterator(
2320  new RecursiveDirectoryIterator($inputdir),
2321  RecursiveIteratorIterator::LEAVES_ONLY
2322  );
2323 
2324  //var_dump($inputdir);
2325  foreach ($files as $name => $file) {
2326  // Skip directories (they would be added automatically)
2327  if (!$file->isDir()) {
2328  // Get real and relative path for current file
2329  $filePath = $file->getPath(); // the full path with filename using the $inputdir root.
2330  $fileName = $file->getFilename();
2331  $fileFullRealPath = $file->getRealPath(); // the full path with name and transformed to use real path directory.
2332 
2333  //$relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr($fileFullRealPath, strlen($inputdir) + 1);
2334  $relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr(($filePath ? $filePath.'/' : '').$fileName, strlen($inputdir) + 1);
2335 
2336  //var_dump($filePath);var_dump($fileFullRealPath);var_dump($relativePath);
2337  if (empty($excludefiles) || !preg_match($excludefiles, $fileFullRealPath)) {
2338  // Add current file to archive
2339  $zip->addFile($fileFullRealPath, $relativePath);
2340  }
2341  }
2342  }
2343 
2344  // Zip archive will be created only after closing object
2345  $zip->close();
2346 
2347  return 1;
2348  }
2349  }
2350 
2351  if (!$foundhandler) {
2352  dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR);
2353  return -2;
2354  } else {
2355  return 0;
2356  }
2357  } catch (Exception $e) {
2358  global $langs, $errormsg;
2359  $langs->load("errors");
2360  dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
2361  dol_syslog($e->getMessage(), LOG_ERR);
2362  $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
2363  return -1;
2364  }
2365 }
2366 
2367 
2368 
2379 function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$', '^\.'), $nohook = false, $mode = '')
2380 {
2381  $tmparray = dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook);
2382  return $tmparray[0];
2383 }
2384 
2398 function dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser = '', $refname = '', $mode = 'read')
2399 {
2400  global $conf, $db, $user, $hookmanager;
2401  global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2402  global $object;
2403 
2404  if (!is_object($fuser)) {
2405  $fuser = $user;
2406  }
2407 
2408  if (empty($modulepart)) {
2409  return 'ErrorBadParameter';
2410  }
2411  if (empty($entity)) {
2412  if (empty($conf->multicompany->enabled)) {
2413  $entity = 1;
2414  } else {
2415  $entity = 0;
2416  }
2417  }
2418  // Fix modulepart for backward compatibility
2419  if ($modulepart == 'users') {
2420  $modulepart = 'user';
2421  }
2422  if ($modulepart == 'tva') {
2423  $modulepart = 'tax-vat';
2424  }
2425 
2426  //print 'dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity;
2427  dol_syslog('dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
2428 
2429  // We define $accessallowed and $sqlprotectagainstexternals
2430  $accessallowed = 0;
2431  $sqlprotectagainstexternals = '';
2432  $ret = array();
2433 
2434  // Find the subdirectory name as the reference. For example original_file='10/myfile.pdf' -> refname='10'
2435  if (empty($refname)) {
2436  $refname = basename(dirname($original_file)."/");
2437  if ($refname == 'thumbs') {
2438  // If we get the thumbns directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
2439  $refname = basename(dirname(dirname($original_file))."/");
2440  }
2441  }
2442 
2443  // Define possible keys to use for permission check
2444  $lire = 'lire';
2445  $read = 'read';
2446  $download = 'download';
2447  if ($mode == 'write') {
2448  $lire = 'creer';
2449  $read = 'write';
2450  $download = 'upload';
2451  }
2452 
2453  // Wrapping for miscellaneous medias files
2454  if ($modulepart == 'medias' && !empty($dolibarr_main_data_root)) {
2455  if (empty($entity) || empty($conf->medias->multidir_output[$entity])) {
2456  return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2457  }
2458  $accessallowed = 1;
2459  $original_file = $conf->medias->multidir_output[$entity].'/'.$original_file;
2460  } elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root)) {
2461  // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
2462  $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
2463  $original_file = $dolibarr_main_data_root.'/'.$original_file;
2464  } elseif ($modulepart == 'doctemplates' && !empty($dolibarr_main_data_root)) {
2465  // Wrapping for doctemplates
2466  $accessallowed = $user->admin;
2467  $original_file = $dolibarr_main_data_root.'/doctemplates/'.$original_file;
2468  } elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
2469  // Wrapping for doctemplates of websites
2470  $accessallowed = ($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file)));
2471  $original_file = $dolibarr_main_data_root.'/doctemplates/websites/'.$original_file;
2472  } elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root)) {
2473  // Wrapping for *.zip package files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
2474  // Dir for custom dirs
2475  $tmp = explode(',', $dolibarr_main_document_root_alt);
2476  $dirins = $tmp[0];
2477 
2478  $accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
2479  $original_file = $dirins.'/'.$original_file;
2480  } elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output)) {
2481  // Wrapping for some images
2482  $accessallowed = 1;
2483  $original_file = $conf->mycompany->dir_output.'/'.$original_file;
2484  } elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output)) {
2485  // Wrapping for users photos
2486  $accessallowed = 0;
2487  if (preg_match('/^\d+\/photos\//', $original_file)) {
2488  $accessallowed = 1;
2489  }
2490  $original_file = $conf->user->dir_output.'/'.$original_file;
2491  } elseif (($modulepart == 'companylogo') && !empty($conf->mycompany->dir_output)) {
2492  // Wrapping for users logos
2493  $accessallowed = 1;
2494  $original_file = $conf->mycompany->dir_output.'/logos/'.$original_file;
2495  } elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output)) {
2496  // Wrapping for members photos
2497  $accessallowed = 0;
2498  if (preg_match('/^\d+\/photos\//', $original_file)) {
2499  $accessallowed = 1;
2500  }
2501  $original_file = $conf->adherent->dir_output.'/'.$original_file;
2502  } elseif ($modulepart == 'apercufacture' && !empty($conf->facture->multidir_output[$entity])) {
2503  // Wrapping pour les apercu factures
2504  if ($fuser->rights->facture->{$lire}) {
2505  $accessallowed = 1;
2506  }
2507  $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
2508  } elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity])) {
2509  // Wrapping pour les apercu propal
2510  if ($fuser->rights->propale->{$lire}) {
2511  $accessallowed = 1;
2512  }
2513  $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
2514  } elseif ($modulepart == 'apercucommande' && !empty($conf->commande->multidir_output[$entity])) {
2515  // Wrapping pour les apercu commande
2516  if ($fuser->rights->commande->{$lire}) {
2517  $accessallowed = 1;
2518  }
2519  $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
2520  } elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output)) {
2521  // Wrapping pour les apercu intervention
2522  if ($fuser->rights->ficheinter->{$lire}) {
2523  $accessallowed = 1;
2524  }
2525  $original_file = $conf->ficheinter->dir_output.'/'.$original_file;
2526  } elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->multidir_output[$entity])) {
2527  // Wrapping pour les apercu contrat
2528  if ($fuser->rights->contrat->{$lire}) {
2529  $accessallowed = 1;
2530  }
2531  $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file;
2532  } elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) {
2533  // Wrapping pour les apercu supplier proposal
2534  if ($fuser->rights->supplier_proposal->{$lire}) {
2535  $accessallowed = 1;
2536  }
2537  $original_file = $conf->supplier_proposal->dir_output.'/'.$original_file;
2538  } elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) {
2539  // Wrapping pour les apercu supplier order
2540  if ($fuser->rights->fournisseur->commande->{$lire}) {
2541  $accessallowed = 1;
2542  }
2543  $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
2544  } elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) {
2545  // Wrapping pour les apercu supplier invoice
2546  if ($fuser->rights->fournisseur->facture->{$lire}) {
2547  $accessallowed = 1;
2548  }
2549  $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
2550  } elseif (($modulepart == 'holiday') && !empty($conf->holiday->dir_output)) {
2551  if ($fuser->rights->holiday->{$read} || !empty($fuser->rights->holiday->readall) || preg_match('/^specimen/i', $original_file)) {
2552  $accessallowed = 1;
2553  // If we known $id of holiday, call checkUserAccessToObject to check permission on properties and hierarchy of leave request
2554  if ($refname && empty($fuser->rights->holiday->readall) && !preg_match('/^specimen/i', $original_file)) {
2555  include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
2556  $tmpholiday = new Holiday($db);
2557  $tmpholiday->fetch('', $refname);
2558  $accessallowed = checkUserAccessToObject($user, array('holiday'), $tmpholiday, 'holiday', '', '', 'rowid', '');
2559  }
2560  }
2561  $original_file = $conf->holiday->dir_output.'/'.$original_file;
2562  } elseif (($modulepart == 'expensereport') && !empty($conf->expensereport->dir_output)) {
2563  if ($fuser->rights->expensereport->{$lire} || !empty($fuser->rights->expensereport->readall) || preg_match('/^specimen/i', $original_file)) {
2564  $accessallowed = 1;
2565  // If we known $id of expensereport, call checkUserAccessToObject to check permission on properties and hierarchy of expense report
2566  if ($refname && empty($fuser->rights->expensereport->readall) && !preg_match('/^specimen/i', $original_file)) {
2567  include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
2568  $tmpexpensereport = new ExpenseReport($db);
2569  $tmpexpensereport->fetch('', $refname);
2570  $accessallowed = checkUserAccessToObject($user, array('expensereport'), $tmpexpensereport, 'expensereport', '', '', 'rowid', '');
2571  }
2572  }
2573  $original_file = $conf->expensereport->dir_output.'/'.$original_file;
2574  } elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output)) {
2575  // Wrapping pour les apercu expense report
2576  if ($fuser->rights->expensereport->{$lire}) {
2577  $accessallowed = 1;
2578  }
2579  $original_file = $conf->expensereport->dir_output.'/'.$original_file;
2580  } elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity])) {
2581  // Wrapping pour les images des stats propales
2582  if ($fuser->rights->propale->{$lire}) {
2583  $accessallowed = 1;
2584  }
2585  $original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file;
2586  } elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp)) {
2587  // Wrapping pour les images des stats commandes
2588  if ($fuser->rights->commande->{$lire}) {
2589  $accessallowed = 1;
2590  }
2591  $original_file = $conf->commande->dir_temp.'/'.$original_file;
2592  } elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) {
2593  if ($fuser->rights->fournisseur->commande->{$lire}) {
2594  $accessallowed = 1;
2595  }
2596  $original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file;
2597  } elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp)) {
2598  // Wrapping pour les images des stats factures
2599  if ($fuser->rights->facture->{$lire}) {
2600  $accessallowed = 1;
2601  }
2602  $original_file = $conf->facture->dir_temp.'/'.$original_file;
2603  } elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) {
2604  if ($fuser->rights->fournisseur->facture->{$lire}) {
2605  $accessallowed = 1;
2606  }
2607  $original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file;
2608  } elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp)) {
2609  // Wrapping pour les images des stats expeditions
2610  if ($fuser->rights->expedition->{$lire}) {
2611  $accessallowed = 1;
2612  }
2613  $original_file = $conf->expedition->dir_temp.'/'.$original_file;
2614  } elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp)) {
2615  // Wrapping pour les images des stats expeditions
2616  if ($fuser->rights->deplacement->{$lire}) {
2617  $accessallowed = 1;
2618  }
2619  $original_file = $conf->deplacement->dir_temp.'/'.$original_file;
2620  } elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp)) {
2621  // Wrapping pour les images des stats expeditions
2622  if ($fuser->rights->adherent->{$lire}) {
2623  $accessallowed = 1;
2624  }
2625  $original_file = $conf->adherent->dir_temp.'/'.$original_file;
2626  } elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp)) {
2627  // Wrapping pour les images des stats produits
2628  if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) {
2629  $accessallowed = 1;
2630  }
2631  $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file;
2632  } elseif (in_array($modulepart, array('tax', 'tax-vat', 'tva')) && !empty($conf->tax->dir_output)) {
2633  // Wrapping for taxes
2634  if ($fuser->rights->tax->charges->{$lire}) {
2635  $accessallowed = 1;
2636  }
2637  $modulepartsuffix = str_replace('tax-', '', $modulepart);
2638  $original_file = $conf->tax->dir_output.'/'.($modulepartsuffix != 'tax' ? $modulepartsuffix.'/' : '').$original_file;
2639  } elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) {
2640  // Wrapping for events
2641  if ($fuser->rights->agenda->myactions->{$read}) {
2642  $accessallowed = 1;
2643  // If we known $id of project, call checkUserAccessToObject to check permission on the given agenda event on properties and assigned users
2644  if ($refname && !preg_match('/^specimen/i', $original_file)) {
2645  include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2646  $tmpobject = new ActionComm($db);
2647  $tmpobject->fetch((int) $refname);
2648  $accessallowed = checkUserAccessToObject($user, array('agenda'), $tmpobject->id, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id', '');
2649  if ($user->socid && $tmpobject->socid) {
2650  $accessallowed = checkUserAccessToObject($user, array('societe'), $tmpobject->socid);
2651  }
2652  }
2653  }
2654  $original_file = $conf->agenda->dir_output.'/'.$original_file;
2655  } elseif ($modulepart == 'category' && !empty($conf->categorie->multidir_output[$entity])) {
2656  // Wrapping for categories
2657  if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) {
2658  return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2659  }
2660  if ($fuser->rights->categorie->{$lire} || $fuser->rights->takepos->run) {
2661  $accessallowed = 1;
2662  }
2663  $original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file;
2664  } elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output)) {
2665  // Wrapping pour les prelevements
2666  if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) {
2667  $accessallowed = 1;
2668  }
2669  $original_file = $conf->prelevement->dir_output.'/'.$original_file;
2670  } elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp)) {
2671  // Wrapping pour les graph energie
2672  $accessallowed = 1;
2673  $original_file = $conf->stock->dir_temp.'/'.$original_file;
2674  } elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp)) {
2675  // Wrapping pour les graph fournisseurs
2676  $accessallowed = 1;
2677  $original_file = $conf->fournisseur->dir_temp.'/'.$original_file;
2678  } elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp)) {
2679  // Wrapping pour les graph des produits
2680  $accessallowed = 1;
2681  $original_file = $conf->product->multidir_temp[$entity].'/'.$original_file;
2682  } elseif ($modulepart == 'barcode') {
2683  // Wrapping pour les code barre
2684  $accessallowed = 1;
2685  // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
2686  //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
2687  $original_file = '';
2688  } elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp)) {
2689  // Wrapping pour les icones de background des mailings
2690  $accessallowed = 1;
2691  $original_file = $conf->mailing->dir_temp.'/'.$original_file;
2692  } elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
2693  // Wrapping pour le scanner
2694  $accessallowed = 1;
2695  $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2696  } elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output)) {
2697  // Wrapping pour les images fckeditor
2698  $accessallowed = 1;
2699  $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
2700  } elseif ($modulepart == 'user' && !empty($conf->user->dir_output)) {
2701  // Wrapping for users
2702  $canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire});
2703  if ($fuser->id == (int) $refname) {
2704  $canreaduser = 1;
2705  } // A user can always read its own card
2706  if ($canreaduser || preg_match('/^specimen/i', $original_file)) {
2707  $accessallowed = 1;
2708  }
2709  $original_file = $conf->user->dir_output.'/'.$original_file;
2710  } elseif (($modulepart == 'company' || $modulepart == 'societe' || $modulepart == 'thirdparty') && !empty($conf->societe->multidir_output[$entity])) {
2711  // Wrapping for third parties
2712  if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
2713  return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2714  }
2715  if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i', $original_file)) {
2716  $accessallowed = 1;
2717  }
2718  $original_file = $conf->societe->multidir_output[$entity].'/'.$original_file;
2719  $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")";
2720  } elseif ($modulepart == 'contact' && !empty($conf->societe->multidir_output[$entity])) {
2721  // Wrapping for contact
2722  if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
2723  return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2724  }
2725  if ($fuser->rights->societe->{$lire}) {
2726  $accessallowed = 1;
2727  }
2728  $original_file = $conf->societe->multidir_output[$entity].'/contact/'.$original_file;
2729  } elseif (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->multidir_output[$entity])) {
2730  // Wrapping for invoices
2731  if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
2732  $accessallowed = 1;
2733  }
2734  $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
2735  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('invoice').")";
2736  } elseif ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity])) {
2737  // Wrapping for mass actions
2738  if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i', $original_file)) {
2739  $accessallowed = 1;
2740  }
2741  $original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2742  } elseif ($modulepart == 'massfilesarea_orders') {
2743  if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
2744  $accessallowed = 1;
2745  }
2746  $original_file = $conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2747  } elseif ($modulepart == 'massfilesarea_sendings') {
2748  if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) {
2749  $accessallowed = 1;
2750  }
2751  $original_file = $conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file;
2752  } elseif ($modulepart == 'massfilesarea_invoices') {
2753  if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
2754  $accessallowed = 1;
2755  }
2756  $original_file = $conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2757  } elseif ($modulepart == 'massfilesarea_expensereport') {
2758  if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
2759  $accessallowed = 1;
2760  }
2761  $original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2762  } elseif ($modulepart == 'massfilesarea_interventions') {
2763  if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) {
2764  $accessallowed = 1;
2765  }
2766  $original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2767  } elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) {
2768  if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i', $original_file)) {
2769  $accessallowed = 1;
2770  }
2771  $original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2772  } elseif ($modulepart == 'massfilesarea_supplier_order') {
2773  if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
2774  $accessallowed = 1;
2775  }
2776  $original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2777  } elseif ($modulepart == 'massfilesarea_supplier_invoice') {
2778  if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
2779  $accessallowed = 1;
2780  }
2781  $original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2782  } elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output)) {
2783  if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) {
2784  $accessallowed = 1;
2785  }
2786  $original_file = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2787  } elseif (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output)) {
2788  // Wrapping for interventions
2789  if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) {
2790  $accessallowed = 1;
2791  }
2792  $original_file = $conf->ficheinter->dir_output.'/'.$original_file;
2793  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2794  } elseif ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output)) {
2795  // Wrapping pour les deplacements et notes de frais
2796  if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i', $original_file)) {
2797  $accessallowed = 1;
2798  }
2799  $original_file = $conf->deplacement->dir_output.'/'.$original_file;
2800  //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2801  } elseif (($modulepart == 'propal' || $modulepart == 'propale') && !empty($conf->propal->multidir_output[$entity])) {
2802  // Wrapping pour les propales
2803  if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i', $original_file)) {
2804  $accessallowed = 1;
2805  }
2806  $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
2807  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('propal').")";
2808  } elseif (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->multidir_output[$entity])) {
2809  // Wrapping pour les commandes
2810  if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
2811  $accessallowed = 1;
2812  }
2813  $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
2814  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('order').")";
2815  } elseif ($modulepart == 'project' && !empty($conf->project->dir_output)) {
2816  // Wrapping pour les projets
2817  if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file)) {
2818  $accessallowed = 1;
2819  // If we known $id of project, call checkUserAccessToObject to check permission on properties and contact of project
2820  if ($refname && !preg_match('/^specimen/i', $original_file)) {
2821  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
2822  $tmpproject = new Project($db);
2823  $tmpproject->fetch('', $refname);
2824  $accessallowed = checkUserAccessToObject($user, array('projet'), $tmpproject->id, 'projet&project', '', '', 'rowid', '');
2825  }
2826  }
2827  $original_file = $conf->project->dir_output.'/'.$original_file;
2828  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2829  } elseif ($modulepart == 'project_task' && !empty($conf->project->dir_output)) {
2830  if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file)) {
2831  $accessallowed = 1;
2832  // If we known $id of project, call checkUserAccessToObject to check permission on properties and contact of project
2833  if ($refname && !preg_match('/^specimen/i', $original_file)) {
2834  include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
2835  $tmptask = new Task($db);
2836  $tmptask->fetch('', $refname);
2837  $accessallowed = checkUserAccessToObject($user, array('projet_task'), $tmptask->id, 'projet_task&project', '', '', 'rowid', '');
2838  }
2839  }
2840  $original_file = $conf->project->dir_output.'/'.$original_file;
2841  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2842  } elseif (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output)) {
2843  // Wrapping pour les commandes fournisseurs
2844  if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
2845  $accessallowed = 1;
2846  }
2847  $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
2848  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2849  } elseif (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output)) {
2850  // Wrapping pour les factures fournisseurs
2851  if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
2852  $accessallowed = 1;
2853  }
2854  $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
2855  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2856  } elseif ($modulepart == 'supplier_payment') {
2857  // Wrapping pour les rapport de paiements
2858  if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
2859  $accessallowed = 1;
2860  }
2861  $original_file = $conf->fournisseur->payment->dir_output.'/'.$original_file;
2862  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2863  } elseif ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output)) {
2864  // Wrapping pour les rapport de paiements
2865  if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
2866  $accessallowed = 1;
2867  }
2868  if ($fuser->socid > 0) {
2869  $original_file = $conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
2870  } else {
2871  $original_file = $conf->facture->dir_output.'/payments/'.$original_file;
2872  }
2873  } elseif ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output)) {
2874  // Wrapping for accounting exports
2875  if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i', $original_file)) {
2876  $accessallowed = 1;
2877  }
2878  $original_file = $conf->accounting->dir_output.'/'.$original_file;
2879  } elseif (($modulepart == 'expedition' || $modulepart == 'shipment') && !empty($conf->expedition->dir_output)) {
2880  // Wrapping pour les expedition
2881  if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) {
2882  $accessallowed = 1;
2883  }
2884  $original_file = $conf->expedition->dir_output."/".(strpos('sending/', $original_file) === 0 ? '' : 'sending/').$original_file;
2885  //$original_file = $conf->expedition->dir_output."/".$original_file;
2886  } elseif (($modulepart == 'livraison' || $modulepart == 'delivery') && !empty($conf->expedition->dir_output)) {
2887  // Delivery Note Wrapping
2888  if ($fuser->rights->expedition->delivery->{$lire} || preg_match('/^specimen/i', $original_file)) {
2889  $accessallowed = 1;
2890  }
2891  $original_file = $conf->expedition->dir_output."/".(strpos('receipt/', $original_file) === 0 ? '' : 'receipt/').$original_file;
2892  } elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) {
2893  // Wrapping pour les actions
2894  if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i', $original_file)) {
2895  $accessallowed = 1;
2896  }
2897  $original_file = $conf->agenda->dir_output.'/'.$original_file;
2898  } elseif ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp)) {
2899  // Wrapping pour les actions
2900  if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i', $original_file)) {
2901  $accessallowed = 1;
2902  }
2903  $original_file = $conf->agenda->dir_temp."/".$original_file;
2904  } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
2905  // Wrapping pour les produits et services
2906  if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) {
2907  return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2908  }
2909  if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i', $original_file)) {
2910  $accessallowed = 1;
2911  }
2912  if (!empty($conf->product->enabled)) {
2913  $original_file = $conf->product->multidir_output[$entity].'/'.$original_file;
2914  } elseif (!empty($conf->service->enabled)) {
2915  $original_file = $conf->service->multidir_output[$entity].'/'.$original_file;
2916  }
2917  } elseif ($modulepart == 'product_batch' || $modulepart == 'produitlot') {
2918  // Wrapping pour les lots produits
2919  if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) {
2920  return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2921  }
2922  if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i', $original_file)) {
2923  $accessallowed = 1;
2924  }
2925  if (!empty($conf->productbatch->enabled)) {
2926  $original_file = $conf->productbatch->multidir_output[$entity].'/'.$original_file;
2927  }
2928  } elseif ($modulepart == 'movement' || $modulepart == 'mouvement') {
2929  // Wrapping for stock movements
2930  if (empty($entity) || empty($conf->stock->multidir_output[$entity])) {
2931  return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2932  }
2933  if (($fuser->rights->stock->{$lire} || $fuser->rights->stock->movement->{$lire} || $fuser->rights->stock->mouvement->{$lire}) || preg_match('/^specimen/i', $original_file)) {
2934  $accessallowed = 1;
2935  }
2936  if (!empty($conf->stock->enabled)) {
2937  $original_file = $conf->stock->multidir_output[$entity].'/movement/'.$original_file;
2938  }
2939  } elseif ($modulepart == 'contract' && !empty($conf->contrat->multidir_output[$entity])) {
2940  // Wrapping pour les contrats
2941  if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) {
2942  $accessallowed = 1;
2943  }
2944  $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file;
2945  $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
2946  } elseif ($modulepart == 'donation' && !empty($conf->don->dir_output)) {
2947  // Wrapping pour les dons
2948  if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i', $original_file)) {
2949  $accessallowed = 1;
2950  }
2951  $original_file = $conf->don->dir_output.'/'.$original_file;
2952  } elseif ($modulepart == 'dolresource' && !empty($conf->resource->dir_output)) {
2953  // Wrapping pour les dons
2954  if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i', $original_file)) {
2955  $accessallowed = 1;
2956  }
2957  $original_file = $conf->resource->dir_output.'/'.$original_file;
2958  } elseif ($modulepart == 'remisecheque' && !empty($conf->bank->dir_output)) {
2959  // Wrapping pour les remises de cheques
2960  if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i', $original_file)) {
2961  $accessallowed = 1;
2962  }
2963 
2964  $original_file = $conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result
2965  } elseif (($modulepart == 'banque' || $modulepart == 'bank') && !empty($conf->bank->dir_output)) {
2966  // Wrapping for bank
2967  if ($fuser->rights->banque->{$lire}) {
2968  $accessallowed = 1;
2969  }
2970  $original_file = $conf->bank->dir_output.'/'.$original_file;
2971  } elseif ($modulepart == 'export' && !empty($conf->export->dir_temp)) {
2972  // Wrapping for export module
2973  // Note that a test may not be required because we force the dir of download on the directory of the user that export
2974  $accessallowed = $user->rights->export->lire;
2975  $original_file = $conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
2976  } elseif ($modulepart == 'import' && !empty($conf->import->dir_temp)) {
2977  // Wrapping for import module
2978  $accessallowed = $user->rights->import->run;
2979  $original_file = $conf->import->dir_temp.'/'.$original_file;
2980  } elseif ($modulepart == 'recruitment' && !empty($conf->recruitment->dir_output)) {
2981  // Wrapping for recruitment module
2982  $accessallowed = $user->rights->recruitment->recruitmentjobposition->read;
2983  $original_file = $conf->recruitment->dir_output.'/'.$original_file;
2984  } elseif ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output)) {
2985  // Wrapping for wysiwyg editor
2986  $accessallowed = 1;
2987  $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
2988  } elseif ($modulepart == 'systemtools' && !empty($conf->admin->dir_output)) {
2989  // Wrapping for backups
2990  if ($fuser->admin) {
2991  $accessallowed = 1;
2992  }
2993  $original_file = $conf->admin->dir_output.'/'.$original_file;
2994  } elseif ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp)) {
2995  // Wrapping for upload file test
2996  if ($fuser->admin) {
2997  $accessallowed = 1;
2998  }
2999  $original_file = $conf->admin->dir_temp.'/'.$original_file;
3000  } elseif ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output)) {
3001  // Wrapping pour BitTorrent
3002  $accessallowed = 1;
3003  $dir = 'files';
3004  if (dol_mimetype($original_file) == 'application/x-bittorrent') {
3005  $dir = 'torrents';
3006  }
3007  $original_file = $conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
3008  } elseif ($modulepart == 'member' && !empty($conf->adherent->dir_output)) {
3009  // Wrapping pour Foundation module
3010  if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i', $original_file)) {
3011  $accessallowed = 1;
3012  }
3013  $original_file = $conf->adherent->dir_output.'/'.$original_file;
3014  } elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
3015  // Wrapping for Scanner
3016  $accessallowed = 1;
3017  $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
3018  // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
3019  // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
3020  // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
3021  // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
3022  // If modulepart=module-abc Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
3023  } else {
3024  // GENERIC Wrapping
3025  //var_dump($modulepart);
3026  //var_dump($original_file);
3027  if (preg_match('/^specimen/i', $original_file)) {
3028  $accessallowed = 1; // If link to a file called specimen. Test must be done before changing $original_file int full path.
3029  }
3030  if ($fuser->admin) {
3031  $accessallowed = 1; // If user is admin
3032  }
3033 
3034  $tmpmodulepart = explode('-', $modulepart);
3035  if (!empty($tmpmodulepart[1])) {
3036  $modulepart = $tmpmodulepart[0];
3037  $original_file = $tmpmodulepart[1].'/'.$original_file;
3038  }
3039 
3040  // Define $accessallowed
3041  $reg = array();
3042  if (preg_match('/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
3043  if (empty($conf->{$reg[1]}->dir_temp)) { // modulepart not supported
3044  dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3045  exit;
3046  }
3047  if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
3048  $accessallowed = 1;
3049  }
3050  $original_file = $conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
3051  } elseif (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg)) {
3052  if (empty($conf->{$reg[1]}->dir_temp)) { // modulepart not supported
3053  dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3054  exit;
3055  }
3056  if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
3057  $accessallowed = 1;
3058  }
3059  $original_file = $conf->{$reg[1]}->dir_temp.'/'.$original_file;
3060  } elseif (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg)) {
3061  if (empty($conf->{$reg[1]}->dir_output)) { // modulepart not supported
3062  dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3063  exit;
3064  }
3065  if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
3066  $accessallowed = 1;
3067  }
3068  $original_file = $conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
3069  } elseif (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
3070  if (empty($conf->{$reg[1]}->dir_output)) { // modulepart not supported
3071  dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3072  exit;
3073  }
3074  if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file)) {
3075  $accessallowed = 1;
3076  }
3077  $original_file = $conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3078  } else {
3079  if (empty($conf->$modulepart->dir_output)) { // modulepart not supported
3080  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.');
3081  exit;
3082  }
3083 
3084  // Check fuser->rights->modulepart->myobject->read and fuser->rights->modulepart->read
3085  $partsofdirinoriginalfile = explode('/', $original_file);
3086  if (!empty($partsofdirinoriginalfile[1])) { // If original_file is xxx/filename (xxx is a part we will use)
3087  $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3088  if ($partofdirinoriginalfile && !empty($fuser->rights->$modulepart->$partofdirinoriginalfile) && ($fuser->rights->$modulepart->$partofdirinoriginalfile->{$lire} || $fuser->rights->$modulepart->$partofdirinoriginalfile->{$read})) {
3089  $accessallowed = 1;
3090  }
3091  }
3092  if (!empty($fuser->rights->$modulepart->{$lire}) || !empty($fuser->rights->$modulepart->{$read})) {
3093  $accessallowed = 1;
3094  }
3095 
3096  if (is_array($conf->$modulepart->multidir_output) && !empty($conf->$modulepart->multidir_output[$entity])) {
3097  $original_file = $conf->$modulepart->multidir_output[$entity].'/'.$original_file;
3098  } else {
3099  $original_file = $conf->$modulepart->dir_output.'/'.$original_file;
3100  }
3101  }
3102 
3103  $parameters = array(
3104  'modulepart' => $modulepart,
3105  'original_file' => $original_file,
3106  'entity' => $entity,
3107  'fuser' => $fuser,
3108  'refname' => '',
3109  'mode' => $mode
3110  );
3111  $reshook = $hookmanager->executeHooks('checkSecureAccess', $parameters, $object);
3112  if ($reshook > 0) {
3113  if (!empty($hookmanager->resArray['original_file'])) {
3114  $original_file = $hookmanager->resArray['original_file'];
3115  }
3116  if (!empty($hookmanager->resArray['accessallowed'])) {
3117  $accessallowed = $hookmanager->resArray['accessallowed'];
3118  }
3119  if (!empty($hookmanager->resArray['sqlprotectagainstexternals'])) {
3120  $sqlprotectagainstexternals = $hookmanager->resArray['sqlprotectagainstexternals'];
3121  }
3122  }
3123  }
3124 
3125  $ret = array(
3126  'accessallowed' => ($accessallowed ? 1 : 0),
3127  'sqlprotectagainstexternals' => $sqlprotectagainstexternals,
3128  'original_file' => $original_file
3129  );
3130 
3131  return $ret;
3132 }
3133 
3142 function dol_filecache($directory, $filename, $object)
3143 {
3144  if (!dol_is_dir($directory)) {
3145  dol_mkdir($directory);
3146  }
3147  $cachefile = $directory.$filename;
3148  file_put_contents($cachefile, serialize($object), LOCK_EX);
3149  @chmod($cachefile, 0644);
3150 }
3151 
3160 function dol_cache_refresh($directory, $filename, $cachetime)
3161 {
3162  $now = dol_now();
3163  $cachefile = $directory.$filename;
3164  $refresh = !file_exists($cachefile) || ($now - $cachetime) > dol_filemtime($cachefile);
3165  return $refresh;
3166 }
3167 
3175 function dol_readcachefile($directory, $filename)
3176 {
3177  $cachefile = $directory.$filename;
3178  $object = unserialize(file_get_contents($cachefile));
3179  return $object;
3180 }
3181 
3182 
3194 function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path = '', $pathref = '', &$checksumconcat = array())
3195 {
3196  global $conffile;
3197 
3198  $exclude = 'install';
3199 
3200  foreach ($dir->md5file as $file) { // $file is a simpleXMLElement
3201  $filename = $path.$file['name'];
3202  $file_list['insignature'][] = $filename;
3203  $expectedsize = (empty($file['size']) ? '' : $file['size']);
3204  $expectedmd5 = (string) $file;
3205 
3206  //if (preg_match('#'.$exclude.'#', $filename)) continue;
3207 
3208  if (!file_exists($pathref.'/'.$filename)) {
3209  $file_list['missing'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize);
3210  } else {
3211  $md5_local = md5_file($pathref.'/'.$filename);
3212 
3213  if ($conffile == '/etc/dolibarr/conf.php' && $filename == '/filefunc.inc.php') { // For install with deb or rpm, we ignore test on filefunc.inc.php that was modified by package
3214  $checksumconcat[] = $expectedmd5;
3215  } else {
3216  if ($md5_local != $expectedmd5) {
3217  $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize, 'md5'=>(string) $md5_local);
3218  }
3219  $checksumconcat[] = $md5_local;
3220  }
3221  }
3222  }
3223 
3224  foreach ($dir->dir as $subdir) { // $subdir['name'] is '' or '/accountancy/admin' for example
3225  getFilesUpdated($file_list, $subdir, $path.$subdir['name'].'/', $pathref, $checksumconcat);
3226  }
3227 
3228  return $file_list;
3229 }
dol_convert_file($fileinput, $ext= 'png', $fileoutput= '', $page= '')
Convert an image file or a PDF into another image format.
Definition: files.lib.php:1963
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Class to manage utility methods.
Definition: utils.class.php:30
dol_compare_file($a, $b)
Fast compare of 2 files identified by their properties -&gt;name, -&gt;date and -&gt;size. ...
Definition: files.lib.php:404
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto= 'UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Class of the module paid holiday.
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
Copy a file to another file.
Definition: files.lib.php:702
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)...
Definition: images.lib.php:485
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0)
Copy a dir to another dir.
Definition: files.lib.php:761
dol_sanitizePathName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a path name.
getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path= '', $pathref= '', &$checksumconcat=array())
Function to get list of updated or modified files.
Definition: files.lib.php:3194
Classe permettant la generation du formulaire html d&#39;envoi de mail unitaire Usage: $formail = new For...
dol_unescapefile($filename)
Unescape a file submitted by upload.
Definition: files.lib.php:1037
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.
Definition: files.lib.php:232
dol_cache_refresh($directory, $filename, $cachetime)
Test if Refresh needed.
Definition: files.lib.php:3160
deleteFilesIntoDatabaseIndex($dir, $file, $mode= 'uploaded')
Delete files into database index using search criterias.
Definition: files.lib.php:1904
dol_mkdir($dir, $dataroot= '', $newmask= '')
Creation of a directory (this can create recursive subdir)
Class to manage agenda events (actions)
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
Definition: files.lib.php:310
dol_now($mode= 'auto')
Return date for now.
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1434
Class to scan for virus.
dol_filesize($pathoffile)
Return size of a file.
Definition: files.lib.php:580
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:446
dolCheckVirus($src_file)
Check virus into a file.
Definition: files.lib.php:1052
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:58
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_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:854
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
dol_fileperm($pathoffile)
Return permissions of a file.
Definition: files.lib.php:604
dol_is_url($url)
Return if path is an URL.
Definition: files.lib.php:500
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser= '', $refname= '', $mode= 'read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices to g...
Definition: files.lib.php:2398
Class to manage projects.
dol_mimetype($file, $default= 'application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
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) ...
Definition: files.lib.php:1382
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
dol_basename($pathfile)
Make a basename working with all page code (default PHP basenamed fails with cyrillic).
Definition: files.lib.php:36
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_move_dir($srcdir, $destdir, $overwriteifexists=1, $indexdatabase=1, $renamedircontent=1)
Move a directory into another name.
Definition: files.lib.php:978
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
utf8_check($str)
Check if a string is in UTF8.
dol_count_nb_of_line($file)
Count number of lines in a file.
Definition: files.lib.php:549
Class to manage Trips and Expenses.
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.
Definition: files.lib.php:1091
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:476
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->supplier_invoice->lire)) if(isModEnabled('don')&&!empty($user->rights->don->lire)) if(isModEnabled('tax')&&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture')&&isModEnabled('commande')&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
dol_remove_file_process($filenb, $donotupdatesession=0, $donotdeletefile=1, $trackid= '')
Remove an uploaded file (for example after submitting a new file a mail form).
Definition: files.lib.php:1785
dolReplaceInFile($srcfile, $arrayreplacement, $destfile= '', $newmask=0, $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
Definition: files.lib.php:622
dol_init_file_process($pathtoscan= '', $trackid= '')
Scan a directory and init $_SESSION to manage uploaded files with list of all found files...
Definition: files.lib.php:1595
dol_sort_array(&$array, $index, $order= 'asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
dol_uncompress($inputfile, $outputdir)
Uncompress a file.
Definition: files.lib.php:2148
Class to manage tasks.
Definition: task.class.php:37
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_filemtime($pathoffile)
Return time of a file.
Definition: files.lib.php:592
dol_most_recent_file($dir, $regexfilter= '', $excludefilter=array('(\.meta|_preview.*\.png)$', '^\.'), $nohook=false, $mode= '')
Return file(s) into a directory (by default most recent)
Definition: files.lib.php:2379
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
addFileIntoDatabaseIndex($dir, $file, $fullpathorig= '', $mode= 'uploaded', $setsharekey=0, $object=null)
Add a file into database index.
Definition: files.lib.php:1843
dol_readcachefile($directory, $filename)
Read object from cachefile.
Definition: files.lib.php:3175
dol_is_link($pathoffile)
Return if path is a symbolic link.
Definition: files.lib.php:488
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=&gt;newva...
dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles= 'addedfile', $savingdocmask= '', $link=null, $trackid= '', $generatethumbs=1, $object=null)
Get and save an upload file (for example after submitting a new file a mail form).
Definition: files.lib.php:1633
dol_dir_is_emtpy($folder)
Test if a folder is empty.
Definition: files.lib.php:517
dol_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
Definition: files.lib.php:1357
Class to manage ECM files.
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.
Definition: files.lib.php:1230
dol_meta_create($object)
Create a meta file with document file into same directory.
Definition: files.lib.php:1511
dol_filecache($directory, $filename, $object)
Store object in file.
Definition: files.lib.php:3142
dol_is_dir_empty($dir)
Return if path is empty.
Definition: files.lib.php:462