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