forked from interconnectit/Search-Replace-DB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
executable file
·2908 lines (2347 loc) · 196 KB
/
index.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
/**
*
* Safe Search and Replace on Database with Serialized Data v3.1.0
*
* This script is to solve the problem of doing database search and replace when
* some data is stored within PHP serialized arrays or objects.
*
* For more information, see
* http://interconnectit.com/124/search-and-replace-for-wordpress-databases/
*
* To contribute go to
* http://github.com/interconnectit/search-replace-db
*
* To use, load the script on your server and point your web browser to it.
* In some situations, consider using the command line interface version.
*
* BIG WARNING! Take a backup first, and carefully test the results of this
* code. If you don't, and you vape your data then you only have yourself to
* blame. Seriously. And if your English is bad and you don't fully
* understand the instructions then STOP. Right there. Yes. Before you do any
* damage.
*
* USE OF THIS SCRIPT IS ENTIRELY AT YOUR OWN RISK. I/We accept no liability
* from its use.
*
* First Written 2009-05-25 by David Coveney of Interconnect IT Ltd (UK)
* http://www.davidcoveney.com or http://interconnectit.com
* and released under the GPL v3
* ie, do what ever you want with the code, and we take no responsibility for it
* OK? If you don't wish to take responsibility, hire us at Interconnect IT Ltd
* on +44 (0)151 331 5140 and we will do the work for you at our hourly rate,
* minimum 1hr
*
* License: GPL v3
* License URL: http://www.gnu.org/copyleft/gpl.html
*
*
* Version 3.1.0:
* * Added port number option to both web and CLI interfaces.
* * More reliable fallback on non-PDO systems.
* * Confirmation on 'Delete me'
* * Comprehensive check to prevent accidental deletion of web projects
* * Removed mysql functions and replaced with mysqli
*
* Version 3.0.0:
* * Major overhaul
* * Multibyte string replacements
* * UI completely redesigned
* * Removed all links from script until 'delete' has been clicked to avoid
* security risk from our access logs
* * Search replace functionality moved to it's own separate class
* * Replacements done table by table to avoid timeouts
* * Convert tables to InnoDB
* * Convert tables to utf8_unicode_ci
* * Use PDO if available
* * Preview/view changes
* * Optionally use preg_replace()
* * Scripts bootstraps WordPress/Drupal to avoid issues with unknown
* serialised objects/classes
* * Added marketing stuff to deleted screen (sorry but we're running a
* business!)
*
* Version 2.2.0:
* * Added remove script patch from David Anderson (wordshell.net)
* * Added ability to replace strings with nothing
* * Copy changes
* * Added code to recursive_unserialize_replace to deal with objects not
* just arrays. This was submitted by Tina Matter.
* ToDo: Test object handling. Not sure how it will cope with object in the
* db created with classes that don't exist in anything but the base PHP.
*
* Version 2.1.0:
* - Changed to version 2.1.0
* * Following change by Sergei Biryukov - merged in and tested by Dave Coveney
* - Added Charset Support (tested with UTF-8, not tested on other charsets)
* * Following changes implemented by James Whitehead with thanks to all the commenters and feedback given!
* - Removed PHP warnings if you go to step 3+ without DB details.
* - Added options to skip changing the guid column. If there are other
* columns that need excluding you can add them to the $exclude_cols global
* array. May choose to add another option to the table select page to let
* you add to this array from the front end.
* - Minor tweak to label styling.
* - Added comments to each of the functions.
* - Removed a dead param from icit_srdb_replacer
* Version 2.0.0:
* - returned to using unserialize function to check if string is
* serialized or not
* - marked is_serialized_string function as deprecated
* - changed form order to improve usability and make use on multisites a
* bit less scary
* - changed to version 2, as really should have done when the UI was
* introduced
* - added a recursive array walker to deal with serialized strings being
* stored in serialized strings. Yes, really.
* - changes by James R Whitehead (kudos for recursive walker) and David
* Coveney 2011-08-26
* Version 1.0.2:
* - typos corrected, button text tweak - David Coveney / Robert O'Rourke
* Version 1.0.1
* - styling and form added by James R Whitehead.
*
* Credits: moz667 at gmail dot com for his recursive_array_replace posted at
* uk.php.net which saved me a little time - a perfect sample for me
* and seems to work in all cases.
*
*/
// always good here
header( 'HTTP/1.1 200 OK' );
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
require_once( 'srdb.class.php' );
class icit_srdb_ui extends icit_srdb {
/**
* @var string Root path of the CMS
*/
public $path;
public $is_wordpress = false;
public $is_drupal = false;
public function __construct() {
// php 5.4 date timezone requirement, shouldn't affect anything
date_default_timezone_set( 'Europe/London' );
// prevent fatals from hiding the UI
register_shutdown_function( array( $this, 'fatal_handler' ) );
// flag to bootstrap WP or Drupal
$bootstrap = true; // isset( $_GET[ 'bootstrap' ] );
// discover environment
if ( $bootstrap && $this->is_wordpress() ) {
// prevent warnings if the charset and collate aren't defined
if ( !defined( 'DB_CHARSET') ) {
define( 'DB_CHARSET', 'utf8' );
}
if ( !defined( 'DB_COLLATE') ) {
define( 'DB_COLLATE', '' );
}
// populate db details
$name = DB_NAME;
$user = DB_USER;
$pass = DB_PASSWORD;
// Port and host need to be split apart.
if ( strstr( DB_HOST, ':' ) !== false ) {
$parts = explode( ':', DB_HOST );
$host = $parts[0];
$port_input = $parts[1];
$port = abs( (int)$port_input );
} else {
$host = DB_HOST;
$port = 3306;
}
$charset = DB_CHARSET;
$collate = DB_COLLATE;
$this->response( $name, $user, $pass, $host, $port, $charset, $collate );
} elseif( $bootstrap && $this->is_drupal() ) {
$database = Database::getConnection();
$database_opts = $database->getConnectionOptions();
// populate db details
$name = $database_opts[ 'database' ];
$user = $database_opts[ 'username' ];
$pass = $database_opts[ 'password' ];
$host = $database_opts[ 'host' ];
$port = $database_opts[ 'port' ];
$charset = 'utf8';
$collate = '';
$port_as_string = (string)$port ? (string)$port : "0";
if ( (string)abs( (int)$port ) !== $port_as_string ) {
$port = 3306;
} else {
$port = (string)abs( (int)$port );
}
$this->response( $name, $user, $pass, $host, $port, $charset, $collate );
} else {
$this->response();
}
}
public function response( $name = '', $user = '', $pass = '', $host = '127.0.0.1', $port = 3306, $charset = 'utf8', $collate = '' ) {
// always override with post data
if ( isset( $_POST[ 'name' ] ) ) {
$name = $_POST[ 'name' ]; // your database
$user = $_POST[ 'user' ]; // your db userid
$pass = $_POST[ 'pass' ]; // your db password
$host = $_POST[ 'host' ]; // normally localhost, but not necessarily.
$port_input = $_POST[ 'port' ];
// Make sure that the string version of absint(port) is identical to the string input.
// This prevents expressions, decimals, spaces, etc.
$port_as_string = (string)$port_input ? (string)$port_input : "0";
if ( (string)abs( (int)$port_input ) !== $port_as_string ) {
// Mangled port number: non numeric.
$this->add_error('Port number must be a positive integer. If you are unsure, try the default port 3306.', 'db');
// Force a bad run by supplying nonsense.
$port = "nonsense";
} else {
$port = abs( (int)$port_input );
}
$charset = 'utf8'; // isset( $_POST[ 'char' ] ) ? stripcslashes( $_POST[ 'char' ] ) : ''; // your db charset
$collate = '';
}
// Search replace details
$search = isset( $_POST[ 'search' ] ) ? $_POST[ 'search' ] : '';
$replace = isset( $_POST[ 'replace' ] ) ? $_POST[ 'replace' ] : '';
// regex options
$regex = isset( $_POST[ 'regex' ] );
$regex_i = isset( $_POST[ 'regex_i' ] );
$regex_m = isset( $_POST[ 'regex_m' ] );
$regex_s = isset( $_POST[ 'regex_s' ] );
$regex_x = isset( $_POST[ 'regex_x' ] );
// Tables to scanned
$tables = isset( $_POST[ 'tables' ] ) && is_array( $_POST[ 'tables' ] ) ? $_POST[ 'tables' ] : array( );
if ( isset( $_POST[ 'use_tables' ] ) && $_POST[ 'use_tables' ] == 'all' )
$tables = array();
// exclude / include columns
$exclude_cols = isset( $_POST[ 'exclude_cols' ] ) ? $_POST[ 'exclude_cols' ] : array();
$include_cols = isset( $_POST[ 'include_cols' ] ) ? $_POST[ 'include_cols' ] : array();
foreach( array( 'exclude_cols', 'include_cols' ) as $maybe_string_arg ) {
if ( is_string( $$maybe_string_arg ) )
$$maybe_string_arg = array_filter( array_map( 'trim', explode( ',', $$maybe_string_arg ) ) );
}
// update class vars
$vars = array(
'name', 'user', 'pass', 'host', 'port',
'charset', 'collate', 'tables',
'search', 'replace',
'exclude_cols', 'include_cols',
'regex', 'regex_i', 'regex_m', 'regex_s', 'regex_x'
);
foreach( $vars as $var ) {
if ( isset( $$var ) )
$this->set( $var, $$var );
}
// are doing something?
$show = '';
if ( isset( $_POST[ 'submit' ] ) ) {
if ( is_array( $_POST[ 'submit' ] ) )
$show = key( $_POST[ 'submit' ] );
if ( is_string( $_POST[ 'submit' ] ) )
$show = preg_replace( '/submit\[([a-z0-9]+)\]/', '$1', $_POST[ 'submit' ] );
}
// is it an AJAX call
$ajax = isset( $_POST[ 'ajax' ] );
// body callback
$html = 'ui';
switch( $show ) {
// remove search replace
case 'delete':
// determine if it's the folder of compiled version
if ( basename( __FILE__ ) == 'index.php' )
$path = str_replace( basename( __FILE__ ), '', __FILE__ );
else
$path = __FILE__;
$delete_script_success = $this->delete_script( $path );
if ( self::DELETE_SCRIPT_FAIL_UNSAFE === $delete_script_success) {
$this->add_error( 'Delete aborted! You seem to have placed Search/Replace into your WordPress or Drupal root. Please remove Search/Replace manually.', 'delete' );
} else {
if ( ( self::DELETE_SCRIPT_SUCCESS === $delete_script_success ) && !( is_file( __FILE__ ) && file_exists( __FILE__ ) ) ) {
$this->add_error( 'Search/Replace has been successfully removed from your server', 'delete' );
} else {
$this->add_error( 'Could not fully delete Search/Replace. You will have to delete it manually', 'delete' );
}
}
$html = 'deleted';
break;
case 'liverun':
// bsy-web, 20130621: Check live run was explicitly clicked and only set false then
$this->set( 'dry_run', false );
case 'dryrun':
// build regex string
// non UI implements can just pass in complete regex string
if ( $this->regex ) {
$mods = '';
if ( $this->regex_i ) $mods .= 'i';
if ( $this->regex_s ) $mods .= 's';
if ( $this->regex_m ) $mods .= 'm';
if ( $this->regex_x ) $mods .= 'x';
$this->search = '/' . $this->search . '/' . $mods;
}
// call search replace class
$parent = parent::__construct( array(
'name' => $this->get( 'name' ),
'user' => $this->get( 'user' ),
'pass' => $this->get( 'pass' ),
'host' => $this->get( 'host' ),
'port' => $this->get( 'port' ),
'search' => $this->get( 'search' ),
'replace' => $this->get( 'replace' ),
'tables' => $this->get( 'tables' ),
'dry_run' => $this->get( 'dry_run' ),
'regex' => $this->get( 'regex' ),
'exclude_cols' => $this->get( 'exclude_cols' ),
'include_cols' => $this->get( 'include_cols' )
) );
break;
case 'innodb':
// call search replace class to alter engine
$parent = parent::__construct( array(
'name' => $this->get( 'name' ),
'user' => $this->get( 'user' ),
'pass' => $this->get( 'pass' ),
'host' => $this->get( 'host' ),
'port' => $this->get( 'port' ),
'tables' => $this->get( 'tables' ),
'alter_engine' => 'InnoDB',
) );
break;
case 'utf8':
// call search replace class to alter engine
$parent = parent::__construct( array(
'name' => $this->get( 'name' ),
'user' => $this->get( 'user' ),
'pass' => $this->get( 'pass' ),
'host' => $this->get( 'host' ),
'port' => $this->get( 'port' ),
'tables' => $this->get( 'tables' ),
'alter_collation' => 'utf8_unicode_ci',
) );
break;
case 'utf8mb4':
// call search replace class to alter engine
$parent = parent::__construct( array(
'name' => $this->get( 'name' ),
'user' => $this->get( 'user' ),
'pass' => $this->get( 'pass' ),
'host' => $this->get( 'host' ),
'port' => $this->get( 'port' ),
'tables' => $this->get( 'tables' ),
'alter_collation' => 'utf8mb4_unicode_ci',
) );
break;
case 'update':
default:
// get tables or error messages
$this->db_setup();
if ( $this->db_valid() ) {
// get engines
$this->set( 'engines', $this->get_engines() );
// get tables
$this->set( 'all_tables', $this->get_tables() );
}
break;
}
$info = array(
'table_select' => $this->table_select( false ),
'engines' => $this->get( 'engines' )
);
// set header again before output in case WP does it's thing
header( 'HTTP/1.1 200 OK' );
if ( ! $ajax ) {
$this->html( $html );
} else {
// return json version of results
header( 'Content-Type: application/json' );
echo json_encode( array(
'errors' => $this->get( 'errors' ),
'report' => $this->get( 'report' ),
'info' => $info
) );
exit;
}
}
public function exceptions( $exception ) {
$this->add_error( '<p class="exception">' . $exception->getMessage() . '</p>' );
}
public function errors( $no, $message, $file, $line ) {
$this->add_error( '<p class="error">' . "<strong>{$no}:</strong> {$message} in {$file} on line {$line}" . '</p>', 'results' );
}
public function fatal_handler() {
$error = error_get_last();
if( $error !== NULL ) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
if ( $errno == 1 ) {
header( 'HTTP/1.1 200 OK' );
$this->add_error( '<p class="error">Could not bootstrap environment.<br /> ' . "Fatal error in {$errfile}, line {$errline}. {$errstr}" . '</p>', 'environment' );
$this->response();
}
}
}
/**
* Return an array of all files and directories recursively below $path.
*
* If $path is a file, returns an array containing just that filename.
*
* @param string $path directory/file path.
*
* @return array
*/
public function determine_all_files_below_path( $path ) {
// A file contains only 'itself'.
if ( is_file( $path ) ) {
return array( $path );
}
$directory_contents = glob( $path . '/*' );
$full_recursive_contents = array();
// Every directory contains all of its files, plus 'itself'.
foreach ( $directory_contents as $item_filename ) {
$full_recursive_contents = array_merge($full_recursive_contents, $this->determine_all_files_below_path( $item_filename ) );
}
$full_recursive_contents = array_merge($full_recursive_contents, array( $path ) );
return $full_recursive_contents;
}
/**
* @param $path Filename to inspect
*
* @return boolean true if it is most likely nothing to do with WordPress or Drupal.
*/
public function safe_to_delete_filename( $path ) {
// You'll have to edit this list if
// more files are included in SRDB.
// Using an untargeted deletion operation is
// entirely unacceptable.
$srdb_filename_whitelist = array(
'composer.json',
'index.php',
'package.json',
'README.md',
'srdb.class.php',
'srdb.cli.php',
'srdb-tests',
'charset-test.php',
'DataSet.xml',
'DataSetGenerator.php',
'db.sql',
'SrdbTest.php'
);
foreach ( $srdb_filename_whitelist as $whitelist_item ) {
if ( false !== stripos( $path, $whitelist_item ) ) {
return true;
}
}
return false;
}
/**
* Checks an array of fully qualified filenames to see if they are all
* SRDB filenames.
*
* @param array $array_of_paths
*
* @return boolean true if all paths are most likely SRDB files.
*/
public function safe_to_delete_all_filenames( $array_of_paths ) {
foreach ( $array_of_paths as $path ) {
if ( !$this->safe_to_delete_filename( $path ) ) {
return false;
}
}
return true;
}
const DELETE_SCRIPT_SUCCESS = 0;
const DELETE_SCRIPT_FAIL_CANT_DELETE = -1;
const DELETE_SCRIPT_FAIL_UNSAFE = -2;
/**
* http://stackoverflow.com/questions/3349753/delete-directory-with-files-in-it
*
* @param string $path directory/file path
*
* @return integer DELETE_SCRIPT_SUCCESS for success, DELETE_SCRIPT_FAIL_CANT_DELETE for physical failure, DELETE_SCRIPT_FAIL_UNSAFE for 'Shouldn't delete wordpress' failure.
*/
public function delete_script( $path ) {
$all_targets = $this->determine_all_files_below_path( $path );
$all_targets_minus_containing_directory = $all_targets;
// Proceed if all files identified (except the current directory)
// match a list of whitelisted deletable filenames.
array_pop( $all_targets_minus_containing_directory );
$can_proceed = $this->safe_to_delete_all_filenames( $all_targets_minus_containing_directory );
if ( !$can_proceed ) return self::DELETE_SCRIPT_FAIL_UNSAFE;
foreach ( $all_targets as $target_filename ) {
if ( is_file( $target_filename ) ) {
if ( false === @unlink( $target_filename ) ) return self::DELETE_SCRIPT_FAIL_CANT_DELETE;
} else {
if ( false === @rmdir( $target_filename ) ) return self::DELETE_SCRIPT_FAIL_CANT_DELETE;
}
}
return self::DELETE_SCRIPT_SUCCESS;
}
/**
* Attempts to detect a WordPress installation and bootstraps the environment with it
*
* @return bool Whether it is a WP install and we have database credentials
*/
public function is_wordpress() {
$path_mod = '';
$depth = 0;
$max_depth = 4;
$bootstrap_file = 'wp-blog-header.php';
while( ! file_exists( dirname( __FILE__ ) . "{$path_mod}/{$bootstrap_file}" ) ) {
$path_mod .= '/..';
if ( $depth++ >= $max_depth )
break;
}
if ( file_exists( dirname( __FILE__ ) . "{$path_mod}/{$bootstrap_file}" ) ) {
// store WP path
$this->path = dirname( __FILE__ ) . $path_mod;
// just in case we're white screening
try {
// need to make as many of the globals available as possible or things can break
// (globals suck)
global $wp, $wpdb, $wp_query, $wp_the_query, $wp_version,
$wp_db_version, $tinymce_version, $manifest_version,
$required_php_version, $required_mysql_version,
$post, $posts, $wp_locale, $authordata, $more, $numpages,
$currentday, $currentmonth, $page, $pages, $multipage,
$wp_rewrite, $wp_filesystem, $blog_id, $request,
$wp_styles, $wp_taxonomies, $wp_post_types, $wp_filter,
$wp_object_cache, $query_string, $single, $post_type,
$is_iphone, $is_chrome, $is_safari, $is_NS4, $is_opera,
$is_macIE, $is_winIE, $is_gecko, $is_lynx, $is_IE,
$is_apache, $is_iis7, $is_IIS;
// prevent multisite redirect
define( 'WP_INSTALLING', true );
// prevent super/total cache
define( 'DONOTCACHEDB', true );
define( 'DONOTCACHEPAGE', true );
define( 'DONOTCACHEOBJECT', true );
define( 'DONOTCDN', true );
define( 'DONOTMINIFY', true );
// cancel batcache
if ( function_exists( 'batcache_cancel' ) )
batcache_cancel();
// bootstrap WordPress
require( dirname( __FILE__ ) . "{$path_mod}/{$bootstrap_file}" );
$this->set( 'path', ABSPATH );
$this->set( 'is_wordpress', true );
return true;
} catch( Exception $error ) {
// try and get database values using regex approach
$db_details = $this->define_find( $this->path . '/wp-config.php' );
if ( $db_details ) {
define( 'DB_NAME', $db_details[ 'name' ] );
define( 'DB_USER', $db_details[ 'user' ] );
define( 'DB_PASSWORD', $db_details[ 'pass' ] );
define( 'DB_HOST', $db_details[ 'host' ] );
define( 'DB_CHARSET', $db_details[ 'char' ] );
define( 'DB_COLLATE', $db_details[ 'coll' ] );
// additional error message
$this->add_error( 'WordPress detected but could not bootstrap environment. There might be a PHP error, possibly caused by changes to the database', 'db' );
}
if ( $db_details )
return true;
}
}
return false;
}
public function is_drupal() {
$path_mod = '';
$depth = 0;
$max_depth = 4;
$bootstrap_file = 'includes/bootstrap.inc';
while( ! file_exists( dirname( __FILE__ ) . "{$path_mod}/{$bootstrap_file}" ) ) {
$path_mod .= '/..';
if ( $depth++ >= $max_depth )
break;
}
if ( file_exists( dirname( __FILE__ ) . "{$path_mod}/{$bootstrap_file}" ) ) {
try {
// require the bootstrap include
require_once( dirname( __FILE__ ) . "{$path_mod}/{$bootstrap_file}" );
// define drupal root
if ( ! defined( 'DRUPAL_ROOT' ) )
define( 'DRUPAL_ROOT', dirname( __FILE__ ) . $path_mod );
// load drupal
drupal_bootstrap( DRUPAL_BOOTSTRAP_FULL );
// confirm environment
$this->set( 'is_drupal', true );
return true;
} catch( Exception $error ) {
// We can't add_error here as 'db' because if the db errors array is not empty, the interface doesn't activate!
// This is a consequence of the 'complete' method in JavaScript
$this->add_error( 'Drupal detected but could not bootstrap to retrieve configuration. There might be a PHP error, possibly caused by changes to the database', 'recoverable_db' );
}
}
return false;
}
/**
* Search through the file name passed for a set of defines used to set up
* WordPress db access.
*
* @param string $filename The file name we need to scan for the defines.
*
* @return array List of db connection details.
*/
public function define_find( $filename = 'wp-config.php' ) {
if ( $filename == 'wp-config.php' ) {
$filename = dirname( __FILE__ ) . '/' . basename( $filename );
// look up one directory if config file doesn't exist in current directory
if ( ! file_exists( $filename ) )
$filename = dirname( __FILE__ ) . '/../' . basename( $filename );
}
if ( file_exists( $filename ) && is_file( $filename ) && is_readable( $filename ) ) {
$file = @fopen( $filename, 'r' );
$file_content = fread( $file, filesize( $filename ) );
@fclose( $file );
}
preg_match_all( '/define\s*?\(\s*?([\'"])(DB_NAME|DB_USER|DB_PASSWORD|DB_HOST|DB_CHARSET|DB_COLLATE)\1\s*?,\s*?([\'"])([^\3]*?)\3\s*?\)\s*?;/si', $file_content, $defines );
if ( ( isset( $defines[ 2 ] ) && ! empty( $defines[ 2 ] ) ) && ( isset( $defines[ 4 ] ) && ! empty( $defines[ 4 ] ) ) ) {
foreach( $defines[ 2 ] as $key => $define ) {
switch( $define ) {
case 'DB_NAME':
$name = $defines[ 4 ][ $key ];
break;
case 'DB_USER':
$user = $defines[ 4 ][ $key ];
break;
case 'DB_PASSWORD':
$pass = $defines[ 4 ][ $key ];
break;
case 'DB_HOST':
$host = $defines[ 4 ][ $key ];
break;
case 'DB_CHARSET':
$char = $defines[ 4 ][ $key ];
break;
case 'DB_COLLATE':
$coll = $defines[ 4 ][ $key ];
break;
}
}
}
return array(
'host' => $host,
'name' => $name,
'user' => $user,
'pass' => $pass,
'char' => $char,
'coll' => $coll
);
}
/**
* Display the current url
*
*/
public function self_link() {
return 'http://' . $_SERVER[ 'HTTP_HOST' ] . rtrim( $_SERVER[ 'REQUEST_URI' ], '/' );
}
/**
* Simple html escaping
*
* @param string $string Thing that needs escaping
* @param bool $echo Do we echo or return?
*
* @return string Escaped string.
*/
public function esc_html_attr( $string = '', $echo = false ) {
$output = htmlentities( $string, ENT_QUOTES, 'UTF-8' );
if ( $echo )
echo $output;
else
return $output;
}
public function checked( $value, $value2, $echo = true ) {
$output = $value == $value2 ? ' checked="checked"' : '';
if ( $echo )
echo $output;
return $output;
}
public function selected( $value, $value2, $echo = true ) {
$output = $value == $value2 ? ' selected="selected"' : '';
if ( $echo )
echo $output;
return $output;
}
public function get_errors( $type ) {
if ( ! isset( $this->errors[ $type ] ) || ! count( $this->errors[ $type ] ) )
return;
echo '<div class="errors">';
foreach( $this->errors[ $type ] as $error ) {
if ( $error instanceof Exception )
echo '<p class="exception">' . $error->getMessage() . '</p>';
elseif ( is_string( $error ) )
echo $error;
}
echo '</div>';
}
public function get_report( $table = null ) {
$report = $this->get( 'report' );
if ( empty( $report ) )
return;
$dry_run = $this->get( 'dry_run' );
$search = $this->get( 'search' );
$replace = $this->get( 'replace' );
// Calc the time taken.
$time = array_sum( explode( ' ', $report[ 'end' ] ) ) - array_sum( explode( ' ', $report[ 'start' ] ) );
$srch_rplc_input_phrase = $dry_run ?
'searching for <strong>"' . $search . '"</strong> (to be replaced by <strong>"' . $replace . '"</strong>)' :
'replacing <strong>"' . $search . '"</strong> with <strong>"' . $replace . '"</strong>';
echo '
<div class="report">';
echo '
<h2>Report</h2>';
echo '
<p>';
printf(
'In the process of %s we scanned <strong>%d</strong> tables with a total of
<strong>%d</strong> rows, <strong>%d</strong> cells %s changed.
<strong>%d</strong> db updates were actually performed.
It all took <strong>%f</strong> seconds.',
$srch_rplc_input_phrase,
$report[ 'tables' ],
$report[ 'rows' ],
$report[ 'change' ],
$dry_run ? 'would have been' : 'were',
$report[ 'updates' ],
$time
);
echo '
</p>';
echo '
<table class="table-reports">
<thead>
<tr>
<th>Table</th>
<th>Rows</th>
<th>Cells changed</th>
<th>Updates</th>
<th>Seconds</th>
</tr>
</thead>
<tbody>';
foreach( $report[ 'table_reports' ] as $table => $t_report ) {
$t_time = array_sum( explode( ' ', $t_report[ 'end' ] ) ) - array_sum( explode( ' ', $t_report[ 'start' ] ) );
echo '
<tr>';
printf( '
<th>%s:</th>
<td>%d</td>
<td>%d</td>
<td>%d</td>
<td>%f</td>',
$table,
$t_report[ 'rows' ],
$t_report[ 'change' ],
$t_report[ 'updates' ],
$t_time
);
echo '
</tr>';
}
echo '
</tbody>
</table>';
echo '
</div>';
}
public function table_select( $echo = true ) {
$table_select = '';
if ( ! empty( $this->all_tables ) ) {
$table_select .= '<select name="tables[]" multiple="multiple">';
foreach( $this->all_tables as $table ) {
$size = $table[ 'Data_length' ] / 1000;
$size_unit = 'kb';
if ( $size > 1000 ) {
$size = $size / 1000;
$size_unit = 'Mb';
}
if ( $size > 1000 ) {
$size = $size / 1000;
$size_unit = 'Gb';
}
$size = number_format( $size, 2 ) . $size_unit;
$rows = $table[ 'Rows' ] > 1 ? 'rows' : 'row';
$table_select .= sprintf( '<option value="%s" %s>%s</option>',
$this->esc_html_attr( $table[ 0 ], false ),
$this->selected( true, in_array( $table[ 0 ], $this->tables ), false ),
"{$table[0]}: {$table['Engine']}, rows: {$table['Rows']}, size: {$size}, collation: {$table['Collation']}, character_set: {$table['Character_set']}"
);
}
$table_select .= '</select>';
}
if ( $echo )
echo $table_select;
return $table_select;
}
public function ui() {
// Warn if we're running in safe mode as we'll probably time out.
if ( ini_get( 'safe_mode' ) ) {
?>
<div class="special-errors">
<h4>Warning</h4>
<?php echo printf( '<p>Safe mode is on so you may run into problems if it takes longer than %s seconds to process your request.</p>', ini_get( 'max_execution_time' ) ); ?>
</div>
<?php
}
?>
<form action="" method="post">
<!-- 1. search/replace -->
<fieldset class="row row-search">
<h1>search<span>/</span>replace</h1>
<?php $this->get_errors( 'search' ); ?>
<div class="fields fields-large">
<label for="search"><span class="label-text">replace</span> <span class="hide-if-regex-off regex-left">/</span><input id="search" type="text" placeholder="search for…" value="<?php $this->esc_html_attr( $this->search, true ); ?>" name="search" /><span class="hide-if-regex-off regex-right">/</span></label>
<label for="replace"><span class="label-text">with</span> <input id="replace" type="text" placeholder="replace with…" value="<?php $this->esc_html_attr( $this->replace, true ); ?>" name="replace" /></label>
<label for="regex" class="field-advanced"><input id="regex" type="checkbox" name="regex" value="1" <?php $this->checked( true, $this->regex ); ?> /> use regex</label>
</div>
<div class="fields field-advanced hide-if-regex-off">
<label for="regex_i" class="field field-advanced"><input type="checkbox" name="regex_i" id="regex_i" value="1" <?php $this->checked( true, $this->regex_i ); ?> /> <abbr title="case insensitive">i</abbr></abbr></label>
<label for="regex_m" class="field field-advanced"><input type="checkbox" name="regex_m" id="regex_m" value="1" <?php $this->checked( true, $this->regex_m ); ?> /> <abbr title="multiline">m</abbr></label>
<label for="regex_s" class="field field-advanced"><input type="checkbox" name="regex_s" id="regex_s" value="1" <?php $this->checked( true, $this->regex_s ); ?> /> <abbr title="dot also matches newlines">s</abbr></label>
<label for="regex_x" class="field field-advanced"><input type="checkbox" name="regex_x" id="regex_x" value="1" <?php $this->checked( true, $this->regex_x ); ?> /> <abbr title="extended mode">x</abbr></label>
</div>
</fieldset>
<!-- 2. db details -->
<fieldset class="row row-db">
<h1>db details</h1>
<?php $this->get_errors( 'environment' ); ?>