mass-rename.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. // Copyright (c) 2020 DBMXPCA Technologies. All rights reserved.
  3. // www.dbmxpca.com
  4. // Date Created: May 18, 2020
  5. // Last Updated: May 19, 2020
  6. // Version: 1.03
  7. // ====================================================================================
  8. // --- SETTINGS --- SETTINGS --- SETTINGS --- SETTINGS --- SETTINGS --- SETTINGS ---
  9. // ====================================================================================
  10. // If true, the script will search for all possible occurrences of itself
  11. // and remove it from the directory traversal so as to prevent any alter-
  12. // ations to the script itself. This can be useful but for larger dir-
  13. // ectory traversals can consume a significant amount of time. It is rec-
  14. // ommended that this is enabled only for small datasets or if time is
  15. // not of significant concern.
  16. $remove_self = false;
  17. // If true, the script will show a preview of all discovered files and dir-
  18. // ectories. See the setting "$max_preview_size" for maximum preview results.
  19. $enable_dir_scan_preview = true;
  20. // If true, the script will spew the full command immediately prior to its
  21. // execution during the final renaming process.
  22. $display_full_cmd = true;
  23. // If true, the script will spew the progress during the rename operation.
  24. $display_progress = true;
  25. // If true, directories will be skipped and thus will not be renamed.
  26. $skip_directories = true;
  27. // Maximum results per preview.
  28. $max_preview_size = 100;
  29. // Number of characters to limit the full path & file command preview. This
  30. // must be a negative number in order to display the last N characters.
  31. $cmd_display_limit = -32;
  32. // ====================================================================================
  33. // +++++++++++ DO NOT EDIT BEYOND THIS POINT +++++++++++ DO NOT EDIT BEYOND THIS POINT
  34. // ====================================================================================
  35. $dirToTraverse = -1;
  36. $regex_search = "";
  37. $replace_str = "";
  38. $thisFile = __DIR__ . "/" . $argv[0];
  39. function GET_DIR_CONTENTS($dir, &$results = array()) {
  40. $files = scandir($dir);
  41. foreach ($files as $key => $value) {
  42. $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
  43. if (!is_dir($path)) {
  44. $results[] = $path;
  45. } else if ($value != "." && $value != "..") {
  46. GET_DIR_CONTENTS($path, $results);
  47. $results[] = $path;
  48. }
  49. }
  50. return $results;
  51. }
  52. function ECHO_USAGE(){
  53. global $argv;
  54. echo "\n > Usage:\n";
  55. echo " \"php " . $argv[0] . " <t-dir> <search-regex> <replace-str>\"\n";
  56. echo " where <t-dir> is the directory to traverse and\n";
  57. echo " <search-regex> is the regular expression to\n";
  58. echo " search for, and <replace-str> is the raw string\n";
  59. echo " to replace the search-regex with. Note that\n";
  60. echo " <replace-str> is NOT a regular expression.\n";
  61. echo " If <replace-str> contains one or more whitespace\n";
  62. echo " character(s), it must be enclosed within double-\n";
  63. echo " quotation marks.\n";
  64. echo "\n > Examples:\n";
  65. echo " > \"php " . $argv[0] . " . /.[a-z]+/ .jpg\"\n";
  66. echo " > \"php " . $argv[0] . " . /.[a-zA-Z]+/ .jpg\"\n";
  67. echo " > \"php " . $argv[0] . " . /.[a-zA-Z0-9]+/ \".jpg\"\"\n";
  68. }
  69. // @BRIEF Replace $search with $replace in $str. This performs a simple replace using PHP's str_replace().
  70. function REPLACE($str, $search, $replace){
  71. return str_replace($search, $replace, $str);
  72. }
  73. // @BRIEF Replace $search with $replace in $str. This expects a regular expression for $search and uses PHP's preg_replace().
  74. function REPLACE2($str, $search, $replace){
  75. return preg_replace($search, $replace, $str);
  76. }
  77. // Returns true if both strings are the same. Performs a case-insensitive comparison unless third parameter is true.
  78. function ARE_STRINGS_EQUAL($str1, $str2, $case_sensitive = false){
  79. switch($case_sensitive){
  80. case true:
  81. if (strcmp($str1, $str2) == 0){
  82. return true;
  83. }
  84. else{
  85. return false;
  86. }
  87. break;
  88. default:
  89. if (strcasecmp($str1, $str2) == 0){
  90. return true;
  91. }
  92. else{
  93. return false;
  94. }
  95. break;
  96. }
  97. return false;
  98. }
  99. // ======================================================================
  100. if (isset($argv[1])){
  101. $dirToTraverse = $argv[1];
  102. echo " > Check passed; Traversal Directory = [" . $dirToTraverse . "]\n";
  103. }
  104. else{
  105. echo " > Check FAILED; Missing Traversal Directory!\n";
  106. ECHO_USAGE();
  107. echo "\n > Script terminated.\n";
  108. exit(1);
  109. }
  110. if (isset($argv[2])){
  111. $regex_search = $argv[2];
  112. echo " > Check passed; Search RegEx = \"" . $regex_search . "\"\n";
  113. }
  114. else{
  115. echo " > Check FAILED; Missing Search RegEx!\n";
  116. ECHO_USAGE();
  117. echo "\n > Script terminated.\n";
  118. exit(1);
  119. }
  120. if (isset($argv[3])){
  121. $replace_str = $argv[3];
  122. echo " > Check passed; Replacement String = \"" . $replace_str . "\"\n";
  123. }
  124. else{
  125. echo " > Check FAILED; Missing Search RegEx!\n";
  126. ECHO_USAGE();
  127. echo "\n > Script terminated.\n";
  128. exit(1);
  129. }
  130. echo " > Performing initial directory traversal, please wait...\n";
  131. $contents = array();
  132. GET_DIR_CONTENTS($dirToTraverse, $contents);
  133. if ($remove_self){
  134. while( ($found = array_search($thisFile, $contents)) !== false ){
  135. echo " > Removing this script from file listing.\n";
  136. unset($contents[$found]);
  137. }
  138. }
  139. // var_dump($contents);
  140. echo " > Initial directory traversal complete.\n";
  141. $counter = 0;
  142. $stop_preview = false;
  143. if ($enable_dir_scan_preview){
  144. echo " > ORIGINAL FILE AND DIRECTORY PREVIEW:\n ================================\n";
  145. foreach ($contents as $c){
  146. if ($stop_preview)
  147. break;
  148. $counter++;
  149. if ($counter > $max_preview_size){
  150. echo " --------- (results truncated)\n";
  151. $stop_preview = true;
  152. break;
  153. }
  154. echo " " . $c . "\n";
  155. }
  156. echo " ================================\n";
  157. }
  158. $content_map = array();
  159. $content_map_new = array();
  160. // Build a content map: array with path => filename format.
  161. foreach ($contents as $c){
  162. if (is_dir($c))
  163. $filename = null;
  164. else
  165. $filename = basename($c);
  166. $content_map[$c] = $filename;
  167. }
  168. $content_map_new = $content_map;
  169. // print_r($content_map);
  170. // Build the replacement content map. This contains the same path => filename
  171. // format but with the updated filename instead of the original.
  172. foreach ($content_map_new as $p => $f){
  173. // REPLACE2($str, $search, $replace)
  174. $filename_new = REPLACE2($f, $regex_search, $replace_str);
  175. $path_new = REPLACE2($p, $regex_search, $replace_str);
  176. $content_map_new[$p] = $filename_new;
  177. }
  178. echo " > New content map created. See below for preview.\n";
  179. echo " > FILE AND DIRECTORY PREVIEW:\n ================================\n";
  180. $counter = 0;
  181. $stop_preview = false;
  182. foreach ($content_map as $p => $f){
  183. if ($stop_preview)
  184. break;
  185. if (!is_dir($p)){
  186. $counter++;
  187. if ($counter > $max_preview_size){
  188. echo " --------- (results truncated)\n";
  189. $stop_preview = true;
  190. break;
  191. }
  192. $new_path = dirname($p) . "/" . $content_map_new[$p];
  193. echo " [before]: " . $p . "\n";
  194. echo " [after]: " . $new_path . "\n\n";
  195. }
  196. }
  197. echo " *** Please review above results carefully ***\n\n";
  198. echo " - To begin operation (cannot be undone), type 'Y' and press ENTER/RETURN.\n";
  199. // echo " - To preview more results, type 'P' and press ENTER/RETURN.\n";
  200. echo " - To cancel script without making any changes, type 'N' and press ENTER/RETURN.\n";
  201. echo "\n >> Begin operation? [Y/n]: ";
  202. $response = fgets(STDIN);
  203. $begin_operation = substr($response, 0, strlen($response) - 1);
  204. if (ARE_STRINGS_EQUAL($begin_operation, "Y", true)){
  205. echo "\n > Operation started by user.\n";
  206. $countdown_timer = 5;
  207. while($countdown_timer > 0){
  208. echo " > Operation starting in " . $countdown_timer . " second(s)...\n";
  209. $countdown_timer--;
  210. sleep(1);
  211. }
  212. echo "\n > Operation in progress, please wait...\n";
  213. $total_items = count($content_map) + 1;
  214. $items_remaining = $total_items;
  215. $curr_item = 0;
  216. $progress_val = 0;
  217. foreach ($content_map as $p => $f){
  218. $curr_item++;
  219. $progress_val = $curr_item / $total_items;
  220. $progress_val *= 100;
  221. $progress_val_d = number_format((float)$progress_val, 2, '.', '');
  222. // TODO: Only perform this check if skip_directories is TRUE.
  223. if (!is_dir($p)){
  224. $new_path = dirname($p) . "/" . $content_map_new[$p];
  225. // Actual command to be executed.
  226. $cmd = "mv \"" . $p . "\" \"" . $new_path . "\"";
  227. // Truncated command to be displayed.
  228. $cmd_d = "-";
  229. // Make sure the strings are actually long enough to get truncated. If either are too short,
  230. // then just display the full command.
  231. if (strlen($p) >= -$cmd_display_limit && strlen($new_path) >= -$cmd_display_limit){
  232. $cmd_d = "mv \"..." . substr($p, $cmd_display_limit) . "\" \"..." . substr($new_path, $cmd_display_limit) . "\"";
  233. }
  234. else{
  235. $cmd_d = $cmd;
  236. }
  237. if (!$display_progress && !$display_full_cmd){ //00
  238. // print nothing
  239. }
  240. else if (!$display_progress && $display_full_cmd){ //01
  241. echo " >>> [" . $cmd_d . "]\n";
  242. }
  243. else if ($display_progress && !$display_full_cmd){ //10
  244. echo " >>> [Progress: " . $progress_val_d . "% (" . $curr_item . "/" . $total_items . ") | Items Remaining: " . $items_remaining . "]\n";
  245. }
  246. else if ($display_progress && $display_full_cmd){ //11
  247. echo " >>> [Progress: " . $progress_val_d . "% (" . $curr_item . "/" . $total_items . ") | Remaining: " . $items_remaining . "] | [" . $cmd_d . "]\n";
  248. }
  249. exec($cmd);
  250. }
  251. $items_remaining--;
  252. }
  253. echo " > Operation complete.\n";
  254. exit(0);
  255. }
  256. echo "\n > Operation cancelled by user.\n";
  257. exit(0);