filesystem.inc

  1. 8.0.x includes/filesystem.inc
  2. 6.x includes/filesystem.inc
  3. 7.x includes/filesystem.inc
  4. 5.x includes/filesystem.inc
  5. master includes/filesystem.inc

Filesystem utilities.

Functions

Namesort descending Description
drush_copy_dir Copy $src to $dest.
drush_correct_absolute_path_for_exec If we are going to pass a path to exec or proc_open, then we need to fix it up under CYGWIN or MINGW. In both of these environments, PHP works with absolute paths such as "C:\path". CYGWIN expects these to be converted to…
drush_delete_dir Deletes the specified file or directory and everything inside it.
drush_delete_dir_contents Deletes the contents of a directory.
drush_delete_tmp_dir Deletes the provided file or folder and everything inside it. This function explicitely tries to delete read-only files / folders.
drush_dir_md5 Calculates a single md5 hash for all files a directory (incuding subdirectories)
drush_file_append_data Simple helper function to append data to a given file.
drush_file_not_empty Test to see if a file exists and is not empty
drush_find_tmp Returns the path to a temporary directory.
drush_is_absolute_path Determines whether the provided path is absolute or not on the specified O.S. -- starts with "/" on *nix, or starts with "[A-Z]:\" or "[A-Z]:/" on Windows.
drush_mkdir Cross-platform compatible helper function to recursively create a directory tree.
drush_move_dir Move $src to $dest.
drush_normalize_path Makes sure the path has only path separators native for the current operating system
drush_preflight_backup_dir Decide where our backup directory should go
drush_prepare_backup_dir Prepare a backup directory
drush_register_file_for_deletion Any file passed in to this function will be deleted when drush exits.
drush_save_data_to_temp_file Save a string to a temporary file. Does not depend on Drupal's API. The temporary file will be automatically deleted when drush exits.
drush_scan_directory Finds all files that match a given mask in a given directory. Directories and files beginning with a period are excluded; this prevents hidden files and directories (such as SVN working directories and GIT repositories) from being scanned.
drush_tempdir Creates a temporary directory and return its path.
drush_tempnam Creates a temporary file, and registers it so that it will be deleted when drush exits. Whenever possible, drush_save_data_to_temp_file() should be used instead of this function.
drush_trim_path Remove the trailing DIRECTORY_SEPARATOR from a path. Will actually remove either / or \ on Windows.
_drush_delete_registered_files Delete all of the registered temporary files.
_drush_recursive_copy Internal function called by drush_copy_dir; do not use directly.

Constants

Namesort descending Description
FILE_EXISTS_ABORT Behavior for drush_copy_dir() and drush_move_dir() when destinations exist.
FILE_EXISTS_MERGE
FILE_EXISTS_OVERWRITE

File

