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