Merge pull request #10162 from yashodha/CRM-20429
[civicrm-core.git] / CRM / Utils / File.php
index c5906f4b90d3f8795b13e45e82597c68799758a3..8f48b99806345942438da1af521ae08f4462a2f2 100644 (file)
@@ -140,7 +140,7 @@ class CRM_Utils_File {
    */
   public static function cleanDir($target, $rmdir = TRUE, $verbose = TRUE) {
     static $exceptions = array('.', '..');
-    if ($target == '' || $target == '/') {
+    if ($target == '' || $target == '/' || !$target) {
       throw new Exception("Overly broad deletion");
     }
 
@@ -293,16 +293,19 @@ class CRM_Utils_File {
    *   The directory where the file should be saved.
    * @param string $contents
    *   Optional: the contents of the file.
+   * @param string $fileName
    *
    * @return string
    *   The filename saved, or FALSE on failure.
    */
-  public static function createFakeFile($dir, $contents = 'delete me') {
+  public static function createFakeFile($dir, $contents = 'delete me', $fileName = NULL) {
     $dir = self::addTrailingSlash($dir);
-    $file = 'delete-this-' . CRM_Utils_String::createRandom(10, CRM_Utils_String::ALPHANUMERIC);
-    $success = file_put_contents($dir . $file, $contents);
+    if (!$fileName) {
+      $fileName = 'delete-this-' . CRM_Utils_String::createRandom(10, CRM_Utils_String::ALPHANUMERIC);
+    }
+    $success = file_put_contents($dir . $fileName, $contents);
 
-    return ($success === FALSE) ? FALSE : $file;
+    return ($success === FALSE) ? FALSE : $fileName;
   }
 
   /**
@@ -461,6 +464,21 @@ class CRM_Utils_File {
     }
   }
 
+  /**
+   * Copies a file
+   *
+   * @param $filePath
+   * @return mixed
+   */
+  public static function duplicate($filePath) {
+    $oldName = pathinfo($filePath, PATHINFO_FILENAME);
+    $uniqID = md5(uniqid(rand(), TRUE));
+    $newName = preg_replace('/(_[\w]{32})$/', '', $oldName) . '_' . $uniqID;
+    $newPath = str_replace($oldName, $newName, $filePath);
+    copy($filePath, $newPath);
+    return $newPath;
+  }
+
   /**
    * Get files for the extension.
    *