3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * class to provide simple static functions for file objects
37 class CRM_Utils_File
{
40 * Given a file name, determine if the file contents make it an ascii file
46 * true if file is ascii
48 public static function isAscii($name) {
49 $fd = fopen($name, "r");
56 $line = fgets($fd, 8192);
57 if (!CRM_Utils_String
::isAscii($line)) {
68 * Given a file name, determine if the file contents make it an html file
74 * true if file is html
76 public static function isHtml($name) {
77 $fd = fopen($name, "r");
84 while (!feof($fd) & $lineCount <= 5) {
86 $line = fgets($fd, 8192);
87 if (!CRM_Utils_String
::isHtml($line)) {
98 * Create a directory given a path name, creates parent directories
101 * @param string $path
104 * Should we abort or just return an invalid code.
106 * NULL: Folder already exists or was not specified.
107 * TRUE: Creation succeeded.
108 * FALSE: Creation failed.
110 public static function createDir($path, $abort = TRUE) {
111 if (is_dir($path) ||
empty($path)) {
115 CRM_Utils_File
::createDir(dirname($path), $abort);
116 if (@mkdir
($path, 0777) == FALSE) {
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>";
121 CRM_Utils_System
::civiExit();
131 * Delete a directory given a path name, delete children directories
132 * and files if needed
134 * @param string $target
137 * @param bool $verbose
141 public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
142 static $exceptions = array('.', '..');
143 if ($target == '' ||
$target == '/' ||
!$target) {
144 throw new Exception("Overly broad deletion");
147 if ($dh = @opendir
($target)) {
148 while (FALSE !== ($sibling = readdir($dh))) {
149 if (!in_array($sibling, $exceptions)) {
150 $object = $target . DIRECTORY_SEPARATOR
. $sibling;
152 if (is_dir($object)) {
153 CRM_Utils_File
::cleanDir($object, $rmdir, $verbose);
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');
165 if (rmdir($target)) {
167 CRM_Core_Session
::setStatus(ts('Removed directory %1', array(1 => $target)), '', 'success');
172 CRM_Core_Session
::setStatus(ts('Unable to remove directory %1', array(1 => $target)), ts('Warning'), 'error');
179 * Concatenate several files.
181 * @param array $files
182 * List of file names.
183 * @param string $delim
184 * An optional delimiter to put between files.
187 public static function concat($files, $delim = '') {
190 foreach ($files as $file) {
194 $buf .= file_get_contents($file);
201 * @param string $source
202 * @param string $destination
204 public static function copyDir($source, $destination) {
205 if ($dh = opendir($source)) {
206 @mkdir
($destination);
207 while (FALSE !== ($file = readdir($dh))) {
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);
213 copy($source . DIRECTORY_SEPARATOR
. $file, $destination . DIRECTORY_SEPARATOR
. $file);
222 * Given a file name, recode it (in place!) to UTF-8
224 * @param string $name
228 * whether the file was recoded properly
230 public static function toUtf8($name) {
231 static $config = NULL;
232 static $legacyEncoding = NULL;
233 if ($config == NULL) {
234 $config = CRM_Core_Config
::singleton();
235 $legacyEncoding = $config->legacyEncoding
;
238 if (!function_exists('iconv')) {
244 $contents = file_get_contents($name);
245 if ($contents === FALSE) {
249 $contents = iconv($legacyEncoding, 'UTF-8', $contents);
250 if ($contents === FALSE) {
254 $file = fopen($name, 'w');
255 if ($file === FALSE) {
259 $written = fwrite($file, $contents);
260 $closed = fclose($file);
261 if ($written === FALSE or !$closed) {
269 * Appends a slash to the end of a string if it doesn't already end with one
271 * @param string $path
272 * @param string $slash
276 public static function addTrailingSlash($path, $slash = NULL) {
278 // FIXME: Defaulting to backslash on windows systems can produce
279 // unexpected results, esp for URL strings which should always use forward-slashes.
280 // I think this fn should default to forward-slash instead.
281 $slash = DIRECTORY_SEPARATOR
;
283 if (!in_array(substr($path, -1, 1), array('/', '\\'))) {
290 * Save a fake file somewhere
293 * The directory where the file should be saved.
294 * @param string $contents
295 * Optional: the contents of the file.
298 * The filename saved, or FALSE on failure.
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);
305 return ($success === FALSE) ?
FALSE : $file;
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.
312 * @param string $fileName
313 * @param null $prefix
314 * @param bool $isQueryString
315 * @param bool $dieOnErrors
317 public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $isQueryString = FALSE, $dieOnErrors = TRUE) {
319 $db = CRM_Core_DAO
::getConnection();
322 require_once 'DB.php';
323 $db = DB
::connect($dsn);
326 if (PEAR
::isError($db)) {
327 die("Cannot open $dsn: " . $db->getMessage());
329 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
330 $db->query('SET SESSION sql_mode = STRICT_TRANS_TABLES');
332 $db->query('SET NAMES utf8');
333 $transactionId = CRM_Utils_Type
::escape(CRM_Utils_Request
::id(), 'String');
334 $db->query('SET @uniqueID = ' . "'$transactionId'");
336 if (!$isQueryString) {
337 $string = $prefix . file_get_contents($fileName);
340 // use filename as query string
341 $string = $prefix . $fileName;
344 // get rid of comments starting with # and --
346 $string = self
::stripComments($string);
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)) {
356 die("Cannot execute $query: " . $res->getMessage());
359 echo "Cannot execute $query: " . $res->getMessage() . "<p>";
367 * Strips comment from a possibly multiline SQL string
369 * @param string $string
374 public static function stripComments($string) {
375 return preg_replace("/^(#|--).*\R*/m", "", $string);
383 public static function isExtensionSafe($ext) {
384 static $extensions = NULL;
386 $extensions = CRM_Core_OptionGroup
::values('safe_file_extension', TRUE);
388 // make extensions to lowercase
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') ||
393 CRM_Core_Permission
::check('administer CiviCRM') ||
394 (CRM_Mailing_Info
::workflowEnabled() &&
395 CRM_Core_Permission
::check('create mailings')
399 unset($extensions['html']);
400 unset($extensions['htm']);
403 // support lower and uppercase file extensions
404 return isset($extensions[strtolower($ext)]) ?
TRUE : FALSE;
408 * Determine whether a given file is listed in the PHP include path.
410 * @param string $name
414 * whether the file can be include()d or require()d
416 public static function isIncludable($name) {
417 $x = @fopen
($name, 'r', TRUE);
428 * Remove the 32 bit md5 we add to the fileName also remove the unknown tag if we added it.
434 public static function cleanFileName($name) {
435 // replace the last 33 character before the '.' with null
436 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
441 * Make a valid file name.
443 * @param string $name
447 public static function makeFileName($name) {
448 $uniqID = md5(uniqid(rand(), TRUE));
449 $info = pathinfo($name);
450 $basename = substr($info['basename'],
451 0, -(strlen(CRM_Utils_Array
::value('extension', $info)) +
(CRM_Utils_Array
::value('extension', $info) == '' ?
0 : 1))
453 if (!self
::isExtensionSafe(CRM_Utils_Array
::value('extension', $info))) {
454 // munge extension so it cannot have an embbeded dot in it
455 // The maximum length of a filename for most filesystems is 255 chars.
456 // We'll truncate at 240 to give some room for the extension.
457 return CRM_Utils_String
::munge("{$basename}_" . CRM_Utils_Array
::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
460 return CRM_Utils_String
::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array
::value('extension', $info);
465 * Get files for the extension.
467 * @param string $path
472 public static function getFilesByExtension($path, $ext) {
473 $path = self
::addTrailingSlash($path);
475 if ($dh = opendir($path)) {
476 while (FALSE !== ($elem = readdir($dh))) {
477 if (substr($elem, -(strlen($ext) +
1)) == '.' . $ext) {
478 $files[] .= $path . $elem;
487 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
490 * The directory to be secured.
491 * @param bool $overwrite
493 public static function restrictAccess($dir, $overwrite = FALSE) {
494 // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
495 // of site, causing site to stop functioning.
496 // FIXME: we should do more checks here -
497 if (!empty($dir) && is_dir($dir)) {
498 $htaccess = <<<HTACCESS
505 $file = $dir . '.htaccess';
506 if ($overwrite ||
!file_exists($file)) {
507 if (file_put_contents($file, $htaccess) === FALSE) {
508 CRM_Core_Error
::movedSiteError($file);
515 * Restrict remote users from browsing the given directory.
519 public static function restrictBrowsing($publicDir) {
520 if (!is_dir($publicDir) ||
!is_writable($publicDir)) {
525 $nobrowse = realpath($publicDir) . '/index.html';
526 if (!file_exists($nobrowse)) {
527 @file_put_contents
($nobrowse, '');
531 $dir = new RecursiveDirectoryIterator($publicDir);
532 foreach ($dir as $name => $object) {
533 if (is_dir($name) && $name != '..') {
534 $nobrowse = realpath($name) . '/index.html';
535 if (!file_exists($nobrowse)) {
536 @file_put_contents
($nobrowse, '');
543 * Create the base file path from which all our internal directories are
544 * offset. This is derived from the template compile directory set
546 public static function baseFilePath() {
547 static $_path = NULL;
549 // Note: Don't rely on $config; that creates a dependency loop.
550 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
551 throw new RuntimeException("Undefined constant: CIVICRM_TEMPLATE_COMPILEDIR");
553 $templateCompileDir = CIVICRM_TEMPLATE_COMPILEDIR
;
555 $path = dirname($templateCompileDir);
557 //this fix is to avoid creation of upload dirs inside templates_c directory
558 $checkPath = explode(DIRECTORY_SEPARATOR
, $path);
560 $cnt = count($checkPath) - 1;
561 if ($checkPath[$cnt] == 'templates_c') {
562 unset($checkPath[$cnt]);
563 $path = implode(DIRECTORY_SEPARATOR
, $checkPath);
566 $_path = CRM_Utils_File
::addTrailingSlash($path);
572 * Determine if a path is absolute.
574 * @param string $path
577 * TRUE if absolute. FALSE if relative.
579 public static function isAbsolute($path) {
580 if (substr($path, 0, 1) === DIRECTORY_SEPARATOR
) {
583 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
584 if (preg_match('!^[a-zA-Z]:[/\\\\]!', $path)) {
596 public static function relativeDirectory($directory) {
597 // Do nothing on windows
598 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
602 // check if directory is relative, if so return immediately
603 if (!self
::isAbsolute($directory)) {
607 // make everything relative from the baseFilePath
608 $basePath = self
::baseFilePath();
609 // check if basePath is a substr of $directory, if so
610 // return rest of string
611 if (substr($directory, 0, strlen($basePath)) == $basePath) {
612 return substr($directory, strlen($basePath));
615 // return the original value
621 * @param string|NULL $basePath
622 * The base path when evaluating relative paths. Should include trailing slash.
626 public static function absoluteDirectory($directory, $basePath = NULL) {
627 // check if directory is already absolute, if so return immediately
628 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
629 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
633 // check if directory is already absolute, if so return immediately
634 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR
) {
638 // make everything absolute from the baseFilePath
639 $basePath = ($basePath === NULL) ? self
::baseFilePath() : $basePath;
641 // ensure that $basePath has a trailing slash
642 $basePath = self
::addTrailingSlash($basePath);
643 return $basePath . $directory;
647 * Make a file path relative to some base dir.
654 public static function relativize($directory, $basePath) {
655 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
656 $directory = strtr($directory, '\\', '/');
657 $basePath = strtr($basePath, '\\', '/');
659 if (substr($directory, 0, strlen($basePath)) == $basePath) {
660 return substr($directory, strlen($basePath));
668 * Create a path to a temporary file which can endure for multiple requests.
670 * @todo Automatic file cleanup using, eg, TTL policy
672 * @param string $prefix
674 * @return string, path to an openable/writable file
677 public static function tempnam($prefix = 'tmp-') {
678 // $config = CRM_Core_Config::singleton();
679 // $nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
680 // $fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
681 $fileName = tempnam(sys_get_temp_dir(), $prefix);
686 * Create a path to a temporary directory which can endure for multiple requests.
688 * @todo Automatic file cleanup using, eg, TTL policy
690 * @param string $prefix
692 * @return string, path to an openable/writable directory; ends with '/'
695 public static function tempdir($prefix = 'tmp-') {
696 $fileName = self
::tempnam($prefix);
698 mkdir($fileName, 0700);
699 return $fileName . '/';
703 * Search directory tree for files which match a glob pattern.
705 * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
709 * @param string $pattern
710 * glob pattern, eg "*.txt".
711 * @param bool $relative
712 * TRUE if paths should be made relative to $dir
713 * @return array(string)
715 public static function findFiles($dir, $pattern, $relative = FALSE) {
719 $dir = rtrim($dir, '/');
720 $todos = array($dir);
722 while (!empty($todos)) {
723 $subdir = array_shift($todos);
724 $matches = glob("$subdir/$pattern");
725 if (is_array($matches)) {
726 foreach ($matches as $match) {
727 if (!is_dir($match)) {
728 $result[] = $relative ? CRM_Utils_File
::relativize($match, "$dir/") : $match;
732 if ($dh = opendir($subdir)) {
733 while (FALSE !== ($entry = readdir($dh))) {
734 $path = $subdir . DIRECTORY_SEPARATOR
. $entry;
735 if ($entry{0} == '.') {
738 elseif (is_dir($path)) {
749 * Determine if $child is a sub-directory of $parent
751 * @param string $parent
752 * @param string $child
753 * @param bool $checkRealPath
757 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
758 if ($checkRealPath) {
759 $parent = realpath($parent);
760 $child = realpath($child);
762 $parentParts = explode('/', rtrim($parent, '/'));
763 $childParts = explode('/', rtrim($child, '/'));
764 while (($parentPart = array_shift($parentParts)) !== NULL) {
765 $childPart = array_shift($childParts);
766 if ($parentPart != $childPart) {
770 if (empty($childParts)) {
771 return FALSE; // same directory
779 * Move $fromDir to $toDir, replacing/deleting any
780 * pre-existing content.
782 * @param string $fromDir
783 * The directory which should be moved.
784 * @param string $toDir
785 * The new location of the directory.
786 * @param bool $verbose
791 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
792 if (is_dir($toDir)) {
793 if (!self
::cleanDir($toDir, TRUE, $verbose)) {
798 // return rename($fromDir, $toDir); CRM-11987, https://bugs.php.net/bug.php?id=54097
800 CRM_Utils_File
::copyDir($fromDir, $toDir);
801 if (!CRM_Utils_File
::cleanDir($fromDir, TRUE, FALSE)) {
802 CRM_Core_Session
::setStatus(ts('Failed to clean temp dir: %1', array(1 => $fromDir)), '', 'alert');
811 * @param array $param
812 * @param string $fileName
813 * @param array $extraParams
815 public static function formatFile(&$param, $fileName, $extraParams = array()) {
816 if (empty($param[$fileName])) {
821 'uri' => $param[$fileName]['name'],
822 'type' => $param[$fileName]['type'],
823 'location' => $param[$fileName]['name'],
824 'upload_date' => date('YmdHis'),
827 $param[$fileName] = $fileParams;
831 * Return formatted file URL, like for image file return image url with image icon
833 * @param string $path
835 * @param string $fileType
837 * File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
839 * @return string $url
841 public static function getFileURL($path, $fileType, $url = NULL) {
842 if (empty($path) ||
empty($fileType)) {
845 elseif (empty($url)) {
846 $fileName = basename($path);
847 $url = CRM_Utils_System
::url('civicrm/file', "reset=1&filename={$fileName}&mime-type={$fileType}");
856 list($imageWidth, $imageHeight) = getimagesize($path);
857 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
858 $url = "<a href=\"$url\" class='crm-image-popup'>
859 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
864 $url = sprintf('<a href="%s">%s</a>', $url, basename($path));
872 * Return formatted image icon
874 * @param string $imageURL
875 * Contact's image url
877 * @return string $url
879 public static function getImageURL($imageURL) {
880 // retrieve image name from $imageURL
881 $imageURL = CRM_Utils_String
::unstupifyUrl($imageURL);
882 parse_str(parse_url($imageURL, PHP_URL_QUERY
), $query);
884 $path = CRM_Core_Config
::singleton()->customFileUploadDir
. $query['photo'];
885 $mimeType = 'image/' . strtolower(pathinfo($path, PATHINFO_EXTENSION
));
887 return self
::getFileURL($path, $mimeType);
892 * Get file icon class for specific MIME Type
894 * @param string $mimeType
897 public static function getIconFromMimeType($mimeType) {
898 if (!isset(Civi
::$statics[__CLASS__
]['mimeIcons'])) {
899 Civi
::$statics[__CLASS__
]['mimeIcons'] = json_decode(file_get_contents(__DIR__
. '/File/mimeIcons.json'), TRUE);
901 $iconClasses = Civi
::$statics[__CLASS__
]['mimeIcons'];
902 foreach ($iconClasses as $text => $icon) {
903 if (strpos($mimeType, $text) === 0) {
907 return $iconClasses['*'];