Merge pull request #14128 from agileware/CIVICRM-1143
[civicrm-core.git] / CRM / Utils / File.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
35 * class to provide simple static functions for file objects
36 */
37class CRM_Utils_File {
38
39 /**
40 * Given a file name, determine if the file contents make it an ascii file
41 *
77855840
TO
42 * @param string $name
43 * Name of file.
6a488035 44 *
ae5ffbb7 45 * @return bool
a6c01b45 46 * true if file is ascii
6a488035 47 */
00be9182 48 public static function isAscii($name) {
6a488035
TO
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 *
77855840
TO
70 * @param string $name
71 * Name of file.
6a488035 72 *
ae5ffbb7 73 * @return bool
a6c01b45 74 * true if file is html
6a488035 75 */
00be9182 76 public static function isHtml($name) {
6a488035
TO
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 /**
100fef9d 98 * Create a directory given a path name, creates parent directories
6a488035
TO
99 * if needed
100 *
77855840
TO
101 * @param string $path
102 * The path name.
103 * @param bool $abort
104 * Should we abort or just return an invalid code.
3daed292
TO
105 * @return bool|NULL
106 * NULL: Folder already exists or was not specified.
107 * TRUE: Creation succeeded.
108 * FALSE: Creation failed.
6a488035 109 */
00be9182 110 public static function createDir($path, $abort = TRUE) {
6a488035 111 if (is_dir($path) || empty($path)) {
3daed292 112 return NULL;
6a488035
TO
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 /**
100fef9d 131 * Delete a directory given a path name, delete children directories
6a488035
TO
132 * and files if needed
133 *
77855840
TO
134 * @param string $target
135 * The path name.
f4aaa82a
EM
136 * @param bool $rmdir
137 * @param bool $verbose
138 *
139 * @throws Exception
6a488035 140 */
00be9182 141 public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
be2fb01f 142 static $exceptions = ['.', '..'];
d269912e 143 if ($target == '' || $target == '/' || !$target) {
6a488035
TO
144 throw new Exception("Overly broad deletion");
145 }
146
5e7670b1 147 if ($dh = @opendir($target)) {
148 while (FALSE !== ($sibling = readdir($dh))) {
6a488035
TO
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)) {
be2fb01f 157 CRM_Core_Session::setStatus(ts('Unable to remove file %1', [1 => $object]), ts('Warning'), 'error');
e7292422 158 }
6a488035
TO
159 }
160 }
161 }
5e7670b1 162 closedir($dh);
6a488035
TO
163
164 if ($rmdir) {
165 if (rmdir($target)) {
166 if ($verbose) {
be2fb01f 167 CRM_Core_Session::setStatus(ts('Removed directory %1', [1 => $target]), '', 'success');
6a488035
TO
168 }
169 return TRUE;
e7292422 170 }
6a488035 171 else {
be2fb01f 172 CRM_Core_Session::setStatus(ts('Unable to remove directory %1', [1 => $target]), ts('Warning'), 'error');
e7292422
TO
173 }
174 }
6a488035
TO
175 }
176 }
177
7f616c07
TO
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
5bc392e6 200 /**
ae5ffbb7
TO
201 * @param string $source
202 * @param string $destination
5bc392e6 203 */
ae5ffbb7 204 public static function copyDir($source, $destination) {
5e7670b1 205 if ($dh = opendir($source)) {
948d11bf 206 @mkdir($destination);
5e7670b1 207 while (FALSE !== ($file = readdir($dh))) {
948d11bf
CB
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 }
6a488035
TO
215 }
216 }
5e7670b1 217 closedir($dh);
6a488035 218 }
6a488035
TO
219 }
220
221 /**
222 * Given a file name, recode it (in place!) to UTF-8
223 *
77855840
TO
224 * @param string $name
225 * Name of file.
6a488035 226 *
ae5ffbb7 227 * @return bool
a6c01b45 228 * whether the file was recoded properly
6a488035 229 */
00be9182 230 public static function toUtf8($name) {
6a488035
TO
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 /**
5c8cb77f 269 * Appends a slash to the end of a string if it doesn't already end with one
6a488035 270 *
5c8cb77f
CW
271 * @param string $path
272 * @param string $slash
f4aaa82a 273 *
6a488035 274 * @return string
6a488035 275 */
00be9182 276 public static function addTrailingSlash($path, $slash = NULL) {
5c8cb77f 277 if (!$slash) {
ea3ddccf 278 // FIXME: Defaulting to backslash on windows systems can produce
50bfb460 279 // unexpected results, esp for URL strings which should always use forward-slashes.
5c8cb77f
CW
280 // I think this fn should default to forward-slash instead.
281 $slash = DIRECTORY_SEPARATOR;
6a488035 282 }
be2fb01f 283 if (!in_array(substr($path, -1, 1), ['/', '\\'])) {
5c8cb77f 284 $path .= $slash;
6a488035 285 }
5c8cb77f 286 return $path;
6a488035
TO
287 }
288
3f0e59f6
AH
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.
33d245c8 296 * @param string $fileName
3f0e59f6
AH
297 *
298 * @return string
299 * The filename saved, or FALSE on failure.
300 */
33d245c8 301 public static function createFakeFile($dir, $contents = 'delete me', $fileName = NULL) {
3f0e59f6 302 $dir = self::addTrailingSlash($dir);
33d245c8
CW
303 if (!$fileName) {
304 $fileName = 'delete-this-' . CRM_Utils_String::createRandom(10, CRM_Utils_String::ALPHANUMERIC);
305 }
76ceb0c4 306 $success = @file_put_contents($dir . $fileName, $contents);
3f0e59f6 307
33d245c8 308 return ($success === FALSE) ? FALSE : $fileName;
3f0e59f6
AH
309 }
310
5bc392e6 311 /**
e95fbe72
TO
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.
100fef9d 315 * @param string $fileName
c0e4c31d 316 * @param string $prefix
5bc392e6
EM
317 * @param bool $dieOnErrors
318 */
c0e4c31d
JK
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.');
cf369463
JK
324 }
325
c0e4c31d
JK
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
e95fbe72
TO
339 if ($dsn === NULL) {
340 $db = CRM_Core_DAO::getConnection();
341 }
342 else {
343 require_once 'DB.php';
344 $db = DB::connect($dsn);
345 }
6a488035 346
6a488035
TO
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 }
abb74cc1 353 $db->query('SET NAMES utf8');
b228b202 354 $transactionId = CRM_Utils_Type::escape(CRM_Utils_Request::id(), 'String');
65a6387f 355 $db->query('SET @uniqueID = ' . "'$transactionId'");
6a488035 356
50bfb460 357 // get rid of comments starting with # and --
6a488035 358
fc6159c2 359 $string = self::stripComments($string);
6a488035
TO
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 }
c0e4c31d 378
fc6159c2 379 /**
380 *
381 * Strips comment from a possibly multiline SQL string
382 *
383 * @param string $string
384 *
385 * @return string
bd6326bf 386 * stripped string
fc6159c2 387 */
388 public static function stripComments($string) {
389 return preg_replace("/^(#|--).*\R*/m", "", $string);
390 }
6a488035 391
5bc392e6
EM
392 /**
393 * @param $ext
394 *
395 * @return bool
396 */
00be9182 397 public static function isExtensionSafe($ext) {
6a488035
TO
398 static $extensions = NULL;
399 if (!$extensions) {
400 $extensions = CRM_Core_OptionGroup::values('safe_file_extension', TRUE);
401
50bfb460 402 // make extensions to lowercase
6a488035
TO
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') ||
353ffa53
TO
407 CRM_Core_Permission::check('administer CiviCRM') ||
408 (CRM_Mailing_Info::workflowEnabled() &&
409 CRM_Core_Permission::check('create mailings')
410 )
411 )
412 ) {
6a488035
TO
413 unset($extensions['html']);
414 unset($extensions['htm']);
415 }
416 }
50bfb460 417 // support lower and uppercase file extensions
6a488035
TO
418 return isset($extensions[strtolower($ext)]) ? TRUE : FALSE;
419 }
420
421 /**
fe482240 422 * Determine whether a given file is listed in the PHP include path.
6a488035 423 *
77855840
TO
424 * @param string $name
425 * Name of file.
6a488035 426 *
ae5ffbb7 427 * @return bool
a6c01b45 428 * whether the file can be include()d or require()d
6a488035 429 */
00be9182 430 public static function isIncludable($name) {
6a488035
TO
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 /**
ea3ddccf 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
6a488035 447 */
00be9182 448 public static function cleanFileName($name) {
6a488035
TO
449 // replace the last 33 character before the '.' with null
450 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
451 return $name;
452 }
453
5bc392e6 454 /**
8246bca4 455 * Make a valid file name.
456 *
100fef9d 457 * @param string $name
5bc392e6
EM
458 *
459 * @return string
460 */
00be9182 461 public static function makeFileName($name) {
353ffa53
TO
462 $uniqID = md5(uniqid(rand(), TRUE));
463 $info = pathinfo($name);
6a488035
TO
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
33d245c8
CW
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
5bc392e6 493 /**
8246bca4 494 * Get files for the extension.
495 *
496 * @param string $path
497 * @param string $ext
5bc392e6
EM
498 *
499 * @return array
500 */
00be9182 501 public static function getFilesByExtension($path, $ext) {
353ffa53 502 $path = self::addTrailingSlash($path);
be2fb01f 503 $files = [];
948d11bf 504 if ($dh = opendir($path)) {
948d11bf
CB
505 while (FALSE !== ($elem = readdir($dh))) {
506 if (substr($elem, -(strlen($ext) + 1)) == '.' . $ext) {
507 $files[] .= $path . $elem;
508 }
6a488035 509 }
948d11bf 510 closedir($dh);
6a488035 511 }
6a488035
TO
512 return $files;
513 }
514
515 /**
516 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
517 *
77855840
TO
518 * @param string $dir
519 * The directory to be secured.
f4aaa82a 520 * @param bool $overwrite
6a488035 521 */
00be9182 522 public static function restrictAccess($dir, $overwrite = FALSE) {
6a488035
TO
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 -
ea3b22b5 526 if (!empty($dir) && is_dir($dir)) {
6a488035
TO
527 $htaccess = <<<HTACCESS
528<Files "*">
529 Order allow,deny
530 Deny from all
531</Files>
532
533HTACCESS;
534 $file = $dir . '.htaccess';
ea3b22b5
TO
535 if ($overwrite || !file_exists($file)) {
536 if (file_put_contents($file, $htaccess) === FALSE) {
537 CRM_Core_Error::movedSiteError($file);
538 }
6a488035
TO
539 }
540 }
541 }
542
af5201d4
TO
543 /**
544 * Restrict remote users from browsing the given directory.
545 *
546 * @param $publicDir
547 */
00be9182 548 public static function restrictBrowsing($publicDir) {
9404eeac
TO
549 if (!is_dir($publicDir) || !is_writable($publicDir)) {
550 return;
551 }
552
af5201d4
TO
553 // base dir
554 $nobrowse = realpath($publicDir) . '/index.html';
555 if (!file_exists($nobrowse)) {
556 @file_put_contents($nobrowse, '');
557 }
558
559 // child dirs
560 $dir = new RecursiveDirectoryIterator($publicDir);
561 foreach ($dir as $name => $object) {
562 if (is_dir($name) && $name != '..') {
563 $nobrowse = realpath($name) . '/index.html';
564 if (!file_exists($nobrowse)) {
565 @file_put_contents($nobrowse, '');
566 }
567 }
568 }
569 }
570
6a488035
TO
571 /**
572 * Create the base file path from which all our internal directories are
573 * offset. This is derived from the template compile directory set
574 */
635f0b86 575 public static function baseFilePath() {
6a488035
TO
576 static $_path = NULL;
577 if (!$_path) {
635f0b86
TO
578 // Note: Don't rely on $config; that creates a dependency loop.
579 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
580 throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
6a488035 581 }
635f0b86 582 $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR;
6a488035
TO
583
584 $path = dirname($templateCompileDir);
585
586 //this fix is to avoid creation of upload dirs inside templates_c directory
587 $checkPath = explode(DIRECTORY_SEPARATOR, $path);
588
589 $cnt = count($checkPath) - 1;
590 if ($checkPath[$cnt] == 'templates_c') {
591 unset($checkPath[$cnt]);
592 $path = implode(DIRECTORY_SEPARATOR, $checkPath);
593 }
594
595 $_path = CRM_Utils_File::addTrailingSlash($path);
596 }
597 return $_path;
598 }
599
9f87b14b
TO
600 /**
601 * Determine if a path is absolute.
602 *
ea3ddccf 603 * @param string $path
604 *
9f87b14b
TO
605 * @return bool
606 * TRUE if absolute. FALSE if relative.
607 */
608 public static function isAbsolute($path) {
609 if (substr($path, 0, 1) === DIRECTORY_SEPARATOR) {
610 return TRUE;
611 }
612 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
613 if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
614 return TRUE;
615 }
616 }
617 return FALSE;
618 }
619
5bc392e6
EM
620 /**
621 * @param $directory
622 *
623 * @return string
624 */
00be9182 625 public static function relativeDirectory($directory) {
6a488035
TO
626 // Do nothing on windows
627 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
628 return $directory;
629 }
630
631 // check if directory is relative, if so return immediately
9f87b14b 632 if (!self::isAbsolute($directory)) {
6a488035
TO
633 return $directory;
634 }
635
636 // make everything relative from the baseFilePath
637 $basePath = self::baseFilePath();
638 // check if basePath is a substr of $directory, if so
639 // return rest of string
640 if (substr($directory, 0, strlen($basePath)) == $basePath) {
641 return substr($directory, strlen($basePath));
642 }
643
644 // return the original value
645 return $directory;
646 }
647
5bc392e6
EM
648 /**
649 * @param $directory
e3d28c74
TO
650 * @param string|NULL $basePath
651 * The base path when evaluating relative paths. Should include trailing slash.
5bc392e6
EM
652 *
653 * @return string
654 */
e3d28c74 655 public static function absoluteDirectory($directory, $basePath = NULL) {
acc609a7
TO
656 // check if directory is already absolute, if so return immediately
657 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
658 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
6a488035
TO
659 return $directory;
660 }
661
662 // check if directory is already absolute, if so return immediately
663 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR) {
664 return $directory;
665 }
666
667 // make everything absolute from the baseFilePath
e3d28c74 668 $basePath = ($basePath === NULL) ? self::baseFilePath() : $basePath;
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) {
cae27189 745 if (!is_dir($dir)) {
be2fb01f 746 return [];
cae27189 747 }
a2dc0f82 748 $dir = rtrim($dir, '/');
be2fb01f
CW
749 $todos = [$dir];
750 $result = [];
6a488035
TO
751 while (!empty($todos)) {
752 $subdir = array_shift($todos);
0b72a00f
TO
753 $matches = glob("$subdir/$pattern");
754 if (is_array($matches)) {
755 foreach ($matches as $match) {
002f1716 756 if (!is_dir($match)) {
a2dc0f82 757 $result[] = $relative ? CRM_Utils_File::relativize($match, "$dir/") : $match;
002f1716 758 }
6a488035
TO
759 }
760 }
948d11bf 761 if ($dh = opendir($subdir)) {
6a488035
TO
762 while (FALSE !== ($entry = readdir($dh))) {
763 $path = $subdir . DIRECTORY_SEPARATOR . $entry;
d7166b43
TO
764 if ($entry{0} == '.') {
765 // ignore
0db6c3e1
TO
766 }
767 elseif (is_dir($path)) {
6a488035
TO
768 $todos[] = $path;
769 }
770 }
771 closedir($dh);
772 }
773 }
774 return $result;
775 }
776
777 /**
778 * Determine if $child is a sub-directory of $parent
779 *
780 * @param string $parent
781 * @param string $child
f4aaa82a
EM
782 * @param bool $checkRealPath
783 *
6a488035
TO
784 * @return bool
785 */
00be9182 786 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
6a488035
TO
787 if ($checkRealPath) {
788 $parent = realpath($parent);
789 $child = realpath($child);
790 }
791 $parentParts = explode('/', rtrim($parent, '/'));
792 $childParts = explode('/', rtrim($child, '/'));
793 while (($parentPart = array_shift($parentParts)) !== NULL) {
794 $childPart = array_shift($childParts);
795 if ($parentPart != $childPart) {
796 return FALSE;
797 }
798 }
799 if (empty($childParts)) {
6714d8d2
SL
800 // same directory
801 return FALSE;
0db6c3e1
TO
802 }
803 else {
6a488035
TO
804 return TRUE;
805 }
806 }
807
808 /**
809 * Move $fromDir to $toDir, replacing/deleting any
810 * pre-existing content.
811 *
77855840
TO
812 * @param string $fromDir
813 * The directory which should be moved.
814 * @param string $toDir
815 * The new location of the directory.
f4aaa82a
EM
816 * @param bool $verbose
817 *
a6c01b45
CW
818 * @return bool
819 * TRUE on success
6a488035 820 */
00be9182 821 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
6a488035
TO
822 if (is_dir($toDir)) {
823 if (!self::cleanDir($toDir, TRUE, $verbose)) {
824 return FALSE;
825 }
826 }
827
50bfb460 828 // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
6a488035
TO
829
830 CRM_Utils_File::copyDir($fromDir, $toDir);
831 if (!CRM_Utils_File::cleanDir($fromDir, TRUE, FALSE)) {
be2fb01f 832 CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', [1 => $fromDir]), '', 'alert');
6a488035
TO
833 return FALSE;
834 }
835 return TRUE;
836 }
96025800 837
8246bca4 838 /**
839 * Format file.
840 *
841 * @param array $param
842 * @param string $fileName
843 * @param array $extraParams
844 */
be2fb01f 845 public static function formatFile(&$param, $fileName, $extraParams = []) {
90a73810 846 if (empty($param[$fileName])) {
847 return;
848 }
849
be2fb01f 850 $fileParams = [
90a73810 851 'uri' => $param[$fileName]['name'],
852 'type' => $param[$fileName]['type'],
853 'location' => $param[$fileName]['name'],
854 'upload_date' => date('YmdHis'),
be2fb01f 855 ] + $extraParams;
90a73810 856
857 $param[$fileName] = $fileParams;
858 }
859
f3726153 860 /**
861 * Return formatted file URL, like for image file return image url with image icon
862 *
863 * @param string $path
864 * Absoulte file path
865 * @param string $fileType
866 * @param string $url
867 * File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
868 *
869 * @return string $url
870 */
871 public static function getFileURL($path, $fileType, $url = NULL) {
872 if (empty($path) || empty($fileType)) {
873 return '';
874 }
875 elseif (empty($url)) {
876 $fileName = basename($path);
877 $url = CRM_Utils_System::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
878 }
879 switch ($fileType) {
880 case 'image/jpeg':
881 case 'image/pjpeg':
882 case 'image/gif':
883 case 'image/x-png':
884 case 'image/png':
c3821398 885 case 'image/jpg':
f3726153 886 list($imageWidth, $imageHeight) = getimagesize($path);
887 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
888 $url = "<a href=\"$url\" class='crm-image-popup'>
889 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
890 </a>";
891 break;
892
893 default:
17ae6ca4 894 $url = sprintf('<a href="%s">%s</a>', $url, self::cleanFileName(basename($path)));
f3726153 895 break;
896 }
897
898 return $url;
899 }
900
c3821398 901 /**
902 * Return formatted image icon
903 *
904 * @param string $imageURL
905 * Contact's image url
906 *
907 * @return string $url
908 */
909 public static function getImageURL($imageURL) {
910 // retrieve image name from $imageURL
911 $imageURL = CRM_Utils_String::unstupifyUrl($imageURL);
912 parse_str(parse_url($imageURL, PHP_URL_QUERY), $query);
913
cb8fb3cf
JP
914 $url = NULL;
915 if (!empty($query['photo'])) {
916 $path = CRM_Core_Config::singleton()->customFileUploadDir . $query['photo'];
917 }
918 else {
919 $path = $url = $imageURL;
920 }
878a913b 921 $fileExtension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
8ece24f4
PN
922 //According to (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types),
923 // there are some extensions that would need translating.:
924 $translateMimeTypes = [
925 'tif' => 'tiff',
926 'jpg' => 'jpeg',
927 'svg' => 'svg+xml',
928 ];
929 $mimeType = 'image/' . CRM_Utils_Array::value(
930 $fileExtension,
931 $translateMimeTypes,
932 $fileExtension
933 );
c3821398 934
cb8fb3cf 935 return self::getFileURL($path, $mimeType, $url);
c3821398 936 }
937
3cd6a7b6 938 /**
62b3b6e7
SM
939 * Resize an image.
940 *
941 * @param string $sourceFile
942 * Filesystem path to existing image on server
943 * @param int $targetWidth
944 * New width desired, in pixels
945 * @param int $targetHeight
946 * New height desired, in pixels
947 * @param string $suffix = ""
948 * If supplied, the image will be renamed to include this suffix. For
949 * example if the original file name is "foo.png" and $suffix = "_bar",
950 * then the final file name will be "foo_bar.png".
ae969bc1
SM
951 * @param bool $preserveAspect = TRUE
952 * When TRUE $width and $height will be used as a bounding box, outside of
953 * which the resized image will not extend.
954 * When FALSE, the image will be resized exactly to $width and $height, even
955 * if it means stretching it.
3cd6a7b6
SM
956 *
957 * @return string
958 * Path to image
62b3b6e7
SM
959 * @throws \CRM_Core_Exception
960 * Under the following conditions
961 * - When GD is not available.
962 * - When the source file is not an image.
3cd6a7b6 963 */
ae969bc1 964 public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) {
3cd6a7b6 965
62b3b6e7
SM
966 // Check if GD is installed
967 $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support');
968 if (!$gdSupport) {
969 throw new CRM_Core_Exception(ts('Unable to resize image because the GD image library is not currently compiled in your PHP installation.'));
970 }
971
972 $sourceMime = mime_content_type($sourceFile);
973 if ($sourceMime == 'image/gif') {
974 $sourceData = imagecreatefromgif($sourceFile);
975 }
976 elseif ($sourceMime == 'image/png') {
977 $sourceData = imagecreatefrompng($sourceFile);
3cd6a7b6 978 }
62b3b6e7
SM
979 elseif ($sourceMime == 'image/jpeg') {
980 $sourceData = imagecreatefromjpeg($sourceFile);
3cd6a7b6
SM
981 }
982 else {
62b3b6e7 983 throw new CRM_Core_Exception(ts('Unable to resize image because the file supplied was not an image.'));
3cd6a7b6
SM
984 }
985
62b3b6e7
SM
986 // get image about original image
987 $sourceInfo = getimagesize($sourceFile);
988 $sourceWidth = $sourceInfo[0];
989 $sourceHeight = $sourceInfo[1];
990
ae969bc1
SM
991 // Adjust target width/height if preserving aspect ratio
992 if ($preserveAspect) {
993 $sourceAspect = $sourceWidth / $sourceHeight;
994 $targetAspect = $targetWidth / $targetHeight;
995 if ($sourceAspect > $targetAspect) {
996 $targetHeight = $targetWidth / $sourceAspect;
997 }
998 if ($sourceAspect < $targetAspect) {
999 $targetWidth = $targetHeight * $sourceAspect;
1000 }
1001 }
1002
62b3b6e7
SM
1003 // figure out the new filename
1004 $pathParts = pathinfo($sourceFile);
1005 $targetFile = $pathParts['dirname'] . DIRECTORY_SEPARATOR
1006 . $pathParts['filename'] . $suffix . "." . $pathParts['extension'];
1007
1008 $targetData = imagecreatetruecolor($targetWidth, $targetHeight);
1009
3cd6a7b6 1010 // resize
62b3b6e7
SM
1011 imagecopyresized($targetData, $sourceData,
1012 0, 0, 0, 0,
1013 $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
3cd6a7b6
SM
1014
1015 // save the resized image
62b3b6e7 1016 $fp = fopen($targetFile, 'w+');
3cd6a7b6 1017 ob_start();
62b3b6e7 1018 imagejpeg($targetData);
3cd6a7b6
SM
1019 $image_buffer = ob_get_contents();
1020 ob_end_clean();
62b3b6e7 1021 imagedestroy($targetData);
3cd6a7b6
SM
1022 fwrite($fp, $image_buffer);
1023 rewind($fp);
1024 fclose($fp);
1025
1026 // return the URL to link to
1027 $config = CRM_Core_Config::singleton();
62b3b6e7 1028 return $config->imageUploadURL . basename($targetFile);
3cd6a7b6 1029 }
4994819e
CW
1030
1031 /**
1032 * Get file icon class for specific MIME Type
1033 *
1034 * @param string $mimeType
1035 * @return string
1036 */
1037 public static function getIconFromMimeType($mimeType) {
892be376
CW
1038 if (!isset(Civi::$statics[__CLASS__]['mimeIcons'])) {
1039 Civi::$statics[__CLASS__]['mimeIcons'] = json_decode(file_get_contents(__DIR__ . '/File/mimeIcons.json'), TRUE);
1040 }
1041 $iconClasses = Civi::$statics[__CLASS__]['mimeIcons'];
4994819e
CW
1042 foreach ($iconClasses as $text => $icon) {
1043 if (strpos($mimeType, $text) === 0) {
1044 return $icon;
1045 }
1046 }
892be376 1047 return $iconClasses['*'];
4994819e
CW
1048 }
1049
a7762e79
SL
1050 /**
1051 * Is the filename a safe and valid filename passed in from URL
1052 *
1053 * @param string $fileName
1054 * @return bool
1055 */
1056 public static function isValidFileName($fileName = NULL) {
1057 if ($fileName) {
1058 $check = $fileName !== basename($fileName) ? FALSE : TRUE;
1059 if ($check) {
1060 if (substr($fileName, 0, 1) == '/' || substr($fileName, 0, 1) == '.' || substr($fileName, 0, 1) == DIRECTORY_SEPARATOR) {
1061 $check = FALSE;
1062 }
1063 }
1064 return $check;
1065 }
1066 return FALSE;
1067 }
1068
6a488035 1069}