CRM_Utils_Hook::hooks - Prettify
[civicrm-core.git] / CRM / Utils / File.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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) {
6a488035 142 static $exceptions = array('.', '..');
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)) {
157 CRM_Core_Session::setStatus(ts('Unable to remove file %1', array(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) {
450f494d 167 CRM_Core_Session::setStatus(ts('Removed directory %1', array(1 => $target)), '', 'success');
6a488035
TO
168 }
169 return TRUE;
e7292422 170 }
6a488035
TO
171 else {
172 CRM_Core_Session::setStatus(ts('Unable to remove directory %1', array(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 }
5c8cb77f
CW
283 if (!in_array(substr($path, -1, 1), array('/', '\\'))) {
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 }
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
5bc392e6
EM
316 * @param null $prefix
317 * @param bool $isQueryString
318 * @param bool $dieOnErrors
319 */
00be9182 320 public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $isQueryString = FALSE, $dieOnErrors = TRUE) {
e95fbe72
TO
321 if ($dsn === NULL) {
322 $db = CRM_Core_DAO::getConnection();
323 }
324 else {
325 require_once 'DB.php';
326 $db = DB::connect($dsn);
327 }
6a488035 328
6a488035
TO
329 if (PEAR::isError($db)) {
330 die("Cannot open $dsn: " . $db->getMessage());
331 }
332 if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) {
333 $db->query('SET SESSION sql_mode = STRICT_TRANS_TABLES');
334 }
abb74cc1 335 $db->query('SET NAMES utf8');
b228b202 336 $transactionId = CRM_Utils_Type::escape(CRM_Utils_Request::id(), 'String');
65a6387f 337 $db->query('SET @uniqueID = ' . "'$transactionId'");
6a488035
TO
338
339 if (!$isQueryString) {
340 $string = $prefix . file_get_contents($fileName);
341 }
342 else {
343 // use filename as query string
344 $string = $prefix . $fileName;
345 }
346
50bfb460 347 // get rid of comments starting with # and --
6a488035 348
fc6159c2 349 $string = self::stripComments($string);
6a488035
TO
350
351 $queries = preg_split('/;\s*$/m', $string);
352 foreach ($queries as $query) {
353 $query = trim($query);
354 if (!empty($query)) {
355 CRM_Core_Error::debug_query($query);
356 $res = &$db->query($query);
357 if (PEAR::isError($res)) {
358 if ($dieOnErrors) {
359 die("Cannot execute $query: " . $res->getMessage());
360 }
361 else {
362 echo "Cannot execute $query: " . $res->getMessage() . "<p>";
363 }
364 }
365 }
366 }
367 }
fc6159c2 368 /**
369 *
370 * Strips comment from a possibly multiline SQL string
371 *
372 * @param string $string
373 *
374 * @return string
bd6326bf 375 * stripped string
fc6159c2 376 */
377 public static function stripComments($string) {
378 return preg_replace("/^(#|--).*\R*/m", "", $string);
379 }
6a488035 380
5bc392e6
EM
381 /**
382 * @param $ext
383 *
384 * @return bool
385 */
00be9182 386 public static function isExtensionSafe($ext) {
6a488035
TO
387 static $extensions = NULL;
388 if (!$extensions) {
389 $extensions = CRM_Core_OptionGroup::values('safe_file_extension', TRUE);
390
50bfb460 391 // make extensions to lowercase
6a488035
TO
392 $extensions = array_change_key_case($extensions, CASE_LOWER);
393 // allow html/htm extension ONLY if the user is admin
394 // and/or has access CiviMail
395 if (!(CRM_Core_Permission::check('access CiviMail') ||
353ffa53
TO
396 CRM_Core_Permission::check('administer CiviCRM') ||
397 (CRM_Mailing_Info::workflowEnabled() &&
398 CRM_Core_Permission::check('create mailings')
399 )
400 )
401 ) {
6a488035
TO
402 unset($extensions['html']);
403 unset($extensions['htm']);
404 }
405 }
50bfb460 406 // support lower and uppercase file extensions
6a488035
TO
407 return isset($extensions[strtolower($ext)]) ? TRUE : FALSE;
408 }
409
410 /**
fe482240 411 * Determine whether a given file is listed in the PHP include path.
6a488035 412 *
77855840
TO
413 * @param string $name
414 * Name of file.
6a488035 415 *
ae5ffbb7 416 * @return bool
a6c01b45 417 * whether the file can be include()d or require()d
6a488035 418 */
00be9182 419 public static function isIncludable($name) {
6a488035
TO
420 $x = @fopen($name, 'r', TRUE);
421 if ($x) {
422 fclose($x);
423 return TRUE;
424 }
425 else {
426 return FALSE;
427 }
428 }
429
430 /**
ea3ddccf 431 * Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
432 *
433 * @param $name
434 *
435 * @return mixed
6a488035 436 */
00be9182 437 public static function cleanFileName($name) {
6a488035
TO
438 // replace the last 33 character before the '.' with null
439 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
440 return $name;
441 }
442
5bc392e6 443 /**
8246bca4 444 * Make a valid file name.
445 *
100fef9d 446 * @param string $name
5bc392e6
EM
447 *
448 * @return string
449 */
00be9182 450 public static function makeFileName($name) {
353ffa53
TO
451 $uniqID = md5(uniqid(rand(), TRUE));
452 $info = pathinfo($name);
6a488035
TO
453 $basename = substr($info['basename'],
454 0, -(strlen(CRM_Utils_Array::value('extension', $info)) + (CRM_Utils_Array::value('extension', $info) == '' ? 0 : 1))
455 );
456 if (!self::isExtensionSafe(CRM_Utils_Array::value('extension', $info))) {
457 // munge extension so it cannot have an embbeded dot in it
458 // The maximum length of a filename for most filesystems is 255 chars.
459 // We'll truncate at 240 to give some room for the extension.
460 return CRM_Utils_String::munge("{$basename}_" . CRM_Utils_Array::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
461 }
462 else {
463 return CRM_Utils_String::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array::value('extension', $info);
464 }
465 }
466
33d245c8
CW
467 /**
468 * Copies a file
469 *
470 * @param $filePath
471 * @return mixed
472 */
473 public static function duplicate($filePath) {
474 $oldName = pathinfo($filePath, PATHINFO_FILENAME);
475 $uniqID = md5(uniqid(rand(), TRUE));
476 $newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
477 $newPath = str_replace($oldName, $newName, $filePath);
478 copy($filePath, $newPath);
479 return $newPath;
480 }
481
5bc392e6 482 /**
8246bca4 483 * Get files for the extension.
484 *
485 * @param string $path
486 * @param string $ext
5bc392e6
EM
487 *
488 * @return array
489 */
00be9182 490 public static function getFilesByExtension($path, $ext) {
353ffa53 491 $path = self::addTrailingSlash($path);
6a488035 492 $files = array();
948d11bf 493 if ($dh = opendir($path)) {
948d11bf
CB
494 while (FALSE !== ($elem = readdir($dh))) {
495 if (substr($elem, -(strlen($ext) + 1)) == '.' . $ext) {
496 $files[] .= $path . $elem;
497 }
6a488035 498 }
948d11bf 499 closedir($dh);
6a488035 500 }
6a488035
TO
501 return $files;
502 }
503
504 /**
505 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
506 *
77855840
TO
507 * @param string $dir
508 * The directory to be secured.
f4aaa82a 509 * @param bool $overwrite
6a488035 510 */
00be9182 511 public static function restrictAccess($dir, $overwrite = FALSE) {
6a488035
TO
512 // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
513 // of site, causing site to stop functioning.
514 // FIXME: we should do more checks here -
ea3b22b5 515 if (!empty($dir) && is_dir($dir)) {
6a488035
TO
516 $htaccess = <<<HTACCESS
517<Files "*">
518 Order allow,deny
519 Deny from all
520</Files>
521
522HTACCESS;
523 $file = $dir . '.htaccess';
ea3b22b5
TO
524 if ($overwrite || !file_exists($file)) {
525 if (file_put_contents($file, $htaccess) === FALSE) {
526 CRM_Core_Error::movedSiteError($file);
527 }
6a488035
TO
528 }
529 }
530 }
531
af5201d4
TO
532 /**
533 * Restrict remote users from browsing the given directory.
534 *
535 * @param $publicDir
536 */
00be9182 537 public static function restrictBrowsing($publicDir) {
9404eeac
TO
538 if (!is_dir($publicDir) || !is_writable($publicDir)) {
539 return;
540 }
541
af5201d4
TO
542 // base dir
543 $nobrowse = realpath($publicDir) . '/index.html';
544 if (!file_exists($nobrowse)) {
545 @file_put_contents($nobrowse, '');
546 }
547
548 // child dirs
549 $dir = new RecursiveDirectoryIterator($publicDir);
550 foreach ($dir as $name => $object) {
551 if (is_dir($name) && $name != '..') {
552 $nobrowse = realpath($name) . '/index.html';
553 if (!file_exists($nobrowse)) {
554 @file_put_contents($nobrowse, '');
555 }
556 }
557 }
558 }
559
6a488035
TO
560 /**
561 * Create the base file path from which all our internal directories are
562 * offset. This is derived from the template compile directory set
563 */
635f0b86 564 public static function baseFilePath() {
6a488035
TO
565 static $_path = NULL;
566 if (!$_path) {
635f0b86
TO
567 // Note: Don't rely on $config; that creates a dependency loop.
568 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
569 throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
6a488035 570 }
635f0b86 571 $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR;
6a488035
TO
572
573 $path = dirname($templateCompileDir);
574
575 //this fix is to avoid creation of upload dirs inside templates_c directory
576 $checkPath = explode(DIRECTORY_SEPARATOR, $path);
577
578 $cnt = count($checkPath) - 1;
579 if ($checkPath[$cnt] == 'templates_c') {
580 unset($checkPath[$cnt]);
581 $path = implode(DIRECTORY_SEPARATOR, $checkPath);
582 }
583
584 $_path = CRM_Utils_File::addTrailingSlash($path);
585 }
586 return $_path;
587 }
588
9f87b14b
TO
589 /**
590 * Determine if a path is absolute.
591 *
ea3ddccf 592 * @param string $path
593 *
9f87b14b
TO
594 * @return bool
595 * TRUE if absolute. FALSE if relative.
596 */
597 public static function isAbsolute($path) {
598 if (substr($path, 0, 1) === DIRECTORY_SEPARATOR) {
599 return TRUE;
600 }
601 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
602 if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
603 return TRUE;
604 }
605 }
606 return FALSE;
607 }
608
5bc392e6
EM
609 /**
610 * @param $directory
611 *
612 * @return string
613 */
00be9182 614 public static function relativeDirectory($directory) {
6a488035
TO
615 // Do nothing on windows
616 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
617 return $directory;
618 }
619
620 // check if directory is relative, if so return immediately
9f87b14b 621 if (!self::isAbsolute($directory)) {
6a488035
TO
622 return $directory;
623 }
624
625 // make everything relative from the baseFilePath
626 $basePath = self::baseFilePath();
627 // check if basePath is a substr of $directory, if so
628 // return rest of string
629 if (substr($directory, 0, strlen($basePath)) == $basePath) {
630 return substr($directory, strlen($basePath));
631 }
632
633 // return the original value
634 return $directory;
635 }
636
5bc392e6
EM
637 /**
638 * @param $directory
e3d28c74
TO
639 * @param string|NULL $basePath
640 * The base path when evaluating relative paths. Should include trailing slash.
5bc392e6
EM
641 *
642 * @return string
643 */
e3d28c74 644 public static function absoluteDirectory($directory, $basePath = NULL) {
acc609a7
TO
645 // check if directory is already absolute, if so return immediately
646 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
647 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
6a488035
TO
648 return $directory;
649 }
650
651 // check if directory is already absolute, if so return immediately
652 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR) {
653 return $directory;
654 }
655
656 // make everything absolute from the baseFilePath
e3d28c74 657 $basePath = ($basePath === NULL) ? self::baseFilePath() : $basePath;
6a488035 658
b89b9154 659 // ensure that $basePath has a trailing slash
54972caa 660 $basePath = self::addTrailingSlash($basePath);
6a488035
TO
661 return $basePath . $directory;
662 }
663
664 /**
fe482240 665 * Make a file path relative to some base dir.
6a488035 666 *
f4aaa82a
EM
667 * @param $directory
668 * @param $basePath
669 *
6a488035
TO
670 * @return string
671 */
00be9182 672 public static function relativize($directory, $basePath) {
9f87b14b
TO
673 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
674 $directory = strtr($directory, '\\', '/');
675 $basePath = strtr($basePath, '\\', '/');
676 }
6a488035
TO
677 if (substr($directory, 0, strlen($basePath)) == $basePath) {
678 return substr($directory, strlen($basePath));
0db6c3e1
TO
679 }
680 else {
6a488035
TO
681 return $directory;
682 }
683 }
684
685 /**
fe482240 686 * Create a path to a temporary file which can endure for multiple requests.
6a488035 687 *
50bfb460 688 * @todo Automatic file cleanup using, eg, TTL policy
6a488035 689 *
5a4f6742 690 * @param string $prefix
6a488035
TO
691 *
692 * @return string, path to an openable/writable file
693 * @see tempnam
694 */
00be9182 695 public static function tempnam($prefix = 'tmp-') {
50bfb460
SB
696 // $config = CRM_Core_Config::singleton();
697 // $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
698 // $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
6a488035
TO
699 $fileName = tempnam(sys_get_temp_dir(), $prefix);
700 return $fileName;
701 }
702
703 /**
fe482240 704 * Create a path to a temporary directory which can endure for multiple requests.
6a488035 705 *
50bfb460 706 * @todo Automatic file cleanup using, eg, TTL policy
6a488035 707 *
5a4f6742 708 * @param string $prefix
6a488035
TO
709 *
710 * @return string, path to an openable/writable directory; ends with '/'
711 * @see tempnam
712 */
00be9182 713 public static function tempdir($prefix = 'tmp-') {
6a488035
TO
714 $fileName = self::tempnam($prefix);
715 unlink($fileName);
716 mkdir($fileName, 0700);
717 return $fileName . '/';
718 }
719
720 /**
d7166b43
TO
721 * Search directory tree for files which match a glob pattern.
722 *
723 * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
6a488035 724 *
5a4f6742
CW
725 * @param string $dir
726 * base dir.
727 * @param string $pattern
728 * glob pattern, eg "*.txt".
a2dc0f82
TO
729 * @param bool $relative
730 * TRUE if paths should be made relative to $dir
6a488035
TO
731 * @return array(string)
732 */
a2dc0f82 733 public static function findFiles($dir, $pattern, $relative = FALSE) {
cae27189
TO
734 if (!is_dir($dir)) {
735 return array();
736 }
a2dc0f82 737 $dir = rtrim($dir, '/');
6a488035
TO
738 $todos = array($dir);
739 $result = array();
740 while (!empty($todos)) {
741 $subdir = array_shift($todos);
0b72a00f
TO
742 $matches = glob("$subdir/$pattern");
743 if (is_array($matches)) {
744 foreach ($matches as $match) {
002f1716 745 if (!is_dir($match)) {
a2dc0f82 746 $result[] = $relative ? CRM_Utils_File::relativize($match, "$dir/") : $match;
002f1716 747 }
6a488035
TO
748 }
749 }
948d11bf 750 if ($dh = opendir($subdir)) {
6a488035
TO
751 while (FALSE !== ($entry = readdir($dh))) {
752 $path = $subdir . DIRECTORY_SEPARATOR . $entry;
d7166b43
TO
753 if ($entry{0} == '.') {
754 // ignore
0db6c3e1
TO
755 }
756 elseif (is_dir($path)) {
6a488035
TO
757 $todos[] = $path;
758 }
759 }
760 closedir($dh);
761 }
762 }
763 return $result;
764 }
765
766 /**
767 * Determine if $child is a sub-directory of $parent
768 *
769 * @param string $parent
770 * @param string $child
f4aaa82a
EM
771 * @param bool $checkRealPath
772 *
6a488035
TO
773 * @return bool
774 */
00be9182 775 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
6a488035
TO
776 if ($checkRealPath) {
777 $parent = realpath($parent);
778 $child = realpath($child);
779 }
780 $parentParts = explode('/', rtrim($parent, '/'));
781 $childParts = explode('/', rtrim($child, '/'));
782 while (($parentPart = array_shift($parentParts)) !== NULL) {
783 $childPart = array_shift($childParts);
784 if ($parentPart != $childPart) {
785 return FALSE;
786 }
787 }
788 if (empty($childParts)) {
789 return FALSE; // same directory
0db6c3e1
TO
790 }
791 else {
6a488035
TO
792 return TRUE;
793 }
794 }
795
796 /**
797 * Move $fromDir to $toDir, replacing/deleting any
798 * pre-existing content.
799 *
77855840
TO
800 * @param string $fromDir
801 * The directory which should be moved.
802 * @param string $toDir
803 * The new location of the directory.
f4aaa82a
EM
804 * @param bool $verbose
805 *
a6c01b45
CW
806 * @return bool
807 * TRUE on success
6a488035 808 */
00be9182 809 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
6a488035
TO
810 if (is_dir($toDir)) {
811 if (!self::cleanDir($toDir, TRUE, $verbose)) {
812 return FALSE;
813 }
814 }
815
50bfb460 816 // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
6a488035
TO
817
818 CRM_Utils_File::copyDir($fromDir, $toDir);
819 if (!CRM_Utils_File::cleanDir($fromDir, TRUE, FALSE)) {
e7292422 820 CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', array(1 => $fromDir)), '', 'alert');
6a488035
TO
821 return FALSE;
822 }
823 return TRUE;
824 }
96025800 825
8246bca4 826 /**
827 * Format file.
828 *
829 * @param array $param
830 * @param string $fileName
831 * @param array $extraParams
832 */
90a73810 833 public static function formatFile(&$param, $fileName, $extraParams = array()) {
834 if (empty($param[$fileName])) {
835 return;
836 }
837
838 $fileParams = array(
839 'uri' => $param[$fileName]['name'],
840 'type' => $param[$fileName]['type'],
841 'location' => $param[$fileName]['name'],
842 'upload_date' => date('YmdHis'),
843 ) + $extraParams;
844
845 $param[$fileName] = $fileParams;
846 }
847
f3726153 848 /**
849 * Return formatted file URL, like for image file return image url with image icon
850 *
851 * @param string $path
852 * Absoulte file path
853 * @param string $fileType
854 * @param string $url
855 * File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
856 *
857 * @return string $url
858 */
859 public static function getFileURL($path, $fileType, $url = NULL) {
860 if (empty($path) || empty($fileType)) {
861 return '';
862 }
863 elseif (empty($url)) {
864 $fileName = basename($path);
865 $url = CRM_Utils_System::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
866 }
867 switch ($fileType) {
868 case 'image/jpeg':
869 case 'image/pjpeg':
870 case 'image/gif':
871 case 'image/x-png':
872 case 'image/png':
c3821398 873 case 'image/jpg':
f3726153 874 list($imageWidth, $imageHeight) = getimagesize($path);
875 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
876 $url = "<a href=\"$url\" class='crm-image-popup'>
877 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
878 </a>";
879 break;
880
881 default:
882 $url = sprintf('<a href="%s">%s</a>', $url, basename($path));
883 break;
884 }
885
886 return $url;
887 }
888
c3821398 889 /**
890 * Return formatted image icon
891 *
892 * @param string $imageURL
893 * Contact's image url
894 *
895 * @return string $url
896 */
897 public static function getImageURL($imageURL) {
898 // retrieve image name from $imageURL
899 $imageURL = CRM_Utils_String::unstupifyUrl($imageURL);
900 parse_str(parse_url($imageURL, PHP_URL_QUERY), $query);
901
902 $path = CRM_Core_Config::singleton()->customFileUploadDir . $query['photo'];
903 $mimeType = 'image/' . strtolower(pathinfo($path, PATHINFO_EXTENSION));
904
905 return self::getFileURL($path, $mimeType);
906 }
907
4994819e
CW
908
909 /**
910 * Get file icon class for specific MIME Type
911 *
912 * @param string $mimeType
913 * @return string
914 */
915 public static function getIconFromMimeType($mimeType) {
892be376
CW
916 if (!isset(Civi::$statics[__CLASS__]['mimeIcons'])) {
917 Civi::$statics[__CLASS__]['mimeIcons'] = json_decode(file_get_contents(__DIR__ . '/File/mimeIcons.json'), TRUE);
918 }
919 $iconClasses = Civi::$statics[__CLASS__]['mimeIcons'];
4994819e
CW
920 foreach ($iconClasses as $text => $icon) {
921 if (strpos($mimeType, $text) === 0) {
922 return $icon;
923 }
924 }
892be376 925 return $iconClasses['*'];
4994819e
CW
926 }
927
6a488035 928}