dolibarr 25.0.0-alpha
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-2026 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2023-2026 Lenin Rivas <lenin.rivas777@gmail.com>
9 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
10 * Copyright (C) 2025 William Mead <william@m34d.com>
11 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
12 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 * or see https://www.gnu.org/
27 */
28
41function dol_basename($pathfile)
42{
43 return preg_replace('/^.*\/([^\/]+)$/', '$1', rtrim($pathfile, '/'));
44}
45
66function dol_dir_list($utf8_path, $types = "all", $recursive = 0, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename = "", $donotfollowsymlinks = 0, $nbsecondsold = 0)
67{
68 global $hookmanager;
69 global $object;
70
71 if ($recursive <= 1) { // Avoid too verbose log
72 $error_info = "";
73
74 // Verify filters (only on the first call of the function)
75 $filter_ok = true;
76 if (!empty($filter) && !is_array($filter)) {
77 if (strlen($filter) > 25000) { // Note that limit depends on syntax of filter
78 dol_syslog("Value for filter is too large", LOG_ERR);
79 $filter_ok = false;
80 } else {
81 // Check that all '/' are escaped.
82 if ((int) preg_match('/(?:^|[^\\\\])\//', $filter) > 0) {
83 $excludefilter_ok = false;
84 $error_info .= " error='filter_has_unescaped_slash'";
85 dol_syslog("'$filter' has unescaped '/'", LOG_ERR);
86 }
87 }
88 }
89
90 // Ensure we have an array for the exclusions
91 $excludefilter_ok = true;
92 $exclude_array = ($excludefilter === null || $excludefilter === '') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
93 foreach ($exclude_array as $f) {
94 // Check that all '/' are escaped.
95 if ((int) preg_match('/(?:^|[^\\\\])\//', $f) > 0) {
96 $excludefilter_ok = false;
97 $error_info .= " error='excludefilter_has_unescaped_slash'";
98 dol_syslog("'$f' has unescaped '/'", LOG_ERR);
99 }
100 }
101
102 dol_syslog("files.lib.php::dol_dir_list path=".$utf8_path." types=".$types." recursive=".$recursive." filter=".json_encode($filter)." excludefilter=".json_encode($excludefilter).$error_info);
103 // print 'xxx'."files.lib.php::dol_dir_list path=".$utf8_path." types=".$types." recursive=".$recursive." filter=".json_encode($filter)." excludefilter=".json_encode($exclude_array);
104 if (!$filter_ok || !$excludefilter_ok) {
105 // Return empty array when filters are invalid
106 return array();
107 }
108 } else {
109 // Already computed before
110 $exclude_array = ($excludefilter === null || $excludefilter === '') ? array() : (is_array($excludefilter) ? $excludefilter : array($excludefilter));
111 }
112
113 // Define excludefilterarray (before while, for speed)
114 $excludefilterarray = array_merge(array('^\.'), $exclude_array);
115
116 $loaddate = ($mode == 1 || $mode == 2 || $nbsecondsold != 0 || $sortcriteria == 'date');
117 $loadsize = ($mode == 1 || $mode == 3 || $sortcriteria == 'size');
118 $loadperm = ($mode == 1 || $mode == 4 || $sortcriteria == 'perm');
119
120 $now = dol_now();
121 $reshook = 0;
122 $file_list = array();
123
124 // Clean parameters
125 $utf8_path = preg_replace('/([\\/]+)$/', '', $utf8_path);
126
127 if (preg_match('/\*/', $utf8_path)) {
128 $utf8_path_array = glob($utf8_path, GLOB_ONLYDIR); // This scan dir for files. If file does not exists, return empty.
129 //$os_path_array = dol_dir_list($utf8_path);
130 } else {
131 $utf8_path_array = array($utf8_path);
132 }
133
134 foreach ($utf8_path_array as $utf8_path_cursor) {
135 $os_path = dol_osencode($utf8_path_cursor);
136 if (!$nohook && $hookmanager instanceof HookManager) {
137 $hookmanager->resArray = array();
138
139 $hookmanager->initHooks(array('fileslib'));
140
141 $parameters = array(
142 'path' => $os_path,
143 'types' => $types,
144 'recursive' => $recursive,
145 'filter' => $filter,
146 'excludefilter' => $exclude_array, // Already converted to array.
147 'sortcriteria' => $sortcriteria,
148 'sortorder' => $sortorder,
149 'loaddate' => $loaddate,
150 'loadsize' => $loadsize,
151 'mode' => $mode
152 );
153 $reshook = $hookmanager->executeHooks('getDirList', $parameters, $object);
154 }
155
156 // $hookmanager->resArray may contain array stacked by other modules
157 if (empty($reshook)) {
158 if (!is_dir($os_path)) {
159 continue;
160 }
161
162 if (($dir = opendir($os_path)) === false) {
163 continue;
164 }
165
166 $filedate = '';
167 $filesize = '';
168 $fileperm = '';
169
170 while (false !== ($os_file = readdir($dir))) { // $utf8_file is always a basename (in directory $os_path)
171 $os_fullpathfile = ($os_path ? $os_path.'/' : '').$os_file;
172
173 if (!utf8_check($os_file)) {
174 $utf8_file = mb_convert_encoding($os_file, 'UTF-8', 'ISO-8859-1'); // Make sure data is stored in utf8 in memory
175 } else {
176 $utf8_file = $os_file;
177 }
178
179 $utf8_fullpathfile = $utf8_path_cursor."/".$utf8_file; // Temp variable for speed
180
181 // Check if file is qualified
182 $qualified = 1;
183 foreach ($excludefilterarray as $filt) {
184 if (preg_match('/'.$filt.'/i', $utf8_file) || preg_match('/'.$filt.'/i', $utf8_fullpathfile)) {
185 $qualified = 0;
186 break;
187 }
188 }
189 //print $utf8_fullpathfile.' '.$utf8_file.' '.$qualified.'<br>';
190
191 if ($qualified) {
192 $isdir = is_dir($os_fullpathfile);
193 // Check whether this is a file or directory and whether we're interested in that type
194 if ($isdir) {
195 // Add entry into file_list array
196 if (($types == "directories") || ($types == "all")) {
197 if ($loaddate || $sortcriteria == 'date') {
198 $filedate = dol_filemtime($utf8_fullpathfile);
199 }
200 if ($loadsize || $sortcriteria == 'size') {
201 $filesize = dol_filesize($utf8_fullpathfile);
202 }
203 if ($loadperm || $sortcriteria == 'perm') {
204 $fileperm = dol_fileperm($utf8_fullpathfile);
205 }
206
207 $qualifiedforfilter = 0;
208 if (empty($filter)) {
209 $qualifiedforfilter = 1;
210 } else {
211 $testpregmatch = false;
212 if (is_array($filter)) {
213 $chunks = array_chunk($filter, 500);
214 foreach ($chunks as $chunk) {
215 $testpregmatch = preg_match('/'.implode('|', $chunk).'/i', $utf8_file); // May failed if $filter too large
216 if ($testpregmatch) {
217 break;
218 }
219 }
220 } else {
221 $testpregmatch = preg_match('/'.$filter.'/i', $utf8_file); // May failed if $filter too large
222 }
223 if ($testpregmatch) {
224 $qualifiedforfilter = 1;
225 }
226 }
227
228 if ($qualifiedforfilter) { // We do not search key $filter into all $path, only into $file part
229 $reg = array();
230 preg_match('/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
231 $level1name = (isset($reg[1]) ? $reg[1] : '');
232 $file_list[] = array(
233 "name" => $utf8_file,
234 "path" => $utf8_path,
235 "level1name" => $level1name,
236 "relativename" => ($relativename ? $relativename.'/' : '').$utf8_file,
237 "fullname" => $utf8_fullpathfile,
238 "date" => $filedate,
239 "size" => $filesize,
240 "perm" => $fileperm,
241 "type" => 'dir'
242 );
243 }
244 }
245
246 // if we're in a directory and we want recursive behavior, call this function again
247 if ($recursive > 0) {
248 if (empty($donotfollowsymlinks) || !is_link($os_fullpathfile)) {
249 //var_dump('eee '. $utf8_fullpathfile. ' '.is_dir($utf8_fullpathfile).' '.is_link($utf8_fullpathfile));
250 $file_list = array_merge($file_list, dol_dir_list($utf8_fullpathfile, $types, $recursive + 1, $filter, $exclude_array, $sortcriteria, $sortorder, $mode, $nohook, ($relativename != '' ? $relativename.'/' : '').$utf8_file, $donotfollowsymlinks, $nbsecondsold));
251 }
252 }
253 } elseif (in_array($types, array("files", "all"))) {
254 // Add file into file_list array
255 if ($loaddate || $sortcriteria == 'date') {
256 $filedate = dol_filemtime($utf8_fullpathfile);
257 }
258 if ($loadsize || $sortcriteria == 'size') {
259 $filesize = dol_filesize($utf8_fullpathfile);
260 }
261
262 $qualifiedforfilter = 0;
263 if (empty($filter)) {
264 $qualifiedforfilter = 1;
265 } else {
266 $testpregmatch = false;
267 if (is_array($filter)) {
268 $chunks = array_chunk($filter, 500);
269 foreach ($chunks as $chunk) {
270 $testpregmatch = preg_match('/'.implode('|', $chunk).'/i', $utf8_file); // May failed if $filter too large
271 if ($testpregmatch) {
272 break;
273 }
274 }
275 } else {
276 $testpregmatch = preg_match('/'.$filter.'/i', $utf8_file); // May failed if $filter too large
277 }
278 if ($testpregmatch) {
279 $qualifiedforfilter = 1;
280 }
281 }
282
283 if ($qualifiedforfilter) { // We do not search key $filter into all $path, only into $file part
284 if (empty($nbsecondsold) || $filedate <= ($now - $nbsecondsold)) {
285 preg_match('/([^\/]+)\/[^\/]+$/', $utf8_fullpathfile, $reg);
286 $level1name = (isset($reg[1]) ? $reg[1] : '');
287 $file_list[] = array(
288 "name" => $utf8_file,
289 "path" => $utf8_path,
290 "level1name" => $level1name,
291 "relativename" => ($relativename ? $relativename.'/' : '').$utf8_file,
292 "fullname" => $utf8_fullpathfile,
293 "date" => $filedate,
294 "size" => $filesize,
295 "type" => 'file'
296 );
297 }
298 }
299 }
300 }
301 }
302 closedir($dir);
303 }
304 }
305
306 // Obtain a list of columns
307 if (!empty($sortcriteria) && $sortorder) {
308 $file_list = dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ? 'asc' : 'desc'));
309 }
310
311 if ($hookmanager instanceof HookManager && is_array($hookmanager->resArray)) {
312 $file_list = array_merge($file_list, $hookmanager->resArray);
313 }
314
315 return $file_list;
316}
317
318
335function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0, $sqlfilters = "", $object = null)
336{
337 global $conf, $db;
338
339 if (is_null($object)) {
340 $object = new stdClass();
341 }
342
343 $sql = "SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,";
344 $sql .= " date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share";
345 if ($mode) {
346 $sql .= ", description";
347 }
348 $sql .= " FROM ".MAIN_DB_PREFIX."ecm_files";
349 if (!empty($object->entity)) {
350 $sql .= " WHERE entity = ".((int) $object->entity);
351 } else {
352 $sql .= " WHERE entity = ".((int) $conf->entity);
353 }
354 if (preg_match('/%$/', $path)) {
355 $sql .= " AND (filepath LIKE '".$db->escape($path)."' OR filepath = '".$db->escape(preg_replace('/\/%$/', '', $path))."')";
356 } else {
357 $sql .= " AND filepath = '".$db->escape($path)."'";
358 }
359
360 // Manage filter
361 $errormessage = '';
362 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
363 if ($errormessage) {
364 dol_print_error(null, $errormessage);
365 return array();
366 }
367
368 $resql = $db->query($sql);
369 if ($resql) {
370 $file_list = array();
371 $num = $db->num_rows($resql);
372 $i = 0;
373 while ($i < $num) {
374 $obj = $db->fetch_object($resql);
375 if ($obj) {
376 $reg = array();
377 preg_match('/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, $reg);
378 $level1name = (isset($reg[1]) ? $reg[1] : '');
379 $file_list[] = array(
380 "rowid" => $obj->rowid,
381 "label" => $obj->label, // md5
382 "name" => $obj->filename,
383 "path" => DOL_DATA_ROOT.'/'.$obj->filepath,
384 "level1name" => $level1name,
385 "fullname" => DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,
386 "fullpath_orig" => $obj->fullpath_orig,
387 "date_c" => $db->jdate($obj->date_c),
388 "date_m" => $db->jdate($obj->date_m),
389 "type" => 'file',
390 "keywords" => $obj->keywords,
391 "cover" => $obj->cover,
392 "position" => (int) $obj->position,
393 "acl" => $obj->acl,
394 "share" => $obj->share,
395 "description" => ($mode ? $obj->description : '')
396 // TODO Add 'content' with $mode == 2 ?
397 );
398 }
399 $i++;
400 }
401
402 // Obtain a list of columns
403 if (!empty($sortcriteria)) {
404 $myarray = array();
405 foreach ($file_list as $key => $row) {
406 $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] : '');
407 }
408 // Sort the data
409 if ($sortorder) {
410 array_multisort($myarray, $sortorder, SORT_REGULAR, $file_list);
411 }
412 }
413
414 return $file_list;
415 } else {
416 dol_print_error($db);
417 return array();
418 }
419}
420
421
431function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object = null)
432{
433 global $conf, $db, $user;
434
435 if (is_null($object)) {
436 $object = new stdClass();
437 $object->id = null;
438 $object->element = null;
439 }
440
441 $filearrayindatabase = dol_dir_list_in_database(rtrim($relativedir, "/\\"), '', null, 'name', SORT_ASC, 0, '', $object);
442
443 global $modulepart;
444 // Note: $modulepart is 'product' when set by product/document.php, but 'produit' in some other contexts, so we accept both.
445 if (in_array($modulepart, array('produit', 'product')) && getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
446 // TODO Remove this when PRODUCT_USE_OLD_PATH_FOR_PHOTO will be removed
447 global $object;
448 if (!empty($object->id)) {
449 if (isModEnabled("product")) {
450 $upload_dirold = $conf->product->multidir_output[$object->entity ?? $conf->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
451 } else {
452 $upload_dirold = $conf->service->multidir_output[$object->entity ?? $conf->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
453 }
454
455 $relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dirold);
456 $relativedirold = ltrim($relativedirold, "/\\");
457
458 // Note: $object must be provided so the entity filter matches the one used to forge $upload_dirold (multicompany)
459 $filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC, 0, '', $object));
460 }
461 } elseif ($modulepart == 'ticket') {
462 foreach ($filearray as $key => $val) {
463 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filearray[$key]['path']);
464 $rel_dir = trim($rel_dir, "/\\");
465 if ($rel_dir != $relativedir) {
466 $filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($rel_dir, '', null, 'name', SORT_ASC));
467 }
468 }
469 }
470
471 // Complete filearray with properties found into $filearrayindatabase
472 foreach ($filearray as $key => $val) {
473 $tmpfilename = preg_replace('/\.noexe$/', '', $filearray[$key]['name']);
474 $found = 0;
475 // Search if it exists into $filearrayindatabase
476 foreach ($filearrayindatabase as $key2 => $val2) {
477 if (($filearrayindatabase[$key2]['path'] == $filearray[$key]['path']) && ($filearrayindatabase[$key2]['name'] == $tmpfilename)) {
478 $filearray[$key]['position_name'] = ($filearrayindatabase[$key2]['position'] ? $filearrayindatabase[$key2]['position'] : '0').'_'.$filearrayindatabase[$key2]['name'];
479 $filearray[$key]['position'] = $filearrayindatabase[$key2]['position'];
480 $filearray[$key]['cover'] = $filearrayindatabase[$key2]['cover'];
481 $filearray[$key]['keywords'] = $filearrayindatabase[$key2]['keywords'];
482 $filearray[$key]['acl'] = $filearrayindatabase[$key2]['acl'];
483 $filearray[$key]['rowid'] = $filearrayindatabase[$key2]['rowid'];
484 $filearray[$key]['label'] = $filearrayindatabase[$key2]['label'];
485 $filearray[$key]['share'] = $filearrayindatabase[$key2]['share'];
486 $found = 1;
487 break;
488 }
489 }
490
491 if (!$found) { // This happen in transition toward version 6, or if files were added manually into os dir.
492 $filearray[$key]['position'] = '999999'; // File not indexed are at end. So if we add a file, it will not replace an existing position
493 $filearray[$key]['cover'] = 0;
494 $filearray[$key]['acl'] = '';
495 $filearray[$key]['share'] = 0;
496
497 $rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filearray[$key]['fullname']);
498
499 if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filename)) { // If not a tmp file
500 dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it");
501
502 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
503 $ecmfile = new EcmFiles($db);
504
505 // Add entry into database
506 $filename = basename($rel_filename);
507 $rel_dir = dirname($rel_filename);
508 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
509 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
510
511 $ecmfile->filepath = $rel_dir;
512 $ecmfile->filename = $filename;
513 $ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname'])); // $destfile is a full path to file
514 $ecmfile->fullpath_orig = $filearray[$key]['fullname'];
515 $ecmfile->gen_or_uploaded = 'unknown';
516 if (is_object($object)) {
517 $ecmfile->src_object_type = $object->element;
518 $ecmfile->src_object_id = $object->id;
519 }
520 $ecmfile->description = ''; // indexed content
521 $ecmfile->keywords = ''; // keyword content
522 // When you scan file with dol_dir_list_in_database, you scan for files in entity of object (like with projects), even if you
523 // are connected into another entity. So we must also create record that was not found into the entity scan, so the one of the object).
524 $ecmfile->entity = empty($object->entity) ? $conf->entity : $object->entity;
525
526 $result = $ecmfile->create($user);
527 if ($result < 0) {
528 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
529 } else {
530 $filearray[$key]['rowid'] = $result;
531 }
532 } else {
533 $filearray[$key]['rowid'] = 0; // Should not happened
534 }
535 }
536 }
537 //var_dump($filearray); var_dump($relativedir.' - tmpfilename='.$tmpfilename.' - found='.$found);
538}
539
540
548function dol_compare_file($a, $b)
549{
550 global $sortorder, $sortfield;
551
552 $sortorder = strtoupper($sortorder);
553
554 if ($sortorder == 'ASC') {
555 $retup = -1;
556 $retdown = 1;
557 } else {
558 $retup = 1;
559 $retdown = -1;
560 }
561
562 if ($sortfield == 'name') {
563 if ($a->name == $b->name) {
564 return 0;
565 }
566 return ($a->name < $b->name) ? $retup : $retdown;
567 }
568 if ($sortfield == 'date') {
569 if ($a->date == $b->date) {
570 return 0;
571 }
572 return ($a->date < $b->date) ? $retup : $retdown;
573 }
574 if ($sortfield == 'size') {
575 if ($a->size == $b->size) {
576 return 0;
577 }
578 return ($a->size < $b->size) ? $retup : $retdown;
579 }
580
581 return 0;
582}
583
584
591function dol_is_dir($folder)
592{
593 $newfolder = dol_osencode($folder);
594 if (is_dir($newfolder)) {
595 return true;
596 } else {
597 return false;
598 }
599}
600
607function dol_is_dir_empty($dir)
608{
609 if (!is_readable($dir)) {
610 return false;
611 }
612 return (count(scandir($dir)) == 2);
613}
614
621function dol_is_file($pathoffile)
622{
623 $newpathoffile = dol_osencode($pathoffile);
624 return is_file($newpathoffile);
625}
626
633function dol_is_link($pathoffile)
634{
635 $newpathoffile = dol_osencode($pathoffile);
636 return is_link($newpathoffile);
637}
638
645function dol_is_writable($folderorfile)
646{
647 $newfolderorfile = dol_osencode($folderorfile);
648 return is_writable($newfolderorfile);
649}
650
659function dol_is_url($uri)
660{
661 $prots = array('file', 'http', 'https', 'ftp', 'zlib', 'data', 'ssh', 'ssh2', 'ogg', 'expect');
662 return false !== preg_match('/^('.implode('|', $prots).'):/i', $uri);
663}
664
671function dol_dir_is_emtpy($folder)
672{
673 $newfolder = dol_osencode($folder);
674 if (is_dir($newfolder)) {
675 $handle = opendir($newfolder);
676 $folder_content = '';
677 $name_array = [];
678 while ((gettype($name = readdir($handle)) != "boolean")) {
679 $name_array[] = $name;
680 }
681 foreach ($name_array as $temp) {
682 $folder_content .= $temp;
683 }
684
685 closedir($handle);
686
687 if ($folder_content == "...") {
688 return true;
689 } else {
690 return false;
691 }
692 } else {
693 return true; // Dir does not exists
694 }
695}
696
704function dol_count_nb_of_line($file)
705{
706 $nb = 0;
707
708 $newfile = dol_osencode($file);
709 //print 'x'.$file;
710 $fp = fopen($newfile, 'r');
711 if ($fp) {
712 while (!feof($fp)) {
713 $line = fgets($fp);
714 // Increase count only if read was success.
715 // Test needed because feof returns true only after fgets
716 // so we do n+1 fgets for a file with n lines.
717 if ($line !== false) {
718 $nb++;
719 }
720 }
721 fclose($fp);
722 } else {
723 $nb = -1;
724 }
725
726 return $nb;
727}
728
729
737function dol_filesize($pathoffile)
738{
739 $newpathoffile = dol_osencode($pathoffile);
740 return filesize($newpathoffile);
741}
742
749function dol_filemtime($pathoffile)
750{
751 $newpathoffile = dol_osencode($pathoffile);
752 return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
753}
754
761function dol_fileperm($pathoffile)
762{
763 $newpathoffile = dol_osencode($pathoffile);
764 return fileperms($newpathoffile);
765}
766
779function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = '0', $indexdatabase = 0, $arrayreplacementisregex = 0)
780{
781 dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase." arrayreplacementisregex=".$arrayreplacementisregex);
782
783 if (empty($srcfile)) {
784 return -1;
785 }
786 if (empty($destfile)) {
787 $destfile = $srcfile;
788 }
789
790 // Clean the aa/bb/../cc into aa/cc
791 $srcfile = preg_replace('/\.\.\/?/', '', $srcfile);
792 $destfile = preg_replace('/\.\.\/?/', '', $destfile);
793
794 $destexists = dol_is_file($destfile);
795 if (($destfile != $srcfile) && $destexists) {
796 return 0;
797 }
798
799 $srcexists = dol_is_file($srcfile);
800 if (!$srcexists) {
801 dol_syslog("files.lib.php::dolReplaceInFile failed to read src file", LOG_WARNING);
802 return -3;
803 }
804
805 $tmpdestfile = $destfile.'.tmp';
806
807 $newpathofsrcfile = dol_osencode($srcfile);
808 $newpathoftmpdestfile = dol_osencode($tmpdestfile);
809 $newpathofdestfile = dol_osencode($destfile);
810 $newdirdestfile = dirname($newpathofdestfile);
811
812 if ($destexists && !is_writable($newpathofdestfile)) {
813 dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
814 return -1;
815 }
816 if (!is_writable($newdirdestfile)) {
817 dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
818 return -2;
819 }
820
821 dol_delete_file($tmpdestfile);
822
823 // Create $newpathoftmpdestfile from $newpathofsrcfile
824 $content = file_get_contents($newpathofsrcfile);
825
826 if (empty($arrayreplacementisregex)) {
827 $content = make_substitutions($content, $arrayreplacement, null);
828 } else {
829 foreach ($arrayreplacement as $key => $value) {
830 $content = preg_replace($key, (string) $value, $content);
831 }
832 }
833
834 file_put_contents($newpathoftmpdestfile, $content);
835 dolChmod($newpathoftmpdestfile, $newmask);
836
837 // Rename
838 $moreinfo = array('gen_or_uploaded' => 'unknown');
839 $result = dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase, $moreinfo);
840 if (!$result) {
841 dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
842 return -3;
843 }
844 if (empty($newmask) && getDolGlobalString('MAIN_UMASK')) {
845 $newmask = getDolGlobalString('MAIN_UMASK');
846 }
847 if (empty($newmask)) { // This should no happen
848 dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
849 $newmask = '0664';
850 }
851
852 dolChmod($newpathofdestfile, $newmask);
853
854 return 1;
855}
856
864function removePatternFromFile(string $filePath, string $pattern): bool
865{
866 // Check if the file exists
867 if (! file_exists($filePath)) {
868 dol_syslog("files.lib.php::removePatternFromFile: File $filePath does not exist", LOG_WARNING);
869
870 return false;
871 }
872
873 // Read the file content
874 $content = file_get_contents($filePath);
875 if ($content === false) {
876 dol_syslog("files.lib.php::removePatternFromFile: Unable to read the file $filePath", LOG_WARNING);
877
878 return false;
879 }
880
881 // Remove content matching the pattern
882 $updatedContent = preg_replace($pattern, '', $content);
883 if ($updatedContent === null) {
884 dol_syslog("files.lib.php::removePatternFromFile: Error while processing the file $filePath", LOG_WARNING);
885
886 return false;
887 }
888
889 // Write the updated content back to the file
890 $result = file_put_contents($filePath, $updatedContent);
891 if ($result === false) {
892 dol_syslog("files.lib.php::removePatternFromFile: Permission denied to overwrite the target file $filePath", LOG_WARNING);
893
894 return false;
895 }
896
897 dol_syslog("files.lib.php::removePatternFromFile: Content successfully removed in the file $filePath", LOG_INFO);
898
899 return true;
900}
901
902
903
916function dol_copy($srcfile, $destfile, $newmask = '0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 0)
917{
918 global $db, $user;
919
920 dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
921
922 if (empty($srcfile) || empty($destfile)) {
923 return -1;
924 }
925
926 $destexists = dol_is_file($destfile);
927 if (!$overwriteifexists && $destexists) {
928 return 0;
929 }
930
931 $newpathofsrcfile = dol_osencode($srcfile);
932 $newpathofdestfile = dol_osencode($destfile);
933 $newdirdestfile = dirname($newpathofdestfile);
934
935 if ($destexists && !is_writable($newpathofdestfile)) {
936 dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
937 return -1;
938 }
939 if (!is_writable($newdirdestfile)) {
940 dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
941 return -2;
942 }
943
944 // Check virus
945 $testvirusarray = array();
946 if ($testvirus) {
947 $testvirusarray = dolCheckVirus($srcfile, $destfile);
948 if (count($testvirusarray)) {
949 dol_syslog("files.lib.php::dol_copy canceled because a virus was found into source file. we ignore the copy request.", LOG_WARNING);
950 return -3;
951 }
952 }
953
954 // Copy with overwriting if exists
955 $result = @copy($newpathofsrcfile, $newpathofdestfile);
956 //$result=copy($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
957 if (!$result) {
958 dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
959 return -3;
960 }
961 if (empty($newmask) && getDolGlobalString('MAIN_UMASK')) {
962 $newmask = getDolGlobalString('MAIN_UMASK');
963 }
964 if (empty($newmask)) { // This should no happen
965 dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
966 $newmask = '0664';
967 }
968
969 dolChmod($newpathofdestfile, $newmask);
970
971 if ($result && $indexdatabase) {
972 // Add entry into ecm database
973 $rel_filetocopyafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $newpathofdestfile);
974 if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetocopyafter)) { // If not a tmp file
975 $rel_filetocopyafter = preg_replace('/^[\\/]/', '', $rel_filetocopyafter);
976 //var_dump($rel_filetorenamebefore.' - '.$rel_filetocopyafter);exit;
977
978 dol_syslog("Try to copy also entries in database for: ".$rel_filetocopyafter, LOG_DEBUG);
979 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
980
981 $ecmfiletarget = new EcmFiles($db);
982 $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetocopyafter);
983 if ($resultecmtarget > 0) { // An entry for target name already exists for target, we delete it, a new one will be created.
984 dol_syslog("ECM dest file found, remove it", LOG_DEBUG);
985 $ecmfiletarget->delete($user);
986 } else {
987 dol_syslog("ECM dest file not found, create it", LOG_DEBUG);
988 }
989
990 $ecmSrcfile = new EcmFiles($db);
991 $resultecm = $ecmSrcfile->fetch(0, '', $srcfile);
992 if ($resultecm) {
993 dol_syslog("Fetch src file ok", LOG_DEBUG);
994 } else {
995 dol_syslog("Fetch src file error", LOG_DEBUG);
996 }
997
998 $ecmfile = new EcmFiles($db);
999 $filename = basename($rel_filetocopyafter);
1000 $rel_dir = dirname($rel_filetocopyafter);
1001 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1002 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1003
1004 $ecmfile->filepath = $rel_dir;
1005 $ecmfile->filename = $filename;
1006 $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file
1007 $ecmfile->fullpath_orig = $srcfile;
1008 $ecmfile->gen_or_uploaded = 'copy';
1009 $ecmfile->description = $ecmSrcfile->description;
1010 $ecmfile->keywords = $ecmSrcfile->keywords;
1011 $resultecm = $ecmfile->create($user);
1012 if ($resultecm < 0) {
1013 dol_syslog("Create ECM file ok", LOG_DEBUG);
1014 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1015 } else {
1016 dol_syslog("Create ECM file error", LOG_DEBUG);
1017 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1018 }
1019
1020 if ($resultecm > 0) {
1021 $result = 1;
1022 } else {
1023 $result = -1;
1024 }
1025 }
1026 }
1027
1028 return (int) $result;
1029}
1030
1045function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement = null, $excludesubdir = 0, $excludefileext = null, $excludearchivefiles = 0)
1046{
1047 $result = 0;
1048
1049 dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
1050
1051 if (empty($srcfile) || empty($destfile)) {
1052 return -1;
1053 }
1054
1055 $destexists = dol_is_dir($destfile);
1056
1057 //if (! $overwriteifexists && $destexists) return 0; // The overwriteifexists is for files only, so propagated to dol_copy only.
1058
1059 if (!$destexists) {
1060 // We must set mask just before creating dir, because it can be set differently by dol_copy
1061 umask(0);
1062 $dirmaskdec = octdec($newmask);
1063 if (empty($newmask) && getDolGlobalString('MAIN_UMASK')) {
1064 $dirmaskdec = octdec(getDolGlobalString('MAIN_UMASK'));
1065 }
1066 $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
1067
1068 $result = dol_mkdir($destfile, '', decoct($dirmaskdec));
1069
1070 if (!dol_is_dir($destfile)) {
1071 // The output directory does not exists and we failed to create it. So we stop here.
1072 return -1;
1073 }
1074 }
1075
1076 $ossrcfile = dol_osencode($srcfile);
1077 $osdestfile = dol_osencode($destfile);
1078
1079 // Recursive function to copy all subdirectories and contents:
1080 if (is_dir($ossrcfile)) {
1081 $dir_handle = opendir($ossrcfile);
1082 $tmpresult = 0; // Initialised before loop to keep old behavior, may be needed inside loop
1083 while ($file = readdir($dir_handle)) {
1084 if ($file != "." && $file != ".." && !is_link($ossrcfile."/".$file)) {
1085 if (is_dir($ossrcfile."/".$file)) {
1086 if (empty($excludesubdir) || ($excludesubdir == 2 && dol_strlen($file) == 2)) {
1087 $newfile = $file;
1088 // Replace destination filename with a new one
1089 if (is_array($arrayreplacement)) {
1090 foreach ($arrayreplacement as $key => $val) {
1091 $newfile = str_replace($key, $val, $newfile);
1092 }
1093 }
1094 //var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists");
1095 $tmpresult = dolCopyDir($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir, $excludefileext, $excludearchivefiles);
1096 }
1097 } else {
1098 $newfile = $file;
1099
1100 if (is_array($excludefileext)) {
1101 $extension = pathinfo($file, PATHINFO_EXTENSION);
1102 if (in_array($extension, $excludefileext)) {
1103 //print "We exclude the file ".$file." because its extension is inside list ".join(', ', $excludefileext); exit;
1104 continue;
1105 }
1106 }
1107
1108 if ($excludearchivefiles == 1) {
1109 $extension = pathinfo($file, PATHINFO_EXTENSION);
1110 if (preg_match('/^[v|d]\d+$/', $extension)) {
1111 continue;
1112 }
1113 }
1114
1115 // Replace destination filename with a new one
1116 if (is_array($arrayreplacement)) {
1117 foreach ($arrayreplacement as $key => $val) {
1118 $newfile = str_replace($key, $val, $newfile);
1119 }
1120 }
1121 $tmpresult = dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists);
1122 }
1123 // Set result
1124 if ($result > 0 && $tmpresult >= 0) {
1125 // Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass
1126 } else {
1127 $result = $tmpresult;
1128 }
1129 if ($result < 0) {
1130 break;
1131 }
1132 }
1133 }
1134 closedir($dir_handle);
1135 } else {
1136 // Source directory does not exists
1137 $result = -2;
1138 }
1139
1140 return (int) $result;
1141}
1142
1143
1162function dol_move($srcfile, $destfile, $newmask = '0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1, $moreinfo = array(), $entity = null)
1163{
1164 global $user, $db;
1165 $result = false;
1166
1167 dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
1168 $srcexists = dol_is_file($srcfile);
1169 $destexists = dol_is_file($destfile);
1170
1171 if (!$srcexists) {
1172 dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
1173 return false;
1174 }
1175
1176 if ($overwriteifexists || !$destexists) {
1177 $newpathofsrcfile = dol_osencode($srcfile);
1178 $newpathofdestfile = dol_osencode($destfile);
1179
1180 // Check on virus
1181 $testvirusarray = array();
1182 if ($testvirus) {
1183 // Check using filename + antivirus
1184 $testvirusarray = dolCheckVirus($newpathofsrcfile, $newpathofdestfile);
1185 if (count($testvirusarray)) {
1186 dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1187 return false;
1188 }
1189 } else {
1190 // Check using filename only
1191 $testvirusarray = dolCheckOnFileName($newpathofsrcfile, $newpathofdestfile);
1192 if (count($testvirusarray)) {
1193 dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. We ignore the move request.", LOG_WARNING);
1194 return false;
1195 }
1196 }
1197
1198 global $dolibarr_main_restrict_os_commands;
1199 if (!empty($dolibarr_main_restrict_os_commands)) {
1200 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
1201 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
1202 if (in_array(basename($destfile), $arrayofallowedcommand)) {
1203 //$langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
1204 //setEventMessages($langs->trans("ErrorFilenameReserved", basename($destfile)), null, 'errors');
1205 dol_syslog("files.lib.php::dol_move canceled because target filename ".basename($destfile)." is using a reserved command name. we ignore the move request.", LOG_WARNING);
1206 return false;
1207 }
1208 }
1209
1210 $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
1211 if (!$result) {
1212 if ($destexists) {
1213 dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
1214 // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
1215 dol_delete_file($destfile);
1216 $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
1217 } else {
1218 dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
1219 }
1220 }
1221
1222 // Move ok
1223 if ($result && $indexdatabase) {
1224 // Rename entry into ecm database
1225 $rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $srcfile);
1226 $rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destfile);
1227 if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) { // If not a tmp file
1228 $rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
1229 $rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
1230 //var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter);exit;
1231
1232 dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG);
1233 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1234
1235 $ecmfiletarget = new EcmFiles($db);
1236 $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter, '', '', '', 0, $entity);
1237 if ($resultecmtarget > 0) { // An entry for target name already exists for target, we delete it, a new one will be created.
1238 $ecmfiletarget->delete($user);
1239 }
1240
1241 $ecmfile = new EcmFiles($db);
1242 $resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore, '', '', '', 0, $entity);
1243 if ($resultecm > 0) { // If an entry was found for src file, we use it to move entry
1244 $filename = basename($rel_filetorenameafter);
1245 $rel_dir = dirname($rel_filetorenameafter);
1246 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1247 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1248
1249 $ecmfile->filepath = $rel_dir;
1250 $ecmfile->filename = $filename;
1251
1252 $resultecm = $ecmfile->update($user);
1253 } elseif ($resultecm == 0) { // If no entry were found for src files, create/update target file
1254 $filename = basename($rel_filetorenameafter);
1255 $rel_dir = dirname($rel_filetorenameafter);
1256 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1257 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1258
1259 $ecmfile->filepath = $rel_dir;
1260 $ecmfile->filename = $filename;
1261 $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file
1262 $ecmfile->fullpath_orig = basename($srcfile);
1263 if (!empty($moreinfo) && !empty($moreinfo['gen_or_uploaded'])) {
1264 $ecmfile->gen_or_uploaded = $moreinfo['gen_or_uploaded'];
1265 } else {
1266 $ecmfile->gen_or_uploaded = 'unknown'; // 'generated', 'uploaded', 'api'
1267 }
1268 if (!empty($moreinfo) && !empty($moreinfo['description'])) {
1269 $ecmfile->description = $moreinfo['description']; // indexed content
1270 } else {
1271 $ecmfile->description = ''; // indexed content
1272 }
1273 if (!empty($moreinfo) && !empty($moreinfo['keywords'])) {
1274 $ecmfile->keywords = $moreinfo['keywords']; // indexed content
1275 } else {
1276 $ecmfile->keywords = ''; // keyword content
1277 }
1278 if (!empty($moreinfo) && !empty($moreinfo['note_private'])) {
1279 $ecmfile->note_private = $moreinfo['note_private'];
1280 }
1281 if (!empty($moreinfo) && !empty($moreinfo['note_public'])) {
1282 $ecmfile->note_public = $moreinfo['note_public'];
1283 }
1284 if (!empty($moreinfo) && !empty($moreinfo['src_object_type'])) {
1285 $ecmfile->src_object_type = $moreinfo['src_object_type']; // Usually the $object->table_element
1286 }
1287 if (!empty($moreinfo) && !empty($moreinfo['src_object_id'])) {
1288 $ecmfile->src_object_id = $moreinfo['src_object_id'];
1289 }
1290 if (!empty($moreinfo) && !empty($moreinfo['agenda_id'])) {
1291 $ecmfile->agenda_id = $moreinfo['agenda_id'];
1292 }
1293 if (!empty($moreinfo) && !empty($moreinfo['position'])) {
1294 $ecmfile->position = $moreinfo['position'];
1295 }
1296 if (!empty($moreinfo) && !empty($moreinfo['cover'])) {
1297 $ecmfile->cover = $moreinfo['cover'];
1298 }
1299 if (!empty($moreinfo) && !empty($moreinfo['share'])) {
1300 $ecmfile->share = $moreinfo['share'];
1301 }
1302 if (! empty($entity)) {
1303 $ecmfile->entity = $entity;
1304 }
1305
1306 $resultecm = $ecmfile->create($user);
1307 if ($resultecm < 0) {
1308 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1309 } else {
1310 if (!empty($moreinfo) && !empty($moreinfo['array_options']) && is_array($moreinfo['array_options'])) {
1311 $ecmfile->array_options = $moreinfo['array_options'];
1312 $resultecm = $ecmfile->insertExtraFields();
1313 if ($resultecm < 0) {
1314 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1315 }
1316 }
1317 }
1318 } elseif ($resultecm < 0) {
1319 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1320 }
1321
1322 if ($resultecm > 0) {
1323 $result = true;
1324 } else {
1325 $result = false;
1326 }
1327 }
1328 }
1329
1330 if (empty($newmask)) {
1331 $newmask = getDolGlobalString('MAIN_UMASK', '0755');
1332 }
1333
1334 // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
1335 // to allow mask usage for dir, we should introduce a new param "isdir" to 1 to complete newmask like this
1336 // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories
1337 dolChmod($newpathofdestfile, $newmask);
1338 }
1339
1340 return $result;
1341}
1342
1353function dol_move_dir($srcdir, $destdir, $overwriteifexists = 1, $indexdatabase = 1, $renamedircontent = 1)
1354{
1355 $result = false;
1356
1357 dol_syslog("files.lib.php::dol_move_dir srcdir=".$srcdir." destdir=".$destdir." overwritifexists=".$overwriteifexists." indexdatabase=".$indexdatabase." renamedircontent=".$renamedircontent);
1358 $srcexists = dol_is_dir($srcdir);
1359 $srcbasename = basename($srcdir);
1360 $destexists = dol_is_dir($destdir);
1361
1362 if (!$srcexists) {
1363 dol_syslog("files.lib.php::dol_move_dir srcdir does not exists. Move fails");
1364 return false;
1365 }
1366
1367 if ($overwriteifexists || !$destexists) {
1368 $newpathofsrcdir = dol_osencode($srcdir);
1369 $newpathofdestdir = dol_osencode($destdir);
1370
1371 // On windows, if destination directory exists and is empty, command fails. So if overwrite is on, we first remove destination directory.
1372 // On linux, if destination directory exists and is empty, command succeed. So no need to delete di destination directory first.
1373 // Note: If dir exists and is not empty, it will and must fail on both linux and windows even, if option $overwriteifexists is on.
1374 if ($overwriteifexists) {
1375 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1376 if (is_dir($newpathofdestdir)) {
1377 @rmdir($newpathofdestdir);
1378 }
1379 }
1380 }
1381
1382 $result = @rename($newpathofsrcdir, $newpathofdestdir);
1383
1384 // Now rename contents in the directory after the move to match the new destination
1385 if ($result && $renamedircontent) {
1386 if (file_exists($newpathofdestdir)) {
1387 $destbasename = basename($newpathofdestdir);
1388 $files = dol_dir_list($newpathofdestdir);
1389 if (!empty($files) && is_array($files)) {
1390 foreach ($files as $key => $file) {
1391 if (!file_exists($file["fullname"])) {
1392 continue;
1393 }
1394 $filepath = $file["path"];
1395 $oldname = $file["name"];
1396
1397 $newname = str_replace($srcbasename, $destbasename, $oldname);
1398 if (!empty($newname) && $newname !== $oldname) {
1399 if ($file["type"] == "dir") {
1400 $res = dol_move_dir($filepath.'/'.$oldname, $filepath.'/'.$newname, $overwriteifexists, $indexdatabase, $renamedircontent);
1401 } else {
1402 $moreinfo = array('gen_or_uploaded' => 'unknown');
1403 $res = dol_move($filepath.'/'.$oldname, $filepath.'/'.$newname, '0', $overwriteifexists, 0, $indexdatabase, $moreinfo);
1404 }
1405 if (!$res) {
1406 return $result;
1407 }
1408 }
1409 }
1410 $result = true;
1411 }
1412 }
1413 }
1414 }
1415 return $result;
1416}
1417
1425function dol_unescapefile($filename)
1426{
1427 // Remove path information and dots around the filename, to prevent uploading
1428 // into different directories or replacing hidden system files.
1429 // Also remove control characters and spaces (\x00..\x20) around the filename:
1430 return trim(basename($filename), ".\x00..\x20");
1431}
1432
1433
1441function dolCheckVirus($src_file, $dest_file = '')
1442{
1443 global $db;
1444
1445 $reterrors = dolCheckOnFileName($src_file, $dest_file);
1446 if (!empty($reterrors)) {
1447 return $reterrors;
1448 }
1449
1450 if (getDolGlobalString('MAIN_ANTIVIRUS_UPLOAD_ON')) {
1451 if (!class_exists('AntiVir')) {
1452 require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
1453 }
1454 $antivir = new AntiVir($db);
1455 $result = $antivir->dol_avscan_file($src_file);
1456 if ($result < 0) { // If virus or error, we stop here
1457 if ($result == -99) {
1458 $reterrors['ErrorFileIsInfectedKnownVirus'] = implode(', ', $antivir->errors);
1459 } else { // -98, -97, etc.
1460 $reterrors['ErrorAntivirusNotAvailable'] = implode(', ', $antivir->errors);
1461 }
1462 return $reterrors;
1463 }
1464 }
1465 return array();
1466}
1467
1475function dolCheckOnFileName($src_file, $dest_file = '')
1476{
1477 if (preg_match('/\.pdf$/i', $dest_file)) {
1478 if (!getDolGlobalString('MAIN_ANTIVIRUS_ALLOW_JS_IN_PDF')) {
1479 dol_syslog("dolCheckOnFileName Check that pdf does not contains js code");
1480
1481 $tmp = file_get_contents(trim($src_file));
1482 if (preg_match('/[\n\s]+\/JavaScript[\n\s]+/m', $tmp)) {
1483 return array('ErrorFileIsAnInfectedPDFWithJSInside' => 'File is a PDF with javascript inside');
1484 }
1485 } else {
1486 dol_syslog("dolCheckOnFileName Check js into pdf disabled");
1487 }
1488 }
1489
1490 return array();
1491}
1492
1493
1515function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $keyforsourcefile = 'addedfile', $upload_dir = '', $mode = 0)
1516{
1517 global $conf;
1518 global $object, $hookmanager;
1519
1520 $reshook = 0;
1521 $file_name = $dest_file;
1522 $successcode = 1;
1523
1524 if (empty($nohook)) {
1525 $reshook = $hookmanager->initHooks(array('fileslib'));
1526
1527 $parameters = array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $keyforsourcefile, 'allowoverwrite' => $allowoverwrite);
1528 $reshook = $hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
1529 }
1530
1531 if (empty($reshook)) {
1532 // If an upload error has been reported
1533 if ($uploaderrorcode) {
1534 switch ($uploaderrorcode) {
1535 case UPLOAD_ERR_INI_SIZE: // 1
1536 return 'ErrorFileSizeTooLarge';
1537 case UPLOAD_ERR_FORM_SIZE: // 2 - Exceed the MAX_FILE_SIZE specified into a field in form
1538 return 'ErrorFileSizeTooLarge';
1539 case UPLOAD_ERR_PARTIAL: // 3
1540 return 'ErrorPartialFile';
1541 case UPLOAD_ERR_NO_TMP_DIR: //
1542 return 'ErrorNoTmpDir';
1543 case UPLOAD_ERR_CANT_WRITE:
1544 return 'ErrorFailedToWriteInDir';
1545 case UPLOAD_ERR_EXTENSION:
1546 return 'ErrorUploadBlockedByAddon';
1547 default:
1548 break;
1549 }
1550 }
1551
1552 // Security:
1553 // If we need to make a virus scan
1554 if (empty($disablevirusscan) && file_exists($src_file)) {
1555 $checkvirusarray = dolCheckVirus($src_file, $dest_file);
1556 if (count($checkvirusarray)) {
1557 dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: errors='.implode(',', $checkvirusarray), LOG_WARNING);
1558 // We return a translation key alone, so the caller can translate it. The technical message of the
1559 // antivirus is not appended to it (that would break the translation), it is kept into the log only.
1560 foreach (array_keys($checkvirusarray) as $errorkey) {
1561 if (is_string($errorkey)) { // A check that knows its own error key returns it as array key
1562 return $errorkey;
1563 }
1564 }
1565 return 'ErrorFileIsInfectedWithAVirus';
1566 }
1567 }
1568
1569 // Security:
1570 // Disallow file with some extensions. We rename them.
1571 // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
1572 if (isAFileWithExecutableContent($dest_file) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
1573 // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
1574 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
1575 if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
1576 $publicmediasdirwithslash .= '/';
1577 }
1578
1579 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0 || !getDolGlobalInt("MAIN_DOCUMENT_DISABLE_NOEXE_IN_MEDIAS_DIR")) { // We never add .noexe on files into media directory
1580 $file_name .= '.noexe';
1581 $successcode = 2;
1582 }
1583 }
1584
1585 // Security:
1586 // We refuse cache files/dirs, upload using .. and pipes into filenames.
1587 if (preg_match('/^\./', basename($src_file)) || preg_match('/\.\./', $src_file) || preg_match('/[<>|]/', $src_file)) {
1588 dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
1589 return -1;
1590 }
1591
1592 // Security:
1593 // We refuse cache files/dirs, upload using .. and pipes into filenames.
1594 if (preg_match('/^\./', basename($dest_file)) || preg_match('/\.\./', $dest_file) || preg_match('/[<>|]/', $dest_file)) {
1595 dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
1596 return -2;
1597 }
1598 }
1599
1600 if ($reshook < 0) { // At least one blocking error returned by one hook
1601 $errmsg = implode(',', $hookmanager->errors);
1602 if (empty($errmsg)) {
1603 $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1604 }
1605 return $errmsg;
1606 } elseif (empty($reshook)) {
1607 // The file functions must be in OS filesystem encoding.
1608 $src_file_osencoded = dol_osencode($src_file);
1609 $file_name_osencoded = dol_osencode($file_name);
1610
1611 // Check if destination dir is writable
1612 if (!is_writable(dirname($file_name_osencoded))) {
1613 dol_syslog("Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded)." is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1614 return 'ErrorDirNotWritable';
1615 }
1616
1617 // Check if destination file already exists
1618 if (!$allowoverwrite) {
1619 if (file_exists($file_name_osencoded)) {
1620 dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1621 return 'ErrorFileAlreadyExists';
1622 }
1623 } else { // We are allowed to erase
1624 if (is_dir($file_name_osencoded)) { // If there is a directory with name of file to create
1625 dol_syslog("Files.lib::dol_move_uploaded_file A directory with name ".$file_name." already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
1626 return 'ErrorDirWithFileNameAlreadyExists';
1627 }
1628 }
1629
1630 // Move file using a simple system function
1631 if ($mode == 0) {
1632 $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1633 } else {
1634 $return = rename($src_file_osencoded, $file_name_osencoded);
1635 }
1636
1637 if ($return) {
1638 dolChmod($file_name_osencoded);
1639 dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=" . getDolGlobalString('MAIN_UMASK'), LOG_DEBUG);
1640 return $successcode; // Success
1641 } else {
1642 dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
1643 return -3; // Unknown error
1644 }
1645 }
1646
1647 return $successcode; // Success
1648}
1649
1665function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, $object = null, $allowdotdot = false, $indexdatabase = 1, $nolog = 0)
1666{
1667 global $db, $user;
1668 global $hookmanager;
1669
1670 if (empty($nolog)) {
1671 dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
1672 }
1673
1674 // Security:
1675 // We refuse transversal using .. and pipes into filenames.
1676 if ((!$allowdotdot && preg_match('/\.\./', $file)) || preg_match('/[<>|]/', $file)) {
1677 dol_syslog("Refused to delete file ".$file, LOG_WARNING);
1678 return false;
1679 }
1680
1681 $reshook = 0;
1682 if (empty($nohook) && !empty($hookmanager)) {
1683 $hookmanager->initHooks(array('fileslib'));
1684
1685 $parameters = array(
1686 'file' => $file,
1687 'disableglob' => $disableglob,
1688 'nophperrors' => $nophperrors
1689 );
1690 $reshook = $hookmanager->executeHooks('deleteFile', $parameters, $object);
1691 }
1692
1693 if (empty($nohook) && $reshook != 0) { // reshook = 0 to do standard actions, 1 = ok and replace, -1 = ko
1694 dol_syslog("reshook=".$reshook);
1695 if ($reshook < 0) {
1696 return false;
1697 }
1698 return true;
1699 } else {
1700 $file_osencoded = dol_osencode($file); // New filename encoded in OS filesystem encoding charset
1701 if (empty($disableglob) && !empty($file_osencoded)) {
1702 $ok = true;
1703 $globencoded = str_replace('[', '\[', $file_osencoded);
1704 $globencoded = str_replace(']', '\]', $globencoded);
1705 $listoffiles = glob($globencoded); // This scan dir for files. If file does not exists, return empty.
1706
1707 if (!empty($listoffiles) && is_array($listoffiles)) {
1708 foreach ($listoffiles as $filename) {
1709 if ($nophperrors) {
1710 $ok = @unlink($filename);
1711 } else {
1712 $ok = unlink($filename);
1713 }
1714
1715 // If it fails and it is because of the missing write permission on parent dir
1716 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1717 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);
1718 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1719 // Now we retry deletion
1720 if ($nophperrors) {
1721 $ok = @unlink($filename);
1722 } else {
1723 $ok = unlink($filename);
1724 }
1725 }
1726
1727 if ($ok) {
1728 if (empty($nolog)) {
1729 dol_syslog("Removed file ".$filename, LOG_DEBUG);
1730 }
1731
1732 // Delete entry into ecm database
1733 $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filename);
1734 if (!preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) { // If not a tmp file
1735 if (is_object($db) && $indexdatabase) { // $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
1736 $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
1737 $rel_filetodelete = preg_replace('/\.noexe$/', '', $rel_filetodelete);
1738
1739 dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1740 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1741 $ecmfile = new EcmFiles($db);
1742 $entity = (isset($object->entity) ? $object->entity : null);
1743 $result = $ecmfile->fetch(0, '', $rel_filetodelete, '', '', '', 0, $entity);
1744 if ($result >= 0 && $ecmfile->id > 0) {
1745 $result = $ecmfile->delete($user);
1746 }
1747 if ($result < 0) {
1748 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1749 }
1750 }
1751 }
1752 } else {
1753 dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
1754 // TODO Failure to remove can be because file was already removed or because of permission
1755 // If error because it does not exists, we should return true, and we should return false if this is a permission problem
1756 }
1757 }
1758 } else {
1759 $ok = true; // nothing to delete when glob is on must return ok
1760 dol_syslog("No files to delete found", LOG_DEBUG);
1761 }
1762 } else {
1763 $ok = false;
1764 if ($nophperrors) {
1765 $ok = @unlink($file_osencoded);
1766 } else {
1767 $ok = unlink($file_osencoded);
1768 }
1769
1770 $filename = $file_osencoded;
1771
1772 // If it fails and it is because of the missing write permission on parent dir
1773 if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
1774 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);
1775 dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
1776 // Now we retry deletion
1777 if ($nophperrors) {
1778 $ok = @unlink($filename);
1779 } else {
1780 $ok = unlink($filename);
1781 }
1782 }
1783
1784 if ($ok) {
1785 if (empty($nolog)) {
1786 dol_syslog("Removed file ".$filename, LOG_DEBUG);
1787 }
1788
1789 // Delete entry into ecm database
1790 $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filename);
1791 if (!preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) { // If not a tmp file
1792 if (is_object($db) && $indexdatabase) { // $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
1793 $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
1794 $rel_filetodelete = preg_replace('/\.noexe$/', '', $rel_filetodelete);
1795
1796 dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1797 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1798 $ecmfile = new EcmFiles($db);
1799 $entity = (isset($object->entity) ? $object->entity : null);
1800 $result = $ecmfile->fetch(0, '', $rel_filetodelete, '', '', '', 0, $entity);
1801 if ($result >= 0 && $ecmfile->id > 0) {
1802 $result = $ecmfile->delete($user);
1803 }
1804 if ($result < 0) {
1805 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1806 }
1807 }
1808 }
1809 } else {
1810 dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
1811 }
1812 }
1813
1814 return $ok;
1815 }
1816}
1817
1827function dol_delete_dir($dir, $nophperrors = 0)
1828{
1829 // Security:
1830 // We refuse transversal using .. and pipes into filenames.
1831 if (preg_match('/\.\./', $dir) || preg_match('/[<>|]/', $dir)) {
1832 dol_syslog("Refused to delete dir ".$dir.' (contains invalid char sequence)', LOG_WARNING);
1833 return false;
1834 }
1835
1836 $dir_osencoded = dol_osencode($dir);
1837 return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1838}
1839
1853function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0, $indexdatabase = 1, $nolog = 0, $level = 0)
1854{
1855 if (empty($nolog) || empty($level)) {
1856 dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1857 }
1858 if ($level > 1000) {
1859 dol_syslog("functions.lib:dol_delete_dir_recursive too many depth", LOG_WARNING);
1860 }
1861
1862 if (dol_is_dir($dir)) {
1863 $dir_osencoded = dol_osencode($dir);
1864 if ($handle = opendir("$dir_osencoded")) {
1865 while (false !== ($item = readdir($handle))) {
1866 if (!utf8_check($item)) {
1867 $item = mb_convert_encoding($item, 'UTF-8', 'ISO-8859-1'); // should be useless
1868 }
1869
1870 if ($item != "." && $item != "..") {
1871 if (is_dir(dol_osencode("$dir/$item")) && !is_link(dol_osencode("$dir/$item"))) {
1872 $count = dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted, $indexdatabase, $nolog, ($level + 1));
1873 } else {
1874 if (!is_link(dol_osencode("$dir/$item"))) {
1875 dolChmod(dol_osencode("$dir/$item")); // Try to set permission to write on file (chmod would follow a symlink and change its target)
1876 }
1877 $result = dol_delete_file("$dir/$item", 1, $nophperrors, 0, null, false, $indexdatabase, $nolog);
1878 $count++;
1879 if ($result) {
1880 $countdeleted++;
1881 }
1882 //else print 'Error on '.$item."\n";
1883 }
1884 }
1885 }
1886 closedir($handle);
1887
1888 // Delete also the main directory
1889 if (empty($onlysub)) {
1890 $result = dol_delete_dir($dir, $nophperrors);
1891 $count++;
1892 if ($result) {
1893 $countdeleted++;
1894 }
1895 //else print 'Error on '.$dir."\n";
1896 }
1897 }
1898 }
1899
1900 return $count;
1901}
1902
1903
1913{
1914 global $langs, $conf;
1915
1916 // Define parent dir of elements
1917 $element = $object->element;
1918
1919 if ($object->element == 'order_supplier') {
1920 $dir = $conf->fournisseur->commande->dir_output;
1921 } elseif ($object->element == 'invoice_supplier') {
1922 $dir = $conf->fournisseur->facture->dir_output;
1923 } elseif ($object->element == 'project') {
1924 $dir = $conf->project->dir_output;
1925 } elseif ($object->element == 'shipping') {
1926 $dir = $conf->expedition->dir_output.'/sending';
1927 } elseif ($object->element == 'delivery') {
1928 $dir = $conf->expedition->dir_output.'/receipt';
1929 } elseif ($object->element == 'fichinter') {
1930 $dir = $conf->ficheinter->dir_output;
1931 } elseif ($object->element == 'chequereceipt') {
1932 $dir = $conf->bank->dir_output.'/checkdeposits';
1933 } else {
1934 $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
1935 }
1936
1937 if (empty($dir)) {
1938 $object->error = $langs->trans('ErrorObjectNoSupportedByFunction');
1939 return 0;
1940 }
1941
1942 $refsan = dol_sanitizeFileName($object->ref);
1943 $dir = $dir."/".$refsan;
1944 $filepreviewnew = $dir."/".$refsan.".pdf_preview.png";
1945 $filepreviewnewbis = $dir."/".$refsan.".pdf_preview-0.png";
1946 $filepreviewold = $dir."/".$refsan.".pdf.png";
1947
1948 // For new preview files
1949 if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
1950 if (!dol_delete_file($filepreviewnew, 1)) {
1951 $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnew);
1952 return 0;
1953 }
1954 }
1955 if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
1956 if (!dol_delete_file($filepreviewnewbis, 1)) {
1957 $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnewbis);
1958 return 0;
1959 }
1960 }
1961 // For old preview files
1962 if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
1963 if (!dol_delete_file($filepreviewold, 1)) {
1964 $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewold);
1965 return 0;
1966 }
1967 } else {
1968 $multiple = $filepreviewold.".";
1969 for ($i = 0; $i < 20; $i++) {
1970 $preview = $multiple.$i;
1971
1972 if (file_exists($preview) && is_writable($preview)) {
1973 if (!dol_delete_file($preview, 1)) {
1974 $object->error = $langs->trans("ErrorFailedToOpenFile", $preview);
1975 return 0;
1976 }
1977 }
1978 }
1979 }
1980
1981 return 1;
1982}
1983
1993{
1994 global $conf;
1995
1996 // Create meta file
1997 if (!getDolGlobalString('MAIN_DOC_CREATE_METAFILE')) {
1998 return 0; // By default, no metafile.
1999 }
2000
2001 // Define parent dir of elements
2002 $element = $object->element;
2003
2004 if ($object->element == 'order_supplier') {
2005 $dir = $conf->fournisseur->dir_output.'/commande';
2006 } elseif ($object->element == 'invoice_supplier') {
2007 $dir = $conf->fournisseur->dir_output.'/facture';
2008 } elseif ($object->element == 'project') {
2009 $dir = $conf->project->dir_output;
2010 } elseif ($object->element == 'shipping') {
2011 $dir = $conf->expedition->dir_output.'/sending';
2012 } elseif ($object->element == 'delivery') {
2013 $dir = $conf->expedition->dir_output.'/receipt';
2014 } elseif ($object->element == 'fichinter') {
2015 $dir = $conf->ficheinter->dir_output;
2016 } else {
2017 $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
2018 }
2019
2020 if ($dir) {
2021 $object->fetch_thirdparty();
2022
2023 $objectref = dol_sanitizeFileName((string) $object->ref);
2024 $dir = $dir."/".$objectref;
2025 $file = $dir."/".$objectref.".meta";
2026
2027 if (!is_dir($dir)) {
2028 dol_mkdir($dir);
2029 }
2030
2031 $meta = '';
2032 if (is_dir($dir)) {
2033 if (is_countable($object->lines) && count($object->lines) > 0) {
2034 $nblines = count($object->lines);
2035 } else {
2036 $nblines = 0;
2037 }
2038 $client = $object->thirdparty->name." ".$object->thirdparty->address." ".$object->thirdparty->zip." ".$object->thirdparty->town;
2039 $meta = "REFERENCE=\"".$object->ref."\"
2040 DATE=\"" . dol_print_date($object->date, '')."\"
2041 NB_ITEMS=\"" . $nblines."\"
2042 CLIENT=\"" . $client."\"
2043 AMOUNT_EXCL_TAX=\"" . $object->total_ht."\"
2044 AMOUNT=\"" . $object->total_ttc."\"\n";
2045
2046 for ($i = 0; $i < $nblines; $i++) {
2047 //For the items
2048 $meta .= "ITEM_".$i."_QUANTITY=\"".$object->lines[$i]->qty."\"
2049 ITEM_" . $i."_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht."\"
2050 ITEM_" . $i."_VAT=\"".$object->lines[$i]->tva_tx."\"
2051 ITEM_" . $i."_DESCRIPTION=\"".str_replace("\r\n", "", nl2br($object->lines[$i]->desc))."\"
2052 ";
2053 }
2054 }
2055
2056 $fp = fopen($file, "w");
2057 fwrite($fp, $meta);
2058 fclose($fp);
2059
2060 dolChmod($file);
2061
2062 return 1;
2063 } else {
2064 dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
2065 }
2066
2067 return 0;
2068}
2069
2070
2071
2080function dol_init_file_process($pathtoscan = '', $trackid = '')
2081{
2082 $listofpaths = array();
2083 $listofnames = array();
2084 $listofmimes = array();
2085
2086 if ($pathtoscan) {
2087 $listoffiles = dol_dir_list($pathtoscan, 'files');
2088 foreach ($listoffiles as $key => $val) {
2089 $listofpaths[] = $val['fullname'];
2090 $listofnames[] = $val['name'];
2091 $listofmimes[] = dol_mimetype($val['name']);
2092 }
2093 }
2094 $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
2095 $_SESSION["listofpaths".$keytoavoidconflict] = implode(';', $listofpaths);
2096 $_SESSION["listofnames".$keytoavoidconflict] = implode(';', $listofnames);
2097 $_SESSION["listofmimes".$keytoavoidconflict] = implode(';', $listofmimes);
2098}
2099
2100
2121function dol_add_file_process($upload_dir, $allowoverwrite = 0, $updatesessionordb = 0, $keyforsourcefile = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1, $object = null, $forceFullTextIndexation = '', $mode = 0)
2122{
2123 global $db, $user, $conf, $langs;
2124
2125 $res = 0;
2126
2127 // If mode 1, prepare environment to be compatible with mode 0
2128 if ($mode == 1) {
2129 $_FILES = array($keyforsourcefile => array());
2130 $_FILES[$keyforsourcefile]['tmp_name'] = $keyforsourcefile;
2131 $_FILES[$keyforsourcefile]['name'] = $keyforsourcefile;
2132 $mode = 0;
2133 }
2134
2135 if (!empty($_FILES[$keyforsourcefile])) { // For view $_FILES[$keyforsourcefile]['error']
2136 dol_syslog('dol_add_file_process varfiles = '.$keyforsourcefile.' upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' updatesessionordb='.$updatesessionordb.' savingdocmask='.$savingdocmask, LOG_DEBUG);
2137 $maxfilesinform = getDolGlobalInt("MAIN_SECURITY_MAX_ATTACHMENT_ON_FORMS", 10);
2138 if (is_array($_FILES[$keyforsourcefile]["name"]) && count($_FILES[$keyforsourcefile]["name"]) > $maxfilesinform) {
2139 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
2140 setEventMessages($langs->trans("ErrorTooMuchFileInForm", $maxfilesinform), null, "errors");
2141 return -1;
2142 }
2143
2144 $result = dol_mkdir($upload_dir);
2145 //var_dump($result);exit;
2146
2147 if ($result >= 0) {
2148 $TFile = $_FILES[$keyforsourcefile];
2149 // Convert value of $TFile
2150 if (!is_array($TFile['name'])) {
2151 foreach ($TFile as $key => &$val) {
2152 $val = array($val);
2153 }
2154 }
2155
2156 $nbfile = count($TFile['name']);
2157 $nbok = 0;
2158 for ($i = 0; $i < $nbfile; $i++) {
2159 if (empty($TFile['name'][$i])) {
2160 continue; // For example, when submitting a form with no file name
2161 }
2162
2163 // Define $destfull (path to file including filename) and $destfile (only filename)
2164 $destfile = trim($TFile['name'][$i]);
2165 $destfull = $upload_dir."/".$destfile;
2166 $destfilewithoutext = preg_replace('/\.[^\.]+$/', '', $destfile);
2167
2168 if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
2169 $destfile = trim(preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask));
2170 $destfull = $upload_dir."/".$destfile;
2171 }
2172
2173 $filenameto = basename($destfile);
2174 if (preg_match('/^\./', $filenameto)) {
2175 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
2176 setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
2177 break;
2178 }
2179 // dol_sanitizeFileName the file name and lowercase extension
2180 $info = pathinfo($destfull);
2181 $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
2182 $info = pathinfo($destfile);
2183 $destfile = dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
2184
2185 // Check extension is allowed for upload.
2186 $defaultexecutableextensions = function_exists('getExecutableContent') ? implode(',', getExecutableContent()) : 'htm,html,shtml,js,phar,php,php3,php4,php5,phtml,pht,pl,py,cgi,ksh,sh,bash,bat,cmd,wpk,exe';
2187 $fileextensionrestriction = getDolGlobalString("MAIN_FILE_EXTENSION_UPLOAD_RESTRICTION", $defaultexecutableextensions);
2188 if (!empty($fileextensionrestriction)) {
2189 $arrayofregexextension = explode(",", $fileextensionrestriction);
2190
2191 foreach ($arrayofregexextension as $fileextension) {
2192 if (preg_match('/\.'.preg_quote(trim($fileextension), '/').'$/i', $destfull)) {
2193 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
2194 setEventMessages($langs->trans("ErrorFilenameExtensionNotAllowed", $filenameto), null, 'errors');
2195 return -1;
2196 }
2197 }
2198 }
2199
2200 // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
2201 // this function is also applied when we rename and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
2202 $destfile = dol_string_nohtmltag($destfile);
2203 $destfull = dol_string_nohtmltag($destfull);
2204
2205 // Check that filename is not the one of a reserved allowed CLI command
2206 global $dolibarr_main_restrict_os_commands;
2207 if (!empty($dolibarr_main_restrict_os_commands)) {
2208 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
2209 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
2210 if (in_array($destfile, $arrayofallowedcommand)) {
2211 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
2212 setEventMessages($langs->trans("ErrorFilenameReserved", $destfile), null, 'errors');
2213 return -1;
2214 }
2215 }
2216
2217 // Move file from source directory to final destination. Check for virus is also embedded and a .noexe may also be appended on file name.
2218 $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $keyforsourcefile, $upload_dir, $mode);
2219
2220 if (is_numeric($resupload) && $resupload > 0) { // $resupload can be 'ErrorFileAlreadyExists', 'ErrorFileIsInfectedWithAVirus', 'ErrorFileIsInfectedKnownVirus', 'ErrorAntivirusNotAvailable'
2221 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2222
2223 $tmparraysize = getDefaultImageSizes();
2224 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
2225 $maxheightsmall = $tmparraysize['maxheightsmall'];
2226 $maxwidthmini = $tmparraysize['maxwidthmini'];
2227 $maxheightmini = $tmparraysize['maxheightmini'];
2228 //$quality = $tmparraysize['quality'];
2229 $quality = 50; // For thumbs, we force quality to 50
2230
2231 // Generate thumbs.
2232 if ($generatethumbs) {
2233 if (image_format_supported($destfull) == 1) {
2234 // Create thumbs
2235 // We can't use $object->addThumbs here because there is no $object known
2236
2237 // Used on logon for example
2238 $imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', $quality, "thumbs");
2239 // Create mini thumbs for image (Ratio is near 16/9)
2240 // Used on menu or for setup page for example
2241 $imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', $quality, "thumbs");
2242 }
2243 }
2244
2245 // Update session
2246 if (empty($updatesessionordb)) {
2247 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2248 $formmail = new FormMail($db);
2249 $formmail->trackid = $trackid;
2250 $formmail->add_attached_files($destfull, $destfile, $TFile['type'][$i]);
2251 }
2252
2253 // Update index table of files (llx_ecm_files)
2254 if ($updatesessionordb == 1) {
2255 $sharefile = 0;
2256 if ($TFile['type'][$i] == 'application/pdf' && strpos($_SERVER["REQUEST_URI"], 'product') !== false && getDolGlobalString('PRODUCT_ALLOW_EXTERNAL_DOWNLOAD')) {
2257 $sharefile = 1;
2258 }
2259
2260 // If we allow overwrite, we may need to also overwrite index, so we delete index first so insert can work
2261 if ($allowoverwrite) {
2262 deleteFilesIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), '', $object);
2263 }
2264
2265 $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', $sharefile, $object, $forceFullTextIndexation);
2266 if ($result < 0) {
2267 if ($allowoverwrite) {
2268 // Do not show error message. We can have an error due to DB_ERROR_RECORD_ALREADY_EXISTS
2269 } else {
2270 setEventMessages('WarningFailedToAddFileIntoDatabaseIndex', null, 'warnings');
2271 }
2272 }
2273 }
2274
2275 $nbok++;
2276 } else {
2277 $langs->load("errors");
2278 if (is_numeric($resupload) && $resupload < 0) { // Unknown error
2279 setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
2280 } else { // Known error, $resupload is a translation key
2281 setEventMessages($langs->trans($resupload), null, 'errors');
2282 }
2283 }
2284 }
2285 if ($nbok > 0) {
2286 $res = $nbok;
2287 setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
2288 }
2289 } else {
2290 setEventMessages($langs->trans("ErrorFailedToCreateDir", $upload_dir), null, 'errors');
2291 }
2292 } elseif ($link) {
2293 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
2294 $linkObject = new Link($db);
2295 $linkObject->entity = $conf->entity;
2296 $linkObject->url = $link;
2297 $linkObject->objecttype = GETPOST('objecttype', 'alpha');
2298 $linkObject->objectid = GETPOSTINT('objectid');
2299 $linkObject->label = GETPOST('label', 'alpha');
2300 $res = $linkObject->create($user);
2301
2302 if ($res > 0) {
2303 setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
2304 } else {
2305 setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
2306 }
2307 } else {
2308 $langs->load("errors");
2309 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
2310 }
2311
2312 return $res;
2313}
2314
2315
2327function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletefile = 1, $trackid = '')
2328{
2329 global $db, $langs;
2330
2331 $keytodelete = $filenb;
2332 $keytodelete--;
2333
2334 $listofpaths = array();
2335 $listofnames = array();
2336 $listofmimes = array();
2337 $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
2338 if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
2339 $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
2340 }
2341 if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
2342 $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
2343 }
2344 if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
2345 $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
2346 }
2347
2348 if ($keytodelete >= 0) {
2349 $pathtodelete = $listofpaths[$keytodelete];
2350 $filetodelete = $listofnames[$keytodelete];
2351 if (empty($donotdeletefile)) {
2352 $result = dol_delete_file($pathtodelete, 1); // The delete of ecm database is inside the function dol_delete_file
2353 } else {
2354 $result = 0;
2355 }
2356 if ($result >= 0) {
2357 if (empty($donotdeletefile)) {
2358 $langs->load("other");
2359 setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
2360 }
2361 if (empty($donotupdatesession)) {
2362 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2363 $formmail = new FormMail($db);
2364 $formmail->trackid = $trackid;
2365 $formmail->remove_attached_files($keytodelete);
2366 }
2367 }
2368 }
2369}
2370
2371
2386function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0, $object = null, $forceFullTextIndexation = '')
2387{
2388 global $db, $user;
2389
2390 $result = 0;
2391 $error = 0;
2392
2393 dol_syslog("addFileIntoDatabaseIndex dir=".$dir." file=".$file, LOG_DEBUG);
2394
2395 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
2396
2397 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a temporary directory. TODO Does this test work ?
2398 $filename = basename(preg_replace('/\.noexe$/', '', $file));
2399 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
2400 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
2401
2402 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
2403 $ecmfile = new EcmFiles($db);
2404 $ecmfile->filepath = $rel_dir;
2405 $ecmfile->filename = $filename;
2406 $ecmfile->label = md5_file(dol_osencode($dir.'/'.$file)); // MD5 of file content
2407 $ecmfile->fullpath_orig = $fullpathorig;
2408 $ecmfile->gen_or_uploaded = $mode;
2409 $ecmfile->description = ''; // indexed content
2410 $ecmfile->keywords = ''; // keyword content
2411
2412 if (is_object($object) && $object->id > 0) {
2413 $ecmfile->src_object_id = $object->id;
2414 if (isset($object->table_element)) {
2415 $ecmfile->src_object_type = $object->table_element;
2416 } else {
2417 dol_syslog('Error: object ' . get_class($object) . ' has no table_element attribute.');
2418 return -1;
2419 }
2420 if (isset($object->src_object_description)) {
2421 $ecmfile->description = $object->src_object_description;
2422 }
2423 if (isset($object->src_object_keywords)) {
2424 $ecmfile->keywords = $object->src_object_keywords;
2425 }
2426 if (isset($object->entity)) {
2427 $ecmfile->entity = $object->entity;
2428 }
2429 }
2430
2431 if (getDolGlobalString('MAIN_FORCE_SHARING_ON_ANY_UPLOADED_FILE')) {
2432 $setsharekey = 1;
2433 }
2434
2435 if ($setsharekey) {
2436 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
2437 $ecmfile->share = getRandomPassword(true);
2438 }
2439
2440 // Use a convert tool for Doc to Text
2441 $useFullTextIndexation = getDolGlobalString('MAIN_SAVE_FILE_CONTENT_AS_TEXT'); // Can be '', 'pdftotext' or 'docling'
2442 if (empty($useFullTextIndexation) && $forceFullTextIndexation == '1') {
2443 if (getDolGlobalString('MAIN_SAVE_FILE_CONTENT_AS_TEXT_PDFTOTEXT')) { // Command line for pdftotext
2444 $useFullTextIndexation = 'pdftotext';
2445 } elseif (getDolGlobalString('MAIN_SAVE_FILE_CONTENT_AS_TEXT_DOCLING')) { // Command line for docling
2446 $useFullTextIndexation = 'docling';
2447 }
2448 }
2449
2450 //$useFullTextIndexation = 1;
2451 if ($useFullTextIndexation) {
2452 $ecmfile->filepath = $rel_dir;
2453 $ecmfile->filename = $filename;
2454
2455 $filetoprocess = $dir.'/'.$ecmfile->filename;
2456
2457 $textforfulltextindex = '';
2458 $keywords = '';
2459 $cmd = '';
2460 if (preg_match('/\.pdf/i', $filename)) {
2461 // Convertfile into text
2462 $result = dolDocToText($filetoprocess);
2463
2464 if (empty($result['error'])) {
2465 $textforfulltextindex = $result['content'];
2466 $filetoprocess = $result['keywords'];
2467 $cmd = $result['cmd'];
2468 } else {
2469 $error++;
2470 }
2471 }
2472
2473 if ($cmd) {
2474 $ecmfile->description = 'File content generated by '.$cmd;
2475 }
2476 $ecmfile->content = $textforfulltextindex;
2477 $ecmfile->keywords = $keywords;
2478 }
2479
2480 if (!$error) {
2481 $result = $ecmfile->create($user);
2482 if ($result < 0) {
2483 dol_syslog($ecmfile->error);
2484 }
2485 }
2486 }
2487
2488 return $result;
2489}
2490
2500function deleteFilesIntoDatabaseIndex($dir, $file, $mode = 'uploaded', $object = null)
2501{
2502 global $conf, $db;
2503
2504 $error = 0;
2505
2506 if (empty($dir)) {
2507 dol_syslog("deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
2508 return -1;
2509 }
2510
2511 dol_syslog("deleteFilesIntoDatabaseIndex dir=".$dir." file=".$file, LOG_DEBUG);
2512
2513 $db->begin();
2514
2515 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
2516
2517 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a temporary directory. TODO Does this test work ?
2518 //$filename = basename($file);
2519 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
2520 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
2521
2522 if (!$error) {
2523 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'ecm_files';
2524 if (isset($object->entity)) {
2525 $sql .= ' WHERE entity = ' . ((int) $object->entity);
2526 } else {
2527 $sql .= ' WHERE entity = ' . ((int) $conf->entity);
2528 }
2529 $sql .= " AND filepath = '".$db->escape($rel_dir)."'";
2530 if ($file) {
2531 $sql .= " AND filename = '".$db->escape($file)."'";
2532 }
2533 if ($mode) {
2534 $sql .= " AND gen_or_uploaded = '".$db->escape($mode)."'";
2535 }
2536
2537 $resql = $db->query($sql);
2538 if (!$resql) {
2539 $error++;
2540 dol_syslog(__FUNCTION__.' '.$db->lasterror(), LOG_ERR);
2541 }
2542 }
2543 }
2544
2545 // Commit or rollback
2546 if ($error) {
2547 $db->rollback();
2548 return -1 * $error;
2549 } else {
2550 $db->commit();
2551 return 1;
2552 }
2553}
2554
2562function isRealPdf(string $filePath)
2563{
2564 if (!is_file($filePath) || !is_readable($filePath)) {
2565 return false;
2566 }
2567
2568 // Open file
2569 $handle = fopen($filePath, 'rb');
2570 if (!$handle) {
2571 return false;
2572 }
2573 $header = fread($handle, 5);
2574 fclose($handle);
2575
2576 if ($header !== '%PDF-') {
2577 return false;
2578 }
2579
2580 // Check using finfo_file
2581 /*
2582 $finfo = finfo_open(FILEINFO_MIME_TYPE);
2583 $mime = finfo_file($finfo, $filePath);
2584 finfo_close($finfo);
2585 if ($mime !== 'application/pdf') {
2586 return false;
2587 }
2588 */
2589
2590 return true;
2591}
2592
2604function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '', $page = '')
2605{
2606 if (class_exists('Imagick')) {
2607 $image = new Imagick();
2608 try {
2609 // Imagick may have a support for Magick Scripting Language (MSL) that allows to run execution code with some files like SVG. So we need to check
2610 // that file is really a PDF file.
2611 // Note: The Imagick policy options can be disabled into /etc/ImageMagick*/policy.xml.
2612 if (!isRealPdf($fileinput)) {
2613 dol_syslog("We try to convert a PDF file with name ".$fileinput." but it is not a real PDF file (hack attempt ?).", LOG_WARNING);
2614 return -4;
2615 }
2616
2617 $filetoconvert = $fileinput.(($page != '') ? '['.$page.']' : '');
2618 //var_dump($filetoconvert);
2619 $ret = $image->readImage($filetoconvert);
2620 } catch (Exception $e) {
2621 $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
2622 dol_syslog("Failed to read image using Imagick (Try to install package 'apt-get install php-imagick ghostscript' and check there is no policy to disable ".$ext." conversion in /etc/ImageMagick*/policy.xml): ".$e->getMessage(), LOG_WARNING);
2623 return 0;
2624 }
2625
2626 if ($ret) {
2627 $ret = $image->setImageFormat($ext);
2628 if ($ret) {
2629 if (empty($fileoutput)) {
2630 $fileoutput = $fileinput.".".$ext;
2631 }
2632
2633 $count = $image->getNumberImages();
2634
2635 if (!dol_is_file($fileoutput) || is_writable($fileoutput)) {
2636 try {
2637 $ret = $image->writeImages($fileoutput, true);
2638 } catch (Exception $e) {
2639 dol_syslog($e->getMessage(), LOG_WARNING);
2640 }
2641 } else {
2642 dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
2643 }
2644 if ($ret) {
2645 return $count;
2646 } else {
2647 return -3;
2648 }
2649 } else {
2650 return -2;
2651 }
2652 } else {
2653 return -1;
2654 }
2655 } else {
2656 return 0;
2657 }
2658}
2659
2660
2672function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring = null)
2673{
2674 $foundhandler = 0;
2675 //var_dump(basename($inputfile)); exit;
2676
2677 try {
2678 dol_syslog("dol_compress_file mode=".$mode." inputfile=".$inputfile." outputfile=".$outputfile);
2679
2680 $data = implode("", file(dol_osencode($inputfile)));
2681 $compressdata = null;
2682 if ($mode == 'gz' && function_exists('gzencode')) {
2683 $foundhandler = 1;
2684 $compressdata = gzencode($data, 9);
2685 } elseif ($mode == 'bz' && function_exists('bzcompress')) {
2686 $foundhandler = 1;
2687 $compressdata = bzcompress($data, 9);
2688 } elseif ($mode == 'zstd' && function_exists('zstd_compress')) {
2689 $foundhandler = 1;
2690 $compressdata = zstd_compress($data, 9);
2691 } elseif ($mode == 'zip') {
2692 if (class_exists('ZipArchive') && getDolGlobalString('MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS')) {
2693 $foundhandler = 1;
2694
2695 $rootPath = realpath($inputfile);
2696
2697 dol_syslog("Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.' rootPath='.$rootPath);
2698 $zip = new ZipArchive();
2699
2700 if ($zip->open($outputfile, ZipArchive::CREATE) !== true) {
2701 $errorstring = "dol_compress_file failure - Failed to open file ".$outputfile."\n";
2702 dol_syslog($errorstring, LOG_ERR);
2703
2704 global $errormsg;
2705 $errormsg = $errorstring;
2706
2707 return -6;
2708 }
2709
2710 // Create recursive directory iterator
2712 $files = new RecursiveIteratorIterator(
2713 new RecursiveDirectoryIterator($rootPath, FilesystemIterator::UNIX_PATHS),
2714 RecursiveIteratorIterator::LEAVES_ONLY
2715 );
2716 '@phan-var-force SplFileInfo[] $files';
2717
2718 foreach ($files as $name => $file) {
2719 // Skip directories (they would be added automatically)
2720 if (!$file->isDir()) {
2721 // Get real and relative path for current file
2722 $filePath = $file->getPath(); // the full path with filename using the $inputdir root.
2723 $fileName = $file->getFilename();
2724 $fileFullRealPath = $file->getRealPath(); // the full path with name and transformed to use real path directory.
2725
2726 //$relativePath = dol_substr($fileFullRealPath, strlen($rootPath) + 1);
2727 $relativePath = substr(($filePath ? $filePath.'/' : '').$fileName, strlen($rootPath) + 1);
2728
2729 // Add current file to archive
2730 $zip->addFile($fileFullRealPath, $relativePath);
2731 }
2732 }
2733
2734 // Zip archive will be created only after closing object
2735 $zip->close();
2736
2737 dol_syslog("dol_compress_file success - ".$zip->numFiles." files");
2738 return 1;
2739 }
2740
2741 if (defined('ODTPHP_PATHTOPCLZIP')) {
2742 $foundhandler = 1;
2743
2744 include_once ODTPHP_PATHTOPCLZIP.'pclzip.lib.php';
2745 $archive = new PclZip($outputfile);
2746
2747 $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2748
2749 if ($result === 0) {
2750 global $errormsg;
2751 $errormsg = $archive->errorInfo(true);
2752
2753 if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
2754 $errorstring = "PCLZIP_ERR_WRITE_OPEN_FAIL";
2755 dol_syslog("dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
2756 return -4;
2757 }
2758
2759 $errorstring = "dol_compress_file error archive->errorCode = ".$archive->errorCode()." errormsg=".$errormsg;
2760 dol_syslog("dol_compress_file failure - ".$errormsg, LOG_ERR);
2761 return -3;
2762 } else {
2763 dol_syslog("dol_compress_file success - ".count($result)." files");
2764 return 1;
2765 }
2766 }
2767 }
2768
2769 if ($foundhandler && is_string($compressdata)) {
2770 $fp = fopen($outputfile, "w");
2771 fwrite($fp, $compressdata);
2772 fclose($fp);
2773 return 1;
2774 } else {
2775 $errorstring = "Try to zip with format ".$mode." with no handler for this format";
2776 dol_syslog($errorstring, LOG_ERR);
2777
2778 global $errormsg;
2779 $errormsg = $errorstring;
2780 return -2;
2781 }
2782 } catch (Exception $e) {
2783 global $langs, $errormsg;
2784 $langs->load("errors");
2785 $errormsg = $langs->trans("ErrorFailedToWriteInDir");
2786
2787 $errorstring = "Failed to open file ".$outputfile;
2788 dol_syslog($errorstring, LOG_ERR);
2789 return -1;
2790 }
2791}
2792
2801function dol_uncompress($inputfile, $outputdir)
2802{
2803 global $langs, $db;
2804
2805 $fileinfo = pathinfo($inputfile);
2806 $fileinfo["extension"] = strtolower($fileinfo["extension"]);
2807
2808 if ($fileinfo["extension"] == "zip") {
2809 if (defined('ODTPHP_PATHTOPCLZIP') && !getDolGlobalString('MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS')) {
2810 dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
2811 include_once ODTPHP_PATHTOPCLZIP.'pclzip.lib.php';
2812 $archive = new PclZip($inputfile);
2813
2814 // We create output dir manually, so it uses the correct permission (When created by the archive->extract, dir is rwx for everybody).
2815 dol_mkdir(dol_sanitizePathName($outputdir));
2816
2817 try {
2818 // Extract into outputdir, but only files that match the regex '/^((?!\.\.).)*$/' that means "does not include .."
2819 $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG, '/^((?!\.\.).)*$/');
2820 } catch (Exception $e) {
2821 return array('error' => $e->getMessage());
2822 }
2823
2824 if (!is_array($result) && $result <= 0) {
2825 return array('error' => $archive->errorInfo(true));
2826 } else {
2827 $ok = 1;
2828 $errmsg = '';
2829 // Loop on each file to check result for unzipping file
2830 foreach ($result as $key => $val) {
2831 if ($val['status'] == 'path_creation_fail') {
2832 $langs->load("errors");
2833 $ok = 0;
2834 $errmsg = $langs->trans("ErrorFailToCreateDir", $val['filename']);
2835 break;
2836 }
2837 if ($val['status'] == 'write_protected') {
2838 $langs->load("errors");
2839 $ok = 0;
2840 $errmsg = $langs->trans("ErrorFailToCreateFile", $val['filename']);
2841 break;
2842 }
2843 }
2844
2845 if ($ok) {
2846 return array();
2847 } else {
2848 return array('error' => $errmsg);
2849 }
2850 }
2851 }
2852
2853 if (class_exists('ZipArchive')) { // Must install php-zip to have it
2854 dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
2855 $zip = new ZipArchive();
2856 $res = $zip->open($inputfile);
2857 if ($res === true) {
2858 //$zip->extractTo($outputdir.'/');
2859 // We must extract one file at time so we can check that file name does not contain '..' to avoid transversal path of zip built for example using
2860 // python3 path_traversal_archiver.py <Created_file_name> test.zip -l 10 -p tmp/
2861 // with -l is the range of dot to go back in path.
2862 // and path_traversal_archiver.py found at https://github.com/Alamot/code-snippets/blob/master/path_traversal/path_traversal_archiver.py
2863 for ($i = 0; $i < $zip->numFiles; $i++) {
2864 if (preg_match('/\.\./', $zip->getNameIndex($i))) {
2865 dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
2866 continue; // Discard the file
2867 }
2868 $zip->extractTo($outputdir.'/', array($zip->getNameIndex($i)));
2869 }
2870
2871 $zip->close();
2872 return array();
2873 } else {
2874 return array('error' => 'ErrUnzipFails');
2875 }
2876 }
2877
2878 return array('error' => 'ErrNoZipEngine');
2879 } elseif (in_array($fileinfo["extension"], array('gz', 'bz2', 'zst'))) {
2880 include_once DOL_DOCUMENT_ROOT."/core/class/utils.class.php";
2881 $utils = new Utils($db);
2882
2883 dol_mkdir(dol_sanitizePathName($outputdir));
2884 $outputfilename = escapeshellcmd(dol_sanitizePathName($outputdir).'/'.dol_sanitizeFileName($fileinfo["filename"]));
2885 dol_delete_file($outputfilename.'.tmp');
2886 dol_delete_file($outputfilename.'.err');
2887
2888 $extension = strtolower(pathinfo($fileinfo["filename"], PATHINFO_EXTENSION));
2889 if ($extension == "tar") {
2890 $cmd = 'tar -C '.escapeshellcmd(dol_sanitizePathName($outputdir)).' -xvf '.escapeshellcmd(dol_sanitizePathName($fileinfo["dirname"]).'/'.dol_sanitizeFileName($fileinfo["basename"]));
2891
2892 $resarray = $utils->executeCLI($cmd, $outputfilename.'.tmp', 0, $outputfilename.'.err', 0);
2893 if ($resarray["result"] != 0) {
2894 $resarray["error"] .= file_get_contents($outputfilename.'.err');
2895 }
2896 } else {
2897 $program = "";
2898 if ($fileinfo["extension"] == "gz") {
2899 $program = 'gzip';
2900 } elseif ($fileinfo["extension"] == "bz2") {
2901 $program = 'bzip2';
2902 } elseif ($fileinfo["extension"] == "zst") {
2903 $program = 'zstd';
2904 } else {
2905 return array('error' => 'ErrorBadFileExtension');
2906 }
2907 $cmd = $program.' -dc '.escapeshellcmd(dol_sanitizePathName($fileinfo["dirname"]).'/'.dol_sanitizeFileName($fileinfo["basename"]));
2908 $cmd .= ' > '.$outputfilename;
2909
2910 $resarray = $utils->executeCLI($cmd, $outputfilename.'.tmp', 0, null, 1, $outputfilename.'.err');
2911 if ($resarray["result"] != 0) {
2912 $errfilecontent = @file_get_contents($outputfilename.'.err');
2913 if ($errfilecontent) {
2914 $resarray["error"] .= " - ".$errfilecontent;
2915 }
2916 }
2917 }
2918 return $resarray["result"] != 0 ? array('error' => $resarray["error"]) : array();
2919 }
2920
2921 return array('error' => 'ErrorBadFileExtension');
2922}
2923
2924
2937function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '', $newmask = '0')
2938{
2939 $foundhandler = 0;
2940
2941 dol_syslog("Try to zip dir ".$inputdir." into ".$outputfile." mode=".$mode);
2942
2943 if (!dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
2944 global $langs, $errormsg;
2945 $langs->load("errors");
2946 $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
2947 return -3;
2948 }
2949
2950 try {
2951 if ($mode == 'gz') {
2952 $foundhandler = 0;
2953 } elseif ($mode == 'bz') {
2954 $foundhandler = 0;
2955 } elseif ($mode == 'zip') {
2956 /*if (defined('ODTPHP_PATHTOPCLZIP'))
2957 {
2958 $foundhandler=0; // TODO implement this
2959
2960 include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
2961 $archive = new PclZip($outputfile);
2962 $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
2963 //$archive->add($inputfile);
2964 return 1;
2965 }
2966 else*/
2967 //if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS))
2968
2969 if (class_exists('ZipArchive')) {
2970 $foundhandler = 1;
2971
2972 // Initialize archive object
2973 $zip = new ZipArchive();
2974 $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2975 if ($result !== true) {
2976 global $langs, $errormsg;
2977 $langs->load("errors");
2978 $errormsg = $langs->trans("ErrorFailedToBuildArchive", $outputfile);
2979 return -4;
2980 }
2981
2982 // Create recursive directory iterator
2983 // This does not return symbolic links
2985 $files = new RecursiveIteratorIterator(
2986 new RecursiveDirectoryIterator($inputdir, FilesystemIterator::UNIX_PATHS),
2987 RecursiveIteratorIterator::LEAVES_ONLY
2988 );
2989 '@phan-var-force SplFileInfo[] $files';
2990
2991 //var_dump($inputdir);
2992 foreach ($files as $name => $file) {
2993 // Skip directories (they would be added automatically)
2994 if (!$file->isDir()) {
2995 // Get real and relative path for current file
2996 $filePath = $file->getPath(); // the full path with filename using the $inputdir root.
2997 $fileName = $file->getFilename();
2998 $fileFullRealPath = $file->getRealPath(); // the full path with name and transformed to use real path directory.
2999
3000 //$relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').dol_substr($fileFullRealPath, strlen($inputdir) + 1);
3001 $relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr(($filePath ? $filePath.'/' : '').$fileName, strlen($inputdir) + 1);
3002
3003 //var_dump($filePath);var_dump($fileFullRealPath);var_dump($relativePath);
3004 if (empty($excludefiles) || !preg_match($excludefiles, $fileFullRealPath)) {
3005 // Add current file to archive
3006 $zip->addFile($fileFullRealPath, $relativePath);
3007 }
3008 }
3009 }
3010
3011 // Zip archive will be created only after closing object
3012 $zip->close();
3013
3014 if (empty($newmask) && getDolGlobalString('MAIN_UMASK')) {
3015 $newmask = getDolGlobalString('MAIN_UMASK');
3016 }
3017 if (empty($newmask)) { // This should no happen
3018 dol_syslog("Warning: dol_compress_dir called with empty value for newmask and no default value defined", LOG_WARNING);
3019 $newmask = '0664';
3020 }
3021
3022 dolChmod($outputfile, $newmask);
3023
3024 return 1;
3025 }
3026 }
3027
3028 if (!$foundhandler) {
3029 dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR);
3030 return -2;
3031 } else {
3032 return 0;
3033 }
3034 } catch (Exception $e) {
3035 global $langs, $errormsg;
3036 $langs->load("errors");
3037 dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
3038 dol_syslog($e->getMessage(), LOG_ERR);
3039 $errormsg = $langs->trans("ErrorFailedToBuildArchive", $outputfile).' - '.$e->getMessage();
3040 return -1;
3041 }
3042}
3043
3044
3045
3057function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$', '^\.'), $nohook = 0, $mode = 0, $limit = 0)
3058{
3059 $tmparray = dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook);
3060 if ($limit > 1) {
3061 return array_slice($tmparray, 0, $limit);
3062 }
3063 return isset($tmparray[0]) ? $tmparray[0] : null;
3064}
3065
3079function dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser = null, $refname = '', $mode = 'read')
3080{
3081 global $conf, $db, $user, $hookmanager;
3082 global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
3083 global $object;
3084
3085 if (!is_object($fuser)) {
3086 $fuser = $user;
3087 }
3088
3089 if (empty($modulepart)) {
3090 return 'ErrorBadParameter';
3091 }
3092
3093 $originalmodulepart = $modulepart;
3094
3095 if (empty($entity)) {
3096 if (!isModEnabled('multicompany')) {
3097 $entity = 1;
3098 } else {
3099 $entity = 0;
3100 }
3101 } else {
3102 // TODO Test that the user in session of conf->entity can see objects of the target $entity like restrictedArea() does, however
3103 // it is better to limit the scope of this function to check "per module" permission only, and to do the test on "per object" permission
3104 // by calling restrictedArea()by the caller.
3105 }
3106
3107 // Fix modulepart for backward compatibility
3108 if ($modulepart == 'facture') {
3109 $modulepart = 'invoice';
3110 } elseif ($modulepart == 'users') {
3111 $modulepart = 'user';
3112 } elseif ($modulepart == 'tva') {
3113 $modulepart = 'tax-vat';
3114 } elseif ($modulepart == 'expedition' && strpos($original_file, 'receipt/') === 0) {
3115 // Fix modulepart delivery
3116 $modulepart = 'delivery';
3117 } elseif ($modulepart == 'propale') {
3118 $modulepart = 'propal';
3119 }
3120
3121 // If modulepart is composed of an objectpart@modulepart, we keep modulepart.
3122 $reg = array();
3123 if (preg_match('/(\w+)@(\w+)$/', $modulepart, $reg)) {
3124 $modulepart = $reg[2];
3125 }
3126
3127 //print 'dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity;
3128 dol_syslog('dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
3129
3130 // We define $accessallowed and $sqlprotectagainstexternals
3131 $accessallowed = 0;
3132 $sqlprotectagainstexternals = '';
3133 $ret = array();
3134 $checksecureaccesshook = false;
3135
3136 // Find the subdirectory name as the reference. For example original_file='10/myfile.pdf' -> refname='10'
3137 if (empty($refname)) {
3138 $refname = basename(dirname($original_file)."/");
3139 if ($refname == 'thumbs' || $refname == 'temp') {
3140 // If we get the thumbs directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
3141 $refname = basename(dirname(dirname($original_file))."/");
3142 }
3143 }
3144
3145 // Define possible keys to use for permission check
3146 $lire = 'lire';
3147 $read = 'read';
3148 $download = 'download';
3149 if ($mode == 'write') {
3150 $lire = 'creer';
3151 $read = 'write';
3152 $download = 'upload';
3153 } elseif ($mode == 'delete') {
3154 $lire = 'supprimer';
3155 $read = 'delete';
3156 $download = 'upload';
3157 }
3158
3159 // Wrapping for miscellaneous medias files
3160 if ($modulepart == 'common') {
3161 // Wrapping for some images
3162 $accessallowed = 1;
3163 $original_file = DOL_DOCUMENT_ROOT.'/public/theme/common/'.$original_file;
3164 } elseif ($modulepart == 'medias' && !empty($dolibarr_main_data_root)) {
3165 /* the medias directory is by default a public directory accessible online for everybody, so test on permission per entity is not done, it has no sense */
3166 if (empty($entity)) {
3167 $entity = 1;
3168 }
3169 $accessallowed = 0;
3170 if ($mode == 'write') {
3171 if ($fuser->hasRight('website', 'write')) {
3172 $accessallowed = 1;
3173 }
3174 } else {
3175 $accessallowed = 1; // As dir is public, we allow read access to all files in medias directory
3176 }
3177 $original_file = (empty($conf->medias->multidir_output[$entity]) ? (empty($conf->medias->dir_output) ? DOL_DATA_ROOT.'/medias' : $conf->medias->dir_output) : $conf->medias->multidir_output[$entity]).'/'.$original_file;
3178 } elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root)) {
3179 // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
3180 $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.(log|json)$/', basename($original_file)));
3181 $original_file = $dolibarr_main_data_root.'/'.$original_file;
3182 } elseif ($modulepart == 'doctemplates' && !empty($dolibarr_main_data_root)) {
3183 $accessallowed = $user->admin;
3184 $relative_file = $original_file;
3185 $ent = ($entity > 0 ? $entity : $conf->entity);
3186 $path_with_entity = $dolibarr_main_data_root . '/' . $ent . '/doctemplates/' . $relative_file;
3187 if ($ent > 1 && file_exists(dol_osencode($path_with_entity))) {
3188 $original_file = $path_with_entity;
3189 } else {
3190 $original_file = $dolibarr_main_data_root . '/doctemplates/' . $relative_file;
3191 }
3192 } elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
3193 // Wrapping for doctemplates of websites
3194 $accessallowed = ($fuser->hasRight('website', 'write') && preg_match('/\.jpg$/i', basename($original_file)));
3195 $original_file = $dolibarr_main_data_root.'/doctemplates/websites/'.$original_file;
3196 } elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root)) { // To download zip of modules
3197 // Wrapping for *.zip package files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
3198 // Dir for custom dirs
3199 $tmp = explode(',', $dolibarr_main_document_root_alt);
3200 $dirins = $tmp[0];
3201
3202 $accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
3203 $original_file = $dirins.'/'.$original_file;
3204 } elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output)) {
3205 // Wrapping for some images
3206 $accessallowed = 1;
3207 $original_file = $conf->mycompany->dir_output.'/'.$original_file;
3208 } elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output)) {
3209 // Wrapping for users photos (user photos are allowed to any connected users)
3210 $accessallowed = 0;
3211 if (preg_match('/^\d+\/photos\//', $original_file)) {
3212 $accessallowed = 1;
3213 }
3214 // To write or delete a photo, the user needs the permission to modify users (or to modify its own user card for its own photo)
3215 if ($mode != 'read' && empty($fuser->admin) && !$fuser->hasRight('user', 'user', $lire) && !((int) $original_file == $fuser->id && $fuser->hasRight('user', 'self', $lire))) {
3216 $accessallowed = 0;
3217 }
3218 $original_file = $conf->user->dir_output.'/'.$original_file;
3219 } elseif ($modulepart == 'userphotopublic' && !empty($conf->user->dir_output)) {
3220 // Wrapping for users photos that were set to public (for virtual credit card) by their owner (public user photos can be read
3221 // with the public link and securekey)
3222 $accessok = false;
3223 $reg = array();
3224 if (preg_match('/^(\d+)\/photos\//', $original_file, $reg)) {
3225 if ((int) $reg[1]) {
3226 $tmpobject = new User($db);
3227 $tmpobject->fetch((int) $reg[1], '', '', 1);
3228 if (getDolUserInt('USER_ENABLE_PUBLIC', 0, $tmpobject)) {
3229 $securekey = GETPOST('securekey', 'alpha', 1);
3230 // Security check
3231 global $dolibarr_main_cookie_cryptkey, $dolibarr_main_instance_unique_id;
3232 $valuetouse = $dolibarr_main_instance_unique_id ? $dolibarr_main_instance_unique_id : $dolibarr_main_cookie_cryptkey; // Use $dolibarr_main_instance_unique_id first then $dolibarr_main_cookie_cryptkey
3233 $encodedsecurekey = dol_hash($valuetouse.'uservirtualcard'.$tmpobject->id.'-'.$tmpobject->login, 'md5');
3234 if (hash_equals($encodedsecurekey, (string) $securekey)) {
3235 $accessok = true;
3236 }
3237 }
3238 }
3239 }
3240 if ($accessok) {
3241 $accessallowed = 1;
3242 }
3243 $original_file = $conf->user->dir_output.'/'.$original_file;
3244 } elseif (($modulepart == 'companylogo') && !empty($conf->mycompany->dir_output)) {
3245 // Wrapping for company logos (company logos are allowed to anyboby, they are public)
3246 $accessallowed = 1;
3247 $original_file = $conf->mycompany->dir_output.'/logos/'.$original_file;
3248 } elseif ($modulepart == 'memberphoto' && !empty($conf->member->dir_output)) {
3249 // Wrapping for members photos
3250 $accessallowed = 0;
3251 // Simple chosen for automatic generation of member codes
3252 if (preg_match('/^\d+\/photos\//', $original_file)) {
3253 $accessallowed = 1;
3254 }
3255 // Advanced chosen for automatic generation of member codes
3256 if (preg_match('/^MEM\d\d\d\d-\d\d\d\d\/photos\//', $original_file)) {
3257 $accessallowed = 1;
3258 }
3259 $original_file = $conf->member->dir_output.'/'.$original_file;
3260 } elseif ($modulepart == 'apercufacture' && !empty($conf->invoice->multidir_output[$entity])) {
3261 // Wrapping for invoices (user need permission to read invoices)
3262 if ($fuser->hasRight('facture', $lire)) {
3263 $accessallowed = 1;
3264 }
3265 $original_file = $conf->invoice->multidir_output[$entity].'/'.$original_file;
3266 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('invoice').")";
3267 } elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity])) {
3268 // Wrapping for preview of proposals
3269 if ($fuser->hasRight('propal', $lire)) {
3270 $accessallowed = 1;
3271 }
3272 $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
3273 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('propal').")";
3274 } elseif ($modulepart == 'apercucommande' && !empty($conf->order->multidir_output[$entity])) {
3275 // Wrapping for preview of orders
3276 if ($fuser->hasRight('commande', $lire)) {
3277 $accessallowed = 1;
3278 }
3279 $original_file = $conf->order->multidir_output[$entity].'/'.$original_file;
3280 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('order').")";
3281 } elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->multidir_output[$entity])) {
3282 // Wrapping for preview of intervention
3283 if ($fuser->hasRight('ficheinter', $lire)) {
3284 $accessallowed = 1;
3285 }
3286 $original_file = $conf->ficheinter->multidir_output[$entity].'/'.$original_file;
3287 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".((int) $entity);
3288 } elseif (($modulepart == 'apercucontract') && !empty($conf->contract->multidir_output[$entity])) {
3289 // Wrapping for preview of contracts
3290 if ($fuser->hasRight('contrat', $lire)) {
3291 $accessallowed = 1;
3292 }
3293 $original_file = $conf->contract->multidir_output[$entity].'/'.$original_file;
3294 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
3295 } elseif (($modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) {
3296 // Wrapping for preview of vendor proposals
3297 if ($fuser->hasRight('supplier_proposal', $lire)) {
3298 $accessallowed = 1;
3299 }
3300 $original_file = $conf->supplier_proposal->dir_output.'/'.$original_file;
3301 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('supplier_proposal').")";
3302 } elseif (($modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) {
3303 // Wrapping for preview of purchase orders
3304 if ($fuser->hasRight('fournisseur', 'commande', $lire)) {
3305 $accessallowed = 1;
3306 }
3307 $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
3308 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity = ".((int) $conf->entity);
3309 } elseif (($modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) {
3310 // Wrapping for preview of supplier invoices
3311 if ($fuser->hasRight('fournisseur', $lire)) {
3312 $accessallowed = 1;
3313 }
3314 $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
3315 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".((int) $conf->entity);
3316 } elseif (($modulepart == 'holiday') && !empty($conf->holiday->dir_output)) {
3317 if ($fuser->hasRight('holiday', $read) || ($mode == 'read' && $fuser->hasRight('holiday', 'readall')) || preg_match('/^specimen/i', $original_file)) {
3318 $accessallowed = 1;
3319 // If we known $id of holiday, call checkUserAccessToObject to check permission on properties and hierarchy of leave request
3320 if ($refname && !$fuser->hasRight('holiday', 'readall') && !preg_match('/^specimen/i', $original_file)) {
3321 include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
3322 $tmpholiday = new Holiday($db);
3323 $tmpholiday->fetch(0, $refname);
3324 $accessallowed = checkUserAccessToObject($user, array('holiday'), $tmpholiday, 'holiday', '', '', 'rowid', '');
3325 }
3326 }
3327 $original_file = $conf->holiday->dir_output.'/'.$original_file;
3328 } elseif (($modulepart == 'salaries') && !empty($conf->salaries->dir_output)) {
3329 // Wrapping for salaries. The subdirectory is the id of the salary, see salaries/document.php.
3330 if ($fuser->hasRight('salaries', $read) || ($mode == 'read' && $fuser->hasRight('salaries', 'readall')) || preg_match('/^specimen/i', $original_file)) {
3331 $accessallowed = 1;
3332 // The 'read' permission is labelled "yours only" and the two screens leading to this
3333 // download, salaries/card.php and salaries/document.php, do enforce it on fk_user.
3334 // checkUserAccessToObject() only tests the entity for this feature, so the same rule has to
3335 // be applied here: without it any holder of salaries->read downloads every payslip.
3336 if ($refname && !$fuser->hasRight('salaries', 'readall') && !preg_match('/^specimen/i', $original_file)) {
3337 include_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php';
3338 $tmpsalary = new Salary($db);
3339 $tmpsalary->fetch((int) $refname);
3340 // Same condition as salaries/card.php and salaries/document.php, word for word.
3341 // getAllChildIds(1) includes the current user, so this covers their own payslip as well
3342 // as those of the users below them. The test on fk_user also closes the case of an id
3343 // that matches no salary, Salary::fetch() returning 1 even then.
3344 $accessallowed = ($tmpsalary->fk_user > 0 && in_array($tmpsalary->fk_user, $fuser->getAllChildIds(1))) ? 1 : 0;
3345 }
3346 }
3347 $original_file = $conf->salaries->dir_output.'/'.$original_file;
3348 } elseif (($modulepart == 'expensereport') && !empty($conf->expensereport->dir_output)) {
3349 if ($fuser->hasRight('expensereport', $lire) || ($mode == 'read' && $fuser->hasRight('expensereport', 'readall')) || preg_match('/^specimen/i', $original_file)) {
3350 $accessallowed = 1;
3351 // If we known $id of expensereport, call checkUserAccessToObject to check permission on properties and hierarchy of expense report
3352 if ($refname && !$fuser->hasRight('expensereport', 'readall') && !preg_match('/^specimen/i', $original_file)) {
3353 include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
3354 $tmpexpensereport = new ExpenseReport($db);
3355 $tmpexpensereport->fetch(0, $refname);
3356 $accessallowed = checkUserAccessToObject($user, array('expensereport'), $tmpexpensereport, 'expensereport', '', '', 'rowid', '');
3357 }
3358 }
3359 $original_file = $conf->expensereport->dir_output.'/'.$original_file;
3360 } elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output)) {
3361 // Wrapping for preview of expense report
3362 if ($fuser->hasRight('expensereport', $lire)) {
3363 $accessallowed = 1;
3364 // An expense report is always owned by an internal user, so an external user can never be allowed to access it
3365 if ($fuser->socid > 0) {
3366 $accessallowed = 0;
3367 }
3368 }
3369 $original_file = $conf->expensereport->dir_output.'/'.$original_file;
3370 } elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity])) {
3371 // Wrapping for statistics images of proposal
3372 if ($fuser->hasRight('propal', $lire)) {
3373 $accessallowed = 1;
3374 }
3375 $original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file;
3376 } elseif ($modulepart == 'contractstats' && !empty($conf->contract->dir_temp)) {
3377 // Wrapping for statistics images of contracts
3378 if ($fuser->hasRight('contrat', $lire)) {
3379 $accessallowed = 1;
3380 }
3381 $original_file = $conf->contract->dir_temp.'/'.$original_file;
3382 } elseif ($modulepart == 'orderstats' && !empty($conf->order->dir_temp)) {
3383 // Wrapping for statistics images of orders
3384 if ($fuser->hasRight('commande', $lire)) {
3385 $accessallowed = 1;
3386 }
3387 $original_file = $conf->order->dir_temp.'/'.$original_file;
3388 } elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) {
3389 if ($fuser->hasRight('fournisseur', 'commande', $lire)) {
3390 $accessallowed = 1;
3391 }
3392 $original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file;
3393 } elseif ($modulepart == 'billstats' && !empty($conf->invoice->dir_temp)) {
3394 // Wrapping for statistics images of purchase orders
3395 if ($fuser->hasRight('facture', $lire)) {
3396 $accessallowed = 1;
3397 }
3398 $original_file = $conf->invoice->dir_temp.'/'.$original_file;
3399 } elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) {
3400 if ($fuser->hasRight('fournisseur', 'facture', $lire)) {
3401 $accessallowed = 1;
3402 }
3403 $original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file;
3404 } elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp)) {
3405 // Wrapping for statistics images of shipments
3406 if ($fuser->hasRight('expedition', $lire)) {
3407 $accessallowed = 1;
3408 }
3409 $original_file = $conf->expedition->dir_temp.'/'.$original_file;
3410 } elseif ($modulepart == 'memberstats' && !empty($conf->member->dir_temp)) {
3411 // Wrapping for statistics images of memberships
3412 if ($fuser->hasRight('adherent', $lire)) {
3413 $accessallowed = 1;
3414 }
3415 $original_file = $conf->member->dir_temp.'/'.$original_file;
3416 } elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp)) {
3417 // Wrapping for statistics images of products
3418 if ($fuser->hasRight('produit', $lire) || $fuser->hasRight('service', $lire)) {
3419 $accessallowed = 1;
3420 }
3421 $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file;
3422 } elseif (in_array($modulepart, array('tax', 'tax-vat', 'tva')) && !empty($conf->tax->dir_output)) {
3423 // Wrapping for taxes
3424 if ($fuser->hasRight('tax', 'charges', $lire)) {
3425 $accessallowed = 1;
3426 }
3427 $modulepartsuffix = str_replace('tax-', '', $modulepart);
3428 $original_file = $conf->tax->dir_output.'/'.($modulepartsuffix != 'tax' ? $modulepartsuffix.'/' : '').$original_file;
3429 } elseif (($modulepart == 'actions' || $modulepart == 'actioncomm') && !empty($conf->agenda->dir_output)) {
3430 // Wrapping for events
3431 if ($fuser->hasRight('agenda', 'myactions', $read)) {
3432 $accessallowed = 1;
3433 // If we known $id of project, call checkUserAccessToObject to check permission on the given agenda event on properties and assigned users
3434 if ($refname && !preg_match('/^specimen/i', $original_file)) {
3435 include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3436 $tmpobject = new ActionComm($db);
3437 $tmpobject->fetch((int) $refname);
3438 $accessallowed = checkUserAccessToObject($user, array('agenda'), $tmpobject->id, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id', '');
3439 if ($user->socid && $tmpobject->socid) {
3440 $accessallowed = checkUserAccessToObject($user, array('societe'), $tmpobject->socid);
3441 }
3442 }
3443 }
3444 $original_file = $conf->agenda->dir_output.'/'.$original_file;
3445 } elseif ($modulepart == 'category' && !empty($conf->categorie->multidir_output[$entity])) {
3446 // Wrapping for categories (categories are allowed if user has permission to read categories or to work on TakePos)
3447 if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) {
3448 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3449 }
3450 if ($fuser->hasRight("categorie", $lire) || ($mode == 'read' && $fuser->hasRight("takepos", "run"))) {
3451 $accessallowed = 1;
3452 }
3453 $original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file;
3454 } elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output)) {
3455 // Wrapping for direct debits
3456 if ($fuser->hasRight('prelevement', 'bons', $lire) || preg_match('/^specimen/i', $original_file)) {
3457 $accessallowed = 1;
3458 }
3459 $original_file = $conf->prelevement->dir_output.'/'.$original_file;
3460 } elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp)) {
3461 // Wrapping for energy graphs
3462 $accessallowed = 1;
3463 $original_file = $conf->stock->dir_temp.'/'.$original_file;
3464 } elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp)) {
3465 // Wrapping for supplier graphs
3466 $accessallowed = 1;
3467 $original_file = $conf->fournisseur->dir_temp.'/'.$original_file;
3468 } elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp)) {
3469 // Wrapping for product graphs
3470 $accessallowed = 1;
3471 $original_file = $conf->product->multidir_temp[$entity].'/'.$original_file;
3472 } elseif ($modulepart == 'barcode') {
3473 // Wrapping for barcodes
3474 $accessallowed = 1;
3475 // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
3476 //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
3477 $original_file = '';
3478 } elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp)) {
3479 // Wrapping for icon of background of mailings
3480 $accessallowed = 1;
3481 $original_file = $conf->mailing->dir_temp.'/'.$original_file;
3482 } elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
3483 // Wrapping for the scanner
3484 $accessallowed = 1;
3485 $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
3486 } elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output)) {
3487 // Wrapping for fckeditor images
3488 $accessallowed = 1;
3489 $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
3490 } elseif ($modulepart == 'user' && !empty($conf->user->dir_output)) {
3491 // Wrapping for users
3492 $canreaduser = (!empty($fuser->admin) || $fuser->hasRight('user', 'user', $lire));
3493 if ($fuser->id == (int) $refname) {
3494 $canreaduser = 1;
3495 } // A user can always read its own card
3496 if ($canreaduser || preg_match('/^specimen/i', $original_file)) {
3497 $accessallowed = 1;
3498 }
3499 $original_file = $conf->user->dir_output.'/'.$original_file;
3500 } elseif (($modulepart == 'company' || $modulepart == 'societe' || $modulepart == 'thirdparty') && !empty($conf->societe->multidir_output[$entity])) {
3501 // Wrapping for third parties
3502 if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
3503 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3504 }
3505 if ($fuser->hasRight('societe', $lire) || preg_match('/^specimen/i', $original_file)) {
3506 $accessallowed = 1;
3507 }
3508 $original_file = $conf->societe->multidir_output[$entity].'/'.$original_file;
3509 $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid = ".((int) $refname)." AND entity IN (".getEntity('societe').")";
3510 } elseif (($modulepart == 'contact' || $modulepart == 'socpeople') && !empty($conf->societe->multidir_output[$entity])) {
3511 // Wrapping for contact
3512 $checksecureaccesshook = true;
3513 if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
3514 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3515 }
3516 if ($fuser->hasRight('societe', 'contact', $lire)) {
3517 $accessallowed = 1;
3518 }
3519 $original_file = $conf->societe->multidir_output[$entity].'/contact/'.$original_file;
3520 $sqlprotectagainstexternals = "SELECT fk_soc FROM ".MAIN_DB_PREFIX."socpeople WHERE rowid = ".((int) $refname)." AND entity IN (".getEntity('contact').")";
3521 } elseif (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->invoice->multidir_output[$entity])) {
3522 // Wrapping for invoices
3523 if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3524 $accessallowed = 1;
3525 }
3526 $original_file = $conf->invoice->multidir_output[$entity].'/'.$original_file;
3527 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('invoice').")";
3528 } elseif ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity])) {
3529 // Wrapping for mass actions
3530 if ($fuser->hasRight('propal', $lire) || preg_match('/^specimen/i', $original_file)) {
3531 $accessallowed = 1;
3532 }
3533 $original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
3534 } elseif ($modulepart == 'massfilesarea_orders') {
3535 if ($fuser->hasRight('commande', $lire) || preg_match('/^specimen/i', $original_file)) {
3536 $accessallowed = 1;
3537 }
3538 $original_file = $conf->order->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
3539 } elseif ($modulepart == 'massfilesarea_sendings') {
3540 if ($fuser->hasRight('expedition', $lire) || preg_match('/^specimen/i', $original_file)) {
3541 $accessallowed = 1;
3542 }
3543 $original_file = $conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file;
3544 } elseif ($modulepart == 'massfilesarea_receipts') {
3545 if ($fuser->hasRight('reception', $lire) || preg_match('/^specimen/i', $original_file)) {
3546 $accessallowed = 1;
3547 }
3548 $original_file = $conf->reception->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3549 } elseif ($modulepart == 'massfilesarea_invoices') {
3550 if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3551 $accessallowed = 1;
3552 }
3553 $original_file = $conf->invoice->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
3554 } elseif ($modulepart == 'massfilesarea_expensereport') {
3555 if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3556 $accessallowed = 1;
3557 }
3558 $original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3559 } elseif ($modulepart == 'massfilesarea_interventions') {
3560 if ($fuser->hasRight('ficheinter', $lire) || preg_match('/^specimen/i', $original_file)) {
3561 $accessallowed = 1;
3562 }
3563 $original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3564 } elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) {
3565 if ($fuser->hasRight('supplier_proposal', $lire) || preg_match('/^specimen/i', $original_file)) {
3566 $accessallowed = 1;
3567 }
3568 $original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3569 } elseif ($modulepart == 'massfilesarea_supplier_order') {
3570 if ($fuser->hasRight('fournisseur', 'commande', $lire) || preg_match('/^specimen/i', $original_file)) {
3571 $accessallowed = 1;
3572 }
3573 $original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3574 } elseif ($modulepart == 'massfilesarea_supplier_invoice') {
3575 if ($fuser->hasRight('fournisseur', 'facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3576 $accessallowed = 1;
3577 }
3578 $original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3579 } elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contract->dir_output)) {
3580 if ($fuser->hasRight('contrat', $lire) || preg_match('/^specimen/i', $original_file)) {
3581 $accessallowed = 1;
3582 }
3583 $original_file = $conf->contract->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3584 } elseif ($modulepart == 'massfilesarea_stock' && !empty($conf->stock->dir_output)) {
3585 if ($fuser->hasRight('stock', $lire) || preg_match('/^specimen/i', $original_file)) {
3586 $accessallowed = 1;
3587 }
3588 $original_file = $conf->stock->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3589 } elseif (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->multidir_output[$entity])) {
3590 // Wrapping for interventions
3591 if ($fuser->hasRight('ficheinter', $lire) || preg_match('/^specimen/i', $original_file)) {
3592 $accessallowed = 1;
3593 }
3594 $original_file = $conf->ficheinter->multidir_output[$entity].'/'.$original_file;
3595 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".((int) $conf->entity);
3596 } elseif (($modulepart == 'propal' || $modulepart == 'propale') && isset($conf->propal->multidir_output[$entity])) {
3597 // Wrapping for proposals
3598 if ($fuser->hasRight('propal', $lire) || preg_match('/^specimen/i', $original_file)) {
3599 $accessallowed = 1;
3600 }
3601 $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
3602 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('propal').")";
3603 } elseif (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->order->multidir_output[$entity])) {
3604 // Wrapping for orders
3605 if ($fuser->hasRight('commande', $lire) || preg_match('/^specimen/i', $original_file)) {
3606 $accessallowed = 1;
3607 }
3608 $original_file = $conf->order->multidir_output[$entity].'/'.$original_file;
3609 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('order').")";
3610 } elseif ($modulepart == 'project' && !empty($conf->project->multidir_output[$entity])) {
3611 // Wrapping for projects
3612 if ($fuser->hasRight('projet', $lire) || preg_match('/^specimen/i', $original_file)) {
3613 $accessallowed = 1;
3614 // If we known $id of project, call checkUserAccessToObject to check permission on properties and contact of project
3615 if ($refname && !preg_match('/^specimen/i', $original_file)) {
3616 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
3617 $tmpproject = new Project($db);
3618 $tmpproject->fetch(0, $refname);
3619 $accessallowed = checkUserAccessToObject($user, array('projet'), $tmpproject->id, 'projet&project', '', '', 'rowid', '');
3620 }
3621 }
3622 $original_file = $conf->project->multidir_output[$entity].'/'.$original_file;
3623 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
3624 } elseif ($modulepart == 'project_task' && !empty($conf->project->multidir_output[$entity])) {
3625 if ($fuser->hasRight('projet', $lire) || preg_match('/^specimen/i', $original_file)) {
3626 $accessallowed = 1;
3627 // If we known $id of project, call checkUserAccessToObject to check permission on properties and contact of project
3628 if ($refname && !preg_match('/^specimen/i', $original_file)) {
3629 include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
3630 $tmptask = new Task($db);
3631 $tmptask->fetch(0, $refname);
3632 $accessallowed = checkUserAccessToObject($user, array('projet_task'), $tmptask->id, 'projet_task&project', '', '', 'rowid', '');
3633 }
3634 }
3635 $original_file = $conf->project->multidir_output[$entity].'/'.$original_file;
3636 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
3637 } elseif (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier' || $modulepart == 'supplier_order') && !empty($conf->fournisseur->commande->dir_output)) {
3638 // Wrapping for purchase orders
3639 if ($fuser->hasRight('fournisseur', 'commande', $lire) || preg_match('/^specimen/i', $original_file)) {
3640 $accessallowed = 1;
3641 }
3642 $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
3643 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity = ".((int) $conf->entity);
3644 } elseif (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier' || $modulepart == 'supplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) {
3645 // Wrapping for supplier invoices
3646 if ($fuser->hasRight('fournisseur', 'facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3647 $accessallowed = 1;
3648 }
3649 $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
3650 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".((int) $conf->entity);
3651 } elseif ($modulepart == 'supplier_payment') {
3652 // Wrapping for supplier payments
3653 if ($fuser->hasRight('fournisseur', 'facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3654 $accessallowed = 1;
3655 }
3656 $original_file = preg_replace("/payment\//", "", $original_file); // Because the $conf->fournisseur->payment->dir_output already contains the "payment/"
3657 $original_file = $conf->fournisseur->payment->dir_output.'/'.$original_file;
3658 $sqlprotectagainstexternals = "SELECT f.fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfourn as p";
3659 $sqlprotectagainstexternals .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid";
3660 $sqlprotectagainstexternals .= " INNER JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON pf.fk_facturefourn = f.rowid";
3661 $sqlprotectagainstexternals .= " WHERE p.ref = '".$db->escape($refname)."' AND p.entity=".((int) $conf->entity);
3662 } elseif ($modulepart == 'payment') {
3663 // Wrapping for report of payments
3664 if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3665 $accessallowed = 1;
3666 }
3667 $original_file = $conf->compta->payment->dir_output.'/'.$original_file;
3668 } elseif ($modulepart == 'facture_paiement' && !empty($conf->invoice->dir_output)) {
3669 // Wrapping for report of payments
3670 if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
3671 $accessallowed = 1;
3672 }
3673 if ($fuser->socid > 0) {
3674 $original_file = $conf->invoice->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
3675 } else {
3676 $original_file = $conf->invoice->dir_output.'/payments/'.$original_file;
3677 }
3678 /* $sqlprotectagainstexternals = "SELECT f.fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiement as p";
3679 $sqlprotectagainstexternals .= " INNER JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid";
3680 $sqlprotectagainstexternals .= " INNER JOIN ".MAIN_DB_PREFIX."facture as f ON pf.fk_facture = p.rowid";
3681 $sqlprotectagainstexternals .= " WHERE p.ref = '".$db->escape($refname)."' AND p.entity=".((int) $conf->entity);
3682 var_dump($sqlprotectagainstexternals);exit;*/
3683 } elseif ($modulepart == 'accounting' && !empty($conf->accounting->dir_output)) {
3684 // Wrapping for accounting exports
3685 if ($fuser->hasRight('accounting', 'bind', 'write') || $fuser->hasRight('accounting', 'mouvements', 'export') || preg_match('/^specimen/i', $original_file)) {
3686 $accessallowed = 1;
3687 }
3688 $original_file = $conf->accounting->dir_output.'/'.$original_file;
3689 } elseif (($modulepart == 'expedition' || $modulepart == 'shipment' || $modulepart == 'shipping') && !empty($conf->expedition->dir_output)) {
3690 // Wrapping for shipments
3691 if ($fuser->hasRight('expedition', $lire) || preg_match('/^specimen/i', $original_file)) {
3692 $accessallowed = 1;
3693 }
3694 $original_file = $conf->expedition->dir_output."/".(strpos($original_file, 'sending/') === 0 ? '' : 'sending/').$original_file;
3695 //$original_file = $conf->expedition->dir_output."/".$original_file;
3696 } elseif (($modulepart == 'livraison' || $modulepart == 'delivery') && !empty($conf->expedition->dir_output)) {
3697 // Delivery Note Wrapping
3698 if ($fuser->hasRight('expedition', 'delivery', $lire) || preg_match('/^specimen/i', $original_file)) {
3699 $accessallowed = 1;
3700 }
3701 $original_file = $conf->expedition->dir_output."/".(strpos($original_file, 'receipt/') === 0 ? '' : 'receipt/').$original_file;
3702 } elseif ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp)) {
3703 // Wrapping for actions
3704 if ($fuser->hasRight('agenda', 'allactions', $read) || preg_match('/^specimen/i', $original_file)) {
3705 $accessallowed = 1;
3706 }
3707 $original_file = $conf->agenda->dir_temp."/".$original_file;
3708 } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
3709 // Wrapping for products and services
3710 $checksecureaccesshook = true;
3711 if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) {
3712 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3713 }
3714 if (($fuser->hasRight('produit', $lire) || $fuser->hasRight('service', $lire)) || preg_match('/^specimen/i', $original_file)) {
3715 $accessallowed = 1;
3716 }
3717 if (isModEnabled("product")) {
3718 $original_file = $conf->product->multidir_output[$entity].'/'.$original_file;
3719 } elseif (isModEnabled("service")) {
3720 $original_file = $conf->service->multidir_output[$entity].'/'.$original_file;
3721 }
3722 } elseif ($modulepart == 'product_batch' || $modulepart == 'produitlot') {
3723 // Wrapping for product lots
3724 if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) {
3725 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3726 }
3727 if (($fuser->hasRight('produit', $lire)) || preg_match('/^specimen/i', $original_file)) {
3728 $accessallowed = 1;
3729 }
3730 if (isModEnabled('productbatch')) {
3731 $original_file = $conf->productbatch->multidir_output[$entity].'/'.$original_file;
3732 }
3733 } elseif ($modulepart == 'movement' || $modulepart == 'mouvement') {
3734 // Wrapping for stock movements
3735 if (empty($entity) || empty($conf->stock->multidir_output[$entity])) {
3736 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3737 }
3738 if (($fuser->hasRight('stock', $lire) || $fuser->hasRight('stock', 'movement', $lire) || $fuser->hasRight('stock', 'mouvement', $lire)) || preg_match('/^specimen/i', $original_file)) {
3739 $accessallowed = 1;
3740 }
3741 if (isModEnabled('stock')) {
3742 $original_file = $conf->stock->multidir_output[$entity].'/movement/'.$original_file;
3743 }
3744 } elseif ($modulepart == 'inventory') {
3745 // Wrapping for stock inventories
3746 if (empty($entity) || empty($conf->stock->multidir_output[$entity])) {
3747 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3748 }
3749 if ($fuser->hasRight('stock', $lire) || preg_match('/^specimen/i', $original_file)) {
3750 $accessallowed = 1;
3751 }
3752 if (isModEnabled('stock')) {
3753 $original_file = $conf->stock->multidir_output[$entity].'/inventory/'.$original_file;
3754 }
3755 } elseif ($modulepart == 'entrepot') {
3756 // Wrapping for stock warehouse
3757 if (empty($entity) || empty($conf->stock->multidir_output[$entity])) {
3758 return array('accessallowed' => 0, 'error' => 'Value entity must be provided');
3759 }
3760 if (($fuser->hasRight('stock', $lire) || $fuser->hasRight('stock', 'movement', $lire) || $fuser->hasRight('stock', 'mouvement', $lire)) || preg_match('/^specimen/i', $original_file)) {
3761 $accessallowed = 1;
3762 }
3763 if (isModEnabled('stock')) {
3764 $original_file = $conf->stock->multidir_output[$entity].'/'.$original_file;
3765 }
3766 } elseif ($modulepart == 'contract' && !empty($conf->contract->multidir_output[$entity])) {
3767 // Wrapping for contracts
3768 if ($fuser->hasRight('contrat', $lire) || preg_match('/^specimen/i', $original_file)) {
3769 $accessallowed = 1;
3770 }
3771 $original_file = $conf->contract->multidir_output[$entity].'/'.$original_file;
3772 $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
3773 } elseif ($modulepart == 'donation' && !empty($conf->don->dir_output)) {
3774 // Wrapping for donation
3775 if ($fuser->hasRight('don', $lire) || preg_match('/^specimen/i', $original_file)) {
3776 $accessallowed = 1;
3777 }
3778 $original_file = $conf->don->dir_output.'/'.$original_file;
3779 } elseif ($modulepart == 'dolresource' && !empty($conf->resource->dir_output)) {
3780 // Wrapping for resources
3781 if ($fuser->hasRight('resource', $read) || preg_match('/^specimen/i', $original_file)) {
3782 $accessallowed = 1;
3783 }
3784 $original_file = $conf->resource->dir_output.'/'.$original_file;
3785 } elseif (($modulepart == 'remisecheque' || $modulepart == 'chequereceipt') && !empty($conf->bank->dir_output)) {
3786 // Wrapping for check deposits
3787 if ($fuser->hasRight('banque', $lire) || preg_match('/^specimen/i', $original_file)) {
3788 $accessallowed = 1;
3789 }
3790 $original_file = $conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result
3791 } elseif (($modulepart == 'banque' || $modulepart == 'bank') && !empty($conf->bank->dir_output)) {
3792 // Wrapping for bank
3793 // The bank module has no 'creer' permission: writing a bank file requires 'modifier', like account_statement_document.php
3794 if ($fuser->hasRight('banque', ($mode == 'read' ? 'lire' : 'modifier'))) {
3795 $accessallowed = 1;
3796 }
3797 $original_file = $conf->bank->dir_output.'/'.$original_file;
3798 } elseif ($modulepart == 'export' && !empty($conf->export->dir_temp)) {
3799 // Wrapping for export module
3800 // Note that a test may not be required because we force the dir of download on the directory of the user that export
3801 $accessallowed = $fuser->hasRight('export', $lire);
3802 $original_file = $conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
3803 } elseif ($modulepart == 'import' && !empty($conf->import->dir_temp)) {
3804 // Wrapping for import module
3805 $accessallowed = $user->hasRight('import', 'run');
3806 $original_file = $conf->import->dir_temp.'/'.$original_file;
3807 } elseif ($modulepart == 'recruitment' && !empty($conf->recruitment->dir_output)) {
3808 // Wrapping for recruitment module
3809 $accessallowed = $fuser->hasRight('recruitment', 'recruitmentjobposition', $read);
3810 $original_file = $conf->recruitment->dir_output.'/'.$original_file;
3811 } elseif ($modulepart == 'hrm' && !empty($conf->hrm->dir_output)) {
3812 // Wrapping for hrm module
3813 $accessallowed = $fuser->hasRight('hrm', 'all', $read);
3814 $original_file = $conf->hrm->dir_output.'/'.$original_file;
3815 } elseif ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output)) {
3816 // Wrapping for wysiwyg editor
3817 $accessallowed = 1;
3818 $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
3819 } elseif ($modulepart == 'systemtools' && !empty($conf->admin->dir_output)) {
3820 // Wrapping for backups
3821 if ($fuser->admin) {
3822 $accessallowed = 1;
3823 }
3824 $original_file = $conf->admin->dir_output.'/'.$original_file;
3825 } elseif ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp)) {
3826 // Wrapping for upload file test
3827 if ($fuser->admin) {
3828 $accessallowed = 1;
3829 }
3830 $original_file = $conf->admin->dir_temp.'/'.$original_file;
3831 } elseif ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output)) {
3832 // Wrapping for BitTorrent
3833 $accessallowed = 1;
3834 $dir = 'files';
3835 if (dol_mimetype($original_file) == 'application/x-bittorrent') {
3836 $dir = 'torrents';
3837 }
3838 $original_file = $conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
3839 } elseif ($modulepart == 'member' && !empty($conf->member->dir_output)) {
3840 // Wrapping for Foundation module
3841 if ($fuser->hasRight('adherent', $lire) || preg_match('/^specimen/i', $original_file)) {
3842 $accessallowed = 1;
3843 }
3844 $original_file = $conf->member->dir_output.'/'.$original_file;
3845 } elseif ($modulepart == 'ticket' && !empty($conf->ticket->multidir_output[$entity])) {
3846 // Wrapping for events
3847 if ($fuser->hasRight('ticket', $read)) {
3848 $accessallowed = 1;
3849 }
3850 if (!isset($_SESSION['email_customer'])) {
3851 // Request to check socid for external users
3852 $sqlprotectagainstexternals = "SELECT fk_soc FROM ".MAIN_DB_PREFIX."ticket WHERE ref='".$db->escape($refname)."' AND entity=".((int) $conf->entity);
3853 } else {
3854 $email_split = explode('@', $_SESSION['email_customer']);
3855
3856 $sqlprotectagainstexternals = 'SELECT t.rowid, t.fk_soc FROM '.MAIN_DB_PREFIX.'ticket t';
3857 $sqlprotectagainstexternals .= ' LEFT JOIN '.MAIN_DB_PREFIX.'element_contact ec ON ec.element_id = t.rowid';
3858 $sqlprotectagainstexternals .= ' LEFT JOIN '.MAIN_DB_PREFIX.'socpeople c ON c.rowid = ec.fk_socpeople';
3859 $sqlprotectagainstexternals .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_contact tc ON tc.element = "ticket" AND tc.rowid = ec.fk_c_type_contact';
3860 $sqlprotectagainstexternals .= " WHERE t.ref LIKE '".$db->escape($refname)."'";
3861 $sqlprotectagainstexternals .= ' AND (';
3862 $sqlprotectagainstexternals .= ' (';
3863 $sqlprotectagainstexternals .= ' tc.rowid IS NOT NULL';
3864 $sqlprotectagainstexternals .= " AND c.email = '".$db->escape($email_split[0]).'@'.$db->sanitize($email_split[1])."'";
3865 $sqlprotectagainstexternals .= ' )';
3866 $sqlprotectagainstexternals .= " OR t.origin_email = '".$db->escape($email_split[0]).'@'.$db->sanitize($email_split[1])."'";
3867 $sqlprotectagainstexternals .= ' )';
3868 }
3869 $original_file = $conf->ticket->multidir_output[$entity].'/'.$original_file;
3870 // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
3871 // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
3872 // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
3873 // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
3874 // If modulepart=module-abc Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
3875 } else {
3876 // GENERIC Wrapping
3877 $checksecureaccesshook = true;
3878 //var_dump($modulepart);
3879 //var_dump($original_file);
3880 if (preg_match('/^specimen/i', $original_file)) {
3881 $accessallowed = 1; // If link to a file called specimen. Test must be done before changing $original_file int full path.
3882 }
3883 if ($fuser->admin) {
3884 $accessallowed = 1; // If user is admin
3885 }
3886
3887 // For external modules, we can have (modulepart=mymodule and original_file=myobject/...) or (modulepart=mymodule-myobject and original_file=...)
3888 $tmpmodulepart = explode('-', $modulepart);
3889 if (!empty($tmpmodulepart[1])) {
3890 $modulepart = $tmpmodulepart[0];
3891 $original_file = $tmpmodulepart[1].'/'.$original_file;
3892 }
3893
3894 // Define $accessallowed
3895 $reg = array();
3896 if (preg_match('/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
3897 $tmpmodule = $reg[1];
3898 if (empty($conf->$tmpmodule->dir_temp)) { // modulepart not supported
3899 dol_print_error(null, 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3900 exit;
3901 }
3902 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3903 $accessallowed = 1;
3904 }
3905 $original_file = $conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
3906 } elseif (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg)) {
3907 $tmpmodule = $reg[1];
3908 if (empty($conf->$tmpmodule->dir_temp)) { // modulepart not supported
3909 dol_print_error(null, 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3910 exit;
3911 }
3912 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3913 $accessallowed = 1;
3914 }
3915 $original_file = $conf->$tmpmodule->dir_temp.'/'.$original_file;
3916 } elseif (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg)) {
3917 $tmpmodule = $reg[1];
3918 if (empty($conf->$tmpmodule->dir_output)) { // modulepart not supported
3919 dol_print_error(null, 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3920 exit;
3921 }
3922 if ($fuser->hasRight($tmpmodule, $lire) || $fuser->hasRight($tmpmodule, $read) || $fuser->hasRight($tmpmodule, $download)) {
3923 $accessallowed = 1;
3924 }
3925 $original_file = $conf->$tmpmodule->dir_output.'/'.$fuser->id.'/'.$original_file;
3926 } elseif (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
3927 $tmpmodule = $reg[1];
3928 if (empty($conf->$tmpmodule->dir_output)) { // modulepart not supported
3929 dol_print_error(null, 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3930 exit;
3931 }
3932
3933 // Check fuser->rights->modulepart->myobject->read and fuser->rights->modulepart->read
3934 $partsofdirinoriginalfile = explode('/', $original_file);
3935 if (!empty($partsofdirinoriginalfile[1])) { // If original_file is xxx/filename (xxx is a part we will use)
3936 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3937 if (($partofdirinoriginalfile && $fuser->hasRight($tmpmodule, $partofdirinoriginalfile, 'read')) || preg_match('/^specimen/i', $original_file)) {
3938 $accessallowed = 1;
3939 }
3940 }
3941 if ($fuser->hasRight($tmpmodule, $read) || preg_match('/^specimen/i', $original_file)) {
3942 $accessallowed = 1;
3943 }
3944 $original_file = $conf->$tmpmodule->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
3945 } else {
3946 // Main generic case
3947 if (empty($conf->$modulepart->dir_output)) { // modulepart not supported
3948 dol_print_error(null, 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.'). The module for this modulepart value may not be activated.');
3949 exit;
3950 }
3951
3952 // Check fuser->hasRight('modulepart', 'myobject', 'read') and fuser->hasRight('modulepart', 'read')
3953 $partsofdirinoriginalfile = explode('/', $original_file);
3954 if (!empty($partsofdirinoriginalfile[1])) { // If original_file is xxx/filename (xxx is a part we will use)
3955 $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
3956 if ($partofdirinoriginalfile && ($fuser->hasRight($modulepart, $partofdirinoriginalfile, $lire) || $fuser->hasRight($modulepart, $partofdirinoriginalfile, $read))) {
3957 $accessallowed = 1;
3958 }
3959 }
3960 if (($fuser->hasRight($modulepart, $lire) || $fuser->hasRight($modulepart, $read)) || ($fuser->hasRight($modulepart, 'all', $lire) || $fuser->hasRight($modulepart, 'all', $read))) {
3961 $accessallowed = 1;
3962 }
3963
3964 $subdir = '';
3965 $regs = array();
3966 if (preg_match('/^(\w+)@(\w+)$/', $originalmodulepart, $regs)) {
3967 $subdir = $regs[1].'/';
3968 }
3969
3970 if (is_array($conf->$modulepart->multidir_output) && !empty($conf->$modulepart->multidir_output[$entity])) {
3971 $original_file = $conf->$modulepart->multidir_output[$entity].'/'.$subdir.$original_file;
3972 } else {
3973 $original_file = $conf->$modulepart->dir_output.'/'.$subdir.$original_file;
3974 }
3975
3976 // TODO
3977 // Implement a way for the generic case to set $sqlprotectagainstexternals automatically.
3978 // For the moment, external modules can use the following hook checkSecureAccess if they need to protect against external users.
3979 }
3980 }
3981
3982 // Keep the session entity; modules must validate any requested shared entity themselves.
3983 if ($checksecureaccesshook) {
3984 $parameters = array(
3985 'modulepart' => $modulepart,
3986 'original_file' => $original_file,
3987 'entity' => $entity,
3988 'fuser' => $fuser,
3989 'refname' => '',
3990 'mode' => $mode
3991 );
3992 $reshook = $hookmanager->executeHooks('checkSecureAccess', $parameters, $object);
3993 if ($reshook < 0) {
3994 $accessallowed = 0;
3995 } elseif ($reshook > 0) {
3996 if (!empty($hookmanager->resArray['original_file'])) {
3997 $original_file = $hookmanager->resArray['original_file'];
3998 }
3999 // A hook that replaces the result (return > 0) may also refuse access, by setting accessallowed to 0
4000 if (array_key_exists('accessallowed', $hookmanager->resArray)) {
4001 $accessallowed = ($hookmanager->resArray['accessallowed'] ? 1 : 0);
4002 }
4003 if (!empty($hookmanager->resArray['sqlprotectagainstexternals'])) {
4004 $sqlprotectagainstexternals = $hookmanager->resArray['sqlprotectagainstexternals'];
4005 }
4006 }
4007 }
4008
4009 // Some wrappers are open to everybody for reading (company logos, graphs, images of the WYSIWYG editor, photos...). This must not
4010 // allow to write or delete files: this is reserved to admins (the logos are managed by the setup of the company) or, for photos
4011 // of members, to users that can modify members.
4012 if ($mode != 'read' && empty($fuser->admin)) {
4013 if (in_array($modulepart, array('mycompany', 'companylogo', 'graph_stock', 'graph_fourn', 'graph_product', 'barcode', 'iconmailing', 'fckeditor', 'editor', 'bittorrent'))) {
4014 $accessallowed = 0;
4015 }
4016 if ($modulepart == 'memberphoto' && !$fuser->hasRight('adherent', $lire)) {
4017 $accessallowed = 0;
4018 }
4019 }
4020
4021 $ret = array(
4022 'accessallowed' => ($accessallowed ? 1 : 0),
4023 'sqlprotectagainstexternals' => $sqlprotectagainstexternals,
4024 'original_file' => $original_file
4025 );
4026
4027 return $ret;
4028}
4029
4038function dol_filecache($directory, $filename, $object)
4039{
4040 if (!dol_is_dir($directory)) {
4041 $result = dol_mkdir($directory);
4042 if ($result < -1) {
4043 dol_syslog("Failed to create the cache directory ".$directory, LOG_WARNING);
4044 }
4045 }
4046 $cachefile = $directory.$filename;
4047
4048 file_put_contents($cachefile, json_encode($object), LOCK_EX);
4049 dolChmod($cachefile);
4050}
4051
4060function dol_cache_refresh($directory, $filename, $cachetime)
4061{
4062 $now = dol_now();
4063 $cachefile = $directory.$filename;
4064 $refresh = !file_exists($cachefile) || ($now - $cachetime) > dol_filemtime($cachefile);
4065 return $refresh;
4066}
4067
4075function dol_readcachefile($directory, $filename)
4076{
4077 $cachefile = $directory.$filename;
4078 $object = json_decode(file_get_contents($cachefile));
4079 return $object;
4080}
4081
4088function dirbasename($pathfile)
4089{
4090 return preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'\//', '', $pathfile);
4091}
4092
4093
4105function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path = '', $pathref = '', &$checksumconcat = array())
4106{
4107 global $conffile;
4108
4109 //$exclude = 'install';
4110
4111 $entry = array();
4112 $algo = '';
4113 if (!empty($dir->md5file)) {
4114 $entry = $dir->md5file;
4115 $algo = 'md5';
4116 } elseif (!empty($dir->sha256file)) {
4117 $entry = $dir->sha256file;
4118 $algo = 'sha256';
4119 }
4120
4121 foreach ($entry as $file) { // $file is a simpleXMLElement
4122 $filename = $path.$file['name'];
4123 $file_list['insignature'][] = $filename;
4124 $expectedsize = (empty($file['size']) ? '' : $file['size']);
4125 $expectedhash = (string) $file;
4126
4127 if (!file_exists($pathref.'/'.$filename)) {
4128 $file_list['missing'][] = array('filename' => $filename, 'expectedhash' => $expectedhash, 'expectedsize' => $expectedsize, 'algo' => (string) $algo);
4129 } else {
4130 $hash_local = hash_file($algo, $pathref.'/'.$filename);
4131
4132 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
4133 $checksumconcat[] = $expectedhash;
4134 } else {
4135 if ($hash_local != $expectedhash) {
4136 $file_list['updated'][] = array('filename' => $filename, 'expectedhash' => $expectedhash, 'expectedsize' => $expectedsize, 'hash' => (string) $hash_local, 'algo' => (string) $algo);
4137 }
4138 $checksumconcat[] = $hash_local;
4139 }
4140 }
4141 }
4142
4143 foreach ($dir->dir as $subdir) { // $subdir['name'] is '' or '/accountancy/admin' for example
4144 getFilesUpdated($file_list, $subdir, $path.$subdir['name'].'/', $pathref, $checksumconcat);
4145 }
4146
4147 return $file_list;
4148}
4149
4157function dragAndDropFileUpload($htmlname)
4158{
4159 global $object, $langs;
4160
4161 // Every generated javascript string that carries an interpolated value is delimited by a single quote, so
4162 // dol_escape_js() is called with the mode 1 everywhere below: it escapes a single quote and leaves a double
4163 // quote alone. The default mode would rewrite a double quote into an escaped single quote, which is safe
4164 // inside a '...' string but silently alters the value.
4165 // dol_escape_js() escapes the quotes but not '</', and PHP_SELF holds the path info of the request on a
4166 // server that accepts it, so a request could close the script tag below and open one of its own.
4167 $pageurl = str_replace('</', '<\\/', dol_escape_js($_SERVER["PHP_SELF"], 1));
4168
4169 // Values interpolated into the heredoc below via {$...}: dol_escape_js() is still called with
4170 // mode 1 on each of them for the same reason as $pageurl above (they are embedded into JS '...' strings).
4171 $nonce = getNonce();
4172 $fkElement = dol_escape_js((string) $object->id, 1);
4173 $elementType = dol_escape_js($object->element, 1);
4174 $token = currentToken();
4175 $ajaxUrl = DOL_URL_ROOT.'/core/ajax/fileupload.php';
4176
4177 $out = "";
4178 $out .= '<div id="'.$htmlname.'Message" class="dragDropAreaMessage hidden"><span>'.img_picto("", 'download').'<br>'.$langs->trans("DropFileToAddItToObject").'</span></div>';
4179 $out .= "\n<!-- JS CODE TO ENABLE DRAG AND DROP OF FILE -->\n";
4180 $out .= <<<JS
4181<script nonce="{$nonce}">
4182 jQuery(document).ready(function() {
4183 var enterTargetDragDrop = null;
4184
4185 $('#{$htmlname}').addClass('cssDragDropArea');
4186
4187 $(".cssDragDropArea").on("dragenter", function(ev, ui) {
4188 var dataTransfer = ev.originalEvent.dataTransfer;
4189 var dataTypes = dataTransfer.types;
4190 // console.log(dataTransfer);
4191 // console.log(dataTypes);
4192
4193 if (!dataTypes || ($.inArray('Files', dataTypes) === -1)) {
4194 // The element dragged is not a file, so we avoid the "dragenter"
4195 ev.preventDefault();
4196 return false;
4197 }
4198
4199 // Entering drop area. Highlight area
4200 console.log("dragAndDropFileUpload: We add class highlightDragDropArea")
4201 enterTargetDragDrop = ev.target;
4202 $(this).addClass("highlightDragDropArea");
4203 $('#{$htmlname}Message').removeClass('hidden');
4204 ev.preventDefault();
4205 });
4206
4207 $(".cssDragDropArea").on("dragleave", function(ev) {
4208 // Going out of drop area. Remove Highlight
4209 if (enterTargetDragDrop == ev.target){
4210 console.log("dragAndDropFileUpload: We remove class highlightDragDropArea")
4211 $('#{$htmlname}Message').addClass('hidden');
4212 $(this).removeClass("highlightDragDropArea");
4213 }
4214 });
4215
4216 $(".cssDragDropArea").on("dragover", function(ev) {
4217 ev.preventDefault();
4218 return false;
4219 });
4220
4221 $(".cssDragDropArea").on("drop", function(e) {
4222 console.log('Trigger event file dropped. fk_element={$fkElement} element={$elementType}');
4223 e.preventDefault();
4224 fd = new FormData();
4225 fd.append('fk_element', '{$fkElement}');
4226 fd.append('element', '{$elementType}');
4227 fd.append('token', '{$token}');
4228 fd.append("action", "linkit");
4229
4230 var dataTransfer = e.originalEvent.dataTransfer;
4231
4232 if (dataTransfer.files && dataTransfer.files.length){
4233 var droppedFiles = e.originalEvent.dataTransfer.files;
4234 $.each(droppedFiles, function(index,file){
4235 fd.append("files[]", file,file.name)
4236 });
4237 }
4238 $(".cssDragDropArea").removeClass("highlightDragDropArea");
4239 counterdragdrop = 0;
4240 $.ajax({
4241 url: '{$ajaxUrl}',
4242 type: "POST",
4243 processData: false,
4244 contentType: false,
4245 data: fd,
4246 success:function() {
4247 console.log("Uploaded.", arguments);
4248 /* arguments[0] is the json string of files */
4249 /* arguments[1] is the value for variable "success", can be 0 or 1 */
4250 let listoffiles = [];
4251 /* The answer is not the expected json when php stopped before answering, for example when
4252 post_max_size was reached. Without this, the exception of JSON.parse() would leave the
4253 user on a page with no message at all, thinking the file was added. */
4254 try {
4255 listoffiles = JSON.parse(arguments[0]);
4256 } catch (e) {
4257 window.location.href = '{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDrop:errors';
4258 return;
4259 }
4260 console.log(listoffiles);
4261 let nboferror = 0;
4262 for (let i = 0; i < listoffiles.length; i++) {
4263 console.log(listoffiles[i].error);
4264 if (listoffiles[i].error) {
4265 nboferror++;
4266 }
4267 }
4268 console.log(nboferror);
4269 /* An empty list means no file was stored at all, so it is an error and not a success:
4270 php empties \$_FILES when post_max_size is reached. */
4271 if (listoffiles.length == 0) {
4272 window.location.href = '{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDrop:errors';
4273 } else if (nboferror > 0) {
4274 window.location.href = '{$pageurl}?id={$fkElement}&seteventmessages=ErrorOnAtLeastOneFileUpload:warnings';
4275 } else {
4276 window.location.href = '{$pageurl}?id={$fkElement}&seteventmessages=UploadFileDragDropSuccess:mesgs';
4277 }
4278 },
4279 error:function(jqXHR) {
4280 console.log("Error Uploading.", arguments)
4281 if (jqXHR.status == 403) {
4282 window.location.href = '{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDropPermissionDenied:errors';
4283 } else {
4284 window.location.href = '{$pageurl}?id={$fkElement}&seteventmessages=ErrorUploadFileDragDrop:errors';
4285 }
4286 },
4287 })
4288 });
4289 });
4290</script>
4291
4292JS;
4293 return $out;
4294}
4295
4306function archiveOrBackupFile($srcfile, $max_versions = 5, $archivedir = '', $suffix = "v", $moveorcopy = 'move')
4307{
4308 $base_file_pattern = ($archivedir ? $archivedir : dirname($srcfile)).'/'.basename($srcfile).".".$suffix;
4309 $files_in_directory = glob($base_file_pattern . "*");
4310
4311 // Extract the modification timestamps for each file
4312 $files_with_timestamps = [];
4313 foreach ($files_in_directory as $file) {
4314 $files_with_timestamps[] = [
4315 'file' => $file,
4316 'timestamp' => filemtime($file)
4317 ];
4318 }
4319
4320 // Sort the files by modification date
4321 $sorted_files = [];
4322 while (count($files_with_timestamps) > 0) {
4323 $latest_file = null;
4324 $latest_index = null;
4325
4326 // Find the latest file by timestamp
4327 foreach ($files_with_timestamps as $index => $file_info) {
4328 if ($latest_file === null || (is_array($latest_file) && $file_info['timestamp'] > $latest_file['timestamp'])) {
4329 $latest_file = $file_info;
4330 $latest_index = $index;
4331 }
4332 }
4333
4334 // Add the latest file to the sorted list and remove it from the original list (the list is never empty here, so a latest file was always found)
4335 $sorted_files[] = $latest_file['file'];
4336 unset($files_with_timestamps[$latest_index]);
4337 }
4338
4339 // Delete the oldest files to keep only the allowed number of versions
4340 if (count($sorted_files) >= $max_versions) {
4341 $oldest_files = array_slice($sorted_files, $max_versions - 1);
4342 foreach ($oldest_files as $oldest_file) {
4343 dol_delete_file($oldest_file, 0, 0, 0, null, false, 0);
4344 }
4345 }
4346
4347 $timestamp = dol_now('gmt');
4348 $new_backup = $srcfile . ".v" . $timestamp;
4349
4350 // Move or copy the original file to the new backup with the timestamp
4351 if ($moveorcopy == 'move') {
4352 $result = dol_move($srcfile, $new_backup, '0', 1, 0, 0);
4353 } else {
4354 $result = dol_copy($srcfile, $new_backup, '0', 1, 0, 0);
4355 }
4356
4357 if (!$result) {
4358 return false;
4359 }
4360
4361 return true;
4362}
4363
4370function dolDocToText($filetoprocess, $useFullTextIndexation = 'pdftotext', $options = 'html')
4371{
4372 global $conf, $db, $user;
4373
4374 $error = 0;
4375 $keywords = array();
4376 $textforfulltextindex = '';
4377 $cmd = '';
4378 $message = '';
4379
4380 if (empty($useFullTextIndexation)) {
4381 $useFullTextIndexation = 'pdftotext';
4382 }
4383
4384 // TODO Move this into external submodule files
4385
4386 // TODO Develop a native PHP parser using sample code in https://github.com/adeel/php-pdf-parser or https://github.com/smalot/pdfparser
4387 // Use the method pdftotext to generate a HTML
4388 if (preg_match('/pdftotext/i', $useFullTextIndexation)) {
4389 include_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
4390 $utils = new Utils($db);
4391 $outputfile = $conf->admin->dir_temp.'/tmppdftotext.'.$user->id.'.out'; // File used with popen method
4392
4393 // We also exclude '/temp/' dir and 'documents/admin/documents'
4394 // We make escapement here and call executeCLI without escapement because we don't want to have the '*.log' escaped.
4395 if ($options == 'fulltext') {
4396 $params = '-nodiag -layout';
4397 } else {
4398 $params = '-htmlmeta';
4399 }
4400
4401 // MAIN_SAVE_FILE_CONTENT_AS_TEXT_PDFTOTEXT can be for example: "/usr/bin/pdftotext"
4402 // It is for the moment a hidden constant.
4403 $cmd = escapeshellcmd(dol_sanitizePathName(getDolGlobalString('MAIN_SAVE_FILE_CONTENT_AS_TEXT_PDFTOTEXT', 'pdftotext'))) . " " . $params ." ".escapeshellarg($filetoprocess)." - ";
4404 $resultexec = $utils->executeCLI($cmd, $outputfile, 0, null, 1);
4405
4406 if (empty($resultexec['error'])) {
4407 $matches = array();
4408 if ($options == 'fulltext') {
4409 $textforfulltextindex = $resultexec['output'];
4410 }
4411 if ($options == 'html') {
4412 $txt = $resultexec['output'];
4413 if (preg_match('/<meta name="keywords" content="([^\/]+)"\s*\/>/i', $txt, $matches)) {
4414 $keywords = $matches[1];
4415 }
4416 if (preg_match('/<pre>(.*)<\/pre>/si', $txt, $matches)) {
4417 $textforfulltextindex = dol_string_nounprintableascii($matches[1], 0);
4418 }
4419 }
4420 } else {
4421 $message .= $resultexec['output'];
4422 $message .= ($message ? "\n" : "").$resultexec['error'];
4423 dol_syslog($resultexec['error']);
4424 $error++;
4425 }
4426 }
4427
4428
4429 // Use the method docling to generate a .md (https://ds4sd.github.io/docling/)
4430 if (preg_match('/docling/i', $useFullTextIndexation)) {
4431 include_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
4432 $utils = new Utils($db);
4433 $outputfile = $conf->admin->dir_temp.'/tmpdocling.'.$user->id.'.out'; // File used with popen method
4434 $outputfiletxt = $conf->admin->dir_temp.'/tmpdocling.'.$user->id.'.txt'; // File where docling writes the converted text
4435
4436 // Docling can convert images with OCR, so we set the input format according to the file extension
4437 $fromformat = (preg_match('/\.(png|jpe?g|gif|bmp|tiff?|webp)$/i', $filetoprocess) ? 'image' : 'pdf');
4438
4439 // We also exclude '/temp/' dir and 'documents/admin/documents'
4440 // We make escapement here and call executeCLI without escapement because we don't want to have the '*.log' escaped.
4441 // MAIN_SAVE_FILE_CONTENT_AS_TEXT_DOCLING can be for example: "/usr/bin/docling"
4442 dol_delete_file($outputfiletxt);
4443 $cmd = escapeshellcmd(dol_sanitizePathName(getDolGlobalString('MAIN_SAVE_FILE_CONTENT_AS_TEXT_DOCLING', 'docling')))." --from ".$fromformat." --to text --output-file ".escapeshellarg($outputfiletxt)." ".escapeshellarg($filetoprocess);
4444 $resultexec = $utils->executeCLI($cmd, $outputfile, 0, null, 1);
4445
4446 // Docling writes the result into the file set with --output-file. The standard output contains only logs, and docling may
4447 // return no error even if conversion failed, so the conversion is a success only if the output file was created.
4448 if (!$resultexec['error'] && dol_is_file($outputfiletxt)) {
4449 $txt = (string) file_get_contents($outputfiletxt);
4450 dol_delete_file($outputfiletxt);
4451 //$matches = array();
4452 //if (preg_match('/<meta name="Keywords" content="([^\/]+)"\s*\/>/i', $txt, $matches)) {
4453 // $keywords = $matches[1];
4454 //}
4455 //if (preg_match('/<pre>(.*)<\/pre>/si', $txt, $matches)) {
4456 // $textforfulltextindex = dol_string_nounprintableascii($matches[1], 0);
4457 //}
4458 $textforfulltextindex = $txt;
4459 } else {
4460 $message .= $resultexec['output'];
4461 $message .= ($message ? "\n" : "").($resultexec['error'] ? $resultexec['error'] : 'Docling did not generate the output file');
4462 dol_syslog('dolDocToText docling failed: '.($resultexec['error'] ? $resultexec['error'] : 'no output file'), LOG_WARNING);
4463 $error++;
4464 }
4465 }
4466
4467 return array('error' => $error, 'message' => $message, 'keywords' => $keywords, 'content' => $textforfulltextindex, 'cmd' => $cmd);
4468}
4469
4476function removeLastLine($fullpath)
4477{
4478 // Generate tmp file content without the last line
4479 $fp = fopen($fullpath, "r");
4480 fseek($fp, -1, SEEK_END);
4481 $pos = -1;
4482 $char = fgetc($fp);
4483 while ($char === "\n" || $char === "\r") { // Go to last real char of last line
4484 fseek($fp, $pos--, SEEK_END);
4485 $char = fgetc($fp);
4486 }
4487 while ($char !== "\n" && $char !== false) {
4488 fseek($fp, $pos--, SEEK_END);
4489 $char = fgetc($fp);
4490 }
4491 /*
4492 while ($char === "\n" || $char === "\r") { // Go to last real char of last-1 line
4493 fseek($fp, $pos--, SEEK_END);
4494 $char = fgetc($fp);
4495 }
4496 */
4497 $truncatePos = ftell($fp);
4498 fclose($fp);
4499 // Truncate the tmp file to remove the last line
4500 $fp = fopen($fullpath, "c+");
4501 ftruncate($fp, $truncatePos);
4502 fclose($fp);
4503
4504 return 1;
4505}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to scan for virus.
Class to manage ECM files.
Class to manage Trips and Expenses.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class of the module paid holiday.
Class to manage hooks.
Class to manage projects.
Class to manage salary payments.
Class to manage tasks.
Class to manage Dolibarr users.
Class to manage utility methods.
$conffile
dirbasename($pathfile)
Return the relative dirname (relative to DOL_DATA_ROOT) of a full path string.
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0, $limit=0)
Return file(s) into a directory (by default most recent)
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_dir_list_in_database($path, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $sqlfilters="", $object=null)
Scan a directory and return a list of files/directories.
dol_is_link($pathoffile)
Return if path is a symbolic link.
dol_compare_file($a, $b)
Fast compare of 2 files identified by their properties ->name, ->date and ->size.
removePatternFromFile(string $filePath, string $pattern)
Removes content from a file that matches a given pattern.
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_is_url($uri)
Return if path is an URI (the name of the method is misleading).
dol_basename($pathfile)
Make a basename working with all page code (default PHP basenamed fails with cyrillic).
Definition files.lib.php:41
getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path='', $pathref='', &$checksumconcat=array())
Function to get list of updated or modified files.
dol_filemtime($pathoffile)
Return time of a file.
dol_filesize($pathoffile)
Return size of a file.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_add_file_process($upload_dir, $allowoverwrite=0, $updatesessionordb=0, $keyforsourcefile='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null, $forceFullTextIndexation='', $mode=0)
Get and save an upload file (for example after submitting a new file in a mail form).
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object=null)
Complete $filearray with data from database.
archiveOrBackupFile($srcfile, $max_versions=5, $archivedir='', $suffix="v", $moveorcopy='move')
Manage backup versions for a given file, ensuring only a maximum number of versions are kept.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_move_dir($srcdir, $destdir, $overwriteifexists=1, $indexdatabase=1, $renamedircontent=1)
Move a directory into another name.
addFileIntoDatabaseIndex($dir, $file, $fullpathorig='', $mode='uploaded', $setsharekey=0, $object=null, $forceFullTextIndexation='')
Add a file into database index.
dol_fileperm($pathoffile)
Return permissions of a file.
dol_is_writable($folderorfile)
Test if directory or filename is writable.
dol_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
isRealPdf(string $filePath)
Check if a file is a real PDF file by checking its signature and its MIME type.
dol_uncompress($inputfile, $outputdir)
Uncompress a file.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser=null, $refname='', $mode='read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices to g...
dol_init_file_process($pathtoscan='', $trackid='')
Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
dol_convert_file($fileinput, $ext='png', $fileoutput='', $page='')
Convert a PDF file into another image format.
removeLastLine($fullpath)
Remove the last line of a text file.
dol_filecache($directory, $filename, $object)
Store object in file.
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0, $excludefileext=null, $excludearchivefiles=0)
Copy a dir to another dir.
dragAndDropFileUpload($htmlname)
Function to manage the drag and drop of a file.
dol_is_file($pathoffile)
Return if path is a file.
dol_count_nb_of_line($file)
Count number of lines in a file.
dolCheckVirus($src_file, $dest_file='')
Check virus into a file.
dol_unescapefile($filename)
Unescape a file submitted by upload.
dolDocToText($filetoprocess, $useFullTextIndexation='pdftotext', $options='html')
dol_dir_is_emtpy($folder)
Test if a folder is empty.
dol_remove_file_process($filenb, $donotupdatesession=0, $donotdeletefile=1, $trackid='')
Remove an uploaded file (for example after submitting a new file a mail form).
dolCheckOnFileName($src_file, $dest_file='')
Check virus into a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_readcachefile($directory, $filename)
Read object from cachefile.
dol_is_dir($folder)
Test if filename is a directory.
dol_cache_refresh($directory, $filename, $cachetime)
Test if Refresh needed.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask='0', $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_is_dir_empty($dir)
Return if path is empty.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
deleteFilesIntoDatabaseIndex($dir, $file, $mode='uploaded', $object=null)
Delete files into database index using search criteria.
dol_now($mode='gmt')
Return date for now.
getExecutableContent()
Return array of extension for executable files of text files that can contains executable code.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
getDolUserInt($key, $default=0, $tmpuser=null)
Return Dolibarr user constant int value.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
currentToken()
Return the value of token currently saved into session with name 'token'.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_string_nounprintableascii($str, $removetabcrlf=1)
Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
getNonce()
Return a random string to be used as a nonce value for js.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
utf8_check($str)
Check if a string is in UTF8.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.