-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathFile.php
1151 lines (1055 loc) · 33.8 KB
/
File.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 CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* class to provide simple static functions for file objects
*/
class CRM_Utils_File {
/**
* Given a file name, determine if the file contents make it an ascii file
*
* @param string $name
* Name of file.
*
* @return bool
* true if file is ascii
*/
public static function isAscii($name) {
$fd = fopen($name, "r");
if (!$fd) {
return FALSE;
}
$ascii = TRUE;
while (!feof($fd)) {
$line = fgets($fd, 8192);
if (!CRM_Utils_String::isAscii($line)) {
$ascii = FALSE;
break;
}
}
fclose($fd);
return $ascii;
}
/**
* Given a file name, determine if the file contents make it an html file
*
* @param string $name
* Name of file.
*
* @return bool
* true if file is html
*/
public static function isHtml($name) {
$fd = fopen($name, "r");
if (!$fd) {
return FALSE;
}
$html = FALSE;
$lineCount = 0;
while (!feof($fd) & $lineCount <= 5) {
$lineCount++;
$line = fgets($fd, 8192);
if (!CRM_Utils_String::isHtml($line)) {
$html = TRUE;
break;
}
}
fclose($fd);
return $html;
}
/**
* Create a directory given a path name, creates parent directories
* if needed
*
* @param string $path
* The path name.
* @param bool $abort
* Should we abort or just return an invalid code.
* @return bool|NULL
* NULL: Folder already exists or was not specified.
* TRUE: Creation succeeded.
* FALSE: Creation failed.
*/
public static function createDir($path, $abort = TRUE) {
if (is_dir($path) || empty($path)) {
return NULL;
}
CRM_Utils_File::createDir(dirname($path), $abort);
if (@mkdir($path, 0777) == FALSE) {
if ($abort) {
$docLink = CRM_Utils_System::docURL2('Moving an Existing Installation to a New Server or Location', NULL, NULL, NULL, NULL, "wiki");
echo "Error: Could not create directory: $path.<p>If you have moved an existing CiviCRM installation from one location or server to another there are several steps you will need to follow. They are detailed on this CiviCRM wiki page - {$docLink}. A fix for the specific problem that caused this error message to be displayed is to set the value of the config_backend column in the civicrm_domain table to NULL. However we strongly recommend that you review and follow all the steps in that document.</p>";
CRM_Utils_System::civiExit();
}
else {
return FALSE;
}
}
return TRUE;
}
/**
* Delete a directory given a path name, delete children directories
* and files if needed
*
* @param string $target
* The path name.
* @param bool $rmdir
* @param bool $verbose
*
* @throws Exception
*/
public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
static $exceptions = ['.', '..'];
if ($target == '' || $target == '/' || !$target) {
throw new Exception("Overly broad deletion");
}
if ($dh = @opendir($target)) {
while (FALSE !== ($sibling = readdir($dh))) {
if (!in_array($sibling, $exceptions)) {
$object = $target . DIRECTORY_SEPARATOR . $sibling;
if (is_dir($object)) {
CRM_Utils_File::cleanDir($object, $rmdir, $verbose);
}
elseif (is_file($object)) {
if (!unlink($object)) {
CRM_Core_Session::setStatus(ts('Unable to remove file %1', [1 => $object]), ts('Warning'), 'error');
}
}
}
}
closedir($dh);
if ($rmdir) {
if (rmdir($target)) {
if ($verbose) {
CRM_Core_Session::setStatus(ts('Removed directory %1', [1 => $target]), '', 'success');
}
return TRUE;
}
else {
CRM_Core_Session::setStatus(ts('Unable to remove directory %1', [1 => $target]), ts('Warning'), 'error');
}
}
}
}
/**
* Concatenate several files.
*
* @param array $files
* List of file names.
* @param string $delim
* An optional delimiter to put between files.
* @return string
*/
public static function concat($files, $delim = '') {
$buf = '';
$first = TRUE;
foreach ($files as $file) {
if (!$first) {
$buf .= $delim;
}
$buf .= file_get_contents($file);
$first = FALSE;
}
return $buf;
}
/**
* @param string $source
* @param string $destination
*/
public static function copyDir($source, $destination) {
if ($dh = opendir($source)) {
@mkdir($destination);
while (FALSE !== ($file = readdir($dh))) {
if (($file != '.') && ($file != '..')) {
if (is_dir($source . DIRECTORY_SEPARATOR . $file)) {
CRM_Utils_File::copyDir($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
}
else {
copy($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
}
}
}
closedir($dh);
}
}
/**
* Given a file name, recode it (in place!) to UTF-8
*
* @param string $name
* Name of file.
*
* @return bool
* whether the file was recoded properly
*/
public static function toUtf8($name) {
static $config = NULL;
static $legacyEncoding = NULL;
if ($config == NULL) {
$config = CRM_Core_Config::singleton();
$legacyEncoding = $config->legacyEncoding;
}
if (!function_exists('iconv')) {
return FALSE;
}
$contents = file_get_contents($name);
if ($contents === FALSE) {
return FALSE;
}
$contents = iconv($legacyEncoding, 'UTF-8', $contents);
if ($contents === FALSE) {
return FALSE;
}
$file = fopen($name, 'w');
if ($file === FALSE) {
return FALSE;
}
$written = fwrite($file, $contents);
$closed = fclose($file);
if ($written === FALSE or !$closed) {
return FALSE;
}
return TRUE;
}
/**
* Appends a slash to the end of a string if it doesn't already end with one
*
* @param string $path
* @param string $slash
*
* @return string
*/
public static function addTrailingSlash($path, $slash = NULL) {
if (!$slash) {
// FIXME: Defaulting to backslash on windows systems can produce
// unexpected results, esp for URL strings which should always use forward-slashes.
// I think this fn should default to forward-slash instead.
$slash = DIRECTORY_SEPARATOR;
}
if (!in_array(substr($path, -1, 1), ['/', '\\'])) {
$path .= $slash;
}
return $path;
}
/**
* Save a fake file somewhere
*
* @param string $dir
* The directory where the file should be saved.
* @param string $contents
* Optional: the contents of the file.
* @param string $fileName
*
* @return string
* The filename saved, or FALSE on failure.
*/
public static function createFakeFile($dir, $contents = 'delete me', $fileName = NULL) {
$dir = self::addTrailingSlash($dir);
if (!$fileName) {
$fileName = 'delete-this-' . CRM_Utils_String::createRandom(10, CRM_Utils_String::ALPHANUMERIC);
}
$success = @file_put_contents($dir . $fileName, $contents);
return ($success === FALSE) ? FALSE : $fileName;
}
/**
* @param string|NULL $dsn
* Use NULL to load the default/active connection from CRM_Core_DAO.
* Otherwise, give a full DSN string.
* @param string $fileName
* @param string $prefix
* @param bool $dieOnErrors
*/
public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $dieOnErrors = TRUE) {
if (FALSE === file_get_contents($fileName)) {
// Our file cannot be found.
// Using 'die' here breaks this on extension upgrade.
throw new CRM_Core_Exception('Could not find the SQL file.');
}
self::runSqlQuery($dsn, file_get_contents($fileName), $prefix, $dieOnErrors);
}
/**
*
* @param string|NULL $dsn
* @param string $queryString
* @param string $prefix
* @param bool $dieOnErrors
*/
public static function runSqlQuery($dsn, $queryString, $prefix = NULL, $dieOnErrors = TRUE) {
$string = $prefix . $queryString;
if ($dsn === NULL) {
$db = CRM_Core_DAO::getConnection();
}
else {
require_once 'DB.php';
$dsn = CRM_Utils_SQL::autoSwitchDSN($dsn);
try {
$options = CRM_Utils_SQL::isSSLDSN($dsn) ? ['ssl' => TRUE] : [];
$db = DB::connect($dsn, $options);
}
catch (Exception $e) {
die("Cannot open $dsn: " . $e->getMessage());
}
}
$db->query('SET NAMES utf8mb4');
$transactionId = CRM_Utils_Type::escape(CRM_Utils_Request::id(), 'String');
$db->query('SET @uniqueID = ' . "'$transactionId'");
// get rid of comments starting with # and --
$string = self::stripComments($string);
$queries = preg_split('/;\s*$/m', $string);
foreach ($queries as $query) {
$query = trim($query);
if (!empty($query)) {
CRM_Core_Error::debug_query($query);
try {
$res = &$db->query($query);
}
catch (Exception $e) {
if ($dieOnErrors) {
die("Cannot execute $query: " . $e->getMessage());
}
else {
echo "Cannot execute $query: " . $e->getMessage() . "<p>";
}
}
}
}
}
/**
*
* Strips comment from a possibly multiline SQL string
*
* @param string $string
*
* @return string
* stripped string
*/
public static function stripComments($string) {
return preg_replace("/^(#|--).*\R*/m", "", $string);
}
/**
* @param $ext
*
* @return bool
*/
public static function isExtensionSafe($ext) {
static $extensions = NULL;
if (!$extensions) {
$extensions = CRM_Core_OptionGroup::values('safe_file_extension', TRUE);
// make extensions to lowercase
$extensions = array_change_key_case($extensions, CASE_LOWER);
// allow html/htm extension ONLY if the user is admin
// and/or has access CiviMail
if (!(CRM_Core_Permission::check('access CiviMail') ||
CRM_Core_Permission::check('administer CiviCRM') ||
(CRM_Mailing_Info::workflowEnabled() &&
CRM_Core_Permission::check('create mailings')
)
)
) {
unset($extensions['html']);
unset($extensions['htm']);
}
}
// support lower and uppercase file extensions
return (bool) isset($extensions[strtolower($ext)]);
}
/**
* Determine whether a given file is listed in the PHP include path.
*
* @param string $name
* Name of file.
*
* @return bool
* whether the file can be include()d or require()d
*/
public static function isIncludable($name) {
$full_filepath = stream_resolve_include_path($name);
if ($full_filepath === FALSE) {
return FALSE;
}
return is_readable($full_filepath);
}
/**
* Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
*
* @param $name
*
* @return mixed
*/
public static function cleanFileName($name) {
// replace the last 33 character before the '.' with null
$name = preg_replace('/(_[\w]{32})\./', '.', $name);
return $name;
}
/**
* Make a valid file name.
*
* @param string $name
*
* @return string
*/
public static function makeFileName($name) {
$uniqID = md5(uniqid(rand(), TRUE));
$info = pathinfo($name);
$basename = substr($info['basename'],
0, -(strlen(CRM_Utils_Array::value('extension', $info)) + (CRM_Utils_Array::value('extension', $info) == '' ? 0 : 1))
);
if (!self::isExtensionSafe(CRM_Utils_Array::value('extension', $info))) {
// munge extension so it cannot have an embbeded dot in it
// The maximum length of a filename for most filesystems is 255 chars.
// We'll truncate at 240 to give some room for the extension.
return CRM_Utils_String::munge("{$basename}_" . CRM_Utils_Array::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
}
else {
return CRM_Utils_String::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array::value('extension', $info);
}
}
/**
* CRM_Utils_String::munge() doesn't handle unicode and needs to be able
* to generate valid database tablenames so will sometimes generate a
* random string. Here what we want is a human-sensible filename that might
* contain unicode.
* Note that this does filter out emojis and such, but keeps characters that
* are considered alphanumeric in non-english languages.
*
* @param string $input
* @param string $replacementString Character or string to replace invalid characters with. Can be the empty string.
* @param int $cutoffLength Length to truncate the result after replacements.
* @return string
*/
public static function makeFilenameWithUnicode(string $input, string $replacementString = '_', int $cutoffLength = 63): string {
$filename = preg_replace('/\W/u', $replacementString, $input);
if ($cutoffLength) {
return mb_substr($filename, 0, $cutoffLength);
}
return $filename;
}
/**
* Copies a file
*
* @param $filePath
* @return mixed
*/
public static function duplicate($filePath) {
$oldName = pathinfo($filePath, PATHINFO_FILENAME);
$uniqID = md5(uniqid(rand(), TRUE));
$newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
$newPath = str_replace($oldName, $newName, $filePath);
copy($filePath, $newPath);
return $newPath;
}
/**
* Get files for the extension.
*
* @param string $path
* @param string $ext
*
* @return array
*/
public static function getFilesByExtension($path, $ext) {
$path = self::addTrailingSlash($path);
$files = [];
if ($dh = opendir($path)) {
while (FALSE !== ($elem = readdir($dh))) {
if (substr($elem, -(strlen($ext) + 1)) == '.' . $ext) {
$files[] .= $path . $elem;
}
}
closedir($dh);
}
return $files;
}
/**
* Restrict access to a given directory (by planting there a restrictive .htaccess file)
*
* @param string $dir
* The directory to be secured.
* @param bool $overwrite
*/
public static function restrictAccess($dir, $overwrite = FALSE) {
// note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
// of site, causing site to stop functioning.
// FIXME: we should do more checks here -
if (!empty($dir) && is_dir($dir)) {
$htaccess = <<<HTACCESS
<Files "*">
# Apache 2.2
<IfModule !authz_core_module>
Order allow,deny
Deny from all
</IfModule>
# Apache 2.4+
<IfModule authz_core_module>
Require all denied
</IfModule>
</Files>
HTACCESS;
$file = $dir . '.htaccess';
if ($overwrite || !file_exists($file)) {
if (file_put_contents($file, $htaccess) === FALSE) {
CRM_Core_Error::movedSiteError($file);
}
}
}
}
/**
* Restrict remote users from browsing the given directory.
*
* @param $publicDir
*/
public static function restrictBrowsing($publicDir) {
if (!is_dir($publicDir) || !is_writable($publicDir)) {
return;
}
// base dir
$nobrowse = realpath($publicDir) . '/index.html';
if (!file_exists($nobrowse)) {
@file_put_contents($nobrowse, '');
}
// child dirs
$dir = new RecursiveDirectoryIterator($publicDir);
foreach ($dir as $name => $object) {
if (is_dir($name) && $name != '..') {
$nobrowse = realpath($name) . '/index.html';
if (!file_exists($nobrowse)) {
@file_put_contents($nobrowse, '');
}
}
}
}
/**
* (Deprecated) Create the file-path from which all other internal paths are
* computed. This implementation determines it as `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
*
* This approach is problematic - e.g. it prevents one from authentically
* splitting the CIVICRM_TEMPLATE_COMPILEDIR away from other dirs. The implementation
* is preserved for backwards compatibility (and should only be called by
* CMS-adapters and by Civi\Core\Paths).
*
* Do not use it for new path construction logic. Instead, use Civi::paths().
*
* @deprecated
* @see \Civi::paths()
* @see \Civi\Core\Paths
*/
public static function baseFilePath() {
static $_path = NULL;
if (!$_path) {
// Note: Don't rely on $config; that creates a dependency loop.
if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
}
$templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR;
$path = dirname($templateCompileDir);
//this fix is to avoid creation of upload dirs inside templates_c directory
$checkPath = explode(DIRECTORY_SEPARATOR, $path);
$cnt = count($checkPath) - 1;
if ($checkPath[$cnt] == 'templates_c') {
unset($checkPath[$cnt]);
$path = implode(DIRECTORY_SEPARATOR, $checkPath);
}
$_path = CRM_Utils_File::addTrailingSlash($path);
}
return $_path;
}
/**
* Determine if a path is absolute.
*
* @param string $path
*
* @return bool
* TRUE if absolute. FALSE if relative.
*/
public static function isAbsolute($path) {
if (substr($path, 0, 1) === DIRECTORY_SEPARATOR) {
return TRUE;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
return TRUE;
}
}
return FALSE;
}
/**
* @param $directory
* @param string $basePath
* The base path when evaluating relative paths. Should include trailing slash.
*
* @return string
*/
public static function absoluteDirectory($directory, $basePath) {
// check if directory is already absolute, if so return immediately
// Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
return $directory;
}
// check if directory is already absolute, if so return immediately
if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR) {
return $directory;
}
if ($basePath === NULL) {
// Previous versions interpreted `NULL` to mean "default to `self::baseFilePath()`".
// However, no code in the known `universe` relies on this interpretation, and
// the `baseFilePath()` function is problematic/deprecated.
throw new \RuntimeException("absoluteDirectory() requires specifying a basePath");
}
// ensure that $basePath has a trailing slash
$basePath = self::addTrailingSlash($basePath);
return $basePath . $directory;
}
/**
* Make a file path relative to some base dir.
*
* @param $directory
* @param $basePath
*
* @return string
*/
public static function relativize($directory, $basePath) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$directory = strtr($directory, '\\', '/');
$basePath = strtr($basePath, '\\', '/');
}
if (substr($directory, 0, strlen($basePath)) == $basePath) {
return substr($directory, strlen($basePath));
}
else {
return $directory;
}
}
/**
* Create a path to a temporary file which can endure for multiple requests.
*
* @todo Automatic file cleanup using, eg, TTL policy
*
* @param string $prefix
*
* @return string, path to an openable/writable file
* @see tempnam
*/
public static function tempnam($prefix = 'tmp-') {
// $config = CRM_Core_Config::singleton();
// $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
// $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
$fileName = tempnam(sys_get_temp_dir(), $prefix);
return $fileName;
}
/**
* Create a path to a temporary directory which can endure for multiple requests.
*
* @todo Automatic file cleanup using, eg, TTL policy
*
* @param string $prefix
*
* @return string, path to an openable/writable directory; ends with '/'
* @see tempnam
*/
public static function tempdir($prefix = 'tmp-') {
$fileName = self::tempnam($prefix);
unlink($fileName);
mkdir($fileName, 0700);
return $fileName . '/';
}
/**
* Search directory tree for files which match a glob pattern.
*
* Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
*
* @param string $dir
* base dir.
* @param string $pattern
* glob pattern, eg "*.txt".
* @param bool $relative
* TRUE if paths should be made relative to $dir
* @return array(string)
*/
public static function findFiles($dir, $pattern, $relative = FALSE) {
if (!is_dir($dir) || !is_readable($dir)) {
return [];
}
// Which dirs should we exclude from our searches?
// If not defined, we default to excluding any dirname that begins
// with a . which is the old behaviour and therefore excludes .git/
$excludeDirsPattern = defined('CIVICRM_EXCLUDE_DIRS_PATTERN')
? constant('CIVICRM_EXCLUDE_DIRS_PATTERN')
: '@' . preg_quote(DIRECTORY_SEPARATOR) . '\.@';
$dir = rtrim($dir, '/');
$todos = [$dir];
$result = [];
while (!empty($todos)) {
$subdir = array_shift($todos);
$matches = glob("$subdir/$pattern");
if (is_array($matches)) {
foreach ($matches as $match) {
if (!is_dir($match)) {
$result[] = $relative ? CRM_Utils_File::relativize($match, "$dir/") : $match;
}
}
}
// Find subdirs to recurse into.
if ($dh = opendir($subdir)) {
while (FALSE !== ($entry = readdir($dh))) {
$path = $subdir . DIRECTORY_SEPARATOR . $entry;
// Exclude . (self) and .. (parent) to avoid infinite loop.
// Exclude configured exclude dirs.
// Exclude dirs we can't read.
// Exclude anything that's not a dir.
if (
$entry !== '.'
&& $entry !== '..'
&& (empty($excludeDirsPattern) || !preg_match($excludeDirsPattern, $path))
&& is_dir($path)
&& is_readable($path)
) {
$todos[] = $path;
}
}
closedir($dh);
}
}
return $result;
}
/**
* Determine if $child is a sub-directory of $parent
*
* @param string $parent
* @param string $child
* @param bool $checkRealPath
*
* @return bool
*/
public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
if ($checkRealPath) {
$parent = realpath($parent);
$child = realpath($child);
if ($parent === FALSE || $child === FALSE) {
return FALSE;
}
}
$parentParts = explode('/', rtrim($parent, '/'));
$childParts = explode('/', rtrim($child, '/'));
while (($parentPart = array_shift($parentParts)) !== NULL) {
$childPart = array_shift($childParts);
if ($parentPart != $childPart) {
return FALSE;
}
}
if (empty($childParts)) {
// same directory
return FALSE;
}
else {
return TRUE;
}
}
/**
* Move $fromDir to $toDir, replacing/deleting any
* pre-existing content.
*
* @param string $fromDir
* The directory which should be moved.
* @param string $toDir
* The new location of the directory.
* @param bool $verbose
*
* @return bool
* TRUE on success
*/
public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
if (is_dir($toDir)) {
if (!self::cleanDir($toDir, TRUE, $verbose)) {
return FALSE;
}
}
// return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
CRM_Utils_File::copyDir($fromDir, $toDir);
if (!CRM_Utils_File::cleanDir($fromDir, TRUE, FALSE)) {
CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', [1 => $fromDir]), '', 'alert');
return FALSE;
}
return TRUE;
}
/**
* Format file.
*
* @param array $param
* @param string $fileName
* @param array $extraParams
*/
public static function formatFile(&$param, $fileName, $extraParams = []) {
if (empty($param[$fileName])) {
return;
}
$fileParams = [
'uri' => $param[$fileName]['name'],
'type' => $param[$fileName]['type'],
'location' => $param[$fileName]['name'],
'upload_date' => date('YmdHis'),
] + $extraParams;
$param[$fileName] = $fileParams;
}
/**
* Return formatted file URL, like for image file return image url with image icon
*
* @param string $path
* Absoulte file path
* @param string $fileType
* @param string $url
* File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
*
* @return string $url
*/
public static function getFileURL($path, $fileType, $url = NULL) {
if (empty($path) || empty($fileType)) {
return '';
}
elseif (empty($url)) {
$fileName = basename($path);
$url = CRM_Utils_System::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
}
switch ($fileType) {
case 'image/jpeg':
case 'image/pjpeg':
case 'image/gif':
case 'image/x-png':
case 'image/png':
case 'image/jpg':
list($imageWidth, $imageHeight) = getimagesize($path);
list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
$url = "<a href=\"$url\" class='crm-image-popup'>
<img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
</a>";
break;
default:
$url = sprintf('<a href="%s">%s</a>', $url, self::cleanFileName(basename($path)));
break;
}
return $url;
}
/**
* Return formatted image icon
*
* @param string $imageURL
* Contact's image url
*
* @return string $url
*/
public static function getImageURL($imageURL) {
// retrieve image name from $imageURL
$imageURL = CRM_Utils_String::unstupifyUrl($imageURL);
parse_str(parse_url($imageURL, PHP_URL_QUERY), $query);
$url = NULL;
if (!empty($query['photo'])) {
$path = CRM_Core_Config::singleton()->customFileUploadDir . $query['photo'];
}
else {
$path = $url = $imageURL;
}
$fileExtension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
//According to (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types),
// there are some extensions that would need translating.:
$translateMimeTypes = [
'tif' => 'tiff',
'jpg' => 'jpeg',
'svg' => 'svg+xml',
];
$mimeType = 'image/' . CRM_Utils_Array::value(
$fileExtension,
$translateMimeTypes,
$fileExtension
);
return self::getFileURL($path, $mimeType, $url);
}
/**
* Resize an image.
*
* @param string $sourceFile
* Filesystem path to existing image on server
* @param int $targetWidth
* New width desired, in pixels
* @param int $targetHeight
* New height desired, in pixels
* @param string $suffix = ""
* If supplied, the image will be renamed to include this suffix. For
* example if the original file name is "foo.png" and $suffix = "_bar",
* then the final file name will be "foo_bar.png".
* @param bool $preserveAspect = TRUE
* When TRUE $width and $height will be used as a bounding box, outside of
* which the resized image will not extend.
* When FALSE, the image will be resized exactly to $width and $height, even
* if it means stretching it.
*
* @return string
* Path to image
* @throws \CRM_Core_Exception
* Under the following conditions
* - When GD is not available.
* - When the source file is not an image.
*/
public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) {
// Check if GD is installed
$gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
if (!$gdSupport) {
throw new CRM_Core_Exception(ts('Unable to resize image because the GD image library is not currently compiled in your PHP installation.'));
}
$sourceMime = mime_content_type($sourceFile);
if ($sourceMime == 'image/gif') {
$sourceData = imagecreatefromgif($sourceFile);
}
elseif ($sourceMime == 'image/png') {
$sourceData = imagecreatefrompng($sourceFile);
}
elseif ($sourceMime == 'image/jpeg') {
$sourceData = imagecreatefromjpeg($sourceFile);
}
else {