Merge remote-tracking branch 'upstream/4.5' into 4.5-4.6-2015-03-16-17-24-33
[civicrm-core.git] / CRM / Utils / File.php
index f435ad175e5d04928dd8e5a1d3d9d7fc61135a38..70adaed6cccf4e6a32cd513a3cec53f0b5b7515f 100644 (file)
@@ -23,7 +23,7 @@
  | GNU Affero General Public License or the licensing of CiviCRM,     |
  | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
  +--------------------------------------------------------------------+
-*/
+ */
 
 /**
  *
@@ -41,9 +41,11 @@ class CRM_Utils_File {
   /**
    * Given a file name, determine if the file contents make it an ascii file
    *
-   * @param string $name name of file
+   * @param string $name
+   *   Name of file.
    *
-   * @return boolean     true if file is ascii
+   * @return bool
+   *   true if file is ascii
    */
   public static function isAscii($name) {
     $fd = fopen($name, "r");
@@ -67,9 +69,11 @@ class CRM_Utils_File {
   /**
    * Given a file name, determine if the file contents make it an html file
    *
-   * @param string $name name of file
+   * @param string $name
+   *   Name of file.
    *
-   * @return boolean     true if file is html
+   * @return bool
+   *   true if file is html
    */
   public static function isHtml($name) {
     $fd = fopen($name, "r");
@@ -96,11 +100,12 @@ class CRM_Utils_File {
    * Create a directory given a path name, creates parent directories
    * if needed
    *
-   * @param string $path  the path name
-   * @param boolean $abort should we abort or just return an invalid code
+   * @param string $path
+   *   The path name.
+   * @param bool $abort
+   *   Should we abort or just return an invalid code.
    *
    * @return void
-   * @static
    */
   public static function createDir($path, $abort = TRUE) {
     if (is_dir($path) || empty($path)) {
@@ -126,13 +131,13 @@ class CRM_Utils_File {
    * Delete a directory given a path name, delete children directories
    * and files if needed
    *
-   * @param string $target the path name
+   * @param string $target
+   *   The path name.
    * @param bool $rmdir
    * @param bool $verbose
    *
    * @throws Exception
    * @return void
-   * @static
    */
   public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
     static $exceptions = array('.', '..');
@@ -140,8 +145,8 @@ class CRM_Utils_File {
       throw new Exception("Overly broad deletion");
     }
 
-    if ($sourcedir = opendir($target)) {
-      while (FALSE !== ($sibling = readdir($sourcedir))) {
+    if ($dh = @opendir($target)) {
+      while (FALSE !== ($sibling = readdir($dh))) {
         if (!in_array($sibling, $exceptions)) {
           $object = $target . DIRECTORY_SEPARATOR . $sibling;
 
@@ -151,11 +156,11 @@ class CRM_Utils_File {
           elseif (is_file($object)) {
             if (!unlink($object)) {
               CRM_Core_Session::setStatus(ts('Unable to remove file %1', array(1 => $object)), ts('Warning'), 'error');
+            }
           }
         }
       }
-      }
-      closedir($sourcedir);
+      closedir($dh);
 
       if ($rmdir) {
         if (rmdir($target)) {
@@ -163,22 +168,22 @@ class CRM_Utils_File {
             CRM_Core_Session::setStatus(ts('Removed directory %1', array(1 => $target)), '', 'success');
           }
           return TRUE;
-      }
+        }
         else {
           CRM_Core_Session::setStatus(ts('Unable to remove directory %1', array(1 => $target)), ts('Warning'), 'error');
-    }
-  }
+        }
+      }
     }
   }
 
   /**
-   * @param $source
-   * @param $destination
+   * @param string $source
+   * @param string $destination
    */
-  static function copyDir($source, $destination) {
-    if ($dir = opendir($source)) {
+  public static function copyDir($source, $destination) {
+    if ($dh = opendir($source)) {
       @mkdir($destination);
-      while (FALSE !== ($file = readdir($dir))) {
+      while (FALSE !== ($file = readdir($dh))) {
         if (($file != '.') && ($file != '..')) {
           if (is_dir($source . DIRECTORY_SEPARATOR . $file)) {
             CRM_Utils_File::copyDir($source . DIRECTORY_SEPARATOR . $file, $destination . DIRECTORY_SEPARATOR . $file);
@@ -188,16 +193,18 @@ class CRM_Utils_File {
           }
         }
       }
-      closedir($dir);
+      closedir($dh);
     }
   }
 
   /**
    * Given a file name, recode it (in place!) to UTF-8
    *
-   * @param string $name name of file
+   * @param string $name
+   *   Name of file.
    *
-   * @return boolean  whether the file was recoded properly
+   * @return bool
+   *   whether the file was recoded properly
    */
   public static function toUtf8($name) {
     static $config = NULL;
@@ -244,7 +251,6 @@ class CRM_Utils_File {
    * @param string $slash
    *
    * @return string
-   * @static
    */
   public static function addTrailingSlash($path, $slash = NULL) {
     if (!$slash) {
@@ -322,11 +328,12 @@ class CRM_Utils_File {
       // allow html/htm extension ONLY if the user is admin
       // and/or has access CiviMail
       if (!(CRM_Core_Permission::check('access CiviMail') ||
-          CRM_Core_Permission::check('administer CiviCRM') ||
-          (CRM_Mailing_Info::workflowEnabled() &&
-            CRM_Core_Permission::check('create mailings')
-          )
-        )) {
+        CRM_Core_Permission::check('administer CiviCRM') ||
+        (CRM_Mailing_Info::workflowEnabled() &&
+          CRM_Core_Permission::check('create mailings')
+        )
+      )
+      ) {
         unset($extensions['html']);
         unset($extensions['htm']);
       }
@@ -336,11 +343,13 @@ class CRM_Utils_File {
   }
 
   /**
-   * Determine whether a given file is listed in the PHP include path
+   * Determine whether a given file is listed in the PHP include path.
    *
-   * @param string $name name of file
+   * @param string $name
+   *   Name of file.
    *
-   * @return boolean  whether the file can be include()d or require()d
+   * @return bool
+   *   whether the file can be include()d or require()d
    */
   public static function isIncludable($name) {
     $x = @fopen($name, 'r', TRUE);
@@ -369,8 +378,8 @@ class CRM_Utils_File {
    * @return string
    */
   public static function makeFileName($name) {
-    $uniqID   = md5(uniqid(rand(), TRUE));
-    $info     = pathinfo($name);
+    $uniqID = md5(uniqid(rand(), TRUE));
+    $info = pathinfo($name);
     $basename = substr($info['basename'],
       0, -(strlen(CRM_Utils_Array::value('extension', $info)) + (CRM_Utils_Array::value('extension', $info) == '' ? 0 : 1))
     );
@@ -392,23 +401,24 @@ class CRM_Utils_File {
    * @return array
    */
   public static function getFilesByExtension($path, $ext) {
-    $path  = self::addTrailingSlash($path);
+    $path = self::addTrailingSlash($path);
+    $files = array();
     if ($dh = opendir($path)) {
-      $files = array();
       while (FALSE !== ($elem = readdir($dh))) {
         if (substr($elem, -(strlen($ext) + 1)) == '.' . $ext) {
           $files[] .= $path . $elem;
         }
       }
       closedir($dh);
-      return $files;
     }
+    return $files;
   }
 
   /**
    * Restrict access to a given directory (by planting there a restrictive .htaccess file)
    *
-   * @param string $dir the directory to be secured
+   * @param string $dir
+   *   The directory to be secured.
    * @param bool $overwrite
    */
   public static function restrictAccess($dir, $overwrite = FALSE) {
@@ -540,7 +550,7 @@ HTACCESS;
   }
 
   /**
-   * Make a file path relative to some base dir
+   * Make a file path relative to some base dir.
    *
    * @param $directory
    * @param $basePath
@@ -550,17 +560,18 @@ HTACCESS;
   public static function relativize($directory, $basePath) {
     if (substr($directory, 0, strlen($basePath)) == $basePath) {
       return substr($directory, strlen($basePath));
-    } else {
+    }
+    else {
       return $directory;
     }
   }
 
   /**
-   * Create a path to a temporary file which can endure for multiple requests
+   * Create a path to a temporary file which can endure for multiple requests.
    *
    * TODO: Automatic file cleanup using, eg, TTL policy
    *
-   * @param $prefix string
+   * @param string $prefix
    *
    * @return string, path to an openable/writable file
    * @see tempnam
@@ -574,11 +585,11 @@ HTACCESS;
   }
 
   /**
-   * Create a path to a temporary directory which can endure for multiple requests
+   * Create a path to a temporary directory which can endure for multiple requests.
    *
    * TODO: Automatic file cleanup using, eg, TTL policy
    *
-   * @param $prefix string
+   * @param string $prefix
    *
    * @return string, path to an openable/writable directory; ends with '/'
    * @see tempnam
@@ -595,11 +606,16 @@ HTACCESS;
    *
    * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
    *
-   * @param $dir string, base dir
-   * @param $pattern string, glob pattern, eg "*.txt"
+   * @param string $dir
+   *   base dir.
+   * @param string $pattern
+   *   glob pattern, eg "*.txt".
+   * @param bool $relative
+   *   TRUE if paths should be made relative to $dir
    * @return array(string)
    */
-  public static function findFiles($dir, $pattern) {
+  public static function findFiles($dir, $pattern, $relative = FALSE) {
+    $dir = rtrim($dir, '/');
     $todos = array($dir);
     $result = array();
     while (!empty($todos)) {
@@ -608,7 +624,7 @@ HTACCESS;
       if (is_array($matches)) {
         foreach ($matches as $match) {
           if (!is_dir($match)) {
-            $result[] = $match;
+            $result[] = $relative ? CRM_Utils_File::relativize($match, "$dir/") : $match;
           }
         }
       }
@@ -617,7 +633,8 @@ HTACCESS;
           $path = $subdir . DIRECTORY_SEPARATOR . $entry;
           if ($entry{0} == '.') {
             // ignore
-          } elseif (is_dir($path)) {
+          }
+          elseif (is_dir($path)) {
             $todos[] = $path;
           }
         }
@@ -651,7 +668,8 @@ HTACCESS;
     }
     if (empty($childParts)) {
       return FALSE; // same directory
-    } else {
+    }
+    else {
       return TRUE;
     }
   }
@@ -660,11 +678,14 @@ HTACCESS;
    * Move $fromDir to $toDir, replacing/deleting any
    * pre-existing content.
    *
-   * @param string $fromDir the directory which should be moved
-   * @param string $toDir the new location of the directory
+   * @param string $fromDir
+   *   The directory which should be moved.
+   * @param string $toDir
+   *   The new location of the directory.
    * @param bool $verbose
    *
-   * @return bool TRUE on success
+   * @return bool
+   *   TRUE on success
    */
   public static function replaceDir($fromDir, $toDir, $verbose = FALSE) {
     if (is_dir($toDir)) {
@@ -677,9 +698,10 @@ HTACCESS;
 
     CRM_Utils_File::copyDir($fromDir, $toDir);
     if (!CRM_Utils_File::cleanDir($fromDir, TRUE, FALSE)) {
-       CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', array(1 => $fromDir)), '', 'alert');
+      CRM_Core_Session::setStatus(ts('Failed to clean temp dir: %1', array(1 => $fromDir)), '', 'alert');
       return FALSE;
     }
     return TRUE;
   }
+
 }