mass-rename.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. $script_time_start = 0;
  40. $script_time_end = 0;
  41. function GET_DIR_CONTENTS($dir, &$results = array()) {
  42. $files = scandir($dir);
  43. foreach ($files as $key => $value) {
  44. $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
  45. if (!is_dir($path)) {
  46. $results[] = $path;
  47. } else if ($value != "." && $value != "..") {
  48. GET_DIR_CONTENTS($path, $results);
  49. $results[] = $path;
  50. }
  51. }
  52. return $results;
  53. }
  54. function ECHO_USAGE(){
  55. global $argv;
  56. echo "\n > Usage:\n";
  57. echo " \"php " . $argv[0] . " <t-dir> <search-regex> <replace-str>\"\n";
  58. echo " where <t-dir> is the directory to traverse and\n";
  59. echo " <search-regex> is the regular expression to\n";
  60. echo " search for, and <replace-str> is the raw string\n";
  61. echo " to replace the search-regex with. Note that\n";
  62. echo " <replace-str> is NOT a regular expression.\n";
  63. echo " If <replace-str> contains one or more whitespace\n";
  64. echo " character(s), it must be enclosed within double-\n";
  65. echo " quotation marks.\n";
  66. echo "\n > Examples:\n";
  67. echo " > \"php " . $argv[0] . " . /.[a-z]+/ .jpg\"\n";
  68. echo " > \"php " . $argv[0] . " . /.[a-zA-Z]+/ .jpg\"\n";
  69. echo " > \"php " . $argv[0] . " . /.[a-zA-Z0-9]+/ \".jpg\"\"\n";
  70. }
  71. // @BRIEF Replace $search with $replace in $str. This performs a simple replace using PHP's str_replace().
  72. function REPLACE($str, $search, $replace){
  73. return str_replace($search, $replace, $str);
  74. }
  75. // @BRIEF Replace $search with $replace in $str. This expects a regular expression for $search and uses PHP's preg_replace().
  76. function REPLACE2($str, $search, $replace){
  77. return preg_replace($search, $replace, $str);
  78. }
  79. // Returns true if both strings are the same. Performs a case-insensitive comparison unless third parameter is true.
  80. function ARE_STRINGS_EQUAL($str1, $str2, $case_sensitive = false){
  81. switch($case_sensitive){
  82. case true:
  83. if (strcmp($str1, $str2) == 0){
  84. return true;
  85. }
  86. else{
  87. return false;
  88. }
  89. break;
  90. default:
  91. if (strcasecmp($str1, $str2) == 0){
  92. return true;
  93. }
  94. else{
  95. return false;
  96. }
  97. break;
  98. }
  99. return false;
  100. }
  101. // ======================================================================
  102. if (isset($argv[1])){
  103. $dirToTraverse = $argv[1];
  104. echo " > Check passed; Traversal Directory = [" . $dirToTraverse . "]\n";
  105. }
  106. else{
  107. echo " > Check FAILED; Missing Traversal Directory!\n";
  108. ECHO_USAGE();
  109. echo "\n > Script terminated.\n";
  110. exit(1);
  111. }
  112. if (isset($argv[2])){
  113. $regex_search = $argv[2];
  114. echo " > Check passed; Search RegEx = \"" . $regex_search . "\"\n";
  115. }
  116. else{
  117. echo " > Check FAILED; Missing Search RegEx!\n";
  118. ECHO_USAGE();
  119. echo "\n > Script terminated.\n";
  120. exit(1);
  121. }
  122. if (isset($argv[3])){
  123. $replace_str = $argv[3];
  124. echo " > Check passed; Replacement String = \"" . $replace_str . "\"\n";
  125. }
  126. else{
  127. echo " > Check FAILED; Missing Search RegEx!\n";
  128. ECHO_USAGE();
  129. echo "\n > Script terminated.\n";
  130. exit(1);
  131. }
  132. echo " > Performing initial directory traversal, please wait...\n";
  133. $script_time_start = microtime(true);
  134. $contents = array();
  135. GET_DIR_CONTENTS($dirToTraverse, $contents);
  136. if ($remove_self){
  137. while( ($found = array_search($thisFile, $contents)) !== false ){
  138. echo " > Removing this script from file listing.\n";
  139. unset($contents[$found]);
  140. }
  141. }
  142. // var_dump($contents);
  143. $script_time_end = microtime(true);
  144. $script_runtime = $script_time_end - $script_time_start;
  145. echo " > Initial directory traversal complete [" . $script_runtime . " ms].\n";
  146. $counter = 0;
  147. $stop_preview = false;
  148. if ($enable_dir_scan_preview){
  149. echo " > ORIGINAL FILE AND DIRECTORY PREVIEW:\n ================================\n";
  150. foreach ($contents as $c){
  151. if ($stop_preview)
  152. break;
  153. $counter++;
  154. if ($counter > $max_preview_size){
  155. echo " --------- (results truncated)\n";
  156. $stop_preview = true;
  157. break;
  158. }
  159. echo " " . $c . "\n";
  160. }
  161. echo " ================================\n";
  162. }
  163. $content_map = array();
  164. $content_map_new = array();
  165. // Build a content map: array with path => filename format.
  166. foreach ($contents as $c){
  167. if (is_dir($c))
  168. $filename = null;
  169. else
  170. $filename = basename($c);
  171. $content_map[$c] = $filename;
  172. }
  173. $content_map_new = $content_map;
  174. echo " > Creating new content map based on supplied search and replace settings, please wait...\n";
  175. // print_r($content_map);
  176. // Build the replacement content map. This contains the same path => filename
  177. // format but with the updated filename instead of the original.
  178. $script_time_start = microtime(true);
  179. foreach ($content_map_new as $p => $f){
  180. // REPLACE2($str, $search, $replace)
  181. $filename_new = REPLACE2($f, $regex_search, $replace_str);
  182. $path_new = REPLACE2($p, $regex_search, $replace_str);
  183. $content_map_new[$p] = $filename_new;
  184. }
  185. $script_time_end = microtime(true);
  186. $script_runtime = $script_time_end - $script_time_start;
  187. echo " > Success: new content map created [" . $script_runtime . " ms].\n";
  188. echo " > FILE AND DIRECTORY PREVIEW:\n ================================\n";
  189. $counter = 0;
  190. $stop_preview = false;
  191. foreach ($content_map as $p => $f){
  192. if ($stop_preview)
  193. break;
  194. if (!is_dir($p)){
  195. $counter++;
  196. if ($counter > $max_preview_size){
  197. echo " --------- (results truncated)\n";
  198. $stop_preview = true;
  199. break;
  200. }
  201. $new_path = dirname($p) . "/" . $content_map_new[$p];
  202. echo " [before]: " . $p . "\n";
  203. echo " [after]: " . $new_path . "\n\n";
  204. }
  205. }
  206. echo " *** Please review above results carefully ***\n\n";
  207. echo " - To begin operation (cannot be undone), type 'Y' and press ENTER/RETURN.\n";
  208. // echo " - To preview more results, type 'P' and press ENTER/RETURN.\n";
  209. echo " - To cancel script without making any changes, type 'N' and press ENTER/RETURN.\n";
  210. echo "\n >> Begin operation? [Y/n]: ";
  211. $response = fgets(STDIN);
  212. $begin_operation = substr($response, 0, strlen($response) - 1);
  213. if (ARE_STRINGS_EQUAL($begin_operation, "Y", true)){
  214. echo "\n > Operation started by user.\n";
  215. $countdown_timer = 5;
  216. while($countdown_timer > 0){
  217. echo " > Operation starting in " . $countdown_timer . " second(s)...\n";
  218. $countdown_timer--;
  219. sleep(1);
  220. }
  221. echo "\n > Operation in progress, please wait...\n";
  222. $total_items = count($content_map) + 1;
  223. $items_remaining = $total_items;
  224. $curr_item = 0;
  225. $progress_val = 0;
  226. $script_time_start = microtime(true);
  227. foreach ($content_map as $p => $f){
  228. $curr_item++;
  229. $progress_val = $curr_item / $total_items;
  230. $progress_val *= 100;
  231. $progress_val_d = number_format((float)$progress_val, 2, '.', '');
  232. // TODO: Only perform this check if skip_directories is TRUE.
  233. if (!is_dir($p)){
  234. $new_path = dirname($p) . "/" . $content_map_new[$p];
  235. // Actual command to be executed.
  236. $cmd = "mv \"" . $p . "\" \"" . $new_path . "\"";
  237. // Truncated command to be displayed.
  238. $cmd_d = "-";
  239. // Make sure the strings are actually long enough to get truncated. If either are too short,
  240. // then just display the full command.
  241. if (strlen($p) >= -$cmd_display_limit && strlen($new_path) >= -$cmd_display_limit){
  242. $cmd_d = "mv \"..." . substr($p, $cmd_display_limit) . "\" \"..." . substr($new_path, $cmd_display_limit) . "\"";
  243. }
  244. else{
  245. $cmd_d = $cmd;
  246. }
  247. if (!$display_progress && !$display_full_cmd){ //00
  248. // print nothing
  249. }
  250. else if (!$display_progress && $display_full_cmd){ //01
  251. echo " >>> [" . $cmd_d . "]\n";
  252. }
  253. else if ($display_progress && !$display_full_cmd){ //10
  254. echo " >>> [Progress: " . $progress_val_d . "% (" . $curr_item . "/" . $total_items . ") | Items Remaining: " . $items_remaining . "]\n";
  255. }
  256. else if ($display_progress && $display_full_cmd){ //11
  257. echo " >>> [Progress: " . $progress_val_d . "% (" . $curr_item . "/" . $total_items . ") | Remaining: " . $items_remaining . "] | [" . $cmd_d . "]\n";
  258. }
  259. exec($cmd);
  260. }
  261. $items_remaining--;
  262. }
  263. $script_time_end = microtime(true);
  264. $script_runtime = $script_time_end - $script_time_start;
  265. echo " > Operation complete. [" . $script_runtime . " ms].\n";
  266. exit(0);
  267. }
  268. echo "\n > Operation cancelled by user.\n";
  269. exit(0);