3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
37 * class to provide simple static functions for file objects
39 class CRM_Utils_File
{
42 * Given a file name, determine if the file contents make it an ascii file
48 * true if file is ascii
50 public static function isAscii($name) {
51 $fd = fopen($name, "r");
58 $line = fgets($fd, 8192);
59 if (!CRM_Utils_String
::isAscii($line)) {
70 * Given a file name, determine if the file contents make it an html file
76 * true if file is html
78 public static function isHtml($name) {
79 $fd = fopen($name, "r");
86 while (!feof($fd) & $lineCount <= 5) {
88 $line = fgets($fd, 8192);
89 if (!CRM_Utils_String
::isHtml($line)) {
100 * Create a directory given a path name, creates parent directories
103 * @param string $path
106 * Should we abort or just return an invalid code.
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
142 public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
143 static $exceptions = array('.', '..');
144 if ($target == '' ||
$target == '/') {
145 throw new Exception("Overly broad deletion");
148 if ($dh = @opendir
($target)) {
149 while (FALSE !== ($sibling = readdir($dh))) {
150 if (!in_array($sibling, $exceptions)) {
151 $object = $target . DIRECTORY_SEPARATOR
. $sibling;
153 if (is_dir($object)) {
154 CRM_Utils_File
::cleanDir($object, $rmdir, $verbose);
156 elseif (is_file($object)) {
157 if (!unlink($object)) {
158 CRM_Core_Session
::setStatus(ts('Unable to remove file %1', array(1 => $object)), ts('Warning'), 'error');
166 if (rmdir($target)) {
168 CRM_Core_Session
::setStatus(ts('Removed directory %1', array(1 => $target)), '', 'success');
173 CRM_Core_Session
::setStatus(ts('Unable to remove directory %1', array(1 => $target)), ts('Warning'), 'error');
180 * @param string $source
181 * @param string $destination
183 public static function copyDir($source, $destination) {
184 if ($dh = opendir($source)) {
185 @mkdir
($destination);
186 while (FALSE !== ($file = readdir($dh))) {
187 if (($file != '.') && ($file != '..')) {
188 if (is_dir($source . DIRECTORY_SEPARATOR
. $file)) {
189 CRM_Utils_File
::copyDir($source . DIRECTORY_SEPARATOR
. $file, $destination . DIRECTORY_SEPARATOR
. $file);
192 copy($source . DIRECTORY_SEPARATOR
. $file, $destination . DIRECTORY_SEPARATOR
. $file);
201 * Given a file name, recode it (in place!) to UTF-8
203 * @param string $name
207 * whether the file was recoded properly
209 public static function toUtf8($name) {
210 static $config = NULL;
211 static $legacyEncoding = NULL;
212 if ($config == NULL) {
213 $config = CRM_Core_Config
::singleton();
214 $legacyEncoding = $config->legacyEncoding
;
217 if (!function_exists('iconv')) {
223 $contents = file_get_contents($name);
224 if ($contents === FALSE) {
228 $contents = iconv($legacyEncoding, 'UTF-8', $contents);
229 if ($contents === FALSE) {
233 $file = fopen($name, 'w');
234 if ($file === FALSE) {
238 $written = fwrite($file, $contents);
239 $closed = fclose($file);
240 if ($written === FALSE or !$closed) {
248 * Appends a slash to the end of a string if it doesn't already end with one
250 * @param string $path
251 * @param string $slash
255 public static function addTrailingSlash($path, $slash = NULL) {
257 // FIXME: Defaulting to backslash on windows systems can produce unexpected results, esp for URL strings which should always use forward-slashes.
258 // I think this fn should default to forward-slash instead.
259 $slash = DIRECTORY_SEPARATOR
;
261 if (!in_array(substr($path, -1, 1), array('/', '\\'))) {
269 * @param string $fileName
270 * @param null $prefix
271 * @param bool $isQueryString
272 * @param bool $dieOnErrors
274 public static function sourceSQLFile($dsn, $fileName, $prefix = NULL, $isQueryString = FALSE, $dieOnErrors = TRUE) {
275 require_once 'DB.php';
277 $db = DB
::connect($dsn);
278 if (PEAR
::isError($db)) {
279 die("Cannot open $dsn: " . $db->getMessage());
281 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
282 $db->query('SET SESSION sql_mode = STRICT_TRANS_TABLES');
285 if (!$isQueryString) {
286 $string = $prefix . file_get_contents($fileName);
289 // use filename as query string
290 $string = $prefix . $fileName;
293 //get rid of comments starting with # and --
295 $string = preg_replace("/^#[^\n]*$/m", "\n", $string);
296 $string = preg_replace("/^(--[^-]).*/m", "\n", $string);
298 $queries = preg_split('/;\s*$/m', $string);
299 foreach ($queries as $query) {
300 $query = trim($query);
301 if (!empty($query)) {
302 CRM_Core_Error
::debug_query($query);
303 $res = &$db->query($query);
304 if (PEAR
::isError($res)) {
306 die("Cannot execute $query: " . $res->getMessage());
309 echo "Cannot execute $query: " . $res->getMessage() . "<p>";
321 public static function isExtensionSafe($ext) {
322 static $extensions = NULL;
324 $extensions = CRM_Core_OptionGroup
::values('safe_file_extension', TRUE);
326 //make extensions to lowercase
327 $extensions = array_change_key_case($extensions, CASE_LOWER
);
328 // allow html/htm extension ONLY if the user is admin
329 // and/or has access CiviMail
330 if (!(CRM_Core_Permission
::check('access CiviMail') ||
331 CRM_Core_Permission
::check('administer CiviCRM') ||
332 (CRM_Mailing_Info
::workflowEnabled() &&
333 CRM_Core_Permission
::check('create mailings')
337 unset($extensions['html']);
338 unset($extensions['htm']);
341 //support lower and uppercase file extensions
342 return isset($extensions[strtolower($ext)]) ?
TRUE : FALSE;
346 * Determine whether a given file is listed in the PHP include path.
348 * @param string $name
352 * whether the file can be include()d or require()d
354 public static function isIncludable($name) {
355 $x = @fopen
($name, 'r', TRUE);
366 * Remove the 32 bit md5 we add to the fileName
367 * also remove the unknown tag if we added it
369 public static function cleanFileName($name) {
370 // replace the last 33 character before the '.' with null
371 $name = preg_replace('/(_[\w]{32})\./', '.', $name);
376 * @param string $name
380 public static function makeFileName($name) {
381 $uniqID = md5(uniqid(rand(), TRUE));
382 $info = pathinfo($name);
383 $basename = substr($info['basename'],
384 0, -(strlen(CRM_Utils_Array
::value('extension', $info)) +
(CRM_Utils_Array
::value('extension', $info) == '' ?
0 : 1))
386 if (!self
::isExtensionSafe(CRM_Utils_Array
::value('extension', $info))) {
387 // munge extension so it cannot have an embbeded dot in it
388 // The maximum length of a filename for most filesystems is 255 chars.
389 // We'll truncate at 240 to give some room for the extension.
390 return CRM_Utils_String
::munge("{$basename}_" . CRM_Utils_Array
::value('extension', $info) . "_{$uniqID}", '_', 240) . ".unknown";
393 return CRM_Utils_String
::munge("{$basename}_{$uniqID}", '_', 240) . "." . CRM_Utils_Array
::value('extension', $info);
403 public static function getFilesByExtension($path, $ext) {
404 $path = self
::addTrailingSlash($path);
406 if ($dh = opendir($path)) {
407 while (FALSE !== ($elem = readdir($dh))) {
408 if (substr($elem, -(strlen($ext) +
1)) == '.' . $ext) {
409 $files[] .= $path . $elem;
418 * Restrict access to a given directory (by planting there a restrictive .htaccess file)
421 * The directory to be secured.
422 * @param bool $overwrite
424 public static function restrictAccess($dir, $overwrite = FALSE) {
425 // note: empty value for $dir can play havoc, since that might result in putting '.htaccess' to root dir
426 // of site, causing site to stop functioning.
427 // FIXME: we should do more checks here -
428 if (!empty($dir) && is_dir($dir)) {
429 $htaccess = <<<HTACCESS
436 $file = $dir . '.htaccess';
437 if ($overwrite ||
!file_exists($file)) {
438 if (file_put_contents($file, $htaccess) === FALSE) {
439 CRM_Core_Error
::movedSiteError($file);
446 * Restrict remote users from browsing the given directory.
450 public static function restrictBrowsing($publicDir) {
451 if (!is_dir($publicDir) ||
!is_writable($publicDir)) {
456 $nobrowse = realpath($publicDir) . '/index.html';
457 if (!file_exists($nobrowse)) {
458 @file_put_contents
($nobrowse, '');
462 $dir = new RecursiveDirectoryIterator($publicDir);
463 foreach ($dir as $name => $object) {
464 if (is_dir($name) && $name != '..') {
465 $nobrowse = realpath($name) . '/index.html';
466 if (!file_exists($nobrowse)) {
467 @file_put_contents
($nobrowse, '');
474 * Create the base file path from which all our internal directories are
475 * offset. This is derived from the template compile directory set
477 public static function baseFilePath($templateCompileDir = NULL) {
478 static $_path = NULL;
480 if ($templateCompileDir == NULL) {
481 $config = CRM_Core_Config
::singleton();
482 $templateCompileDir = $config->templateCompileDir
;
485 $path = dirname($templateCompileDir);
487 //this fix is to avoid creation of upload dirs inside templates_c directory
488 $checkPath = explode(DIRECTORY_SEPARATOR
, $path);
490 $cnt = count($checkPath) - 1;
491 if ($checkPath[$cnt] == 'templates_c') {
492 unset($checkPath[$cnt]);
493 $path = implode(DIRECTORY_SEPARATOR
, $checkPath);
496 $_path = CRM_Utils_File
::addTrailingSlash($path);
506 public static function relativeDirectory($directory) {
507 // Do nothing on windows
508 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
512 // check if directory is relative, if so return immediately
513 if (substr($directory, 0, 1) != DIRECTORY_SEPARATOR
) {
517 // make everything relative from the baseFilePath
518 $basePath = self
::baseFilePath();
519 // check if basePath is a substr of $directory, if so
520 // return rest of string
521 if (substr($directory, 0, strlen($basePath)) == $basePath) {
522 return substr($directory, strlen($basePath));
525 // return the original value
534 public static function absoluteDirectory($directory) {
535 // check if directory is already absolute, if so return immediately
536 // Note: Windows PHP accepts any mix of "/" or "\", so "C:\htdocs" or "C:/htdocs" would be a valid absolute path
537 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' && preg_match(';^[a-zA-Z]:[/\\\\];', $directory)) {
541 // check if directory is already absolute, if so return immediately
542 if (substr($directory, 0, 1) == DIRECTORY_SEPARATOR
) {
546 // make everything absolute from the baseFilePath
547 $basePath = self
::baseFilePath();
549 return $basePath . $directory;
553 * Make a file path relative to some base dir.
560 public static function relativize($directory, $basePath) {
561 if (substr($directory, 0, strlen($basePath)) == $basePath) {
562 return substr($directory, strlen($basePath));
570 * Create a path to a temporary file which can endure for multiple requests.
572 * TODO: Automatic file cleanup using, eg, TTL policy
574 * @param string $prefix
576 * @return string, path to an openable/writable file
579 public static function tempnam($prefix = 'tmp-') {
580 //$config = CRM_Core_Config::singleton();
581 //$nonce = md5(uniqid() . $config->dsn . $config->userFrameworkResourceURL);
582 //$fileName = "{$config->configAndLogDir}" . $prefix . $nonce . $suffix;
583 $fileName = tempnam(sys_get_temp_dir(), $prefix);
588 * Create a path to a temporary directory which can endure for multiple requests.
590 * TODO: Automatic file cleanup using, eg, TTL policy
592 * @param string $prefix
594 * @return string, path to an openable/writable directory; ends with '/'
597 public static function tempdir($prefix = 'tmp-') {
598 $fileName = self
::tempnam($prefix);
600 mkdir($fileName, 0700);
601 return $fileName . '/';
605 * Search directory tree for files which match a glob pattern.
607 * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
611 * @param string $pattern
612 * glob pattern, eg "*.txt".
613 * @param bool $relative
614 * TRUE if paths should be made relative to $dir
615 * @return array(string)
617 public static function findFiles($dir, $pattern, $relative = FALSE) {
618 $dir = rtrim($dir, '/');
619 $todos = array($dir);
621 while (!empty($todos)) {
622 $subdir = array_shift($todos);
623 $matches = glob("$subdir/$pattern");
624 if (is_array($matches)) {
625 foreach ($matches as $match) {
626 if (!is_dir($match)) {
627 $result[] = $relative ? CRM_Utils_File
::relativize($match, "$dir/") : $match;
631 if ($dh = opendir($subdir)) {
632 while (FALSE !== ($entry = readdir($dh))) {
633 $path = $subdir . DIRECTORY_SEPARATOR
. $entry;
634 if ($entry{0} == '.') {
637 elseif (is_dir($path)) {
648 * Determine if $child is a sub-directory of $parent
650 * @param string $parent
651 * @param string $child
652 * @param bool $checkRealPath
656 public static function isChildPath($parent, $child, $checkRealPath = TRUE) {
657 if ($checkRealPath) {
658 $parent = realpath($parent);
659 $child = realpath($child);
661 $parentParts = explode('/', rtrim($parent, '/'));
662 $childParts = explode('/', rtrim($child, '/'));
663 while (($parentPart = array_shift($parentParts)) !== NULL) {
664 $childPart = array_shift($childParts);
665 if ($parentPart != $childPart) {
669 if (empty($childParts)) {
670 return FALSE; // same directory
678 * Move $fromDir to $toDir, replacing/deleting any
679 * pre-existing content.
681 * @param string $fromDir
682 * The directory which should be moved.
683 * @param string $toDir
684 * The new location of the directory.
685 * @param bool $verbose
690 public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
691 if (is_dir($toDir)) {
692 if (!self
::cleanDir($toDir, TRUE, $verbose)) {
697 // return rename($fromDir, $toDir); // CRM-11987, https://bugs.php.net/bug.php?id=54097
699 CRM_Utils_File
::copyDir($fromDir, $toDir);
700 if (!CRM_Utils_File
::cleanDir($fromDir, TRUE, FALSE)) {
701 CRM_Core_Session
::setStatus(ts('Failed to clean temp dir: %1', array(1 => $fromDir)), '', 'alert');