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_is_nested_directory Return 'TRUE' if one directory is located anywhere inside the other.
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_program_exists
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. * Determine if program exists on user's PATH.
  373. *
  374. * @return bool
  375. */
  376. function drush_program_exists($program) {
  377. $bucket = drush_bit_bucket();
  378. return drush_op_system("command -v $program >$bucket 2>&1") === 0 ? TRUE : FALSE;
  379. }
  380. /**
  381. * Save a string to a temporary file. Does not depend on Drupal's API.
  382. * The temporary file will be automatically deleted when drush exits.
  383. *
  384. * @param string $data
  385. * @param string $suffix
  386. * Append string to filename. use of this parameter if is discouraged. @see
  387. * drush_tempnam().
  388. * @return string
  389. * A path to the file.
  390. */
  391. function drush_save_data_to_temp_file($data, $suffix = NULL) {
  392. static $fp;
  393. $file = drush_tempnam('drush_', NULL, $suffix);
  394. $fp = fopen($file, "w");
  395. fwrite($fp, $data);
  396. $meta_data = stream_get_meta_data($fp);
  397. $file = $meta_data['uri'];
  398. fclose($fp);
  399. return $file;
  400. }
  401. /**
  402. * Returns the path to a temporary directory.
  403. *
  404. * This is a custom version of Drupal's file_directory_path().
  405. * We can't directly rely on sys_get_temp_dir() as this
  406. * path is not valid in some setups for Mac, and we want to honor
  407. * an environment variable (used by tests).
  408. */
  409. function drush_find_tmp() {
  410. static $temporary_directory;
  411. if (!isset($temporary_directory)) {
  412. $directories = array();
  413. // Get user specific and operating system temp folders from system environment variables.
  414. // See http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true
  415. $tempdir = getenv('TEMP');
  416. if (!empty($tempdir)) {
  417. $directories[] = $tempdir;
  418. }
  419. $tmpdir = getenv('TMP');
  420. if (!empty($tmpdir)) {
  421. $directories[] = $tmpdir;
  422. }
  423. // Operating system specific dirs.
  424. if (drush_is_windows()) {
  425. $windir = getenv('WINDIR');
  426. if (isset($windir)) {
  427. // WINDIR itself is not writable, but it always contains a /Temp dir,
  428. // which is the system-wide temporary directory on older versions. Newer
  429. // versions only allow system processes to use it.
  430. $directories[] = $windir . '/Temp';
  431. }
  432. }
  433. else {
  434. $directories[] = '/tmp';
  435. }
  436. $directories[] = sys_get_temp_dir();
  437. foreach ($directories as $directory) {
  438. if (is_dir($directory) && is_writable($directory)) {
  439. $temporary_directory = $directory;
  440. break;
  441. }
  442. }
  443. if (empty($temporary_directory)) {
  444. // If no directory has been found, create one in cwd.
  445. $temporary_directory = drush_cwd() . '/tmp';
  446. drush_mkdir($temporary_directory, TRUE);
  447. if (!is_dir($temporary_directory)) {
  448. return drush_set_error('DRUSH_UNABLE_TO_CREATE_TMP_DIR', dt("Unable to create a temporary directory."));
  449. }
  450. drush_register_file_for_deletion($temporary_directory);
  451. }
  452. }
  453. return $temporary_directory;
  454. }
  455. /**
  456. * Creates a temporary file, and registers it so that
  457. * it will be deleted when drush exits. Whenever possible,
  458. * drush_save_data_to_temp_file() should be used instead
  459. * of this function.
  460. *
  461. * @param string $suffix
  462. * Append this suffix to the filename. Use of this parameter is discouraged as
  463. * it can break the guarantee of tempname(). See http://www.php.net/manual/en/function.tempnam.php#42052.
  464. * Originally added to support Oracle driver.
  465. */
  466. function drush_tempnam($pattern, $tmp_dir = NULL, $suffix = '') {
  467. if ($tmp_dir == NULL) {
  468. $tmp_dir = drush_find_tmp();
  469. }
  470. $tmp_file = tempnam($tmp_dir, $pattern);
  471. drush_register_file_for_deletion($tmp_file);
  472. $tmp_file_with_suffix = $tmp_file . $suffix;
  473. drush_register_file_for_deletion($tmp_file_with_suffix);
  474. return $tmp_file_with_suffix;
  475. }
  476. /**
  477. * Creates a temporary directory and return its path.
  478. */
  479. function drush_tempdir() {
  480. $tmp_dir = drush_trim_path(drush_find_tmp());
  481. $tmp_dir .= '/' . 'drush_tmp_' . uniqid(time() . '_');
  482. drush_mkdir($tmp_dir);
  483. drush_register_file_for_deletion($tmp_dir);
  484. return $tmp_dir;
  485. }
  486. /**
  487. * Any file passed in to this function will be deleted
  488. * when drush exits.
  489. */
  490. function drush_register_file_for_deletion($file = NULL) {
  491. static $registered_files = array();
  492. if (isset($file)) {
  493. if (empty($registered_files)) {
  494. register_shutdown_function('_drush_delete_registered_files');
  495. }
  496. $registered_files[] = $file;
  497. }
  498. return $registered_files;
  499. }
  500. /**
  501. * Delete all of the registered temporary files.
  502. */
  503. function _drush_delete_registered_files() {
  504. $files_to_delete = drush_register_file_for_deletion();
  505. foreach ($files_to_delete as $file) {
  506. // We'll make sure that the file still exists, just
  507. // in case someone came along and deleted it, even
  508. // though they did not need to.
  509. if (file_exists($file)) {
  510. if (is_dir($file)) {
  511. drush_delete_dir($file, TRUE);
  512. }
  513. else {
  514. @chmod($file, 0777); // Make file writeable
  515. unlink($file);
  516. }
  517. }
  518. }
  519. }
  520. /**
  521. * Decide where our backup directory should go
  522. *
  523. * @param string $subdir
  524. * The name of the desired subdirectory(s) under drush-backups.
  525. * Usually a database name.
  526. */
  527. function drush_preflight_backup_dir($subdir = NULL) {
  528. $backup_dir = drush_get_context('DRUSH_BACKUP_DIR', drush_get_option('backup-location'));
  529. if (empty($backup_dir)) {
  530. // Try to use db name as subdir if none was provided.
  531. if (empty($subdir)) {
  532. $subdir = 'unknown';
  533. if ($sql = drush_sql_get_class()) {
  534. $db_spec = $sql->db_spec();
  535. $subdir = $db_spec['database'];
  536. }
  537. }
  538. // Save the date to be used in the backup directory's path name.
  539. $date = gmdate('YmdHis', $_SERVER['REQUEST_TIME']);
  540. $backup_dir = drush_get_option('backup-dir', drush_server_home() . '/' . 'drush-backups');
  541. $backup_dir = drush_trim_path($backup_dir) . '/' . $subdir . '/' . $date;
  542. drush_set_context('DRUSH_BACKUP_DIR', $backup_dir);
  543. }
  544. return $backup_dir;
  545. }
  546. /**
  547. * Prepare a backup directory
  548. */
  549. function drush_prepare_backup_dir($subdir = NULL) {
  550. $backup_dir = drush_preflight_backup_dir($subdir);
  551. $backup_parent = dirname($backup_dir);
  552. $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
  553. $drupal_root .= '/';
  554. if ((!empty($drupal_root)) && (strpos($backup_parent, $drupal_root) === 0)) {
  555. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('It\'s not allowed to store backups inside the Drupal root directory.'));
  556. }
  557. if (!file_exists($backup_parent)) {
  558. if (!drush_mkdir($backup_parent, TRUE)) {
  559. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Unable to create backup directory !dir.', array('!dir' => $backup_parent)));
  560. }
  561. }
  562. if (!is_writable($backup_parent)) {
  563. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Backup directory !dir is not writable.', array('!dir' => $backup_parent)));
  564. }
  565. if (!drush_mkdir($backup_dir, TRUE)) {
  566. return FALSE;
  567. }
  568. return $backup_dir;
  569. }
  570. /**
  571. * Test to see if a file exists and is not empty
  572. */
  573. function drush_file_not_empty($file_to_test) {
  574. if (file_exists($file_to_test)) {
  575. clearstatcache();
  576. $stat = stat($file_to_test);
  577. if ($stat['size'] > 0) {
  578. return TRUE;
  579. }
  580. }
  581. return FALSE;
  582. }
  583. /**
  584. * Finds all files that match a given mask in a given directory.
  585. * Directories and files beginning with a period are excluded; this
  586. * prevents hidden files and directories (such as SVN working directories
  587. * and GIT repositories) from being scanned.
  588. *
  589. * @param $dir
  590. * The base directory for the scan, without trailing slash.
  591. * @param $mask
  592. * The regular expression of the files to find.
  593. * @param $nomask
  594. * An array of files/directories to ignore.
  595. * @param $callback
  596. * The callback function to call for each match.
  597. * @param $recurse_max_depth
  598. * When TRUE, the directory scan will recurse the entire tree
  599. * starting at the provided directory. When FALSE, only files
  600. * in the provided directory are returned. Integer values
  601. * limit the depth of the traversal, with zero being treated
  602. * identically to FALSE, and 1 limiting the traversal to the
  603. * provided directory and its immediate children only, and so on.
  604. * @param $key
  605. * The key to be used for the returned array of files. Possible
  606. * values are "filename", for the path starting with $dir,
  607. * "basename", for the basename of the file, and "name" for the name
  608. * of the file without an extension.
  609. * @param $min_depth
  610. * Minimum depth of directories to return files from.
  611. * @param $include_dot_files
  612. * If TRUE, files that begin with a '.' will be returned if they
  613. * match the provided mask. If FALSE, files that begin with a '.'
  614. * will not be returned, even if they match the provided mask.
  615. * @param $depth
  616. * Current depth of recursion. This parameter is only used internally and should not be passed.
  617. *
  618. * @return
  619. * An associative array (keyed on the provided key) of objects with
  620. * "path", "basename", and "name" members corresponding to the
  621. * matching files.
  622. */
  623. 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) {
  624. $key = (in_array($key, array('filename', 'basename', 'name')) ? $key : 'filename');
  625. $files = array();
  626. if (is_string($dir) && is_dir($dir) && $handle = opendir($dir)) {
  627. while (FALSE !== ($file = readdir($handle))) {
  628. if (!in_array($file, $nomask) && (($include_dot_files && (!preg_match("/\.\+/",$file))) || ($file[0] != '.'))) {
  629. if (is_dir("$dir/$file") && (($recurse_max_depth === TRUE) || ($depth < $recurse_max_depth))) {
  630. // Give priority to files in this folder by merging them in after any subdirectory files.
  631. $files = array_merge(drush_scan_directory("$dir/$file", $mask, $nomask, $callback, $recurse_max_depth, $key, $min_depth, $include_dot_files, $depth + 1), $files);
  632. }
  633. elseif ($depth >= $min_depth && preg_match($mask, $file)) {
  634. // Always use this match over anything already set in $files with the same $$key.
  635. $filename = "$dir/$file";
  636. $basename = basename($file);
  637. $name = substr($basename, 0, strrpos($basename, '.'));
  638. $files[$$key] = new stdClass();
  639. $files[$$key]->filename = $filename;
  640. $files[$$key]->basename = $basename;
  641. $files[$$key]->name = $name;
  642. if ($callback) {
  643. drush_op($callback, $filename);
  644. }
  645. }
  646. }
  647. }
  648. closedir($handle);
  649. }
  650. return $files;
  651. }
  652. /**
  653. * Simple helper function to append data to a given file.
  654. *
  655. * @param string $file
  656. * The full path to the file to append the data to.
  657. * @param string $data
  658. * The data to append.
  659. *
  660. * @return boolean
  661. * TRUE on success, FALSE in case of failure to open or write to the file.
  662. */
  663. function drush_file_append_data($file, $data) {
  664. if (!$fd = fopen($file, 'a+')) {
  665. drush_set_error(dt("ERROR: fopen(@file, 'ab') failed", array('@file' => $file)));
  666. return FALSE;
  667. }
  668. if (!fwrite($fd, $data)) {
  669. drush_set_error(dt("ERROR: fwrite(@file) failed", array('@file' => $file)) . '<pre>' . $data);
  670. return FALSE;
  671. }
  672. return TRUE;
  673. }
  674. /**
  675. * Return 'TRUE' if one directory is located anywhere inside
  676. * the other.
  677. */
  678. function drush_is_nested_directory($base_dir, $test_is_nested) {
  679. // Ensure there is always exactly one '/' at the end of $base_dir
  680. $base_dir = rtrim($base_dir, '/') . '/';
  681. return substr($test_is_nested, 0, strlen($base_dir)) == $base_dir;
  682. }
  683. /**
  684. * @} End of "defgroup filesystemfunctions".
  685. */