includes/filesystem.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Filesystem utilities.
  5. */
  6. /**
  7. * @defgroup filesystemfunctions Filesystem convenience functions.
  8. * @{
  9. */
  10. /**
  11. * Behavior for drush_copy_dir() and drush_move_dir() when destinations exist.
  12. */
  13. define('FILE_EXISTS_ABORT', 0);
  14. define('FILE_EXISTS_OVERWRITE', 1);
  15. define('FILE_EXISTS_MERGE', 2);
  16. /**
  17. * Determines whether the provided path is absolute or not
  18. * on the specified O.S. -- starts with "/" on *nix, or starts
  19. * with "[A-Z]:\" or "[A-Z]:/" on Windows.
  20. */
  21. function drush_is_absolute_path($path, $os = NULL) {
  22. // Relative paths will never start with a '/', even on Windows,
  23. // so it is safe to just call all paths that start with a '/'
  24. // absolute. This simplifies things for Windows with CYGWIN / MINGW / CWRSYNC,
  25. // where absolute paths sometimes start c:\path and sometimes
  26. // start /cygdrive/c/path.
  27. if ($path[0] == '/') {
  28. return TRUE;
  29. }
  30. if (drush_is_windows($os)) {
  31. return preg_match('@^[a-zA-Z]:[\\\/]@', $path);
  32. }
  33. return FALSE;
  34. }
  35. /**
  36. * If we are going to pass a path to exec or proc_open,
  37. * then we need to fix it up under CYGWIN or MINGW. In
  38. * both of these environments, PHP works with absolute paths
  39. * such as "C:\path". CYGWIN expects these to be converted
  40. * to "/cygdrive/c/path" and MINGW expects these to be converted
  41. * to "/c/path"; otherwise, the exec will not work.
  42. *
  43. * This call does nothing if the parameter is not an absolute
  44. * path, or we are not running under CYGWIN / MINGW.
  45. *
  46. * UPDATE: It seems I was mistaken; this is only necessary if we
  47. * are using cwRsync. We do not need to correct every path to
  48. * exec or proc_open (thank god).
  49. */
  50. function drush_correct_absolute_path_for_exec($path, $os = NULL) {
  51. if (drush_is_windows() && drush_is_absolute_path($path, "WINNT")) {
  52. if (drush_is_mingw($os)) {
  53. $path = preg_replace('/(\w):/', '/${1}', str_replace('\\', '/', $path));
  54. }
  55. elseif (drush_is_cygwin($os)) {
  56. $path = preg_replace('/(\w):/', '/cygdrive/${1}', str_replace('\\', '/', $path));
  57. }
  58. }
  59. return $path;
  60. }
  61. /**
  62. * Remove the trailing DIRECTORY_SEPARATOR from a path.
  63. * Will actually remove either / or \ on Windows.
  64. */
  65. function drush_trim_path($path, $os = NULL) {
  66. if (drush_is_windows($os)) {
  67. return rtrim($path, '/\\');
  68. }
  69. else {
  70. return rtrim($path, '/');
  71. }
  72. }
  73. /**
  74. * Makes sure the path has only path separators native for the current operating system
  75. */
  76. function drush_normalize_path($path) {
  77. if (drush_is_windows()) {
  78. $path = str_replace('/', '\\', strtolower($path));
  79. }
  80. else {
  81. $path = str_replace('\\', '/', $path);
  82. }
  83. return drush_trim_path($path);
  84. }
  85. /**
  86. * Calculates a single md5 hash for all files a directory (incuding subdirectories)
  87. */
  88. function drush_dir_md5($dir) {
  89. $flist = drush_scan_directory($dir, '/./', array('.', '..'), 0, TRUE, 'filename', 0, TRUE);
  90. $hashes = array();
  91. foreach ($flist as $f) {
  92. $sum = array();
  93. exec('cksum ' . escapeshellarg($f->filename), $sum);
  94. $hashes[] = trim(str_replace(array($dir), array(''), $sum[0]));
  95. }
  96. sort($hashes);
  97. return md5(implode("\n", $hashes));
  98. }
  99. /**
  100. * Deletes the specified file or directory and everything inside it.
  101. *
  102. * Usually respects read-only files and folders. To do a forced delete use
  103. * drush_delete_tmp_dir() or set the parameter $forced.
  104. *
  105. * @param string $dir
  106. * The file or directory to delete.
  107. * @param bool $force
  108. * Whether or not to try everything possible to delete the directory, even if
  109. * it's read-only. Defaults to FALSE.
  110. * @param bool $follow_symlinks
  111. * Whether or not to delete symlinked files. Defaults to FALSE--simply
  112. * unlinking symbolic links.
  113. *
  114. * @return bool
  115. * FALSE on failure, TRUE if everything was deleted.
  116. */
  117. function drush_delete_dir($dir, $force = FALSE, $follow_symlinks = FALSE) {
  118. // Do not delete symlinked files, only unlink symbolic links
  119. if (is_link($dir) && !$follow_symlinks) {
  120. return unlink($dir);
  121. }
  122. // Allow to delete symlinks even if the target doesn't exist.
  123. if (!is_link($dir) && !file_exists($dir)) {
  124. return TRUE;
  125. }
  126. if (!is_dir($dir)) {
  127. if ($force) {
  128. // Force deletion of items with readonly flag.
  129. @chmod($dir, 0777);
  130. }
  131. return unlink($dir);
  132. }
  133. if (drush_delete_dir_contents($dir, $force) === FALSE) {
  134. return FALSE;
  135. }
  136. if ($force) {
  137. // Force deletion of items with readonly flag.
  138. @chmod($dir, 0777);
  139. }
  140. return rmdir($dir);
  141. }
  142. /**
  143. * Deletes the contents of a directory.
  144. *
  145. * @param string $dir
  146. * The directory to delete.
  147. * @param bool $force
  148. * Whether or not to try everything possible to delete the contents, even if
  149. * they're read-only. Defaults to FALSE.
  150. *
  151. * @return bool
  152. * FALSE on failure, TRUE if everything was deleted.
  153. */
  154. function drush_delete_dir_contents($dir, $force = FALSE) {
  155. $scandir = @scandir($dir);
  156. if (!is_array($scandir)) {
  157. return FALSE;
  158. }
  159. foreach ($scandir as $item) {
  160. if ($item == '.' || $item == '..') {
  161. continue;
  162. }
  163. if ($force) {
  164. @chmod($dir, 0777);
  165. }
  166. if (!drush_delete_dir($dir . '/' . $item, $force)) {
  167. return FALSE;
  168. }
  169. }
  170. return TRUE;
  171. }
  172. /**
  173. * Deletes the provided file or folder and everything inside it.
  174. * This function explicitely tries to delete read-only files / folders.
  175. *
  176. * @param $dir
  177. * The directory to delete
  178. * @return
  179. * FALSE on failure, TRUE if everything was deleted
  180. */
  181. function drush_delete_tmp_dir($dir) {
  182. return drush_delete_dir($dir, TRUE);
  183. }
  184. /**
  185. * Copy $src to $dest.
  186. *
  187. * @param $src
  188. * The directory to copy.
  189. * @param $dest
  190. * The destination to copy the source to, including the new name of
  191. * the directory. To copy directory "a" from "/b" to "/c", then
  192. * $src = "/b/a" and $dest = "/c/a". To copy "a" to "/c" and rename
  193. * it to "d", then $dest = "/c/d".
  194. * @param $overwrite
  195. * Action to take if destination already exists.
  196. * - FILE_EXISTS_OVERWRITE - completely removes existing directory.
  197. * - FILE_EXISTS_ABORT - aborts the operation.
  198. * - FILE_EXISTS_MERGE - Leaves existing files and directories in place.
  199. * @return
  200. * TRUE on success, FALSE on failure.
  201. */
  202. function drush_copy_dir($src, $dest, $overwrite = FILE_EXISTS_ABORT) {
  203. // Preflight based on $overwrite if $dest exists.
  204. if (file_exists($dest)) {
  205. if ($overwrite === FILE_EXISTS_OVERWRITE) {
  206. drush_op('drush_delete_dir', $dest, TRUE);
  207. }
  208. elseif ($overwrite === FILE_EXISTS_ABORT) {
  209. return drush_set_error('DRUSH_DESTINATION_EXISTS', dt('Destination directory !dest already exists.', array('!dest' => $dest)));
  210. }
  211. elseif ($overwrite === FILE_EXISTS_MERGE) {
  212. // $overwrite flag may indicate we should merge instead.
  213. drush_log(dt('Merging existing !dest directory', array('!dest' => $dest)));
  214. }
  215. }
  216. // $src readable?
  217. if (!is_readable($src)) {
  218. return drush_set_error('DRUSH_SOURCE_NOT_EXISTS', dt('Source directory !src is not readable or does not exist.', array('!src' => $src)));
  219. }
  220. // $dest writable?
  221. if (!is_writable(dirname($dest))) {
  222. return drush_set_error('DRUSH_DESTINATION_NOT_WRITABLE', dt('Destination directory !dest is not writable.', array('!dest' => dirname($dest))));
  223. }
  224. // Try to do a recursive copy.
  225. if (@drush_op('_drush_recursive_copy', $src, $dest)) {
  226. return TRUE;
  227. }
  228. return drush_set_error('DRUSH_COPY_DIR_FAILURE', dt('Unable to copy !src to !dest.', array('!src' => $src, '!dest' => $dest)));
  229. }
  230. /**
  231. * Internal function called by drush_copy_dir; do not use directly.
  232. */
  233. function _drush_recursive_copy($src, $dest) {
  234. // all subdirectories and contents:
  235. if(is_dir($src)) {
  236. if (!drush_mkdir($dest, TRUE)) {
  237. return FALSE;
  238. }
  239. $dir_handle = opendir($src);
  240. while($file = readdir($dir_handle)) {
  241. if ($file != "." && $file != "..") {
  242. if (_drush_recursive_copy("$src/$file", "$dest/$file") !== TRUE) {
  243. return FALSE;
  244. }
  245. }
  246. }
  247. closedir($dir_handle);
  248. }
  249. elseif (is_link($src)) {
  250. symlink(readlink($src), $dest);
  251. }
  252. elseif (!copy($src, $dest)) {
  253. return FALSE;
  254. }
  255. // Preserve file modification time.
  256. // https://github.com/drush-ops/drush/pull/1146
  257. touch($dest, filemtime($src));
  258. // Preserve execute permission.
  259. if (!is_link($src) && !drush_is_windows()) {
  260. // Get execute bits of $src.
  261. $execperms = fileperms($src) & 0111;
  262. // Apply execute permissions if any.
  263. if ($execperms > 0) {
  264. $perms = fileperms($dest) | $execperms;
  265. chmod($dest, $perms);
  266. }
  267. }
  268. return TRUE;
  269. }
  270. /**
  271. * Move $src to $dest.
  272. *
  273. * If the php 'rename' function doesn't work, then we'll do copy & delete.
  274. *
  275. * @param $src
  276. * The directory to move.
  277. * @param $dest
  278. * The destination to move the source to, including the new name of
  279. * the directory. To move directory "a" from "/b" to "/c", then
  280. * $src = "/b/a" and $dest = "/c/a". To move "a" to "/c" and rename
  281. * it to "d", then $dest = "/c/d" (just like php rename function).
  282. * @param $overwrite
  283. * If TRUE, the destination will be deleted if it exists.
  284. * @return
  285. * TRUE on success, FALSE on failure.
  286. */
  287. function drush_move_dir($src, $dest, $overwrite = FALSE) {
  288. // Preflight based on $overwrite if $dest exists.
  289. if (file_exists($dest)) {
  290. if ($overwrite) {
  291. drush_op('drush_delete_dir', $dest, TRUE);
  292. }
  293. else {
  294. return drush_set_error('DRUSH_DESTINATION_EXISTS', dt('Destination directory !dest already exists.', array('!dest' => $dest)));
  295. }
  296. }
  297. // $src readable?
  298. if (!drush_op('is_readable', $src)) {
  299. return drush_set_error('DRUSH_SOURCE_NOT_EXISTS', dt('Source directory !src is not readable or does not exist.', array('!src' => $src)));
  300. }
  301. // $dest writable?
  302. if (!drush_op('is_writable', dirname($dest))) {
  303. return drush_set_error('DRUSH_DESTINATION_NOT_WRITABLE', dt('Destination directory !dest is not writable.', array('!dest' => dirname($dest))));
  304. }
  305. // Try rename. It will fail if $src and $dest are not in the same partition.
  306. if (@drush_op('rename', $src, $dest)) {
  307. return TRUE;
  308. }
  309. // Eventually it will create an empty file in $dest. See
  310. // http://www.php.net/manual/es/function.rename.php#90025
  311. elseif (is_file($dest)) {
  312. drush_op('unlink', $dest);
  313. }
  314. // If 'rename' fails, then we will use copy followed
  315. // by a delete of the source.
  316. if (drush_copy_dir($src, $dest)) {
  317. drush_op('drush_delete_dir', $src, TRUE);
  318. return TRUE;
  319. }
  320. return drush_set_error('DRUSH_MOVE_DIR_FAILURE', dt('Unable to move !src to !dest.', array('!src' => $src, '!dest' => $dest)));
  321. }
  322. /**
  323. * Cross-platform compatible helper function to recursively create a directory tree.
  324. *
  325. * @param path
  326. * Path to directory to create.
  327. * @param required
  328. * If TRUE, then drush_mkdir will call drush_set_error on failure.
  329. *
  330. * Callers should *always* do their own error handling after calling drush_mkdir.
  331. * If $required is FALSE, then a different location should be selected, and a final
  332. * error message should be displayed if no usable locations can be found.
  333. * @see drush_directory_cache().
  334. * If $required is TRUE, then the execution of the current command should be
  335. * halted if the required directory cannot be created.
  336. */
  337. function drush_mkdir($path, $required = TRUE) {
  338. if (!is_dir($path)) {
  339. if (drush_mkdir(dirname($path))) {
  340. if (@mkdir($path)) {
  341. return TRUE;
  342. }
  343. elseif (is_dir($path) && is_writable($path)) {
  344. // The directory was created by a concurrent process.
  345. return TRUE;
  346. }
  347. else {
  348. if (!$required) {
  349. return FALSE;
  350. }
  351. if (is_writable(dirname($path))) {
  352. return drush_set_error('DRUSH_CREATE_DIR_FAILURE', dt('Unable to create !dir.', array('!dir' => preg_replace('/\w+\/\.\.\//', '', $path))));
  353. }
  354. else {
  355. return drush_set_error('DRUSH_PARENT_NOT_WRITABLE', dt('Unable to create !newdir in !dir. Please check directory permissions.', array('!newdir' => basename($path), '!dir' => realpath(dirname($path)))));
  356. }
  357. }
  358. }
  359. return FALSE;
  360. }
  361. else {
  362. if (!is_writable($path)) {
  363. if (!$required) {
  364. return FALSE;
  365. }
  366. return drush_set_error('DRUSH_DESTINATION_NOT_WRITABLE', dt('Directory !dir exists, but is not writable. Please check directory permissions.', array('!dir' => realpath($path))));
  367. }
  368. return TRUE;
  369. }
  370. }
  371. /**
  372. * Save a string to a temporary file. Does not depend on Drupal's API.
  373. * The temporary file will be automatically deleted when drush exits.
  374. *
  375. * @param string $data
  376. * @param string $suffix
  377. * Append string to filename. use of this parameter if is discouraged. @see
  378. * drush_tempnam().
  379. * @return string
  380. * A path to the file.
  381. */
  382. function drush_save_data_to_temp_file($data, $suffix = NULL) {
  383. static $fp;
  384. $file = drush_tempnam('drush_', NULL, $suffix);
  385. $fp = fopen($file, "w");
  386. fwrite($fp, $data);
  387. $meta_data = stream_get_meta_data($fp);
  388. $file = $meta_data['uri'];
  389. fclose($fp);
  390. return $file;
  391. }
  392. /**
  393. * Returns the path to a temporary directory.
  394. *
  395. * This is a custom version of Drupal's file_directory_path().
  396. * We can't directly rely on sys_get_temp_dir() as this
  397. * path is not valid in some setups for Mac, and we want to honor
  398. * an environment variable (used by tests).
  399. */
  400. function drush_find_tmp() {
  401. static $temporary_directory;
  402. if (!isset($temporary_directory)) {
  403. $directories = array();
  404. // Get user specific and operating system temp folders from system environment variables.
  405. // See http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true
  406. $tempdir = getenv('TEMP');
  407. if (!empty($tempdir)) {
  408. $directories[] = $tempdir;
  409. }
  410. $tmpdir = getenv('TMP');
  411. if (!empty($tmpdir)) {
  412. $directories[] = $tmpdir;
  413. }
  414. // Operating system specific dirs.
  415. if (drush_is_windows()) {
  416. $windir = getenv('WINDIR');
  417. if (isset($windir)) {
  418. // WINDIR itself is not writable, but it always contains a /Temp dir,
  419. // which is the system-wide temporary directory on older versions. Newer
  420. // versions only allow system processes to use it.
  421. $directories[] = $windir . '/Temp';
  422. }
  423. }
  424. else {
  425. $directories[] = '/tmp';
  426. }
  427. $directories[] = sys_get_temp_dir();
  428. foreach ($directories as $directory) {
  429. if (is_dir($directory) && is_writable($directory)) {
  430. $temporary_directory = $directory;
  431. break;
  432. }
  433. }
  434. if (empty($temporary_directory)) {
  435. // If no directory has been found, create one in cwd.
  436. $temporary_directory = drush_cwd() . '/tmp';
  437. drush_mkdir($temporary_directory, TRUE);
  438. if (!is_dir($temporary_directory)) {
  439. return drush_set_error('DRUSH_UNABLE_TO_CREATE_TMP_DIR', dt("Unable to create a temporary directory."));
  440. }
  441. drush_register_file_for_deletion($temporary_directory);
  442. }
  443. }
  444. return $temporary_directory;
  445. }
  446. /**
  447. * Creates a temporary file, and registers it so that
  448. * it will be deleted when drush exits. Whenever possible,
  449. * drush_save_data_to_temp_file() should be used instead
  450. * of this function.
  451. *
  452. * @param string $suffix
  453. * Append this suffix to the filename. Use of this parameter is discouraged as
  454. * it can break the guarantee of tempname(). See http://www.php.net/manual/en/function.tempnam.php#42052.
  455. * Originally added to support Oracle driver.
  456. */
  457. function drush_tempnam($pattern, $tmp_dir = NULL, $suffix = '') {
  458. if ($tmp_dir == NULL) {
  459. $tmp_dir = drush_find_tmp();
  460. }
  461. $tmp_file = tempnam($tmp_dir, $pattern);
  462. drush_register_file_for_deletion($tmp_file);
  463. $tmp_file_with_suffix = $tmp_file . $suffix;
  464. drush_register_file_for_deletion($tmp_file_with_suffix);
  465. return $tmp_file_with_suffix;
  466. }
  467. /**
  468. * Creates a temporary directory and return its path.
  469. */
  470. function drush_tempdir() {
  471. $tmp_dir = drush_trim_path(drush_find_tmp());
  472. $tmp_dir .= '/' . 'drush_tmp_' . uniqid(time() . '_');
  473. drush_mkdir($tmp_dir);
  474. drush_register_file_for_deletion($tmp_dir);
  475. return $tmp_dir;
  476. }
  477. /**
  478. * Any file passed in to this function will be deleted
  479. * when drush exits.
  480. */
  481. function drush_register_file_for_deletion($file = NULL) {
  482. static $registered_files = array();
  483. if (isset($file)) {
  484. if (empty($registered_files)) {
  485. register_shutdown_function('_drush_delete_registered_files');
  486. }
  487. $registered_files[] = $file;
  488. }
  489. return $registered_files;
  490. }
  491. /**
  492. * Delete all of the registered temporary files.
  493. */
  494. function _drush_delete_registered_files() {
  495. $files_to_delete = drush_register_file_for_deletion();
  496. foreach ($files_to_delete as $file) {
  497. // We'll make sure that the file still exists, just
  498. // in case someone came along and deleted it, even
  499. // though they did not need to.
  500. if (file_exists($file)) {
  501. if (is_dir($file)) {
  502. drush_delete_dir($file, TRUE);
  503. }
  504. else {
  505. @chmod($file, 0777); // Make file writeable
  506. unlink($file);
  507. }
  508. }
  509. }
  510. }
  511. /**
  512. * Decide where our backup directory should go
  513. *
  514. * @param string $subdir
  515. * The name of the desired subdirectory(s) under drush-backups.
  516. * Usually a database name.
  517. */
  518. function drush_preflight_backup_dir($subdir = NULL) {
  519. $backup_dir = drush_get_context('DRUSH_BACKUP_DIR', drush_get_option('backup-location'));
  520. if (empty($backup_dir)) {
  521. // Try to use db name as subdir if none was provided.
  522. if (empty($subdir)) {
  523. $subdir = 'unknown';
  524. if ($sql = drush_sql_get_class()) {
  525. $db_spec = $sql->db_spec();
  526. $subdir = $db_spec['database'];
  527. }
  528. }
  529. // Save the date to be used in the backup directory's path name.
  530. $date = gmdate('YmdHis', $_SERVER['REQUEST_TIME']);
  531. $backup_dir = drush_get_option('backup-dir', drush_server_home() . '/' . 'drush-backups');
  532. $backup_dir = drush_trim_path($backup_dir) . '/' . $subdir . '/' . $date;
  533. drush_set_context('DRUSH_BACKUP_DIR', $backup_dir);
  534. }
  535. return $backup_dir;
  536. }
  537. /**
  538. * Prepare a backup directory
  539. */
  540. function drush_prepare_backup_dir($subdir = NULL) {
  541. $backup_dir = drush_preflight_backup_dir($subdir);
  542. $backup_parent = dirname($backup_dir);
  543. $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
  544. $drupal_root .= '/';
  545. if ((!empty($drupal_root)) && (strpos($backup_parent, $drupal_root) === 0)) {
  546. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('It\'s not allowed to store backups inside the Drupal root directory.'));
  547. }
  548. if (!file_exists($backup_parent)) {
  549. if (!drush_mkdir($backup_parent, TRUE)) {
  550. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Unable to create backup directory !dir.', array('!dir' => $backup_parent)));
  551. }
  552. }
  553. if (!is_writable($backup_parent)) {
  554. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Backup directory !dir is not writable.', array('!dir' => $backup_parent)));
  555. }
  556. if (!drush_mkdir($backup_dir, TRUE)) {
  557. return FALSE;
  558. }
  559. return $backup_dir;
  560. }
  561. /**
  562. * Test to see if a file exists and is not empty
  563. */
  564. function drush_file_not_empty($file_to_test) {
  565. if (file_exists($file_to_test)) {
  566. clearstatcache();
  567. $stat = stat($file_to_test);
  568. if ($stat['size'] > 0) {
  569. return TRUE;
  570. }
  571. }
  572. return FALSE;
  573. }
  574. /**
  575. * Finds all files that match a given mask in a given directory.
  576. * Directories and files beginning with a period are excluded; this
  577. * prevents hidden files and directories (such as SVN working directories
  578. * and GIT repositories) from being scanned.
  579. *
  580. * @param $dir
  581. * The base directory for the scan, without trailing slash.
  582. * @param $mask
  583. * The regular expression of the files to find.
  584. * @param $nomask
  585. * An array of files/directories to ignore.
  586. * @param $callback
  587. * The callback function to call for each match.
  588. * @param $recurse_max_depth
  589. * When TRUE, the directory scan will recurse the entire tree
  590. * starting at the provided directory. When FALSE, only files
  591. * in the provided directory are returned. Integer values
  592. * limit the depth of the traversal, with zero being treated
  593. * identically to FALSE, and 1 limiting the traversal to the
  594. * provided directory and its immediate children only, and so on.
  595. * @param $key
  596. * The key to be used for the returned array of files. Possible
  597. * values are "filename", for the path starting with $dir,
  598. * "basename", for the basename of the file, and "name" for the name
  599. * of the file without an extension.
  600. * @param $min_depth
  601. * Minimum depth of directories to return files from.
  602. * @param $include_dot_files
  603. * If TRUE, files that begin with a '.' will be returned if they
  604. * match the provided mask. If FALSE, files that begin with a '.'
  605. * will not be returned, even if they match the provided mask.
  606. * @param $depth
  607. * Current depth of recursion. This parameter is only used internally and should not be passed.
  608. *
  609. * @return
  610. * An associative array (keyed on the provided key) of objects with
  611. * "path", "basename", and "name" members corresponding to the
  612. * matching files.
  613. */
  614. function drush_scan_directory($dir, $mask, $nomask = array('.', '..', 'CVS'), $callback = 0, $recurse_max_depth = TRUE, $key = 'filename', $min_depth = 0, $include_dot_files = FALSE, $depth = 0) {
  615. $key = (in_array($key, array('filename', 'basename', 'name')) ? $key : 'filename');
  616. $files = array();
  617. if (is_string($dir) && is_dir($dir) && $handle = opendir($dir)) {
  618. while (FALSE !== ($file = readdir($handle))) {
  619. if (!in_array($file, $nomask) && (($include_dot_files && (!preg_match("/\.\+/",$file))) || ($file[0] != '.'))) {
  620. if (is_dir("$dir/$file") && (($recurse_max_depth === TRUE) || ($depth < $recurse_max_depth))) {
  621. // Give priority to files in this folder by merging them in after any subdirectory files.
  622. $files = array_merge(drush_scan_directory("$dir/$file", $mask, $nomask, $callback, $recurse_max_depth, $key, $min_depth, $include_dot_files, $depth + 1), $files);
  623. }
  624. elseif ($depth >= $min_depth && preg_match($mask, $file)) {
  625. // Always use this match over anything already set in $files with the same $$key.
  626. $filename = "$dir/$file";
  627. $basename = basename($file);
  628. $name = substr($basename, 0, strrpos($basename, '.'));
  629. $files[$$key] = new stdClass();
  630. $files[$$key]->filename = $filename;
  631. $files[$$key]->basename = $basename;
  632. $files[$$key]->name = $name;
  633. if ($callback) {
  634. drush_op($callback, $filename);
  635. }
  636. }
  637. }
  638. }
  639. closedir($handle);
  640. }
  641. return $files;
  642. }
  643. /**
  644. * Simple helper function to append data to a given file.
  645. *
  646. * @param string $file
  647. * The full path to the file to append the data to.
  648. * @param string $data
  649. * The data to append.
  650. *
  651. * @return boolean
  652. * TRUE on success, FALSE in case of failure to open or write to the file.
  653. */
  654. function drush_file_append_data($file, $data) {
  655. if (!$fd = fopen($file, 'a+')) {
  656. drush_set_error(dt("ERROR: fopen(@file, 'ab') failed", array('@file' => $file)));
  657. return FALSE;
  658. }
  659. if (!fwrite($fd, $data)) {
  660. drush_set_error(dt("ERROR: fwrite(@file) failed", array('@file' => $file)) . '<pre>' . $data);
  661. return FALSE;
  662. }
  663. return TRUE;
  664. }
  665. /**
  666. * @} End of "defgroup filesystemfunctions".
  667. */