Merge pull request #18069 from civicrm/5.28
[civicrm-core.git] / CRM / Utils / File.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * class to provide simple static functions for file objects
20 */
21 class CRM_Utils_File {
22
23 /**
24 * Given a file name, determine if the file contents make it an ascii file
25 *
26 * @param string $name
27 * Name of file.
28 *
29 * @return bool
30 * true if file is ascii
31 */
32 public static function isAscii($name) {
33 $fd = fopen($name, "r");
34 if (!$fd) {
35 return FALSE;
36 }
37
38 $ascii = TRUE;
39 while (!feof($fd)) {
40 $line = fgets($fd, 8192);
41 if (!CRM_Utils_String::isAscii($line)) {
42 $ascii = FALSE;
43 break;
44 }
45 }
46
47 fclose($fd);
48 return $ascii;
49 }
50
51 /**
52 * Given a file name, determine if the file contents make it an html file
53 *
54 * @param string $name
55 * Name of file.
56 *
57 * @return bool
58 * true if file is html
59 */
60 public static function isHtml($name) {
61 $fd = fopen($name, "r");
62 if (!$fd) {
63 return FALSE;
64 }
65
66 $html = FALSE;
67 $lineCount = 0;
68 while (!feof($fd) & $lineCount <= 5) {
69 $lineCount++;
70 $line = fgets($fd, 8192);
71 if (!CRM_Utils_String::isHtml($line)) {
72 $html = TRUE;
73 break;
74 }
75 }
76
77 fclose($fd);
78 return $html;
79 }
80
81 /**
82 * Create a directory given a path name, creates parent directories
83 * if needed
84 *
85 * @param string $path
86 * The path name.
87 * @param bool $abort
88 * Should we abort or just return an invalid code.
89 * @return bool|NULL
90 * NULL: Folder already exists or was not specified.
91 * TRUE: Creation succeeded.
92 * FALSE: Creation failed.
93 */
94 public static function createDir($path, $abort = TRUE) {
95 if (is_dir($path) || empty($path)) {
96 return NULL;
97 }
98
99 CRM_Utils_File::createDir(dirname($path), $abort);
100 if (@mkdir($path, 0777) == FALSE) {
101 if ($abort) {
102 $docLink = CRM_Utils_System::docURL2('Moving an Existing Installation to a New Server or Location', NULL, NULL, NULL, NULL, "wiki");
103 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>";
104
105 CRM_Utils_System::civiExit();
106 }
107 else {
108 return FALSE;
109 }
110 }
111 return TRUE;
112 }
113
114 /**
115 * Delete a directory given a path name, delete children directories
116 * and files if needed
117 *
118 * @param string $target
119 * The path name.
120 * @param bool $rmdir
121 * @param bool $verbose
122 *
123 * @throws Exception
124 */
125 public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
126 static $exceptions = ['.', '..'];
127 if ($target == '' || $target == '/' || !$target) {
128 throw new Exception("Overly broad deletion");
129 }
130
131 if ($dh = @opendir($target)) {
132 while (FALSE !== ($sibling = readdir($dh))) {
133 if (!in_array($sibling, $exceptions)) {
134 $object = $target . DIRECTORY_SEPARATOR . $sibling;
135
136 if (is_dir($object)) {
137 CRM_Utils_File::cleanDir($object, $rmdir, $verbose);
138 }
139 elseif (is_file($object)) {
140 if (!unlink($object)) {
141 CRM_Core_Session::setStatus(ts('Unable to remove file %1', [1 => $object]), ts('Warning'), 'error');
142 }
143 }
144 }
145 }
146 closedir($dh);
147
148 if ($rmdir) {
149 if (rmdir($target)) {
150 if ($verbose) {
151 CRM_Core_Session::setStatus(ts('Removed directory %1', [1 => $target]), '', 'success');
152 }
153 return TRUE;
154 }
155 else {
156 CRM_Core_Session::setStatus(ts('Unable to remove directory %1', [1 => $target]), ts('Warning'), 'error');
157 }
158 }
159 }
160 }
161
162 /**
163 * Concatenate several files.
164 *
165 * @param array $files
166 * List of file names.
167 * @param string $delim
168 * An optional delimiter to put between files.
169 * @return string
170 */
171 public static function concat($files, $delim = '') {
172 $buf = '';
173 $first = TRUE;
174 foreach ($files as $file) {
175 if (!$first) {
176 $buf .= $delim;
177 }
178 $buf .= file_get_contents($file);
179 $first = FALSE;
180 }
181 return $buf;
182 }
183
184 /**
185 * @param string $source
186 * @param string $destination
187 */
188 public static function copyDir($source, $destination) {
189 if ($dh = opendir($source)) {
190 @mkdir($destination);
191 while (FALSE !== ($file = readdir($dh))) {
192 if (($file != '.') && ($file != '..')) {
193 if (is_dir($source . DIRECTORY_SEPARATOR . $file)) {
194 CRM_Utils_File::copyDir($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
195 }
196 else {
197 copy($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
198 }
199 }
200 }
201 closedir($dh);
202 }
203 }
204
205 /**
206 * Given a file name, recode it (in place!) to UTF-8
207 *
208 * @param string $name
209 * Name of file.
210 *
211 * @return bool
212 * whether the file was recoded properly
213 */
214 public static function toUtf8($name) {
215 static $config = NULL;
216 static $legacyEncoding = NULL;
217 if ($config == NULL) {
218 $config = CRM_Core_Config::singleton();
219 $legacyEncoding = $config->legacyEncoding;
220 }
221
222 if (!function_exists('iconv')) {
223
224 return FALSE;
225
226 }
227
228 $contents = file_get_contents($name);
229 if ($contents === FALSE) {
230 return FALSE;
231 }
232
233 $contents = iconv($legacyEncoding, 'UTF-8', $contents);
234 if ($contents === FALSE) {
235 return FALSE;
236 }
237
238 $file = fopen($name, 'w');
239 if ($file === FALSE) {
240 return FALSE;
241 }
242
243 $written = fwrite($file, $contents);
244 $closed = fclose($file);
245 if ($written === FALSE or !$closed) {
246 return FALSE;
247 }
248
249 return TRUE;
250 }
251
252 /**
253 * Appends a slash to the end of a string if it doesn't already end with one
254 *
255 * @param string $path
256 * @param string $slash
257 *
258 * @return string
259 */
260 public static function addTrailingSlash($path, $slash = NULL) {
261 if (!$slash) {
262 // FIXME: Defaulting to backslash on windows systems can produce
263 // unexpected results, esp for URL strings which should always use forward-slashes.
264 // I think this fn should default to forward-slash instead.
265 $slash = DIRECTORY_SEPARATOR;
266 }
267 if (!in_array(substr($path, -1, 1), ['/', '\\'])) {
268 $path .= $slash;
269 }
270 return $path;
271 }
272
273 /**
274 * Save a fake file somewhere
275 *
276 * @param string $dir
277 * The directory where the file should be saved.
278 * @param string $contents
279 * Optional: the contents of the file.
280 * @param string $fileName
281 *
282 * @return string
283 * The filename saved, or FALSE on failure.
284 */
285 public static function createFakeFile($dir, $contents = 'delete me', $fileName = NULL) {
286 $dir = self::addTrailingSlash($dir);
287 if (!$fileName) {
288 $fileName = 'delete-this-' . CRM_Utils_String::createRandom(10, CRM_Utils_String::ALPHANUMERIC);
289 }
290 $success = @file_put_contents($dir . $fileName, $contents);
291
292 return ($success === FALSE) ? FALSE : $fileName;
293 }
294
295 /**
296 * @param string|NULL $dsn
297 * Use NULL to load the default/active connection from CRM_Core_DAO.
298 * Otherwise, give a full DSN string.
299 * @param string $fileName
300 * @param string $prefix
301 * @param bool $dieOnErrors
302 */
303 public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $dieOnErrors = TRUE) {
304 if (FALSE === file_get_contents($fileName)) {
305 // Our file cannot be found.
306 // Using 'die' here breaks this on extension upgrade.
307 throw new CRM_Core_Exception('Could not find the SQL file.');
308 }
309
310 self::runSqlQuery($dsn, file_get_contents($fileName), $prefix, $dieOnErrors);
311 }
312
313 /**
314 *
315 * @param string|NULL $dsn
316 * @param string $queryString
317 * @param string $prefix
318 * @param bool $dieOnErrors
319 */
320 public static function runSqlQuery($dsn, $queryString, $prefix = NULL, $dieOnErrors = TRUE) {
321 $string = $prefix . $queryString;
322
323 if ($dsn === NULL) {
324 $db = CRM_Core_DAO::getConnection();
325 }
326 else {
327 require_once 'DB.php';
328 $db = DB::connect($dsn);
329 }
330
331 if (PEAR::isError($db)) {
332 die("Cannot open $dsn: " . $db->getMessage());
333 }
334 if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) {
335 $db->query('SET SESSION sql_mode = STRICT_TRANS_TABLES');
336 }
337 $db->query('SET NAMES utf8mb4');
338 $transactionId = CRM_Utils_Type::escape(CRM_Utils_Request::id(), 'String');
339 $db->query('SET @uniqueID = ' . "'$transactionId'");
340
341 // get rid of comments starting with # and --
342
343 $string = self::stripComments($string);
344
345 $queries = preg_split('/;\s*$/m', $string);
346 foreach ($queries as $query) {
347 $query = trim($query);
348 if (!empty($query)) {
349 CRM_Core_Error::debug_query($query);
350 $res = &$db->query($query);
351 if (PEAR::isError($res)) {
352 if ($dieOnErrors) {
353 die("Cannot execute $query: " . $res->getMessage());
354 }
355 else {
356 echo "Cannot execute $query: " . $res->getMessage() . "<p>";
357 }
358 }
359 }
360 }
361 }
362
363 /**
364 *
365 * Strips comment from a possibly multiline SQL string
366 *
367 * @param string $string
368 *
369 * @return string
370 * stripped string
371 */
372 public static function stripComments($string) {
373 return preg_replace("/^(#|--).*\R*/m", "", $string);
374 }
375
376 /**
377 * @param $ext
378 *
379 * @return bool
380 */
381 public static function isExtensionSafe($ext) {
382 static $extensions = NULL;
383 if (!$extensions) {
384 $extensions = CRM_Core_OptionGroup::values('safe_file_extension', TRUE);
385
386 // make extensions to lowercase
387 $extensions = array_change_key_case($extensions, CASE_LOWER);
388 // allow html/htm extension ONLY if the user is admin
389 // and/or has access CiviMail
390 if (!(CRM_Core_Permission::check('access CiviMail') ||
391 CRM_Core_Permission::check('administer CiviCRM') ||
392 (CRM_Mailing_Info::workflowEnabled() &&
393 CRM_Core_Permission::check('create mailings')
394 )
395 )
396 ) {
397 unset($extensions['html']);
398 unset($extensions['htm']);
399 }
400 }
401 // support lower and uppercase file extensions
402 return (bool) isset($extensions[strtolower($ext)]);
403 }
404
405 /**
406 * Determine whether a given file is listed in the PHP include path.
407 *
408 * @param string $name
409 * Name of file.
410 *
411 * @return bool
412 * whether the file can be include()d or require()d
413 */
414 public static function isIncludable($name) {
415 $x = @fopen($name, 'r', TRUE);
416 if ($x) {
417 fclose($x);
418 return TRUE;
419 }
420 else {
421 return FALSE;
422 }
423 }
424
425 /**
426 * Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
427 *
428 * @param $name
429 *
430 * @return mixed
431 */
432 public static function cleanFileName($name) {
433 // replace the last 33 character before the '.' with null
434 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
435 return $name;
436 }
437
438 /**
439 * Make a valid file name.
440 *
441 * @param string $name
442 *
443 * @return string
444 */
445 public static function makeFileName($name) {
446 $uniqID = md5(uniqid(rand(), TRUE));
447 $info = pathinfo($name);
448 $basename = substr($info['basename'],
449 0, -(strlen(CRM_Utils_Array::value('extension', $info)) + (CRM_Utils_Array::value('extension', $info) == '' ? 0 : 1))
450 );
451 if (!self::isExtensionSafe(CRM_Utils_Array::value('extension', $info))) {
452 // munge extension so it cannot have an embbeded dot in it
453 // The maximum length of a filename for most filesystems is 255 chars.
454 // We'll truncate at 240 to give some room for the extension.
455 return CRM_Utils_String::munge("{$basename}_" . CRM_Utils_Array::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
456 }
457 else {
458 return CRM_Utils_String::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array::value('extension', $info);
459 }
460 }
461
462 /**
463 * Copies a file
464 *
465 * @param $filePath
466 * @return mixed
467 */
468 public static function duplicate($filePath) {
469 $oldName = pathinfo($filePath, PATHINFO_FILENAME);
470 $uniqID = md5(uniqid(rand(), TRUE));
471 $newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
472 $newPath = str_replace($oldName, $newName, $filePath);
473 copy($filePath, $newPath);
474 return $newPath;
475 }
476
477 /**
478 * Get files for the extension.
479 *
480 * @param string $path
481 * @param string $ext
482 *
483 * @return array
484 */
485 public static function getFilesByExtension($path, $ext) {
486 $path = self::addTrailingSlash($path);
487 $files = [];
488 if ($dh = opendir($path)) {
489 while (FALSE !== ($elem = readdir($dh))) {
490 if (substr($elem, -(strlen($ext) + 1)) == '.' . $ext) {
491 $files[] .= $path . $elem;
492 }
493 }
494 closedir($dh);
495 }
496 return $files;
497 }
498
499 /**
500 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
501 *
502 * @param string $dir
503 * The directory to be secured.
504 * @param bool $overwrite
505 */
506 public static function restrictAccess($dir, $overwrite = FALSE) {
507 // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
508 // of site, causing site to stop functioning.
509 // FIXME: we should do more checks here -
510 if (!empty($dir) && is_dir($dir)) {
511 $htaccess = <<<HTACCESS
512 <Files "*">
513 # Apache 2.2
514 <IfModule !authz_core_module>
515 Order allow,deny
516 Deny from all
517 </IfModule>
518
519 # Apache 2.4+
520 <IfModule authz_core_module>
521 Require all denied
522 </IfModule>
523 </Files>
524
525 HTACCESS;
526 $file = $dir . '.htaccess';
527 if ($overwrite || !file_exists($file)) {
528 if (file_put_contents($file, $htaccess) === FALSE) {
529 CRM_Core_Error::movedSiteError($file);
530 }
531 }
532 }
533 }
534
535 /**
536 * Restrict remote users from browsing the given directory.
537 *
538 * @param $publicDir
539 */
540 public static function restrictBrowsing($publicDir) {
541 if (!is_dir($publicDir) || !is_writable($publicDir)) {
542 return;
543 }
544
545 // base dir
546 $nobrowse = realpath($publicDir) . '/index.html';
547 if (!file_exists($nobrowse)) {
548 @file_put_contents($nobrowse, '');
549 }
550
551 // child dirs
552 $dir = new RecursiveDirectoryIterator($publicDir);
553 foreach ($dir as $name => $object) {
554 if (is_dir($name) && $name != '..') {
555 $nobrowse = realpath($name) . '/index.html';
556 if (!file_exists($nobrowse)) {
557 @file_put_contents($nobrowse, '');
558 }
559 }
560 }
561 }
562
563 /**
564 * (Deprecated) Create the file-path from which all other internal paths are
565 * computed. This implementation determines it as `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
566 *
567 * This approach is problematic - e.g. it prevents one from authentically
568 * splitting the CIVICRM_TEMPLATE_COMPILEDIR away from other dirs. The implementation
569 * is preserved for backwards compatibility (and should only be called by
570 * CMS-adapters and by Civi\Core\Paths).
571 *
572 * Do not use it for new path construction logic. Instead, use Civi::paths().
573 *
574 * @deprecated
575 * @see \Civi::paths()
576 * @see \Civi\Core\Paths
577 */
578 public static function baseFilePath() {
579 static $_path = NULL;
580 if (!$_path) {
581 // Note: Don't rely on $config; that creates a dependency loop.
582 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
583 throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
584 }
585 $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR;
586
587 $path = dirname($templateCompileDir);
588
589 //this fix is to avoid creation of upload dirs inside templates_c directory
590 $checkPath = explode(DIRECTORY_SEPARATOR, $path);
591
592 $cnt = count($checkPath) - 1;
593 if ($checkPath[$cnt] == 'templates_c') {
594 unset($checkPath[$cnt]);
595 $path = implode(DIRECTORY_SEPARATOR, $checkPath);
596 }
597
598 $_path = CRM_Utils_File::addTrailingSlash($path);
599 }
600 return $_path;
601 }
602
603 /**
604 * Determine if a path is absolute.
605 *
606 * @param string $path
607 *
608 * @return bool
609 * TRUE if absolute. FALSE if relative.
610 */
611 public static function isAbsolute($path) {
612 if (substr($path, 0, 1) === DIRECTORY_SEPARATOR) {
613 return TRUE;
614 }
615 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
616 if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
617 return TRUE;
618 }
619 }
620 return FALSE;
621 }
622
623 /**
624 * @param $directory
625 *
626 * @return string
627 * @deprecated
628 * Computation of a relative path requires some base.
629 * This implementation is problematic because it relies on an
630 * implicit base which was constructed problematically.
631 */
632 public static function relativeDirectory($directory) {
633 // Do nothing on windows
634 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
635 return $directory;
636 }
637
638 // check if directory is relative, if so return immediately
639 if (!self::isAbsolute($directory)) {
640 return $directory;
641 }
642
643 // make everything relative from the baseFilePath
644 $basePath = self::baseFilePath();
645 // check if basePath is a substr of $directory, if so
646 // return rest of string
647 if (substr($directory, 0, strlen($basePath)) == $basePath) {
648 return substr($directory, strlen($basePath));
649 }
650
651 // return the original value
652 return $directory;
653 }
654
655 /**
656 * @param $directory
657 * @param string $basePath
658 * The base path when evaluating relative paths. Should include trailing slash.
659 *
660 * @return string
661 */
662 public static function absoluteDirectory($directory, $basePath) {
663 // check if directory is already absolute, if so return immediately
664 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
665 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
666 return $directory;
667 }
668
669 // check if directory is already absolute, if so return immediately
670 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR) {
671 return $directory;
672 }
673
674 if ($basePath === NULL) {
675 // Previous versions interpreted `NULL` to mean "default to `self::baseFilePath()`".
676 // However, no code in the known `universe` relies on this interpretation, and
677 // the `baseFilePath()` function is problematic/deprecated.
678 throw new \RuntimeException("absoluteDirectory() requires specifying a basePath");
679 }
680
681 // ensure that $basePath has a trailing slash
682 $basePath = self::addTrailingSlash($basePath);
683 return $basePath . $directory;
684 }
685
686 /**
687 * Make a file path relative to some base dir.
688 *
689 * @param $directory
690 * @param $basePath
691 *
692 * @return string
693 */
694 public static function relativize($directory, $basePath) {
695 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
696 $directory = strtr($directory, '\\', '/');
697 $basePath = strtr($basePath, '\\', '/');
698 }
699 if (substr($directory, 0, strlen($basePath)) == $basePath) {
700 return substr($directory, strlen($basePath));
701 }
702 else {
703 return $directory;
704 }
705 }
706
707 /**
708 * Create a path to a temporary file which can endure for multiple requests.
709 *
710 * @todo Automatic file cleanup using, eg, TTL policy
711 *
712 * @param string $prefix
713 *
714 * @return string, path to an openable/writable file
715 * @see tempnam
716 */
717 public static function tempnam($prefix = 'tmp-') {
718 // $config = CRM_Core_Config::singleton();
719 // $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
720 // $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
721 $fileName = tempnam(sys_get_temp_dir(), $prefix);
722 return $fileName;
723 }
724
725 /**
726 * Create a path to a temporary directory which can endure for multiple requests.
727 *
728 * @todo Automatic file cleanup using, eg, TTL policy
729 *
730 * @param string $prefix
731 *
732 * @return string, path to an openable/writable directory; ends with '/'
733 * @see tempnam
734 */
735 public static function tempdir($prefix = 'tmp-') {
736 $fileName = self::tempnam($prefix);
737 unlink($fileName);
738 mkdir($fileName, 0700);
739 return $fileName . '/';
740 }
741
742 /**
743 * Search directory tree for files which match a glob pattern.
744 *
745 * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
746 *
747 * @param string $dir
748 * base dir.
749 * @param string $pattern
750 * glob pattern, eg "*.txt".
751 * @param bool $relative
752 * TRUE if paths should be made relative to $dir
753 * @return array(string)
754 */
755 public static function findFiles($dir, $pattern, $relative = FALSE) {
756 if (!is_dir($dir) || !is_readable($dir)) {
757 return [];
758 }
759 // Which dirs should we exclude from our searches?
760 // If not defined, we default to excluding any dirname that begins
761 // with a . which is the old behaviour and therefore excludes .git/
762 $excludeDirsPattern = defined('CIVICRM_EXCLUDE_DIRS_PATTERN')
763 ? constant('CIVICRM_EXCLUDE_DIRS_PATTERN')
764 : '@' . preg_quote(DIRECTORY_SEPARATOR) . '\.@';
765
766 $dir = rtrim($dir, '/');
767 $todos = [$dir];
768 $result = [];
769 while (!empty($todos)) {
770 $subdir = array_shift($todos);
771 $matches = glob("$subdir/$pattern");
772 if (is_array($matches)) {
773 foreach ($matches as $match) {
774 if (!is_dir($match)) {
775 $result[] = $relative ? CRM_Utils_File::relativize($match, "$dir/") : $match;
776 }
777 }
778 }
779 // Find subdirs to recurse into.
780 if ($dh = opendir($subdir)) {
781 while (FALSE !== ($entry = readdir($dh))) {
782 $path = $subdir . DIRECTORY_SEPARATOR . $entry;
783 // Exclude . (self) and .. (parent) to avoid infinite loop.
784 // Exclude configured exclude dirs.
785 // Exclude dirs we can't read.
786 // Exclude anything that's not a dir.
787 if (
788 $entry !== '.'
789 && $entry !== '..'
790 && (empty($excludeDirsPattern) || !preg_match($excludeDirsPattern, $path))
791 && is_dir($path)
792 && is_readable($path)
793 ) {
794 $todos[] = $path;
795 }
796 }
797 closedir($dh);
798 }
799 }
800 return $result;
801 }
802
803 /**
804 * Determine if $child is a sub-directory of $parent
805 *
806 * @param string $parent
807 * @param string $child
808 * @param bool $checkRealPath
809 *
810 * @return bool
811 */
812 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
813 if ($checkRealPath) {
814 $parent = realpath($parent);
815 $child = realpath($child);
816 }
817 $parentParts = explode('/', rtrim($parent, '/'));
818 $childParts = explode('/', rtrim($child, '/'));
819 while (($parentPart = array_shift($parentParts)) !== NULL) {
820 $childPart = array_shift($childParts);
821 if ($parentPart != $childPart) {
822 return FALSE;
823 }
824 }
825 if (empty($childParts)) {
826 // same directory
827 return FALSE;
828 }
829 else {
830 return TRUE;
831 }
832 }
833
834 /**
835 * Move $fromDir to $toDir, replacing/deleting any
836 * pre-existing content.
837 *
838 * @param string $fromDir
839 * The directory which should be moved.
840 * @param string $toDir
841 * The new location of the directory.
842 * @param bool $verbose
843 *
844 * @return bool
845 * TRUE on success
846 */
847 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
848 if (is_dir($toDir)) {
849 if (!self::cleanDir($toDir, TRUE, $verbose)) {
850 return FALSE;
851 }
852 }
853
854 // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
855
856 CRM_Utils_File::copyDir($fromDir, $toDir);
857 if (!CRM_Utils_File::cleanDir($fromDir, TRUE, FALSE)) {
858 CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', [1 => $fromDir]), '', 'alert');
859 return FALSE;
860 }
861 return TRUE;
862 }
863
864 /**
865 * Format file.
866 *
867 * @param array $param
868 * @param string $fileName
869 * @param array $extraParams
870 */
871 public static function formatFile(&$param, $fileName, $extraParams = []) {
872 if (empty($param[$fileName])) {
873 return;
874 }
875
876 $fileParams = [
877 'uri' => $param[$fileName]['name'],
878 'type' => $param[$fileName]['type'],
879 'location' => $param[$fileName]['name'],
880 'upload_date' => date('YmdHis'),
881 ] + $extraParams;
882
883 $param[$fileName] = $fileParams;
884 }
885
886 /**
887 * Return formatted file URL, like for image file return image url with image icon
888 *
889 * @param string $path
890 * Absoulte file path
891 * @param string $fileType
892 * @param string $url
893 * File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
894 *
895 * @return string $url
896 */
897 public static function getFileURL($path, $fileType, $url = NULL) {
898 if (empty($path) || empty($fileType)) {
899 return '';
900 }
901 elseif (empty($url)) {
902 $fileName = basename($path);
903 $url = CRM_Utils_System::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
904 }
905 switch ($fileType) {
906 case 'image/jpeg':
907 case 'image/pjpeg':
908 case 'image/gif':
909 case 'image/x-png':
910 case 'image/png':
911 case 'image/jpg':
912 list($imageWidth, $imageHeight) = getimagesize($path);
913 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
914 $url = "<a href=\"$url\" class='crm-image-popup'>
915 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
916 </a>";
917 break;
918
919 default:
920 $url = sprintf('<a href="%s">%s</a>', $url, self::cleanFileName(basename($path)));
921 break;
922 }
923
924 return $url;
925 }
926
927 /**
928 * Return formatted image icon
929 *
930 * @param string $imageURL
931 * Contact's image url
932 *
933 * @return string $url
934 */
935 public static function getImageURL($imageURL) {
936 // retrieve image name from $imageURL
937 $imageURL = CRM_Utils_String::unstupifyUrl($imageURL);
938 parse_str(parse_url($imageURL, PHP_URL_QUERY), $query);
939
940 $url = NULL;
941 if (!empty($query['photo'])) {
942 $path = CRM_Core_Config::singleton()->customFileUploadDir . $query['photo'];
943 }
944 else {
945 $path = $url = $imageURL;
946 }
947 $fileExtension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
948 //According to (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types),
949 // there are some extensions that would need translating.:
950 $translateMimeTypes = [
951 'tif' => 'tiff',
952 'jpg' => 'jpeg',
953 'svg' => 'svg+xml',
954 ];
955 $mimeType = 'image/' . CRM_Utils_Array::value(
956 $fileExtension,
957 $translateMimeTypes,
958 $fileExtension
959 );
960
961 return self::getFileURL($path, $mimeType, $url);
962 }
963
964 /**
965 * Resize an image.
966 *
967 * @param string $sourceFile
968 * Filesystem path to existing image on server
969 * @param int $targetWidth
970 * New width desired, in pixels
971 * @param int $targetHeight
972 * New height desired, in pixels
973 * @param string $suffix = ""
974 * If supplied, the image will be renamed to include this suffix. For
975 * example if the original file name is "foo.png" and $suffix = "_bar",
976 * then the final file name will be "foo_bar.png".
977 * @param bool $preserveAspect = TRUE
978 * When TRUE $width and $height will be used as a bounding box, outside of
979 * which the resized image will not extend.
980 * When FALSE, the image will be resized exactly to $width and $height, even
981 * if it means stretching it.
982 *
983 * @return string
984 * Path to image
985 * @throws \CRM_Core_Exception
986 * Under the following conditions
987 * - When GD is not available.
988 * - When the source file is not an image.
989 */
990 public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) {
991
992 // Check if GD is installed
993 $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
994 if (!$gdSupport) {
995 throw new CRM_Core_Exception(ts('Unable to resize image because the GD image library is not currently compiled in your PHP installation.'));
996 }
997
998 $sourceMime = mime_content_type($sourceFile);
999 if ($sourceMime == 'image/gif') {
1000 $sourceData = imagecreatefromgif($sourceFile);
1001 }
1002 elseif ($sourceMime == 'image/png') {
1003 $sourceData = imagecreatefrompng($sourceFile);
1004 }
1005 elseif ($sourceMime == 'image/jpeg') {
1006 $sourceData = imagecreatefromjpeg($sourceFile);
1007 }
1008 else {
1009 throw new CRM_Core_Exception(ts('Unable to resize image because the file supplied was not an image.'));
1010 }
1011
1012 // get image about original image
1013 $sourceInfo = getimagesize($sourceFile);
1014 $sourceWidth = $sourceInfo[0];
1015 $sourceHeight = $sourceInfo[1];
1016
1017 // Adjust target width/height if preserving aspect ratio
1018 if ($preserveAspect) {
1019 $sourceAspect = $sourceWidth / $sourceHeight;
1020 $targetAspect = $targetWidth / $targetHeight;
1021 if ($sourceAspect > $targetAspect) {
1022 $targetHeight = $targetWidth / $sourceAspect;
1023 }
1024 if ($sourceAspect < $targetAspect) {
1025 $targetWidth = $targetHeight * $sourceAspect;
1026 }
1027 }
1028
1029 // figure out the new filename
1030 $pathParts = pathinfo($sourceFile);
1031 $targetFile = $pathParts['dirname'] . DIRECTORY_SEPARATOR
1032 . $pathParts['filename'] . $suffix . "." . $pathParts['extension'];
1033
1034 $targetData = imagecreatetruecolor($targetWidth, $targetHeight);
1035
1036 // resize
1037 imagecopyresized($targetData, $sourceData,
1038 0, 0, 0, 0,
1039 $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
1040
1041 // save the resized image
1042 $fp = fopen($targetFile, 'w+');
1043 ob_start();
1044 imagejpeg($targetData);
1045 $image_buffer = ob_get_contents();
1046 ob_end_clean();
1047 imagedestroy($targetData);
1048 fwrite($fp, $image_buffer);
1049 rewind($fp);
1050 fclose($fp);
1051
1052 // return the URL to link to
1053 $config = CRM_Core_Config::singleton();
1054 return $config->imageUploadURL . basename($targetFile);
1055 }
1056
1057 /**
1058 * Get file icon class for specific MIME Type
1059 *
1060 * @param string $mimeType
1061 * @return string
1062 */
1063 public static function getIconFromMimeType($mimeType) {
1064 if (!isset(Civi::$statics[__CLASS__]['mimeIcons'])) {
1065 Civi::$statics[__CLASS__]['mimeIcons'] = json_decode(file_get_contents(__DIR__ . '/File/mimeIcons.json'), TRUE);
1066 }
1067 $iconClasses = Civi::$statics[__CLASS__]['mimeIcons'];
1068 foreach ($iconClasses as $text => $icon) {
1069 if (strpos($mimeType, $text) === 0) {
1070 return $icon;
1071 }
1072 }
1073 return $iconClasses['*'];
1074 }
1075
1076 /**
1077 * Is the filename a safe and valid filename passed in from URL
1078 *
1079 * @param string $fileName
1080 * @return bool
1081 */
1082 public static function isValidFileName($fileName = NULL) {
1083 if ($fileName) {
1084 $check = ($fileName === basename($fileName));
1085 if ($check) {
1086 if (substr($fileName, 0, 1) == '/' || substr($fileName, 0, 1) == '.' || substr($fileName, 0, 1) == DIRECTORY_SEPARATOR) {
1087 $check = FALSE;
1088 }
1089 }
1090 return $check;
1091 }
1092 return FALSE;
1093 }
1094
1095 /**
1096 * Get the extensions that this MimeTpe is for
1097 * @param string $mimeType the mime-type we want extensions for
1098 * @return array
1099 */
1100 public static function getAcceptableExtensionsForMimeType($mimeType = []) {
1101 $mimeRepostory = new \MimeTyper\Repository\ExtendedRepository();
1102 return $mimeRepostory->findExtensions($mimeType);
1103 }
1104
1105 /**
1106 * Get the extension of a file based on its path
1107 * @param string $path path of the file to query
1108 * @return string
1109 */
1110 public static function getExtensionFromPath($path) {
1111 return pathinfo($path, PATHINFO_EXTENSION);
1112 }
1113
1114 }