-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbreplace.php
1838 lines (1573 loc) · 53.4 KB
/
dbreplace.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// php 5.3 date timezone requirement, shouldn't affect anything
date_default_timezone_set('Europe/London');
$opts = [
'h:' => 'host:',
'n:' => 'name:',
'u:' => 'user:',
'p:' => 'pass:',
'c:' => 'char:',
's:' => 'search:',
'r:' => 'replace:',
't:' => 'tables:',
'i:' => 'include-cols:',
'x:' => 'exclude-cols:',
'g' => 'regex',
'l:' => 'page-size:',
'z' => 'dry-run',
'e:' => 'alter-engine:',
'a:' => 'alter-collation:',
'v::' => 'verbose::',
'port:',
'help',
];
$required = [
'h:',
'n:',
'u:',
'p:',
];
function strip_colons($string)
{
return str_replace(':', '', $string);
}
// store arg values
//$arg_count = $_SERVER['argc'];
//$args_array = $_SERVER['argv'];
$short_opts = array_keys($opts);
$short_opts_normal = array_map('strip_colons', $short_opts);
$long_opts = array_values($opts);
$long_opts_normal = array_map('strip_colons', $long_opts);
// store array of options and values
$options = getopt(implode('', $short_opts), $long_opts);
if (isset($options['help'])) {
echo "
#####################################################################
interconnect/it Safe Search & Replace tool
#####################################################################
This script allows you to search and replace strings in your database
safely without breaking serialised PHP.
Please report any bugs or fork and contribute to this script via
Github: https://github.com/interconnectit/search-replace-db
Argument values are strings unless otherwise specified.
ARGS
-h, --host
Required. The hostname of the database server.
-n, --name
Required. Database name.
-u, --user
Required. Database user.
-p, --pass
Required. Database user's password.
--port
Optional. Port on database server to connect to.
The default is 3306. (MySQL default port).
-s, --search
String to search for or `preg_replace()` style
regular expression.
-r, --replace
None empty string to replace search with or
`preg_replace()` style replacement.
-t, --tables
If set only runs the script on the specified table, comma
separate for multiple values.
-i, --include-cols
If set only runs the script on the specified columns, comma
separate for multiple values.
-x, --exclude-cols
If set excludes the specified columns, comma separate for
multiple values.
-g, --regex [no value]
Treats value for -s or --search as a regular expression and
-r or --replace as a regular expression replacement.
-l, --page-size
How rows to fetch at a time from a table.
-z, --dry-run [no value]
Prevents any updates happening so you can preview the number
of changes to be made
-e, --alter-engine
Changes the database table to the specified database engine
eg. InnoDB or MyISAM. If specified search/replace arguments
are ignored. They will not be run simultaneously.
-a, --alter-collation
Changes the database table to the specified collation
eg. utf8_unicode_ci. If specified search/replace arguments
are ignored. They will not be run simultaneously.
-v, --verbose [true|false]
Defaults to true, can be set to false to run script silently.
--help
Displays this help message ;)
";
exit;
}
// missing field flag, show all missing instead of 1 at a time
$missing_arg = false;
// check required args are passed
foreach ($required as $key) {
$short_opt = strip_colons($key);
$long_opt = strip_colons($opts[$key]);
if (!isset($options[$short_opt]) && !isset($options[$long_opt])) {
fwrite(STDERR, "Error: Missing argument, -{$short_opt} or --{$long_opt} is required.\n");
$missing_arg = true;
}
}
// bail if requirements not met
if ($missing_arg) {
fwrite(STDERR, "Please enter the missing arguments.\n");
exit(1);
}
// new args array
$args = [
'verbose' => true,
'dry_run' => false,
];
// create $args array
foreach ($options as $key => $value) {
// transpose keys
if (($is_short = array_search($key, $short_opts_normal)) !== false) {
$key = $long_opts_normal[$is_short];
}
// true/false string mapping
if (is_string($value) && in_array($value, ['false', 'no', '0'])) {
$value = false;
}
if (is_string($value) && in_array($value, ['true', 'yes', '1'])) {
$value = true;
}
// boolean options as is, eg. a no value arg should be set true
if (in_array($key, $long_opts)) {
$value = true;
}
// change to underscores
$key = str_replace('-', '_', $key);
$args[$key] = $value;
}
$report = new icit_srdb_cli($args);
// Only print a separating newline if verbose mode is on to separate verbose output from result
if ($args['verbose']) {
echo "\n";
}
if ($report && ((isset($args['dry_run']) && $args['dry_run']) || empty($report->errors['results']))) {
echo "And we're done!\n";
} else {
echo "Check the output for errors. You may need to ensure verbose output is on by using -v or --verbose.\n";
}
class icit_srdb
{
/**
* @var array List of all the tables in the database
*/
public $all_tables = [];
/**
* @var array Tables to run the replacement on
*/
public $tables = [];
/**
* @var string Search term
*/
public $search = false;
/**
* @var string Replacement
*/
public $replace = false;
/**
* @var bool Use regular expressions to perform search and replace
*/
public $regex = false;
/**
* @var bool Leave guid column alone
*/
public $guid = false;
/**
* @var array Available engines
*/
public $engines = [];
/**
* @var bool|string Convert to new engine
*/
public $alter_engine = false;
/**
* @var bool|string Convert to new collation
*/
public $alter_collation = false;
/**
* @var array Column names to exclude
*/
public $exclude_cols = [];
/**
* @var array Column names to include
*/
public $include_cols = [];
/**
* @var bool True if doing a dry run
*/
public $dry_run = true;
/**
* @var string Database connection details
*/
public $name = '';
public $user = '';
public $pass = '';
public $host = '127.0.0.1';
public $port = 0;
public $charset = 'utf8';
public $collate = '';
/**
* @var array Stores a list of exceptions
*/
public $errors = [
'search' => [],
'db' => [],
'tables' => [],
'results' => [],
];
public $error_type = 'search';
/**
* @var array Stores the report array
*/
public $report = [];
/**
* @var int Number of modifications to return in report array
*/
public $report_change_num = 30;
/**
* @var bool Whether to echo report as script runs
*/
public $verbose = false;
/**
* @var PDO|mysqli Database connection
*/
public $db;
/**
* @var $use_pdo
*/
public $use_pdo = true;
/**
* @var int How many rows to select at a time when replacing
*/
public $page_size = 50000;
/**
* Searches for WP or Drupal context
* Checks for $_POST data
* Initialises database connection
* Handles ajax
* Runs replacement
*
* @param string $name database name
* @param string $user database username
* @param string $pass database password
* @param string $host database hostname
* @param string $port database connection port
* @param string $search search string / regex
* @param string $replace replacement string
* @param array $tables tables to run replcements against
* @param bool $live live run
* @param array $exclude_cols tables to run replcements against
*/
public function __construct($args)
{
$args = array_merge([
'name' => '',
'user' => '',
'pass' => '',
'host' => '',
'port' => 3306,
'search' => '',
'replace' => '',
'tables' => [],
'exclude_cols' => [],
'include_cols' => [],
'dry_run' => true,
'regex' => false,
'page_size' => 50000,
'alter_engine' => false,
'alter_collation' => false,
'verbose' => false,
], $args);
// handle exceptions
set_exception_handler([$this, 'exceptions']);
// handle errors
set_error_handler([$this, 'errors'], E_ERROR | E_WARNING);
// allow a string for columns
foreach (['exclude_cols', 'include_cols', 'tables'] as $maybe_string_arg) {
if (is_string($args[$maybe_string_arg])) {
$args[$maybe_string_arg] = array_filter(array_map('trim', explode(',', $args[$maybe_string_arg])));
}
}
// verify that the port number is logical
// work around PHPs inability to stringify a zero without making it an empty string
// AND without casting away trailing characters if they are present.
$port_as_string = (string)$args['port'] ? (string)$args['port'] : "0";
if ((string)abs((int)$args['port']) !== $port_as_string) {
$port_error = 'Port number must be a positive integer if specified.';
$this->add_error($port_error, 'db');
if (defined('STDIN')) {
echo 'Error: ' . $port_error;
}
return '';
}
// set class vars
foreach ($args as $name => $value) {
if (is_string($value)) {
$value = stripcslashes($value);
}
if (is_array($value)) {
$value = array_map('stripcslashes', $value);
}
$this->set($name, $value);
}
// only for non cli call, cli set no timeout, no memory limit
if (!defined('STDIN')) {
// increase time out limit
@set_time_limit(60 * 10);
// try to push the allowed memory up, while we're at it
@ini_set('memory_limit', '1024M');
}
// set up db connection
$this->db_setup();
if ($this->db_valid()) {
// update engines
if ($this->alter_engine) {
$report = $this->update_engine($this->alter_engine, $this->tables);
} // update collation
elseif ($this->alter_collation) {
$report = $this->update_collation($this->alter_collation, $this->tables);
} // default search/replace action
else {
$report = $this->replacer($this->search, $this->replace, $this->tables);
}
} else {
$report = $this->report;
}
// store report
$this->set('report', $report);
return $report;
}
/**
* Terminates db connection
*
* @return void
*/
public function __destruct()
{
if ($this->db_valid()) {
$this->db_close();
}
}
public function get($property)
{
return $this->$property;
}
public function set($property, $value)
{
$this->$property = $value;
}
/**
* @param $exception Exception
*/
public function exceptions($exception)
{
echo $exception->getMessage() . "\n";
}
public function errors(
/** @noinspection PhpUnusedParameterInspection */
$no,
$message,
$file,
$line
) {
echo $message . "\n";
}
public function log($type = '')
{
$args = array_slice(func_get_args(), 1);
if ($this->get('verbose')) {
echo "{$type}: ";
print_r($args);
echo "\n";
}
return $args;
}
public function add_error($error, $type = null)
{
if ($type !== null) {
$this->error_type = $type;
}
$this->errors[$this->error_type][] = $error;
$this->log('error', $this->error_type, $error);
}
public function use_pdo()
{
return $this->get('use_pdo');
}
/**
* Setup connection, populate tables array
* Also responsible for selecting the type of connection to use.
*
* @return boolean
*/
public function db_setup()
{
$mysqli_available = class_exists('mysqli');
$pdo_available = class_exists('PDO');
$connection_type = '';
// Default to mysqli type.
// Only advance to PDO if all conditions are met.
if ($mysqli_available) {
$connection_type = 'mysqli';
}
if ($pdo_available) {
// PDO is the interface, but it may not have the 'mysql' module.
$mysql_driver_present = in_array('mysql', pdo_drivers());
if ($mysql_driver_present) {
$connection_type = 'pdo';
}
}
// Abort if mysqli and PDO are both broken.
if ('' === $connection_type) {
$this->add_error('Could not find any MySQL database drivers. (MySQLi or PDO required.)', 'db');
return false;
}
// connect
$this->set('db', $this->connect($connection_type));
return true;
}
/**
* Database connection type router
*
* @param string $type
*
* @return callback
*/
public function connect($type = '')
{
$method = "connect_{$type}";
return $this->$method();
}
/**
* Creates the database connection using newer mysqli functions
*
* @return resource|bool
*/
public function connect_mysqli()
{
// switch off PDO
$this->set('use_pdo', false);
$connection = @mysqli_connect($this->host, $this->user, $this->pass, $this->name, $this->port);
// unset if not available
if (!$connection) {
$this->add_error(mysqli_connect_error(), 'db');
$connection = false;
}
return $connection;
}
/**
* Sets up database connection using PDO
*
* @return PDO|bool
*/
public function connect_pdo()
{
try {
$connection = new PDO("mysql:host={$this->host};port={$this->port};dbname={$this->name}", $this->user,
$this->pass);
} catch (PDOException $e) {
$this->add_error($e->getMessage(), 'db');
$connection = false;
}
// check if there's a problem with our database at this stage
if ($connection && !$connection->query('SHOW TABLES')) {
$error_info = $connection->errorInfo();
if (!empty($error_info) && is_array($error_info)) {
$this->add_error(array_pop($error_info), 'db');
} // Array pop will only accept a $var..
$connection = false;
}
return $connection;
}
/**
* Retrieve all tables from the database
*
* @return array
*/
public function get_tables()
{
// get tables
// A clone of show table status but with character set for the table.
$show_table_status = "SELECT
t.`TABLE_NAME` as Name,
t.`ENGINE` as `Engine`,
t.`version` as `Version`,
t.`ROW_FORMAT` AS `Row_format`,
t.`TABLE_ROWS` AS `Rows`,
t.`AVG_ROW_LENGTH` AS `Avg_row_length`,
t.`DATA_LENGTH` AS `Data_length`,
t.`MAX_DATA_LENGTH` AS `Max_data_length`,
t.`INDEX_LENGTH` AS `Index_length`,
t.`DATA_FREE` AS `Data_free`,
t.`AUTO_INCREMENT` as `Auto_increment`,
t.`CREATE_TIME` AS `Create_time`,
t.`UPDATE_TIME` AS `Update_time`,
t.`CHECK_TIME` AS `Check_time`,
t.`TABLE_COLLATION` as Collation,
c.`CHARACTER_SET_NAME` as Character_set,
t.`Checksum`,
t.`Create_options`,
t.`table_Comment` as `Comment`
FROM information_schema.`TABLES` t
LEFT JOIN information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` c
ON ( t.`TABLE_COLLATION` = c.`COLLATION_NAME` )
WHERE t.`TABLE_SCHEMA` = '{$this->name}';
";
$all_tables_mysql = $this->db_query($show_table_status);
$all_tables = [];
if (!$all_tables_mysql) {
$this->add_error($this->db_error(), 'db');
} else {
// set the character set
//$this->db_set_charset( $this->get( 'charset' ) );
while ($table = $this->db_fetch($all_tables_mysql)) {
// ignore views
if ($table['Comment'] == 'VIEW') {
continue;
}
$all_tables[$table[0]] = $table;
}
}
return $all_tables;
}
/**
* Get the character set for the current table
*
* @param string $table_name The name of the table we want to get the char
* set for
*
* @return string The character encoding;
*/
public function get_table_character_set($table_name = '')
{
$table_name = $this->db_escape($table_name);
$schema = $this->db_escape($this->name);
$charset = $this->db_query("SELECT c.`character_set_name`
FROM information_schema.`TABLES` t
LEFT JOIN information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` c
ON (t.`TABLE_COLLATION` = c.`COLLATION_NAME`)
WHERE t.table_schema = {$schema}
AND t.table_name = {$table_name}
LIMIT 1;");
$encoding = false;
if (!$charset) {
$this->add_error($this->db_error(), 'db');
} else {
$result = $this->db_fetch($charset);
$encoding = isset($result['character_set_name']) ? $result['character_set_name'] : false;
}
return $encoding;
}
/**
* Retrieve all supported database engines
*
* @return array
*/
public function get_engines()
{
// get available engines
$mysql_engines = $this->db_query('SHOW ENGINES;');
$engines = [];
if (!$mysql_engines) {
$this->add_error($this->db_error(), 'db');
} else {
while ($engine = $this->db_fetch($mysql_engines)) {
if (in_array($engine['Support'], ['YES', 'DEFAULT'])) {
$engines[] = $engine['Engine'];
}
}
}
return $engines;
}
public function db_query($query)
{
if ($this->use_pdo()) {
return $this->db->query($query);
} else {
return mysqli_query($this->db, $query);
}
}
public function db_update($query)
{
if ($this->use_pdo()) {
return $this->db->exec($query);
} else {
return mysqli_query($this->db, $query);
}
}
public function db_error()
{
if ($this->use_pdo()) {
$error_info = $this->db->errorInfo();
return !empty($error_info) && is_array($error_info) ? array_pop($error_info) : 'Unknown error';
} else {
return mysqli_error($this->db);
}
}
public function db_fetch($data)
{
// if ($this->use_pdo())
if ($data instanceof PDOStatement) {
return $data->fetch();
} else {
return mysqli_fetch_array($data);
}
}
public function db_escape($string)
{
// if ($this->use_pdo())
if ($this->db instanceof PDO) {
return $this->db->quote($string);
} else {
return "'" . mysqli_real_escape_string($this->db, $string) . "'";
}
}
public function db_free_result($data)
{
// if ($this->use_pdo())
if ($data instanceof PDOStatement) {
$data->closeCursor();
} else {
mysqli_free_result($data);
}
}
public function db_set_charset($charset = '')
{
if (!empty($charset)) {
if (!$this->use_pdo() && function_exists('mysqli_set_charset')) {
mysqli_set_charset($this->db, $charset);
} else {
$this->db_query('SET NAMES ' . $charset);
}
}
}
public function db_close()
{
if ($this->use_pdo()) {
unset($this->db);
} else {
mysqli_close($this->db);
}
}
public function db_valid()
{
return (bool)$this->db;
}
/**
* Walk an array replacing one element for another. ( NOT USED ANY MORE )
*
* @param string $find The string we want to replace.
* @param string $replace What we'll be replacing it with.
* @param array $data Used to pass any subordinate arrays back to the
* function for searching.
*
* @return array The original array with the replacements made.
*/
// public function recursive_array_replace($find, $replace, $data)
// {
// if (is_array($data)) {
// foreach ($data as $key => $value) {
// if (is_array($value)) {
// $this->recursive_array_replace($find, $replace, $data[$key]);
// } else {
// // have to check if it's string to ensure no switching to string for booleans/numbers/nulls - don't need any nasty conversions
// if (is_string($value))
// $data[$key] = $this->str_replace($find, $replace, $value);
// }
// }
// } else {
// if (is_string($data))
// $data = $this->str_replace($find, $replace, $data);
// }
// }
/**
* Take a serialised array and unserialise it replacing elements as needed and
* unserialising any subordinate arrays and performing the replace on those too.
*
* @param string $from String we're looking to replace.
* @param string $to What we want it to be replaced with
* @param array $data Used to pass any subordinate arrays back to in.
* @param bool $serialised Does the array passed via $data need serialising.
*
* @return array The original array with all elements replaced as needed.
*/
// public function recursive_unserialize_replace($from = '', $to = '', $data = '', $serialised = false, $done = [])
// {
//
// // some unserialised data cannot be re-serialised eg. SimpleXMLElements
// try {
//
// if (is_string($data) && ($unserialized = @unserialize($data)) !== false) {
// $data = $this->recursive_unserialize_replace($from, $to, $unserialized, true, $done);
// } elseif (is_array($data)) {
// $_tmp = array();
// foreach ($data as $key => $value) {
// $_tmp[$key] = $this->recursive_unserialize_replace($from, $to, $value, false, $done);
// }
//
// $data = $_tmp;
// unset($_tmp);
// } // Submitted by Tina Matter
// elseif (is_object($data)) {
// if (!in_array(spl_object_hash($data), $done)) {
// $done[] = spl_object_hash($data);
// $props = get_object_vars($data);
// foreach ($props as $key => &$value) {
// $alt = preg_replace('/^[^\p{L}\p{N}]+/', '', $key);
// if ($alt == $key) {
// $this->recursive_unserialize_replace($from, $to, $value, false, $done);
// }
// }
// }
// } else {
// if (is_string($data)) {
// $data = $this->str_replace($from, $to, $data);
//
// }
// }
//
// if ($serialised)
// return serialize($data);
//
// } catch (Exception $error) {
//
// $this->add_error($error->getMessage(), 'results');
//
// }
//
// return $data;
// }
/**
* Regular expression callback to fix serialised string lengths
*
* @param array $matches matches from the regular expression
*
* @return string
*/
public function preg_fix_serialised_count($matches)
{
$length = mb_strlen($matches[2]);
if ($length !== intval($matches[1])) {
return "s:{$length}:\"{$matches[2]}\";";
}
return $matches[0];
}
/**
* The main loop triggered in step 5. Up here to keep it out of the way of the
* HTML. This walks every table in the db that was selected in step 3 and then
* walks every row and column replacing all occurences of a string with another.
* We split large tables into 50,000 row blocks when dealing with them to save
* on memmory consumption.
*
* @param string $search What we want to replace
* @param string $replace What we want to replace it with.
* @param array $tables The tables we want to look at.
*
* @return array|boolean Collection of information gathered during the run or false
*/
public function replacer($search = '', $replace = '', $tables = [])
{
// check we have a search string, bail if not
if (empty($search)) {
$this->add_error('Search string is empty', 'search');
return false;
}
$report = [
'tables' => 0,
'rows' => 0,
'change' => 0,
'updates' => 0,
'start' => microtime(),
'end' => microtime(),
'errors' => [],
'table_reports' => [],
];
$table_report = [
'rows' => 0,
'change' => 0,
'changes' => [],
'updates' => 0,
'start' => microtime(),
'end' => microtime(),
'errors' => [],
];
$dry_run = $this->get('dry_run');
if ($this->get('dry_run')) // Report this as a search-only run.
{
$this->add_error('The dry-run option was selected. No replacements will be made.', 'results');
}
// if no tables selected assume all
if (empty($tables)) {
$all_tables = $this->get_tables();
$tables = array_keys($all_tables);
}
if (is_array($tables) && !empty($tables)) {
$parser = new Parser();
foreach ($tables as $table) {
$encoding = $this->get_table_character_set($table);
switch ($encoding) {
// Tables encoded with this work for me only when I set names to utf8. I don't trust this in the wild so I'm going to avoid.
case 'utf16':
case 'utf32':
//$encoding = 'utf8';
$this->add_error("The table \"{$table}\" is encoded using \"{$encoding}\" which is currently unsupported.",
'results');
continue 2;
default:
$this->db_set_charset($encoding);
break;
}
$report['tables']++;
// get primary key and columns
list($primary_key, $columns) = $this->get_columns($table);
if ($primary_key === null) {
$this->add_error("The table \"{$table}\" has no primary key. Changes will have to be made manually.",
'results');
continue;
}
// create new table report instance
$new_table_report = $table_report;
$new_table_report['start'] = microtime();
$this->log('search_replace_table_start', $table, $search, $replace);
// Count the number of rows we have in the table if large we'll split into blocks, This is a mod from Simon Wheatley
$row_count = $this->db_query("SELECT COUNT(*) FROM `{$table}`");
$rows_result = $this->db_fetch($row_count);
$row_count = $rows_result[0];
$page_size = $this->get('page_size');
$pages = ceil($row_count / $page_size);
for ($page = 0; $page < $pages; $page++) {
$start = $page * $page_size;
// Grab the content of the table
$data = $this->db_query(sprintf('SELECT * FROM `%s` LIMIT %d, %d', $table, $start, $page_size));