/
files.lib.php
2998 lines (2698 loc) · 104 KB
/
files.lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* Copyright (C) 2008-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2012-2015 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2012-2016 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
* Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/core/lib/files.lib.php
* \brief Library for file managing functions
*/
/**
* Make a basename working with all page code (default PHP basenamed fails with cyrillic).
* We supose dir separator for input is '/'.
*
* @param string $pathfile String to find basename.
* @return string Basename of input
*/
function dol_basename($pathfile)
{
return preg_replace('/^.*\/([^\/]+)$/', '$1', rtrim($pathfile, '/'));
}
/**
* Scan a directory and return a list of files/directories.
* Content for string is UTF8 and dir separator is "/".
*
* @param string $path Starting path from which to search. This is a full path.
* @param string $types Can be "directories", "files", or "all"
* @param int $recursive Determines whether subdirectories are searched
* @param string $filter Regex filter to restrict list. This regex value must be escaped for '/' by doing preg_quote($var,'/'), since this char is used for preg_match function,
* but must not contains the start and end '/'. Filter is checked into basename only.
* @param array $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview.*\.png)$','^\.')). Exclude is checked both into fullpath and into basename (So '^xxx' may exclude 'xxx/dirscanned/...' and dirscanned/xxx').
* @param string $sortcriteria Sort criteria ('','fullname','relativename','name','date','size')
* @param string $sortorder Sort order (SORT_ASC, SORT_DESC)
* @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only
* @param int $nohook Disable all hooks
* @param string $relativename For recursive purpose only. Must be "" at first call.
* @param string $donotfollowsymlinks Do not follow symbolic links
* @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file',...)
* @see dol_dir_list_in_database()
*/
function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename = "", $donotfollowsymlinks = 0)
{
global $db, $hookmanager;
global $object;
dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter));
//print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
$loaddate=($mode==1||$mode==2)?true:false;
$loadsize=($mode==1||$mode==3)?true:false;
// Clean parameters
$path=preg_replace('/([\\/]+)$/i', '', $path);
$newpath=dol_osencode($path);
$reshook = 0;
$file_list = array();
if (is_object($hookmanager) && ! $nohook)
{
$hookmanager->resArray=array();
$hookmanager->initHooks(array('fileslib'));
$parameters=array(
'path' => $newpath,
'types'=> $types,
'recursive' => $recursive,
'filter' => $filter,
'excludefilter' => $excludefilter,
'sortcriteria' => $sortcriteria,
'sortorder' => $sortorder,
'loaddate' => $loaddate,
'loadsize' => $loadsize,
'mode' => $mode
);
$reshook=$hookmanager->executeHooks('getDirList', $parameters, $object);
}
// $hookmanager->resArray may contain array stacked by other modules
if (empty($reshook))
{
if (! is_dir($newpath)) return array();
if ($dir = opendir($newpath))
{
$filedate='';
$filesize='';
while (false !== ($file = readdir($dir))) // $file is always a basename (into directory $newpath)
{
if (! utf8_check($file)) $file=utf8_encode($file); // To be sure data is stored in utf8 in memory
$fullpathfile=($newpath?$newpath.'/':'').$file;
$qualified=1;
// Define excludefilterarray
$excludefilterarray=array('^\.');
if (is_array($excludefilter))
{
$excludefilterarray=array_merge($excludefilterarray, $excludefilter);
}
elseif ($excludefilter) $excludefilterarray[]=$excludefilter;
// Check if file is qualified
foreach($excludefilterarray as $filt)
{
if (preg_match('/'.$filt.'/i', $file) || preg_match('/'.$filt.'/i', $fullpathfile)) {
$qualified=0; break;
}
}
//print $fullpathfile.' '.$file.' '.$qualified.'<br>';
if ($qualified)
{
$isdir=is_dir(dol_osencode($path."/".$file));
// Check whether this is a file or directory and whether we're interested in that type
if ($isdir && (($types=="directories") || ($types=="all") || $recursive))
{
// Add entry into file_list array
if (($types=="directories") || ($types=="all"))
{
if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
if (! $filter || preg_match('/'.$filter.'/i', $file)) // We do not search key $filter into all $path, only into $file part
{
preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg);
$level1name=(isset($reg[1])?$reg[1]:'');
$file_list[] = array(
"name" => $file,
"path" => $path,
"level1name" => $level1name,
"relativename" => ($relativename?$relativename.'/':'').$file,
"fullname" => $path.'/'.$file,
"date" => $filedate,
"size" => $filesize,
"type" => 'dir'
);
}
}
// if we're in a directory and we want recursive behavior, call this function again
if ($recursive)
{
if (empty($donotfollowsymlinks) || ! is_link($path."/".$file))
{
//var_dump('eee '. $path."/".$file. ' '.is_dir($path."/".$file).' '.is_link($path."/".$file));
$file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename!=''?$relativename.'/':'').$file, $donotfollowsymlinks));
}
}
}
elseif (! $isdir && (($types == "files") || ($types == "all")))
{
// Add file into file_list array
if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
if (! $filter || preg_match('/'.$filter.'/i', $file)) // We do not search key $filter into $path, only into $file
{
preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg);
$level1name=(isset($reg[1])?$reg[1]:'');
$file_list[] = array(
"name" => $file,
"path" => $path,
"level1name" => $level1name,
"relativename" => ($relativename?$relativename.'/':'').$file,
"fullname" => $path.'/'.$file,
"date" => $filedate,
"size" => $filesize,
"type" => 'file'
);
}
}
}
}
closedir($dir);
// Obtain a list of columns
if (! empty($sortcriteria))
{
$myarray=array();
foreach ($file_list as $key => $row)
{
$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
}
// Sort the data
if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
}
}
}
if (is_object($hookmanager) && is_array($hookmanager->resArray)) $file_list = array_merge($file_list, $hookmanager->resArray);
return $file_list;
}
/**
* Scan a directory and return a list of files/directories.
* Content for string is UTF8 and dir separator is "/".
*
* @param string $path Starting path from which to search. Example: 'produit/MYPROD'
* @param string $filter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
* @param array|null $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview.*\.png)$','^\.'))
* @param string $sortcriteria Sort criteria ("","fullname","name","date","size")
* @param string $sortorder Sort order (SORT_ASC, SORT_DESC)
* @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like description
* @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','type'=>'dir|file',...)
* @see dol_dir_list()
*/
function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0)
{
global $conf, $db;
$sql =" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,";
$sql.=" acl, position, share";
if ($mode) $sql.=", description";
$sql.=" FROM ".MAIN_DB_PREFIX."ecm_files";
$sql.=" WHERE filepath = '".$db->escape($path)."'";
$sql.=" AND entity = ".$conf->entity;
$resql = $db->query($sql);
if ($resql)
{
$file_list=array();
$num = $db->num_rows($resql);
$i = 0;
while ($i < $num)
{
$obj = $db->fetch_object($resql);
if ($obj)
{
preg_match('/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, $reg);
$level1name=(isset($reg[1])?$reg[1]:'');
$file_list[] = array(
"rowid" => $obj->rowid,
"label" => $obj->label, // md5
"name" => $obj->filename,
"path" => DOL_DATA_ROOT.'/'.$obj->filepath,
"level1name" => $level1name,
"fullname" => DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,
"fullpath_orig" => $obj->fullpath_orig,
"date_c" => $db->jdate($obj->date_c),
"date_m" => $db->jdate($obj->date_m),
"type" => 'file',
"keywords" => $obj->keywords,
"cover" => $obj->cover,
"position" => (int) $obj->position,
"acl" => $obj->acl,
"share" => $obj->share
);
}
$i++;
}
// Obtain a list of columns
if (! empty($sortcriteria))
{
$myarray=array();
foreach ($file_list as $key => $row)
{
$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
}
// Sort the data
if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
}
return $file_list;
}
else
{
dol_print_error($db);
return array();
}
}
/**
* Complete $filearray with data from database.
* This will call doldir_list_indatabase to complate filearray.
*
* @param array $filearray Array of files get using dol_dir_list
* @param string $relativedir Relative dir from DOL_DATA_ROOT
* @return void
*/
function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
{
global $conf, $db, $user;
$filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC);
// TODO Remove this when PRODUCT_USE_OLD_PATH_FOR_PHOTO will be removed
global $modulepart;
if ($modulepart == 'produit' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
global $object;
if (! empty($object->id))
{
if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
$relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dirold);
$relativedirold = preg_replace('/^[\\/]/', '', $relativedirold);
$filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC));
}
}
//var_dump($filearray);
//var_dump($filearrayindatabase);
// Complete filearray with properties found into $filearrayindatabase
foreach($filearray as $key => $val)
{
$found=0;
// Search if it exists into $filearrayindatabase
foreach($filearrayindatabase as $key2 => $val2)
{
if ($filearrayindatabase[$key2]['name'] == $filearray[$key]['name'])
{
$filearray[$key]['position_name']=($filearrayindatabase[$key2]['position']?$filearrayindatabase[$key2]['position']:'0').'_'.$filearrayindatabase[$key2]['name'];
$filearray[$key]['position']=$filearrayindatabase[$key2]['position'];
$filearray[$key]['cover']=$filearrayindatabase[$key2]['cover'];
$filearray[$key]['acl']=$filearrayindatabase[$key2]['acl'];
$filearray[$key]['rowid']=$filearrayindatabase[$key2]['rowid'];
$filearray[$key]['label']=$filearrayindatabase[$key2]['label'];
$filearray[$key]['share']=$filearrayindatabase[$key2]['share'];
$found=1;
break;
}
}
if (! $found) // This happen in transition toward version 6, or if files were added manually into os dir.
{
$filearray[$key]['position']='999999'; // File not indexed are at end. So if we add a file, it will not replace an existing position
$filearray[$key]['cover']=0;
$filearray[$key]['acl']='';
$rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filearray[$key]['fullname']);
if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file
{
dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it");
include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
$ecmfile=new EcmFiles($db);
// Add entry into database
$filename = basename($rel_filename);
$rel_dir = dirname($rel_filename);
$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
$ecmfile->filepath = $rel_dir;
$ecmfile->filename = $filename;
$ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname'])); // $destfile is a full path to file
$ecmfile->fullpath_orig = $filearray[$key]['fullname'];
$ecmfile->gen_or_uploaded = 'unknown';
$ecmfile->description = ''; // indexed content
$ecmfile->keyword = ''; // keyword content
$result = $ecmfile->create($user);
if ($result < 0)
{
setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
}
else
{
$filearray[$key]['rowid']=$result;
}
}
else
{
$filearray[$key]['rowid']=0; // Should not happened
}
}
}
/*var_dump($filearray);*/
}
/**
* Fast compare of 2 files identified by their properties ->name, ->date and ->size
*
* @param string $a File 1
* @param string $b File 2
* @return int 1, 0, 1
*/
function dol_compare_file($a, $b)
{
global $sortorder;
global $sortfield;
$sortorder=strtoupper($sortorder);
if ($sortorder == 'ASC') { $retup=-1; $retdown=1; }
else { $retup=1; $retdown=-1; }
if ($sortfield == 'name')
{
if ($a->name == $b->name) return 0;
return ($a->name < $b->name) ? $retup : $retdown;
}
if ($sortfield == 'date')
{
if ($a->date == $b->date) return 0;
return ($a->date < $b->date) ? $retup : $retdown;
}
if ($sortfield == 'size')
{
if ($a->size == $b->size) return 0;
return ($a->size < $b->size) ? $retup : $retdown;
}
}
/**
* Test if filename is a directory
*
* @param string $folder Name of folder
* @return boolean True if it's a directory, False if not found
*/
function dol_is_dir($folder)
{
$newfolder=dol_osencode($folder);
if (is_dir($newfolder)) return true;
else return false;
}
/**
* Return if path is empty
*
* @param string $dir Path of Directory
* @return boolean True or false
*/
function dol_is_dir_empty($dir)
{
if (!is_readable($dir)) return false;
return (count(scandir($dir)) == 2);
}
/**
* Return if path is a file
*
* @param string $pathoffile Path of file
* @return boolean True or false
*/
function dol_is_file($pathoffile)
{
$newpathoffile=dol_osencode($pathoffile);
return is_file($newpathoffile);
}
/**
* Return if path is a symbolic link
*
* @param string $pathoffile Path of file
* @return boolean True or false
*/
function dol_is_link($pathoffile)
{
$newpathoffile=dol_osencode($pathoffile);
return is_link($newpathoffile);
}
/**
* Return if path is an URL
*
* @param string $url Url
* @return boolean True or false
*/
function dol_is_url($url)
{
$tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect');
foreach($tmpprot as $prot)
{
if (preg_match('/^'.$prot.':/i', $url)) return true;
}
return false;
}
/**
* Test if a folder is empty
*
* @param string $folder Name of folder
* @return boolean True if dir is empty or non-existing, False if it contains files
*/
function dol_dir_is_emtpy($folder)
{
$newfolder=dol_osencode($folder);
if (is_dir($newfolder))
{
$handle = opendir($newfolder);
$folder_content = '';
while ((gettype($name = readdir($handle)) != "boolean"))
{
$name_array[] = $name;
}
foreach($name_array as $temp) $folder_content .= $temp;
closedir($handle);
if ($folder_content == "...") return true;
else return false;
}
else
return true; // Dir does not exists
}
/**
* Count number of lines in a file
*
* @param string $file Filename
* @return int <0 if KO, Number of lines in files if OK
* @see dol_nboflines()
*/
function dol_count_nb_of_line($file)
{
$nb=0;
$newfile=dol_osencode($file);
//print 'x'.$file;
$fp=fopen($newfile, 'r');
if ($fp)
{
while (!feof($fp))
{
$line=fgets($fp);
// We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines.
if (! $line === false) $nb++;
}
fclose($fp);
}
else
{
$nb=-1;
}
return $nb;
}
/**
* Return size of a file
*
* @param string $pathoffile Path of file
* @return integer File size
*/
function dol_filesize($pathoffile)
{
$newpathoffile=dol_osencode($pathoffile);
return filesize($newpathoffile);
}
/**
* Return time of a file
*
* @param string $pathoffile Path of file
* @return int Time of file
*/
function dol_filemtime($pathoffile)
{
$newpathoffile=dol_osencode($pathoffile);
return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
}
/**
* Make replacement of strings into a file.
*
* @param string $srcfile Source file (can't be a directory)
* @param array $arrayreplacement Array with strings to replace. Example: array('valuebefore'=>'valueafter', ...)
* @param string $destfile Destination file (can't be a directory). If empty, will be same than source file.
* @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
* @param int $indexdatabase 1=index new file into database.
* @return int <0 if error, 0 if nothing done (dest file already exists), >0 if OK
* @see dol_copy() dolReplaceRegExInFile()
*/
function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = 0, $indexdatabase = 0)
{
global $conf;
dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase);
if (empty($srcfile)) return -1;
if (empty($destfile)) $destfile=$srcfile;
$destexists=dol_is_file($destfile);
if (($destfile != $srcfile) && $destexists) return 0;
$tmpdestfile=$destfile.'.tmp';
$newpathofsrcfile=dol_osencode($srcfile);
$newpathoftmpdestfile=dol_osencode($tmpdestfile);
$newpathofdestfile=dol_osencode($destfile);
$newdirdestfile=dirname($newpathofdestfile);
if ($destexists && ! is_writable($newpathofdestfile))
{
dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
return -1;
}
if (! is_writable($newdirdestfile))
{
dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
return -2;
}
dol_delete_file($tmpdestfile);
// Create $newpathoftmpdestfile from $newpathofsrcfile
$content = file_get_contents($newpathofsrcfile, 'r');
$content = make_substitutions($content, $arrayreplacement, null);
file_put_contents($newpathoftmpdestfile, $content);
@chmod($newpathoftmpdestfile, octdec($newmask));
// Rename
$result=dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile)?1:0), 0, $indexdatabase);
if (! $result)
{
dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
return -3;
}
if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
if (empty($newmask)) // This should no happen
{
dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
$newmask='0664';
}
@chmod($newpathofdestfile, octdec($newmask));
return 1;
}
/**
* Make replacement of strings into a file.
*
* @param string $srcfile Source file (can't be a directory)
* @param array $arrayreplacement Array with strings to replace. Example: array('valuebefore'=>'valueafter', ...)
* @param string $destfile Destination file (can't be a directory). If empty, will be same than source file.
* @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
* @param int $indexdatabase Index new file into database.
* @return int <0 if error, 0 if nothing done (dest file already exists), >0 if OK
* @see dol_copy() dolReplaceInFile()
*/
function dolReplaceRegExInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = 0, $indexdatabase = 0)
{
// TODO
}
/**
* Copy a file to another file.
*
* @param string $srcfile Source file (can't be a directory)
* @param string $destfile Destination file (can't be a directory)
* @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
* @param int $overwriteifexists Overwrite file if exists (1 by default)
* @return int <0 if error, 0 if nothing done (dest file already exists and overwriteifexists=0), >0 if OK
* @see dol_delete_file() dolCopyDir()
*/
function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1)
{
global $conf;
dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
if (empty($srcfile) || empty($destfile)) return -1;
$destexists=dol_is_file($destfile);
if (! $overwriteifexists && $destexists) return 0;
$newpathofsrcfile=dol_osencode($srcfile);
$newpathofdestfile=dol_osencode($destfile);
$newdirdestfile=dirname($newpathofdestfile);
if ($destexists && ! is_writable($newpathofdestfile))
{
dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
return -1;
}
if (! is_writable($newdirdestfile))
{
dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
return -2;
}
// Copy with overwriting if exists
$result=@copy($newpathofsrcfile, $newpathofdestfile);
//$result=copy($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
if (! $result)
{
dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
return -3;
}
if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
if (empty($newmask)) // This should no happen
{
dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
$newmask='0664';
}
@chmod($newpathofdestfile, octdec($newmask));
return 1;
}
/**
* Copy a dir to another dir. This include recursive subdirectories.
*
* @param string $srcfile Source file (a directory)
* @param string $destfile Destination file (a directory)
* @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
* @param int $overwriteifexists Overwrite file if exists (1 by default)
* @param array $arrayreplacement Array to use to replace filenames with another one during the copy (works only on file names, not on directory names).
* @return int <0 if error, 0 if nothing done (all files already exists and overwriteifexists=0), >0 if OK
* @see dol_copy()
*/
function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement = null)
{
global $conf;
$result=0;
dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
if (empty($srcfile) || empty($destfile)) return -1;
$destexists=dol_is_dir($destfile);
//if (! $overwriteifexists && $destexists) return 0; // The overwriteifexists is for files only, so propagated to dol_copy only.
if (! $destexists)
{
// We must set mask just before creating dir, becaause it can be set differently by dol_copy
umask(0);
$dirmaskdec=octdec($newmask);
if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
$dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
dol_mkdir($destfile, '', decoct($dirmaskdec));
}
$ossrcfile=dol_osencode($srcfile);
$osdestfile=dol_osencode($destfile);
// Recursive function to copy all subdirectories and contents:
if (is_dir($ossrcfile))
{
$dir_handle=opendir($ossrcfile);
while ($file=readdir($dir_handle))
{
if ($file != "." && $file != ".." && ! is_link($ossrcfile."/".$file))
{
if (is_dir($ossrcfile."/".$file))
{
//var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists");
$tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement);
}
else
{
$newfile = $file;
// Replace destination filename with a new one
if (is_array($arrayreplacement))
{
foreach($arrayreplacement as $key => $val)
{
$newfile = str_replace($key, $val, $newfile);
}
}
$tmpresult=dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists);
}
// Set result
if ($result > 0 && $tmpresult >= 0)
{
// Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass
}
else
{
$result=$tmpresult;
}
if ($result < 0) break;
}
}
closedir($dir_handle);
}
else
{
// Source directory does not exists
$result = -2;
}
return $result;
}
/**
* Move a file into another name.
* Note:
* - This function differs from dol_move_uploaded_file, because it can be called in any context.
* - Database indexes for files are updated.
* - Test on antivirus is done only if param testvirus is provided and an antivirus was set.
*
* @param string $srcfile Source file (can't be a directory. use native php @rename() to move a directory)
* @param string $destfile Destination file (can't be a directory. use native php @rename() to move a directory)
* @param integer $newmask Mask in octal string for new file (0 by default means $conf->global->MAIN_UMASK)
* @param int $overwriteifexists Overwrite file if exists (1 by default)
* @param int $testvirus Do an antivirus test. Move is canceled if a virus is found.
* @param int $indexdatabase Index new file into database.
* @return boolean True if OK, false if KO
* @see dol_move_uploaded_file()
*/
function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1)
{
global $user, $db, $conf;
$result=false;
dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
$srcexists=dol_is_file($srcfile);
$destexists=dol_is_file($destfile);
if (! $srcexists)
{
dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
return false;
}
if ($overwriteifexists || ! $destexists)
{
$newpathofsrcfile=dol_osencode($srcfile);
$newpathofdestfile=dol_osencode($destfile);
// Check virus
$testvirusarray=array();
if ($testvirus)
{
$testvirusarray=dolCheckVirus($newpathofsrcfile);
if (count($testvirusarray))
{
dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING);
return false;
}
}
$result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
if (! $result)
{
if ($destexists)
{
dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
// We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
dol_delete_file($destfile);
$result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
}
else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
}
// Move ok
if ($result && $indexdatabase)
{
// Rename entry into ecm database
$rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $srcfile);
$rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destfile);
if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file
{
$rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
$rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
//var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter);
dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG);
include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
$ecmfiletarget=new EcmFiles($db);
$resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter);
if ($resultecmtarget > 0) // An entry for target name already exists for target, we delete it, a new one will be created.
{
$ecmfiletarget->delete($user);
}
$ecmfile=new EcmFiles($db);
$resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore);
if ($resultecm > 0) // If an entry was found for src file, we use it to move entry
{
$filename = basename($rel_filetorenameafter);
$rel_dir = dirname($rel_filetorenameafter);
$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
$ecmfile->filepath = $rel_dir;
$ecmfile->filename = $filename;
$resultecm = $ecmfile->update($user);
}
elseif ($resultecm == 0) // If no entry were found for src files, create/update target file
{
$filename = basename($rel_filetorenameafter);
$rel_dir = dirname($rel_filetorenameafter);
$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
$ecmfile->filepath = $rel_dir;
$ecmfile->filename = $filename;
$ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file
$ecmfile->fullpath_orig = $srcfile;
$ecmfile->gen_or_uploaded = 'unknown';
$ecmfile->description = ''; // indexed content
$ecmfile->keyword = ''; // keyword content
$resultecm = $ecmfile->create($user);
if ($resultecm < 0)
{
setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
}
}
elseif ($resultecm < 0)
{
setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
}
if ($resultecm > 0) $result=true;
else $result = false;
}
}
if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
$newmaskdec=octdec($newmask);
// Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
// to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
// if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories
@chmod($newpathofdestfile, $newmaskdec);
}
return $result;
}
/**
* Unescape a file submitted by upload.
* PHP escape char " (%22) or char ' (%27) into $FILES.
*
* @param string $filename Filename
* @return string Filename sanitized
*/
function dol_unescapefile($filename)
{
// Remove path information and dots around the filename, to prevent uploading
// into different directories or replacing hidden system files.
// Also remove control characters and spaces (\x00..\x20) around the filename:
return trim(basename($filename), ".\x00..\x20");
}
/**
* Check virus into a file
*
* @param string $src_file Source file to check
* @return array Array of errors or empty array if not virus found
*/
function dolCheckVirus($src_file)
{
global $conf;
if (! empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
{
if (! class_exists('AntiVir')) {
require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
}
$antivir=new AntiVir($db);
$result = $antivir->dol_avscan_file($src_file);
if ($result < 0) // If virus or error, we stop here
{
$reterrors=$antivir->errors;
return $reterrors;
}
}
return array();
}
/**
* Make control on an uploaded file from an GUI page and move it to final destination.
* If there is errors (virus found, antivir in error, bad filename), file is not moved.
* Note:
* - This function can be used only into a HTML page context. Use dol_move if you are outside.
* - Test on antivirus is always done (if antivirus set).
* - Database of files is NOT updated (this is done by dol_add_file_process() that calls this function).
*
* @param string $src_file Source full path filename ($_FILES['field']['tmp_name'])
* @param string $dest_file Target full path filename ($_FILES['field']['name'])