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) && touch($dest, filemtime($src)))) {
  253. return FALSE;
  254. }
  255. // Preserve execute permission.
  256. if (!is_link($src) && !drush_is_windows()) {
  257. // Get execute bits of $src.
  258. $execperms = fileperms($src) & 0111;
  259. // Apply execute permissions if any.
  260. if ($execperms > 0) {
  261. $perms = fileperms($dest) | $execperms;
  262. chmod($dest, $perms);
  263. }
  264. }
  265. return TRUE;
  266. }
  267. /**
  268. * Move $src to $dest.
  269. *
  270. * If the php 'rename' function doesn't work, then we'll do copy & delete.
  271. *
  272. * @param $src
  273. * The directory to move.
  274. * @param $dest
  275. * The destination to move the source to, including the new name of
  276. * the directory. To move directory "a" from "/b" to "/c", then
  277. * $src = "/b/a" and $dest = "/c/a". To move "a" to "/c" and rename
  278. * it to "d", then $dest = "/c/d" (just like php rename function).
  279. * @param $overwrite
  280. * If TRUE, the destination will be deleted if it exists.
  281. * @return
  282. * TRUE on success, FALSE on failure.
  283. */
  284. function drush_move_dir($src, $dest, $overwrite = FALSE) {
  285. // Preflight based on $overwrite if $dest exists.
  286. if (file_exists($dest)) {
  287. if ($overwrite) {
  288. drush_op('drush_delete_dir', $dest, TRUE);
  289. }
  290. else {
  291. return drush_set_error('DRUSH_DESTINATION_EXISTS', dt('Destination directory !dest already exists.', array('!dest' => $dest)));
  292. }
  293. }
  294. // $src readable?
  295. if (!drush_op('is_readable', $src)) {
  296. return drush_set_error('DRUSH_SOURCE_NOT_EXISTS', dt('Source directory !src is not readable or does not exist.', array('!src' => $src)));
  297. }
  298. // $dest writable?
  299. if (!drush_op('is_writable', dirname($dest))) {
  300. return drush_set_error('DRUSH_DESTINATION_NOT_WRITABLE', dt('Destination directory !dest is not writable.', array('!dest' => dirname($dest))));
  301. }
  302. // Try rename. It will fail if $src and $dest are not in the same partition.
  303. if (@drush_op('rename', $src, $dest)) {
  304. return TRUE;
  305. }
  306. // Eventually it will create an empty file in $dest. See
  307. // http://www.php.net/manual/es/function.rename.php#90025
  308. elseif (is_file($dest)) {
  309. drush_op('unlink', $dest);
  310. }
  311. // If 'rename' fails, then we will use copy followed
  312. // by a delete of the source.
  313. if (drush_copy_dir($src, $dest)) {
  314. drush_op('drush_delete_dir', $src, TRUE);
  315. return TRUE;
  316. }
  317. return drush_set_error('DRUSH_MOVE_DIR_FAILURE', dt('Unable to move !src to !dest.', array('!src' => $src, '!dest' => $dest)));
  318. }
  319. /**
  320. * Cross-platform compatible helper function to recursively create a directory tree.
  321. *
  322. * @param path
  323. * Path to directory to create.
  324. * @param required
  325. * If TRUE, then drush_mkdir will call drush_set_error on failure.
  326. *
  327. * Callers should *always* do their own error handling after calling drush_mkdir.
  328. * If $required is FALSE, then a different location should be selected, and a final
  329. * error message should be displayed if no usable locations can be found.
  330. * @see drush_directory_cache().
  331. * If $required is TRUE, then the execution of the current command should be
  332. * halted if the required directory cannot be created.
  333. */
  334. function drush_mkdir($path, $required = TRUE) {
  335. if (!is_dir($path)) {
  336. if (drush_mkdir(dirname($path))) {
  337. if (@mkdir($path)) {
  338. return TRUE;
  339. }
  340. elseif (is_dir($path) && is_writable($path)) {
  341. // The directory was created by a concurrent process.
  342. return TRUE;
  343. }
  344. else {
  345. if (!$required) {
  346. return FALSE;
  347. }
  348. if (is_writable(dirname($path))) {
  349. return drush_set_error('DRUSH_CREATE_DIR_FAILURE', dt('Unable to create !dir.', array('!dir' => preg_replace('/\w+\/\.\.\//', '', $path))));
  350. }
  351. else {
  352. 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)))));
  353. }
  354. }
  355. }
  356. return FALSE;
  357. }
  358. else {
  359. if (!is_writable($path)) {
  360. if (!$required) {
  361. return FALSE;
  362. }
  363. return drush_set_error('DRUSH_DESTINATION_NOT_WRITABLE', dt('Directory !dir exists, but is not writable. Please check directory permissions.', array('!dir' => realpath($path))));
  364. }
  365. return TRUE;
  366. }
  367. }
  368. /**
  369. * Save a string to a temporary file. Does not depend on Drupal's API.
  370. * The temporary file will be automatically deleted when drush exits.
  371. *
  372. * @param string $data
  373. * @param string $suffix
  374. * Append string to filename. use of this parameter if is discouraged. @see
  375. * drush_tempnam().
  376. * @return string
  377. * A path to the file.
  378. */
  379. function drush_save_data_to_temp_file($data, $suffix = NULL) {
  380. static $fp;
  381. $file = drush_tempnam('drush_', NULL, $suffix);
  382. $fp = fopen($file, "w");
  383. fwrite($fp, $data);
  384. $meta_data = stream_get_meta_data($fp);
  385. $file = $meta_data['uri'];
  386. fclose($fp);
  387. return $file;
  388. }
  389. /**
  390. * Returns the path to a temporary directory.
  391. *
  392. * This is a custom version of Drupal's file_directory_path().
  393. * We can't directly rely on sys_get_temp_dir() as this
  394. * path is not valid in some setups for Mac, and we want to honor
  395. * an environment variable (used by tests).
  396. */
  397. function drush_find_tmp() {
  398. static $temporary_directory;
  399. if (!isset($temporary_directory)) {
  400. $directories = array();
  401. // Get user specific and operating system temp folders from system environment variables.
  402. // See http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true
  403. $tempdir = getenv('TEMP');
  404. if (!empty($tempdir)) {
  405. $directories[] = $tempdir;
  406. }
  407. $tmpdir = getenv('TMP');
  408. if (!empty($tmpdir)) {
  409. $directories[] = $tmpdir;
  410. }
  411. // Operating system specific dirs.
  412. if (drush_is_windows()) {
  413. $windir = getenv('WINDIR');
  414. if (isset($windir)) {
  415. // WINDIR itself is not writable, but it always contains a /Temp dir,
  416. // which is the system-wide temporary directory on older versions. Newer
  417. // versions only allow system processes to use it.
  418. $directories[] = $windir . '/Temp';
  419. }
  420. }
  421. else {
  422. $directories[] = '/tmp';
  423. }
  424. $directories[] = sys_get_temp_dir();
  425. foreach ($directories as $directory) {
  426. if (is_dir($directory) && is_writable($directory)) {
  427. $temporary_directory = $directory;
  428. break;
  429. }
  430. }
  431. if (empty($temporary_directory)) {
  432. // If no directory has been found, create one in cwd.
  433. $temporary_directory = drush_cwd() . '/tmp';
  434. drush_mkdir($temporary_directory, TRUE);
  435. if (!is_dir($temporary_directory)) {
  436. return drush_set_error('DRUSH_UNABLE_TO_CREATE_TMP_DIR', dt("Unable to create a temporary directory."));
  437. }
  438. drush_register_file_for_deletion($temporary_directory);
  439. }
  440. }
  441. return $temporary_directory;
  442. }
  443. /**
  444. * Creates a temporary file, and registers it so that
  445. * it will be deleted when drush exits. Whenever possible,
  446. * drush_save_data_to_temp_file() should be used instead
  447. * of this function.
  448. *
  449. * @param string suffix
  450. * Append this suffix to the filename. Use of this parameter is discouraged as
  451. * it can break the guarantee of tempname(). See http://www.php.net/manual/en/function.tempnam.php#42052.
  452. * Originally added to support Oracle driver.
  453. */
  454. function drush_tempnam($pattern, $tmp_dir = NULL, $suffix = '') {
  455. if ($tmp_dir == NULL) {
  456. $tmp_dir = drush_find_tmp();
  457. }
  458. $tmp_file = tempnam($tmp_dir, $pattern);
  459. drush_register_file_for_deletion($tmp_file);
  460. $tmp_file_with_suffix = $tmp_file . $suffix;
  461. drush_register_file_for_deletion($tmp_file_with_suffix);
  462. return $tmp_file . $suffix;
  463. }
  464. /**
  465. * Creates a temporary directory and return its path.
  466. */
  467. function drush_tempdir() {
  468. $tmp_dir = drush_trim_path(drush_find_tmp());
  469. $tmp_dir .= '/' . 'drush_tmp_' . uniqid(time() . '_');
  470. drush_mkdir($tmp_dir);
  471. drush_register_file_for_deletion($tmp_dir);
  472. return $tmp_dir;
  473. }
  474. /**
  475. * Any file passed in to this function will be deleted
  476. * when drush exits.
  477. */
  478. function drush_register_file_for_deletion($file = NULL) {
  479. static $registered_files = array();
  480. if (isset($file)) {
  481. if (empty($registered_files)) {
  482. register_shutdown_function('_drush_delete_registered_files');
  483. }
  484. $registered_files[] = $file;
  485. }
  486. return $registered_files;
  487. }
  488. /**
  489. * Delete all of the registered temporary files.
  490. */
  491. function _drush_delete_registered_files() {
  492. $files_to_delete = drush_register_file_for_deletion();
  493. foreach ($files_to_delete as $file) {
  494. // We'll make sure that the file still exists, just
  495. // in case someone came along and deleted it, even
  496. // though they did not need to.
  497. if (file_exists($file)) {
  498. if (is_dir($file)) {
  499. drush_delete_dir($file, TRUE);
  500. }
  501. else {
  502. @chmod($dir, 0777); // Make file writeable
  503. unlink($file);
  504. }
  505. }
  506. }
  507. }
  508. /**
  509. * Decide where our backup directory should go
  510. *
  511. * @param string $subdir
  512. * The name of the desired subdirectory(s) under drush-backups.
  513. * Usually a database name.
  514. */
  515. function drush_preflight_backup_dir($subdir = NULL) {
  516. $backup_dir = drush_get_context('DRUSH_BACKUP_DIR', drush_get_option('backup-location'));
  517. if (empty($backup_dir)) {
  518. // Try to use db name as subdir if none was provided.
  519. if (empty($subdir)) {
  520. $subdir = 'unknown';
  521. if ($creds = drush_get_context('DRUSH_DB_CREDENTIALS')) {
  522. $subdir = $creds['name'];
  523. }
  524. }
  525. // Save the date to be used in the backup directory's path name.
  526. $date = gmdate('YmdHis', $_SERVER['REQUEST_TIME']);
  527. $backup_dir = drush_get_option('backup-dir', drush_server_home() . '/' . 'drush-backups');
  528. $backup_dir = drush_trim_path($backup_dir) . '/' . $subdir . '/' . $date;
  529. drush_set_context('DRUSH_BACKUP_DIR', $backup_dir);
  530. }
  531. return $backup_dir;
  532. }
  533. /**
  534. * Prepare a backup directory
  535. */
  536. function drush_prepare_backup_dir($subdir = NULL) {
  537. $backup_dir = drush_preflight_backup_dir($subdir);
  538. $backup_parent = dirname($backup_dir);
  539. $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
  540. $drupal_root .= '/';
  541. if ((!empty($drupal_root)) && (strpos($backup_parent, $drupal_root) === 0)) {
  542. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('It\'s not allowed to store backups inside the Drupal root directory.'));
  543. }
  544. if (!file_exists($backup_parent)) {
  545. if (!drush_mkdir($backup_parent, TRUE)) {
  546. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Unable to create backup directory !dir.', array('!dir' => $backup_parent)));
  547. }
  548. }
  549. if (!is_writable($backup_parent)) {
  550. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Backup directory !dir is not writable.', array('!dir' => $backup_parent)));
  551. }
  552. if (!drush_mkdir($backup_dir, TRUE)) {
  553. return FALSE;
  554. }
  555. return $backup_dir;
  556. }
  557. /**
  558. * Test to see if a file exists and is not empty
  559. */
  560. function drush_file_not_empty($file_to_test) {
  561. if (file_exists($file_to_test)) {
  562. clearstatcache();
  563. $stat = stat($file_to_test);
  564. if ($stat['size'] > 0) {
  565. return TRUE;
  566. }
  567. }
  568. return FALSE;
  569. }
  570. /**
  571. * Finds all files that match a given mask in a given directory.
  572. * Directories and files beginning with a period are excluded; this
  573. * prevents hidden files and directories (such as SVN working directories
  574. * and GIT repositories) from being scanned.
  575. *
  576. * @param $dir
  577. * The base directory for the scan, without trailing slash.
  578. * @param $mask
  579. * The regular expression of the files to find.
  580. * @param $nomask
  581. * An array of files/directories to ignore.
  582. * @param $callback
  583. * The callback function to call for each match.
  584. * @param $recurse_max_depth
  585. * When TRUE, the directory scan will recurse the entire tree
  586. * starting at the provided directory. When FALSE, only files
  587. * in the provided directory are returned. Integer values
  588. * limit the depth of the traversal, with zero being treated
  589. * identically to FALSE, and 1 limiting the traversal to the
  590. * provided directory and its immediate children only, and so on.
  591. * @param $key
  592. * The key to be used for the returned array of files. Possible
  593. * values are "filename", for the path starting with $dir,
  594. * "basename", for the basename of the file, and "name" for the name
  595. * of the file without an extension.
  596. * @param $min_depth
  597. * Minimum depth of directories to return files from.
  598. * @param $include_dot_files
  599. * If TRUE, files that begin with a '.' will be returned if they
  600. * match the provided mask. If FALSE, files that begin with a '.'
  601. * will not be returned, even if they match the provided mask.
  602. * @param $depth
  603. * Current depth of recursion. This parameter is only used internally and should not be passed.
  604. *
  605. * @return
  606. * An associative array (keyed on the provided key) of objects with
  607. * "path", "basename", and "name" members corresponding to the
  608. * matching files.
  609. */
  610. 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) {
  611. $key = (in_array($key, array('filename', 'basename', 'name')) ? $key : 'filename');
  612. $files = array();
  613. if (is_string($dir) && is_dir($dir) && $handle = opendir($dir)) {
  614. while (FALSE !== ($file = readdir($handle))) {
  615. if (!in_array($file, $nomask) && (($include_dot_files && (!preg_match("/\.\+/",$file))) || ($file[0] != '.'))) {
  616. if (is_dir("$dir/$file") && (($recurse_max_depth === TRUE) || ($depth < $recurse_max_depth))) {
  617. // Give priority to files in this folder by merging them in after any subdirectory files.
  618. $files = array_merge(drush_scan_directory("$dir/$file", $mask, $nomask, $callback, $recurse_max_depth, $key, $min_depth, $include_dot_files, $depth + 1), $files);
  619. }
  620. elseif ($depth >= $min_depth && preg_match($mask, $file)) {
  621. // Always use this match over anything already set in $files with the same $$key.
  622. $filename = "$dir/$file";
  623. $basename = basename($file);
  624. $name = substr($basename, 0, strrpos($basename, '.'));
  625. $files[$$key] = new stdClass();
  626. $files[$$key]->filename = $filename;
  627. $files[$$key]->basename = $basename;
  628. $files[$$key]->name = $name;
  629. if ($callback) {
  630. drush_op($callback, $filename);
  631. }
  632. }
  633. }
  634. }
  635. closedir($handle);
  636. }
  637. return $files;
  638. }
  639. /**
  640. * Simple helper function to append data to a given file.
  641. *
  642. * @param string $file
  643. * The full path to the file to append the data to.
  644. * @param string $data
  645. * The data to append.
  646. *
  647. * @return boolean
  648. * TRUE on success, FALSE in case of failure to open or write to the file.
  649. */
  650. function drush_file_append_data($file, $data) {
  651. if (!$fd = fopen($file, 'a+')) {
  652. drush_set_error(dt("ERROR: fopen(@file, 'ab') failed", array('@file' => $file)));
  653. return FALSE;
  654. }
  655. if (!fwrite($fd, $data)) {
  656. drush_set_error(dt("ERROR: fwrite(@file) failed", array('@file' => $file)) . '<pre>' . $data);
  657. return FALSE;
  658. }
  659. return TRUE;
  660. }
  661. /**
  662. * @} End of "defgroup filesystemfunctions".
  663. */