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