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