Merge pull request #18246 from sunilpawar/report_45
[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 $dsn = CRM_Utils_SQL::autoSwitchDSN($dsn);
329 $db = DB::connect($dsn);
330 }
331
332 if (PEAR::isError($db)) {
333 die("Cannot open $dsn: " . $db->getMessage());
334 }
335 if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) {
336 $db->query('SET SESSION sql_mode = STRICT_TRANS_TABLES');
337 }
338 $db->query('SET NAMES utf8mb4');
339 $transactionId = CRM_Utils_Type::escape(CRM_Utils_Request::id(), 'String');
340 $db->query('SET @uniqueID = ' . "'$transactionId'");
341
342 // get rid of comments starting with # and --
343
344 $string = self::stripComments($string);
345
346 $queries = preg_split('/;\s*$/m', $string);
347 foreach ($queries as $query) {
348 $query = trim($query);
349 if (!empty($query)) {
350 CRM_Core_Error::debug_query($query);
351 $res = &$db->query($query);
352 if (PEAR::isError($res)) {
353 if ($dieOnErrors) {
354 die("Cannot execute $query: " . $res->getMessage());
355 }
356 else {
357 echo "Cannot execute $query: " . $res->getMessage() . "<p>";
358 }
359 }
360 }
361 }
362 }
363
364 /**
365 *
366 * Strips comment from a possibly multiline SQL string
367 *
368 * @param string $string
369 *
370 * @return string
371 * stripped string
372 */
373 public static function stripComments($string) {
374 return preg_replace("/^(#|--).*\R*/m", "", $string);
375 }
376
377 /**
378 * @param $ext
379 *
380 * @return bool
381 */
382 public static function isExtensionSafe($ext) {
383 static $extensions = NULL;
384 if (!$extensions) {
385 $extensions = CRM_Core_OptionGroup::values('safe_file_extension', TRUE);
386
387 // make extensions to lowercase
388 $extensions = array_change_key_case($extensions, CASE_LOWER);
389 // allow html/htm extension ONLY if the user is admin
390 // and/or has access CiviMail
391 if (!(CRM_Core_Permission::check('access CiviMail') ||
392 CRM_Core_Permission::check('administer CiviCRM') ||
393 (CRM_Mailing_Info::workflowEnabled() &&
394 CRM_Core_Permission::check('create mailings')
395 )
396 )
397 ) {
398 unset($extensions['html']);
399 unset($extensions['htm']);
400 }
401 }
402 // support lower and uppercase file extensions
403 return (bool) isset($extensions[strtolower($ext)]);
404 }
405
406 /**
407 * Determine whether a given file is listed in the PHP include path.
408 *
409 * @param string $name
410 * Name of file.
411 *
412 * @return bool
413 * whether the file can be include()d or require()d
414 */
415 public static function isIncludable($name) {
416 $x = @fopen($name, 'r', TRUE);
417 if ($x) {
418 fclose($x);
419 return TRUE;
420 }
421 else {
422 return FALSE;
423 }
424 }
425
426 /**
427 * Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
428 *
429 * @param $name
430 *
431 * @return mixed
432 */
433 public static function cleanFileName($name) {
434 // replace the last 33 character before the '.' with null
435 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
436 return $name;
437 }
438
439 /**
440 * Make a valid file name.
441 *
442 * @param string $name
443 *
444 * @return string
445 */
446 public static function makeFileName($name) {
447 $uniqID = md5(uniqid(rand(), TRUE));
448 $info = pathinfo($name);
449 $basename = substr($info['basename'],
450 0, -(strlen(CRM_Utils_Array::value('extension', $info)) + (CRM_Utils_Array::value('extension', $info) == '' ? 0 : 1))
451 );
452 if (!self::isExtensionSafe(CRM_Utils_Array::value('extension', $info))) {
453 // munge extension so it cannot have an embbeded dot in it
454 // The maximum length of a filename for most filesystems is 255 chars.
455 // We'll truncate at 240 to give some room for the extension.
456 return CRM_Utils_String::munge("{$basename}_" . CRM_Utils_Array::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
457 }
458 else {
459 return CRM_Utils_String::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array::value('extension', $info);
460 }
461 }
462
463 /**
464 * Copies a file
465 *
466 * @param $filePath
467 * @return mixed
468 */
469 public static function duplicate($filePath) {
470 $oldName = pathinfo($filePath, PATHINFO_FILENAME);
471 $uniqID = md5(uniqid(rand(), TRUE));
472 $newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
473 $newPath = str_replace($oldName, $newName, $filePath);
474 copy($filePath, $newPath);
475 return $newPath;
476 }
477
478 /**
479 * Get files for the extension.
480 *
481 * @param string $path
482 * @param string $ext
483 *
484 * @return array
485 */
486 public static function getFilesByExtension($path, $ext) {
487 $path = self::addTrailingSlash($path);
488 $files = [];
489 if ($dh = opendir($path)) {
490 while (FALSE !== ($elem = readdir($dh))) {
491 if (substr($elem, -(strlen($ext) + 1)) == '.' . $ext) {
492 $files[] .= $path . $elem;
493 }
494 }
495 closedir($dh);
496 }
497 return $files;
498 }
499
500 /**
501 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
502 *
503 * @param string $dir
504 * The directory to be secured.
505 * @param bool $overwrite
506 */
507 public static function restrictAccess($dir, $overwrite = FALSE) {
508 // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
509 // of site, causing site to stop functioning.
510 // FIXME: we should do more checks here -
511 if (!empty($dir) && is_dir($dir)) {
512 $htaccess = <<<HTACCESS
513 <Files "*">
514 # Apache 2.2
515 <IfModule !authz_core_module>
516 Order allow,deny
517 Deny from all
518 </IfModule>
519
520 # Apache 2.4+
521 <IfModule authz_core_module>
522 Require all denied
523 </IfModule>
524 </Files>
525
526 HTACCESS;
527 $file = $dir . '.htaccess';
528 if ($overwrite || !file_exists($file)) {
529 if (file_put_contents($file, $htaccess) === FALSE) {
530 CRM_Core_Error::movedSiteError($file);
531 }
532 }
533 }
534 }
535
536 /**
537 * Restrict remote users from browsing the given directory.
538 *
539 * @param $publicDir
540 */
541 public static function restrictBrowsing($publicDir) {
542 if (!is_dir($publicDir) || !is_writable($publicDir)) {
543 return;
544 }
545
546 // base dir
547 $nobrowse = realpath($publicDir) . '/index.html';
548 if (!file_exists($nobrowse)) {
549 @file_put_contents($nobrowse, '');
550 }
551
552 // child dirs
553 $dir = new RecursiveDirectoryIterator($publicDir);
554 foreach ($dir as $name => $object) {
555 if (is_dir($name) && $name != '..') {
556 $nobrowse = realpath($name) . '/index.html';
557 if (!file_exists($nobrowse)) {
558 @file_put_contents($nobrowse, '');
559 }
560 }
561 }
562 }
563
564 /**
565 * (Deprecated) Create the file-path from which all other internal paths are
566 * computed. This implementation determines it as `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
567 *
568 * This approach is problematic - e.g. it prevents one from authentically
569 * splitting the CIVICRM_TEMPLATE_COMPILEDIR away from other dirs. The implementation
570 * is preserved for backwards compatibility (and should only be called by
571 * CMS-adapters and by Civi\Core\Paths).
572 *
573 * Do not use it for new path construction logic. Instead, use Civi::paths().
574 *
575 * @deprecated
576 * @see \Civi::paths()
577 * @see \Civi\Core\Paths
578 */
579 public static function baseFilePath() {
580 static $_path = NULL;
581 if (!$_path) {
582 // Note: Don't rely on $config; that creates a dependency loop.
583 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
584 throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
585 }
586 $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR;
587
588 $path = dirname($templateCompileDir);
589
590 //this fix is to avoid creation of upload dirs inside templates_c directory
591 $checkPath = explode(DIRECTORY_SEPARATOR, $path);
592
593 $cnt = count($checkPath) - 1;
594 if ($checkPath[$cnt] == 'templates_c') {
595 unset($checkPath[$cnt]);
596 $path = implode(DIRECTORY_SEPARATOR, $checkPath);
597 }
598
599 $_path = CRM_Utils_File::addTrailingSlash($path);
600 }
601 return $_path;
602 }
603
604 /**
605 * Determine if a path is absolute.
606 *
607 * @param string $path
608 *
609 * @return bool
610 * TRUE if absolute. FALSE if relative.
611 */
612 public static function isAbsolute($path) {
613 if (substr($path, 0, 1) === DIRECTORY_SEPARATOR) {
614 return TRUE;
615 }
616 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
617 if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
618 return TRUE;
619 }
620 }
621 return FALSE;
622 }
623
624 /**
625 * @param $directory
626 *
627 * @return string
628 * @deprecated
629 * Computation of a relative path requires some base.
630 * This implementation is problematic because it relies on an
631 * implicit base which was constructed problematically.
632 */
633 public static function relativeDirectory($directory) {
634 // Do nothing on windows
635 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
636 return $directory;
637 }
638
639 // check if directory is relative, if so return immediately
640 if (!self::isAbsolute($directory)) {
641 return $directory;
642 }
643
644 // make everything relative from the baseFilePath
645 $basePath = self::baseFilePath();
646 // check if basePath is a substr of $directory, if so
647 // return rest of string
648 if (substr($directory, 0, strlen($basePath)) == $basePath) {
649 return substr($directory, strlen($basePath));
650 }
651
652 // return the original value
653 return $directory;
654 }
655
656 /**
657 * @param $directory
658 * @param string $basePath
659 * The base path when evaluating relative paths. Should include trailing slash.
660 *
661 * @return string
662 */
663 public static function absoluteDirectory($directory, $basePath) {
664 // check if directory is already absolute, if so return immediately
665 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
666 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
667 return $directory;
668 }
669
670 // check if directory is already absolute, if so return immediately
671 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR) {
672 return $directory;
673 }
674
675 if ($basePath === NULL) {
676 // Previous versions interpreted `NULL` to mean "default to `self::baseFilePath()`".
677 // However, no code in the known `universe` relies on this interpretation, and
678 // the `baseFilePath()` function is problematic/deprecated.
679 throw new \RuntimeException("absoluteDirectory() requires specifying a basePath");
680 }
681
682 // ensure that $basePath has a trailing slash
683 $basePath = self::addTrailingSlash($basePath);
684 return $basePath . $directory;
685 }
686
687 /**
688 * Make a file path relative to some base dir.
689 *
690 * @param $directory
691 * @param $basePath
692 *
693 * @return string
694 */
695 public static function relativize($directory, $basePath) {
696 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
697 $directory = strtr($directory, '\\', '/');
698 $basePath = strtr($basePath, '\\', '/');
699 }
700 if (substr($directory, 0, strlen($basePath)) == $basePath) {
701 return substr($directory, strlen($basePath));
702 }
703 else {
704 return $directory;
705 }
706 }
707
708 /**
709 * Create a path to a temporary file which can endure for multiple requests.
710 *
711 * @todo Automatic file cleanup using, eg, TTL policy
712 *
713 * @param string $prefix
714 *
715 * @return string, path to an openable/writable file
716 * @see tempnam
717 */
718 public static function tempnam($prefix = 'tmp-') {
719 // $config = CRM_Core_Config::singleton();
720 // $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
721 // $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
722 $fileName = tempnam(sys_get_temp_dir(), $prefix);
723 return $fileName;
724 }
725
726 /**
727 * Create a path to a temporary directory which can endure for multiple requests.
728 *
729 * @todo Automatic file cleanup using, eg, TTL policy
730 *
731 * @param string $prefix
732 *
733 * @return string, path to an openable/writable directory; ends with '/'
734 * @see tempnam
735 */
736 public static function tempdir($prefix = 'tmp-') {
737 $fileName = self::tempnam($prefix);
738 unlink($fileName);
739 mkdir($fileName, 0700);
740 return $fileName . '/';
741 }
742
743 /**
744 * Search directory tree for files which match a glob pattern.
745 *
746 * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
747 *
748 * @param string $dir
749 * base dir.
750 * @param string $pattern
751 * glob pattern, eg "*.txt".
752 * @param bool $relative
753 * TRUE if paths should be made relative to $dir
754 * @return array(string)
755 */
756 public static function findFiles($dir, $pattern, $relative = FALSE) {
757 if (!is_dir($dir) || !is_readable($dir)) {
758 return [];
759 }
760 // Which dirs should we exclude from our searches?
761 // If not defined, we default to excluding any dirname that begins
762 // with a . which is the old behaviour and therefore excludes .git/
763 $excludeDirsPattern = defined('CIVICRM_EXCLUDE_DIRS_PATTERN')
764 ? constant('CIVICRM_EXCLUDE_DIRS_PATTERN')
765 : '@' . preg_quote(DIRECTORY_SEPARATOR) . '\.@';
766
767 $dir = rtrim($dir, '/');
768 $todos = [$dir];
769 $result = [];
770 while (!empty($todos)) {
771 $subdir = array_shift($todos);
772 $matches = glob("$subdir/$pattern");
773 if (is_array($matches)) {
774 foreach ($matches as $match) {
775 if (!is_dir($match)) {
776 $result[] = $relative ? CRM_Utils_File::relativize($match, "$dir/") : $match;
777 }
778 }
779 }
780 // Find subdirs to recurse into.
781 if ($dh = opendir($subdir)) {
782 while (FALSE !== ($entry = readdir($dh))) {
783 $path = $subdir . DIRECTORY_SEPARATOR . $entry;
784 // Exclude . (self) and .. (parent) to avoid infinite loop.
785 // Exclude configured exclude dirs.
786 // Exclude dirs we can't read.
787 // Exclude anything that's not a dir.
788 if (
789 $entry !== '.'
790 && $entry !== '..'
791 && (empty($excludeDirsPattern) || !preg_match($excludeDirsPattern, $path))
792 && is_dir($path)
793 && is_readable($path)
794 ) {
795 $todos[] = $path;
796 }
797 }
798 closedir($dh);
799 }
800 }
801 return $result;
802 }
803
804 /**
805 * Determine if $child is a sub-directory of $parent
806 *
807 * @param string $parent
808 * @param string $child
809 * @param bool $checkRealPath
810 *
811 * @return bool
812 */
813 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
814 if ($checkRealPath) {
815 $parent = realpath($parent);
816 $child = realpath($child);
817 }
818 $parentParts = explode('/', rtrim($parent, '/'));
819 $childParts = explode('/', rtrim($child, '/'));
820 while (($parentPart = array_shift($parentParts)) !== NULL) {
821 $childPart = array_shift($childParts);
822 if ($parentPart != $childPart) {
823 return FALSE;
824 }
825 }
826 if (empty($childParts)) {
827 // same directory
828 return FALSE;
829 }
830 else {
831 return TRUE;
832 }
833 }
834
835 /**
836 * Move $fromDir to $toDir, replacing/deleting any
837 * pre-existing content.
838 *
839 * @param string $fromDir
840 * The directory which should be moved.
841 * @param string $toDir
842 * The new location of the directory.
843 * @param bool $verbose
844 *
845 * @return bool
846 * TRUE on success
847 */
848 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
849 if (is_dir($toDir)) {
850 if (!self::cleanDir($toDir, TRUE, $verbose)) {
851 return FALSE;
852 }
853 }
854
855 // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
856
857 CRM_Utils_File::copyDir($fromDir, $toDir);
858 if (!CRM_Utils_File::cleanDir($fromDir, TRUE, FALSE)) {
859 CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', [1 => $fromDir]), '', 'alert');
860 return FALSE;
861 }
862 return TRUE;
863 }
864
865 /**
866 * Format file.
867 *
868 * @param array $param
869 * @param string $fileName
870 * @param array $extraParams
871 */
872 public static function formatFile(&$param, $fileName, $extraParams = []) {
873 if (empty($param[$fileName])) {
874 return;
875 }
876
877 $fileParams = [
878 'uri' => $param[$fileName]['name'],
879 'type' => $param[$fileName]['type'],
880 'location' => $param[$fileName]['name'],
881 'upload_date' => date('YmdHis'),
882 ] + $extraParams;
883
884 $param[$fileName] = $fileParams;
885 }
886
887 /**
888 * Return formatted file URL, like for image file return image url with image icon
889 *
890 * @param string $path
891 * Absoulte file path
892 * @param string $fileType
893 * @param string $url
894 * File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
895 *
896 * @return string $url
897 */
898 public static function getFileURL($path, $fileType, $url = NULL) {
899 if (empty($path) || empty($fileType)) {
900 return '';
901 }
902 elseif (empty($url)) {
903 $fileName = basename($path);
904 $url = CRM_Utils_System::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
905 }
906 switch ($fileType) {
907 case 'image/jpeg':
908 case 'image/pjpeg':
909 case 'image/gif':
910 case 'image/x-png':
911 case 'image/png':
912 case 'image/jpg':
913 list($imageWidth, $imageHeight) = getimagesize($path);
914 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
915 $url = "<a href=\"$url\" class='crm-image-popup'>
916 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
917 </a>";
918 break;
919
920 default:
921 $url = sprintf('<a href="%s">%s</a>', $url, self::cleanFileName(basename($path)));
922 break;
923 }
924
925 return $url;
926 }
927
928 /**
929 * Return formatted image icon
930 *
931 * @param string $imageURL
932 * Contact's image url
933 *
934 * @return string $url
935 */
936 public static function getImageURL($imageURL) {
937 // retrieve image name from $imageURL
938 $imageURL = CRM_Utils_String::unstupifyUrl($imageURL);
939 parse_str(parse_url($imageURL, PHP_URL_QUERY), $query);
940
941 $url = NULL;
942 if (!empty($query['photo'])) {
943 $path = CRM_Core_Config::singleton()->customFileUploadDir . $query['photo'];
944 }
945 else {
946 $path = $url = $imageURL;
947 }
948 $fileExtension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
949 //According to (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types),
950 // there are some extensions that would need translating.:
951 $translateMimeTypes = [
952 'tif' => 'tiff',
953 'jpg' => 'jpeg',
954 'svg' => 'svg+xml',
955 ];
956 $mimeType = 'image/' . CRM_Utils_Array::value(
957 $fileExtension,
958 $translateMimeTypes,
959 $fileExtension
960 );
961
962 return self::getFileURL($path, $mimeType, $url);
963 }
964
965 /**
966 * Resize an image.
967 *
968 * @param string $sourceFile
969 * Filesystem path to existing image on server
970 * @param int $targetWidth
971 * New width desired, in pixels
972 * @param int $targetHeight
973 * New height desired, in pixels
974 * @param string $suffix = ""
975 * If supplied, the image will be renamed to include this suffix. For
976 * example if the original file name is "foo.png" and $suffix = "_bar",
977 * then the final file name will be "foo_bar.png".
978 * @param bool $preserveAspect = TRUE
979 * When TRUE $width and $height will be used as a bounding box, outside of
980 * which the resized image will not extend.
981 * When FALSE, the image will be resized exactly to $width and $height, even
982 * if it means stretching it.
983 *
984 * @return string
985 * Path to image
986 * @throws \CRM_Core_Exception
987 * Under the following conditions
988 * - When GD is not available.
989 * - When the source file is not an image.
990 */
991 public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) {
992
993 // Check if GD is installed
994 $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
995 if (!$gdSupport) {
996 throw new CRM_Core_Exception(ts('Unable to resize image because the GD image library is not currently compiled in your PHP installation.'));
997 }
998
999 $sourceMime = mime_content_type($sourceFile);
1000 if ($sourceMime == 'image/gif') {
1001 $sourceData = imagecreatefromgif($sourceFile);
1002 }
1003 elseif ($sourceMime == 'image/png') {
1004 $sourceData = imagecreatefrompng($sourceFile);
1005 }
1006 elseif ($sourceMime == 'image/jpeg') {
1007 $sourceData = imagecreatefromjpeg($sourceFile);
1008 }
1009 else {
1010 throw new CRM_Core_Exception(ts('Unable to resize image because the file supplied was not an image.'));
1011 }
1012
1013 // get image about original image
1014 $sourceInfo = getimagesize($sourceFile);
1015 $sourceWidth = $sourceInfo[0];
1016 $sourceHeight = $sourceInfo[1];
1017
1018 // Adjust target width/height if preserving aspect ratio
1019 if ($preserveAspect) {
1020 $sourceAspect = $sourceWidth / $sourceHeight;
1021 $targetAspect = $targetWidth / $targetHeight;
1022 if ($sourceAspect > $targetAspect) {
1023 $targetHeight = $targetWidth / $sourceAspect;
1024 }
1025 if ($sourceAspect < $targetAspect) {
1026 $targetWidth = $targetHeight * $sourceAspect;
1027 }
1028 }
1029
1030 // figure out the new filename
1031 $pathParts = pathinfo($sourceFile);
1032 $targetFile = $pathParts['dirname'] . DIRECTORY_SEPARATOR
1033 . $pathParts['filename'] . $suffix . "." . $pathParts['extension'];
1034
1035 $targetData = imagecreatetruecolor($targetWidth, $targetHeight);
1036
1037 // resize
1038 imagecopyresized($targetData, $sourceData,
1039 0, 0, 0, 0,
1040 $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
1041
1042 // save the resized image
1043 $fp = fopen($targetFile, 'w+');
1044 ob_start();
1045 imagejpeg($targetData);
1046 $image_buffer = ob_get_contents();
1047 ob_end_clean();
1048 imagedestroy($targetData);
1049 fwrite($fp, $image_buffer);
1050 rewind($fp);
1051 fclose($fp);
1052
1053 // return the URL to link to
1054 $config = CRM_Core_Config::singleton();
1055 return $config->imageUploadURL . basename($targetFile);
1056 }
1057
1058 /**
1059 * Get file icon class for specific MIME Type
1060 *
1061 * @param string $mimeType
1062 * @return string
1063 */
1064 public static function getIconFromMimeType($mimeType) {
1065 if (!isset(Civi::$statics[__CLASS__]['mimeIcons'])) {
1066 Civi::$statics[__CLASS__]['mimeIcons'] = json_decode(file_get_contents(__DIR__ . '/File/mimeIcons.json'), TRUE);
1067 }
1068 $iconClasses = Civi::$statics[__CLASS__]['mimeIcons'];
1069 foreach ($iconClasses as $text => $icon) {
1070 if (strpos($mimeType, $text) === 0) {
1071 return $icon;
1072 }
1073 }
1074 return $iconClasses['*'];
1075 }
1076
1077 /**
1078 * Is the filename a safe and valid filename passed in from URL
1079 *
1080 * @param string $fileName
1081 * @return bool
1082 */
1083 public static function isValidFileName($fileName = NULL) {
1084 if ($fileName) {
1085 $check = ($fileName === basename($fileName));
1086 if ($check) {
1087 if (substr($fileName, 0, 1) == '/' || substr($fileName, 0, 1) == '.' || substr($fileName, 0, 1) == DIRECTORY_SEPARATOR) {
1088 $check = FALSE;
1089 }
1090 }
1091 return $check;
1092 }
1093 return FALSE;
1094 }
1095
1096 /**
1097 * Get the extensions that this MimeTpe is for
1098 * @param string $mimeType the mime-type we want extensions for
1099 * @return array
1100 */
1101 public static function getAcceptableExtensionsForMimeType($mimeType = []) {
1102 $mimeRepostory = new \MimeTyper\Repository\ExtendedRepository();
1103 return $mimeRepostory->findExtensions($mimeType);
1104 }
1105
1106 /**
1107 * Get the extension of a file based on its path
1108 * @param string $path path of the file to query
1109 * @return string
1110 */
1111 public static function getExtensionFromPath($path) {
1112 return pathinfo($path, PATHINFO_EXTENSION);
1113 }
1114
1115 }