-
Notifications
You must be signed in to change notification settings - Fork 19
/
installer.php
3796 lines (3340 loc) · 345 KB
/
installer.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
/*
Copyright 2011-16 lifeinthegrid.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
SOURCE CONTRIBUTORS:
Gaurav Aggarwal
David Coveney of Interconnect IT Ltd
https://github.com/interconnectit/Search-Replace-DB/
*/
if (file_exists('dtoken.php')) {
//This is most likely inside the snapshot folder.
//DOWNLOAD ONLY: (Only enable download from within the snapshot directory)
if (isset($_GET['get']) && isset($_GET['file'])) {
//Clean the input, strip out anything not alpha-numeric or "_.", so restricts
//only downloading files in same folder, and removes risk of allowing directory
//separators in other charsets (vulnerability in older IIS servers), also
//strips out anything that might cause it to use an alternate stream since
//that would require :// near the front.
$filename = preg_replace('/[^a-zA-Z0-9_.]*/','',$_GET['file']);
if (strlen($filename) && file_exists($filename) && (strstr($filename, '_installer.php'))) {
//Attempt to push the file to the browser
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=installer.php');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
//FIXME: We should consider removing all error supression like this
//as it makes troubleshooting a wild goose chase for times that the
//script failes on such a line. The same can and should be accomplished
//at the server level by turning off displaying errors in PHP.
@ob_clean();
@flush();
if (@readfile($filename) == false) {
$data = file_get_contents($filename);
if ($data == false) {
die("Unable to read installer file. The server currently has readfile and file_get_contents disabled on this server. Please contact your server admin to remove this restriction");
} else {
print $data;
}
}
} else {
header("HTTP/1.1 404 Not Found", true, 404);
header("Status: 404 Not Found");
}
}
//Prevent Access from rovers or direct browsing in snapshop directory, or when
//requesting to download a file, should not go past this point.
exit;
}
?>
<?php if (false) : ?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Error: PHP is not running</title>
</head>
<body>
<h2>Error: PHP is not running</h2>
<p>Duplicator requires that your web server is running PHP. Your server does not have PHP installed, or PHP is turned off.</p>
</body>
</html>
<?php endif; ?>
<?php
/* ==============================================================================================
ADVANCED FEATURES - Allows admins to perform aditional logic on the import.
$GLOBALS['REPLACE_LIST']
Add additional search and replace items to step 2 for the serialize engine.
Place directly below $GLOBALS['REPLACE_LIST'] variable below your items
EXAMPLE:
array_push($GLOBALS['REPLACE_LIST'], array('search' => 'https://oldurl/', 'replace' => 'https://newurl/'));
array_push($GLOBALS['REPLACE_LIST'], array('search' => 'ftps://oldurl/', 'replace' => 'ftps://newurl/'));
================================================================================================= */
//COMPARE VALUES
$GLOBALS['FW_CREATED'] = '2016-10-19 07:03:08';
$GLOBALS['FW_VERSION_DUP'] = '1.1.18';
$GLOBALS['FW_VERSION_WP'] = '4.6.1';
$GLOBALS['FW_VERSION_DB'] = '10.1.18';
$GLOBALS['FW_VERSION_PHP'] = '5.6.26';
$GLOBALS['FW_VERSION_OS'] = 'Linux';
//GENERAL
$GLOBALS['FW_TABLEPREFIX'] = 'wp_';
$GLOBALS['FW_URL_OLD'] = 'http://localhost:8080';
$GLOBALS['FW_URL_NEW'] = '';
$GLOBALS['FW_PACKAGE_NAME'] = '20161019_holzwerk_58071aac6fda65351161019070308_archive.zip';
$GLOBALS['FW_PACKAGE_NOTES'] = '';
$GLOBALS['FW_SECURE_NAME'] = '20161019_holzwerk_58071aac6fda65351161019070308';
$GLOBALS['FW_DBHOST'] = '';
$GLOBALS['FW_DBHOST'] = empty($GLOBALS['FW_DBHOST']) ? 'localhost' : $GLOBALS['FW_DBHOST'];
$GLOBALS['FW_DBPORT'] = '';
$GLOBALS['FW_DBPORT'] = empty($GLOBALS['FW_DBPORT']) ? 3306 : $GLOBALS['FW_DBPORT'];
$GLOBALS['FW_DBNAME'] = '';
$GLOBALS['FW_DBUSER'] = '';
$GLOBALS['FW_DBPASS'] = '';
$GLOBALS['FW_SSL_ADMIN'] = 0;
$GLOBALS['FW_SSL_LOGIN'] = 0;
$GLOBALS['FW_CACHE_WP'] = 0;
$GLOBALS['FW_CACHE_PATH'] = 0;
$GLOBALS['FW_BLOGNAME'] = 'Holzwerk';
$GLOBALS['FW_WPROOT'] = '/var/www/html/';
$GLOBALS['FW_DUPLICATOR_VERSION'] = '1.1.18';
$GLOBALS['FW_OPTS_DELETE'] = json_decode('["duplicator_ui_view_state","duplicator_package_active","duplicator_settings"]', true);
//DATABASE SETUP: all time in seconds
$GLOBALS['DB_MAX_TIME'] = 5000;
$GLOBALS['DB_MAX_PACKETS'] = 268435456;
ini_set('mysql.connect_timeout', '5000');
//PHP SETUP: all time in seconds
ini_set('memory_limit', '2048M');
ini_set("max_execution_time", '5000');
ini_set("max_input_time", '5000');
ini_set('default_socket_timeout', '5000');
@set_time_limit(0);
$GLOBALS['DBCHARSET_DEFAULT'] = 'utf8';
$GLOBALS['DBCOLLATE_DEFAULT'] = 'utf8_general_ci';
//UPDATE TABLE SETTINGS
$GLOBALS['REPLACE_LIST'] = array();
/* ================================================================================================
END ADVANCED FEATURES: Do not edit below here.
=================================================================================================== */
//CONSTANTS
define("DUPLICATOR_INIT", 1);
define("DUPLICATOR_SSDIR_NAME", 'wp-snapshots'); //This should match DUPLICATOR_SSDIR_NAME in duplicator.php
//SHARED POST PARMS
$_POST['action_step'] = isset($_POST['action_step']) ? $_POST['action_step'] : "1";
/* Host has several combinations :
localhost | localhost:55 | localhost: | http://localhost | http://localhost:55 */
$_POST['dbhost'] = isset($_POST['dbhost']) ? trim($_POST['dbhost']) : null;
$_POST['dbport'] = isset($_POST['dbport']) ? trim($_POST['dbport']) : 3306;
$_POST['dbuser'] = isset($_POST['dbuser']) ? trim($_POST['dbuser']) : null;
$_POST['dbpass'] = isset($_POST['dbpass']) ? trim($_POST['dbpass']) : null;
$_POST['dbname'] = isset($_POST['dbname']) ? trim($_POST['dbname']) : null;
$_POST['dbcharset'] = isset($_POST['dbcharset']) ? trim($_POST['dbcharset']) : $GLOBALS['DBCHARSET_DEFAULT'];
$_POST['dbcollate'] = isset($_POST['dbcollate']) ? trim($_POST['dbcollate']) : $GLOBALS['DBCOLLATE_DEFAULT'];
//GLOBALS
$GLOBALS["SQL_FILE_NAME"] = "installer-data.sql";
$GLOBALS["LOG_FILE_NAME"] = "installer-log.txt";
$GLOBALS['SEPERATOR1'] = str_repeat("********", 10);
$GLOBALS['LOGGING'] = isset($_POST['logging']) ? $_POST['logging'] : 1;
$GLOBALS['CURRENT_ROOT_PATH'] = dirname(__FILE__);
$GLOBALS['CHOWN_ROOT_PATH'] = @chmod("{$GLOBALS['CURRENT_ROOT_PATH']}", 0755);
$GLOBALS['CHOWN_LOG_PATH'] = @chmod("{$GLOBALS['CURRENT_ROOT_PATH']}/{$GLOBALS['LOG_FILE_NAME']}", 0644);
$GLOBALS['URL_SSL'] = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? true : false;
$GLOBALS['URL_PATH'] = ($GLOBALS['URL_SSL']) ? "https://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}" : "http://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}";
//Restart log if user starts from step 1
if ($_POST['action_step'] == 1) {
$GLOBALS['LOG_FILE_HANDLE'] = @fopen($GLOBALS['LOG_FILE_NAME'], "w+");
} else {
$GLOBALS['LOG_FILE_HANDLE'] = @fopen($GLOBALS['LOG_FILE_NAME'], "a+");
}
?>
<?php
// Exit if accessed directly
if (! defined('DUPLICATOR_INIT')) {
$_baseURL = "http://" . strlen($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: $_baseURL");
exit;
}
define('ERR_CONFIG_FOUND', 'A wp-config.php already exists in this location. This error prevents users from accidentally overwriting the wrong directories contents. You have two options: <ul><li>Empty this root directory except for the package and installer and try again.</li><li>Delete just the wp-config.php file and try again. This will over-write all other files in the directory.</li></ul>');
define('ERR_ZIPNOTFOUND', 'The packaged zip file was not found. Be sure the zip package is in the same directory as the installer file and as the correct permissions. If you are trying to reinstall a package you can copy the package from the "' . DUPLICATOR_SSDIR_NAME . '" directory back up to your root which is the same location as your installer.php file.');
define('ERR_ZIPOPEN', 'Failed to open zip archive file. Please be sure the archive is completely downloaded before running the installer. Try to extract the archive manually to make sure the file is not corrupted.');
define('ERR_ZIPEXTRACTION', 'Errors extracting zip file. Portions or part of the zip archive did not extract correctly. Try to extract the archive manually with a client side program like unzip/win-zip/winrar to make sure the file is not corrupted. If the file extracts correctly then there is an invalid file or directory that PHP is unable to extract. This can happen if your moving from one operating system to another where certain naming conventions work on one environment and not another. <br/><br/> Workarounds: <br/> 1. Create a new package and be sure to exclude any directories that have invalid names or files in them. This warning will be displayed on the scan results under "Invalid Names". <br/> 2. Manually extract the zip file with a client side program. Then under advanced options in step 1 of the installer check the "Manual package extraction" option and perform the install.');
define('ERR_ZIPMANUAL', 'When choosing manual package extraction, the contents of the package must already be extracted and the wp-config.php and database.sql files must be present in the same directory as the installer.php for the process to continue. Please manually extract the package into the current directory before continuing in manual extraction mode. Also validate that the wp-config.php and database.sql files are present.');
define('ERR_MAKELOG', 'PHP is having issues writing to the log file <b>' . DUPX_Util::set_safe_path($GLOBALS['CURRENT_ROOT_PATH']) . '\installer-log.txt .</b> In order for the Duplicator to proceed validate your owner/group and permission settings for PHP on this path. Try temporarily setting you permissions to 777 to see if the issue gets resolved. If you are on a shared hosting environment please contact your hosting company and tell them you are getting errors writing files to the path above when using PHP.');
define('ERR_ZIPARCHIVE', 'In order to extract the archive.zip file the PHP ZipArchive module must be installed. Please read the FAQ for more details. You can still install this package but you will need to check the Manual package extraction checkbox found in the Advanced Options. Please read the online user guide for details in performing a manual package extraction.');
define('ERR_MYSQLI_SUPPORT', 'In order to complete an install the mysqli extension for PHP is required. If you are on a hosted server please contact your host and request that mysqli be enabled. For more information visit: http://php.net/manual/en/mysqli.installation.php');
define('ERR_DBCONNECT', 'DATABASE CONNECTION FAILED!<br/>');
define('ERR_DBCONNECT_CREATE', 'DATABASE CREATION FAILURE!<br/> Unable to create database "%s". Check to make sure the user has "Create" privileges. Some hosts will restrict creation of a database only through the cpanel. Try creating the database manually to proceed with installation. If the database already exists then check the radio button labeled "Connect and Remove All Data" which will remove all existing tables.');
define('ERR_DBTRYCLEAN', 'DATABASE CREATION FAILURE!<br/> Unable to remove all tables from database "%s".<br/> Please remove all tables from this database and try the installation again.');
define('ERR_DBCREATE', 'The database "%s" does not exists.<br/> Change mode to create in order to create a new database.');
define('ERR_DBEMPTY', 'The database "%s" has "%s" tables. The Duplicator only works with an EMPTY database. Enable the action "Connect and Remove All Data" radio button to remove all tables and or create a new database. Some hosting providers do not allow table removal from scripts. In this case you will need to login to your hosting providers control panel and remove the tables manually. Please contact your hosting provider for further details. Always backup all your data before proceeding!');
define('ERR_TESTDB_UTF8', 'UTF8 Characters were detected as part of the database connection string. If your connection fails be sure to update the MySQL my.ini configuration file setting to support UTF8 characters by enabling this option [character_set_server=utf8] and restarting the database server.');
define('ERR_TESTDB_VERSION', 'In order to avoid database incompatibility issues make sure the database versions between the build and installer servers are as close as possible. If the package was created on a newer database version than where it is being installed then you might run into issues.<br/><br/> It is best to make sure the server where the installer is running has the same or higher version number than where it was built. If the major and minor version are the same or close for example [5.7 to 5.6], then the migration should work without issues. A version pair of [5.7 to 5.1] is more likely to cause issues unless you have a very simple setup. If the versions are too far apart work with your hosting provider to upgrade the MySQL engine on this server.');
/** * *****************************************************
* DUPX_Log
* Class used to log information */
class DUPX_Log {
/** METHOD: LOG
* Used to write debug info to the text log file
* @param string $msg Any text data
* @param int $loglevel Log level
*/
static public function Info($msg, $logging = 1) {
if ($logging <= $GLOBALS["LOGGING"]) {
@fwrite($GLOBALS["LOG_FILE_HANDLE"], "{$msg}\n");
}
}
static public function Error($errorMessage) {
if ($logging <= $GLOBALS["LOGGING"]) {
$breaks = array("<br />","<br>","<br/>");
$msg = str_ireplace($breaks, "\r\n", $errorMessage);
@fwrite($GLOBALS["LOG_FILE_HANDLE"], "\nINSTALLER ERROR:\n{$msg}\n");
@fclose($GLOBALS["LOG_FILE_HANDLE"]);
}
die("<div class='dup-ui-error'><b style='color:#B80000;'>INSTALL ERROR!</b><br/>{$errorMessage}</div><br/>");
}
}
?>
<?php
// Exit if accessed directly
if (! defined('DUPLICATOR_INIT')) {
$_baseURL = "http://" . strlen($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: $_baseURL");
exit;
}
/** * *****************************************************
* Various Static Utility methods for working with the installer */
class DUPX_Util
{
/**
* Get current microtime as a float. Can be used for simple profiling.
*/
static public function get_microtime() {
return microtime(true);
}
/**
* Return a string with the elapsed time.
* Order of $end and $start can be switched.
*/
static public function elapsed_time($end, $start) {
return sprintf("%.4f sec.", abs($end - $start));
}
/**
* @param string $string Thing that needs escaping
* @param bool $echo Do we echo or return?
* @return string Escaped string.
*/
static public function esc_html_attr($string = '', $echo = false) {
$output = htmlentities($string, ENT_QUOTES, 'UTF-8');
if ($echo)
echo $output;
else
return $output;
}
/**
* Count the tables in a given database
* @param string $_POST['dbname'] Database to count tables in
*/
static public function dbtable_count($conn, $dbname) {
$res = mysqli_query($conn, "SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = '{$dbname}' ");
$row = mysqli_fetch_row($res);
return is_null($row) ? 0 : $row[0];
}
/**
* Returns the table count
* @param string $conn A valid link resource
* @param string $table_name A valid table name
*/
static public function table_row_count($conn, $table_name) {
$total = mysqli_query($conn, "SELECT COUNT(*) FROM `$table_name`");
if ($total) {
$total = @mysqli_fetch_array($total);
return $total[0];
} else {
return 0;
}
}
/**
* Adds a slash to the end of a path
* @param string $path A path
*/
static public function add_slash($path) {
$last_char = substr($path, strlen($path) - 1, 1);
if ($last_char != '/') {
$path .= '/';
}
return $path;
}
/**
* Makes path safe for any OS
* Paths should ALWAYS READ be "/"
* uni: /home/path/file.xt
* win: D:/home/path/file.txt
* @param string $path The path to make safe
*/
static public function set_safe_path($path) {
return str_replace("\\", "/", $path);
}
static public function unset_safe_path($path) {
return str_replace("/", "\\", $path);
}
/**
* PHP_SAPI for fcgi requires a data flush of at least 256
* bytes every 40 seconds or else it forces a script hault
*/
static public function fcgi_flush() {
echo(str_repeat(' ', 256));
@flush();
}
/**
* A safe method used to copy larger files
* @param string $source The path to the file being copied
* @param string $destination The path to the file being made
*/
static public function copy_file($source, $destination) {
$sp = fopen($source, 'r');
$op = fopen($destination, 'w');
while (!feof($sp)) {
$buffer = fread($sp, 512); // use a buffer of 512 bytes
fwrite($op, $buffer);
}
// close handles
fclose($op);
fclose($sp);
}
/**
* Finds a string in a file and returns true if found
* @param array $list A list of strings to search for
* @param string $haystack The string to search in
*/
static public function string_has_value($list, $file) {
foreach ($list as $var) {
if (strstr($file, $var) !== false) {
return true;
}
}
return false;
}
/** METHOD: get_active_plugins
* Returns the active plugins for a package
* @param conn $dbh A database connection handle
* @return array $list A list of active plugins
*/
static public function get_active_plugins($dbh) {
$query = @mysqli_query($dbh, "SELECT option_value FROM `{$GLOBALS['FW_TABLEPREFIX']}options` WHERE option_name = 'active_plugins' ");
if ($query) {
$row = @mysqli_fetch_array($query);
$all_plugins = unserialize($row[0]);
if (is_array($all_plugins)) {
return $all_plugins;
}
}
return array();
}
/**
* Returns the tables for a database
* @param conn $dbh A database connection handle
* @return array $list A list of all table names
*/
static public function get_database_tables($dbh) {
$query = @mysqli_query($dbh, 'SHOW TABLES');
if ($query) {
while ($table = @mysqli_fetch_array($query)) {
$all_tables[] = $table[0];
}
if (isset($all_tables) && is_array($all_tables)) {
return $all_tables;
}
}
return array();
}
/**
* MySQL connection support for sock
* @param same as mysqli_connect
* @return database connection handle
*/
static public function db_connect( $host, $username, $password, $dbname = '', $port = null ) {
//sock connections
if ( 'sock' === substr( $host, -4 ) )
{
$url_parts = parse_url( $host );
$dbh = @mysqli_connect( 'localhost', $username, $password, $dbname, null, $url_parts['path'] );
}
else
{
$dbh = @mysqli_connect( $host, $username, $password, $dbname, $port );
}
return $dbh;
}
/**
* MySQL database version number
* @param conn $dbh Database connection handle
* @return false|string false on failure, version number on success
*/
static public function mysql_version($dbh) {
if (function_exists('mysqli_get_server_info')) {
return preg_replace('/[^0-9.].*/', '', mysqli_get_server_info($dbh));
} else {
return 0;
}
}
/**
* MySQL server variable
* @param conn $dbh Database connection handle
* @return string the server variable to query for
*/
static public function mysql_variable_value($dbh, $variable) {
$result = @mysqli_query($dbh, "SHOW VARIABLES LIKE '{$variable}'");
$row = @mysqli_fetch_array($result);
@mysqli_free_result($result);
return isset($row[1]) ? $row[1] : null;
}
/**
* Determine if a MySQL database supports a particular feature
* @param conn $dbh Database connection handle
* @param string $feature the feature to check for
* @return bool
*/
static public function mysql_has_ability($dbh, $feature) {
$version = self::mysql_version($dbh);
switch (strtolower($feature)) {
case 'collation' :
case 'group_concat' :
case 'subqueries' :
return version_compare($version, '4.1', '>=');
case 'set_charset' :
return version_compare($version, '5.0.7', '>=');
};
return false;
}
/**
* Sets the MySQL connection's character set.
* @param resource $dbh The resource given by mysqli_connect
* @param string $charset The character set (optional)
* @param string $collate The collation (optional)
*/
static public function mysql_set_charset($dbh, $charset = null, $collate = null) {
$charset = (!isset($charset) ) ? $GLOBALS['DBCHARSET_DEFAULT'] : $charset;
$collate = (!isset($collate) ) ? $GLOBALS['DBCOLLATE_DEFAULT'] : $collate;
if (self::mysql_has_ability($dbh, 'collation') && !empty($charset)) {
if (function_exists('mysqli_set_charset') && self::mysql_has_ability($dbh, 'set_charset')) {
return mysqli_set_charset($dbh, $charset);
} else {
$sql = " SET NAMES {$charset}";
if (!empty($collate))
$sql .= " COLLATE {$collate}";
return mysqli_query($dbh, $sql);
}
}
}
/**
* Display human readable byte sizes
* @param string $size The size in bytes
*/
static public function readable_bytesize($size) {
try {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
for ($i = 0; $size >= 1024 && $i < 4; $i++)
$size /= 1024;
return round($size, 2) . $units[$i];
} catch (Exception $e) {
return "n/a";
}
}
/**
* The characters that are special in the replacement value of preg_replace are not the
* same characters that are special in the pattern
* @param string $str The string to replace on
*/
static public function preg_replacement_quote($str) {
return preg_replace('/(\$|\\\\)(?=\d)/', '\\\\\1', $str);
}
/**
* Check to see if the internet is accessable
* NOTE: fsocketopen on windows doesn't seem to honor $timeout setting.
*
* @param string $url A url e.g without prefix "ajax.googleapis.com"
* @param string $port A valid port number
* @return bool
*/
public static function is_url_active($url, $port, $timeout=5)
{
if (function_exists('fsockopen'))
{
@ini_set("default_socket_timeout", 5);
$port = isset($port) && is_integer($port) ? $port : 80;
$connected = @fsockopen($url, $port, $errno, $errstr, $timeout); //website and port
if ($connected){
@fclose($connected);
return true;
}
return false;
} else {
return false;
}
}
/**
* Returns an array of zip files found in the current directory
* @return array of zip files
*/
static public function get_zip_files() {
$files = array();
foreach (glob("*.zip") as $name) {
if (file_exists($name)) {
$files[] = $name;
}
}
if (count($files) > 0) {
return $files;
}
//FALL BACK: Windows XP has bug with glob,
//add secondary check for PHP lameness
if ($dh = opendir('.'))
{
while (false !== ($name = readdir($dh))) {
$ext = substr($name, strrpos($name, '.') + 1);
if(in_array($ext, array("zip"))) {
$files[] = $name;
}
}
closedir($dh);
}
return $files;
}
/**
* Does a string have non ascii characters
*/
public static function is_non_ascii($string)
{
return preg_match('/[^\x20-\x7f]/', $string);
}
}
?>
<?php
// Exit if accessed directly
if (!defined('DUPLICATOR_INIT')) {
$_baseURL = "http://" . strlen($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: {$_baseURL}");
exit;
}
/**
* Class used to update and edit web server configuration files
* for both Apache and IIS files .htaccess and web.config */
class DUPX_WPConfig
{
/**
* Updates the web server config files in Step 1 */
public static function UpdateStep1()
{
$root_path = DUPX_Util::set_safe_path($GLOBALS['CURRENT_ROOT_PATH']);
$wpconfig = @file_get_contents('wp-config.php', true);
$patterns = array(
"/'DB_NAME',\s*'.*?'/",
"/'DB_USER',\s*'.*?'/",
"/'DB_PASSWORD',\s*'.*?'/",
"/'DB_HOST',\s*'.*?'/");
$db_host = ($_POST['dbport'] == 3306) ? $_POST['dbhost'] : "{$_POST['dbhost']}:{$_POST['dbport']}";
$replace = array(
"'DB_NAME', " . '\'' . $_POST['dbname'] . '\'',
"'DB_USER', " . '\'' . $_POST['dbuser'] . '\'',
"'DB_PASSWORD', " . '\'' . DUPX_Util::preg_replacement_quote($_POST['dbpass']) . '\'',
"'DB_HOST', " . '\'' . $db_host . '\'');
//SSL CHECKS
if ($_POST['ssl_admin']) {
if (! strstr($wpconfig, 'FORCE_SSL_ADMIN')) {
$wpconfig = $wpconfig . PHP_EOL . "define('FORCE_SSL_ADMIN', true);";
}
} else {
array_push($patterns, "/'FORCE_SSL_ADMIN',\s*true/");
array_push($replace, "'FORCE_SSL_ADMIN', false");
}
if ($_POST['ssl_login']) {
if (! strstr($wpconfig, 'FORCE_SSL_LOGIN')) {
$wpconfig = $wpconfig . PHP_EOL . "define('FORCE_SSL_LOGIN', true);";
}
} else {
array_push($patterns, "/'FORCE_SSL_LOGIN',\s*true/");
array_push($replace, "'FORCE_SSL_LOGIN', false");
}
//CACHE CHECKS
if ($_POST['cache_wp']) {
if (! strstr($wpconfig, 'WP_CACHE')) {
$wpconfig = $wpconfig . PHP_EOL . "define('WP_CACHE', true);";
}
} else {
array_push($patterns, "/'WP_CACHE',\s*true/");
array_push($replace, "'WP_CACHE', false");
}
if (! $_POST['cache_path']) {
array_push($patterns, "/'WPCACHEHOME',\s*'.*?'/");
array_push($replace, "'WPCACHEHOME', ''");
}
if (! is_writable("{$root_path}/wp-config.php") )
{
if (file_exists("{$root_path}/wp-config.php"))
{
chmod("{$root_path}/wp-config.php", 0644)
? DUPX_Log::Info('File Permission Update: wp-config.php set to 0644')
: DUPX_Log::Info('WARNING: Unable to update file permissions and write to wp-config.php. Please visit the online FAQ for setting file permissions and work with your hosting provider or server administrator to enable this installer.php script to write to the wp-config.php file.');
} else {
DUPX_Log::Info('WARNING: Unable to locate wp-config.php file. Be sure the file is present in your archive.');
}
}
$wpconfig = preg_replace($patterns, $replace, $wpconfig);
file_put_contents('wp-config.php', $wpconfig);
$wpconfig = null;
}
/**
* Updates the web server config files in Step 2 */
public static function UpdateStep2()
{
//Placeholder step 2 logic
}
}
?>
<?php
// Exit if accessed directly
if (! defined('DUPLICATOR_INIT')) {
$_baseURL = "http://" . strlen($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: $_baseURL");
exit;
}
/** * *****************************************************
* Class used to update and edit web server configuration files */
class DUPX_ServerConfig {
/**
* Clear .htaccess and web.config files and backup
*/
static public function Reset() {
DUPX_Log::Info("\nWEB SERVER CONFIGURATION FILE RESET:");
//Apache
@copy('.htaccess', '.htaccess.orig');
@unlink('.htaccess');
//IIS
@copy('web.config', 'web.config.orig');
@unlink('web.config');
//.user.ini - For WordFence
@copy('.user.ini', '.user.ini.orig');
@unlink('.user.ini');
DUPX_Log::Info("- Backup of .htaccess/web.config made to .orig");
DUPX_Log::Info("- Reset of .htaccess/web.config files");
$tmp_htaccess = '# RESET FOR DUPLICATOR INSTALLER USEAGE';
file_put_contents('.htaccess', $tmp_htaccess);
@chmod('.htaccess', 0644);
}
/** METHOD: ResetHTACCESS
* Resets the .htaccess file
*/
static public function Setup() {
if (! isset($_POST['url_new'])) {
return;
}
DUPX_Log::Info("\nWEB SERVER CONFIGURATION FILE BASIC SETUP:");
$currdata = parse_url($_POST['url_old']);
$newdata = parse_url($_POST['url_new']);
$currpath = DUPX_Util::add_slash(isset($currdata['path']) ? $currdata['path'] : "");
$newpath = DUPX_Util::add_slash(isset($newdata['path']) ? $newdata['path'] : "");
$tmp_htaccess = <<<HTACCESS
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase {$newpath}
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . {$newpath}index.php [L]
</IfModule>
# END WordPress
HTACCESS;
file_put_contents('.htaccess', $tmp_htaccess);
@chmod('.htaccess', 0644);
DUPX_Log::Info("created basic .htaccess file. If using IIS web.config this process will need to be done manually.");
}
}
?>
<?php
// Exit if accessed directly
if (!defined('DUPLICATOR_INIT')) {
$_baseURL = "http://" . strlen($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: {$_baseURL}");
exit;
}
/** * *****************************************************
* CLASS::DUPX_UpdateEngine
* Walks every table in db that then walks every row and column replacing searches with replaces
* large tables are split into 50k row blocks to save on memory. */
class DUPX_UpdateEngine
{
/**
* LOG ERRORS
*/
public static function log_errors($report)
{
if (!empty($report['errsql'])) {
DUPX_Log::Info("====================================");
DUPX_Log::Info("DATA-REPLACE ERRORS (MySQL)");
foreach ($report['errsql'] as $error) {
DUPX_Log::Info($error);
}
DUPX_Log::Info("");
}
if (!empty($report['errser'])) {
DUPX_Log::Info("====================================");
DUPX_Log::Info("DATA-REPLACE ERRORS (Serialization):");
foreach ($report['errser'] as $error) {
DUPX_Log::Info($error);
}
DUPX_Log::Info("");
}
if (!empty($report['errkey'])) {
DUPX_Log::Info("====================================");
DUPX_Log::Info("DATA-REPLACE ERRORS (Key):");
DUPX_Log::Info('Use SQL: SELECT @row := @row + 1 as row, t.* FROM some_table t, (SELECT @row := 0) r');
foreach ($report['errkey'] as $error) {
DUPX_Log::Info($error);
}
}
}
/**
* LOG STATS
*/
public static function log_stats($report)
{
if (!empty($report) && is_array($report))
{
$stats = "--------------------------------------\n";
$srchnum = 0;
foreach ($GLOBALS['REPLACE_LIST'] as $item)
{
$srchnum++;
$stats .= sprintf("Search{$srchnum}:\t'%s' \nChange{$srchnum}:\t'%s' \n", $item['search'], $item['replace']);
}
$stats .= sprintf("SCANNED:\tTables:%d \t|\t Rows:%d \t|\t Cells:%d \n", $report['scan_tables'], $report['scan_rows'], $report['scan_cells']);
$stats .= sprintf("UPDATED:\tTables:%d \t|\t Rows:%d \t|\t Cells:%d \n", $report['updt_tables'], $report['updt_rows'], $report['updt_cells']);
$stats .= sprintf("ERRORS:\t\t%d \nRUNTIME:\t%f sec", $report['err_all'], $report['time']);
DUPX_Log::Info($stats);
}
}
/**
* Returns only the text type columns of a table ignoring all numeric types
*/
public static function getTextColumns($conn, $table)
{
$type_where = "type NOT LIKE 'tinyint%' AND ";
$type_where .= "type NOT LIKE 'smallint%' AND ";
$type_where .= "type NOT LIKE 'mediumint%' AND ";
$type_where .= "type NOT LIKE 'int%' AND ";
$type_where .= "type NOT LIKE 'bigint%' AND ";
$type_where .= "type NOT LIKE 'float%' AND ";
$type_where .= "type NOT LIKE 'double%' AND ";
$type_where .= "type NOT LIKE 'decimal%' AND ";
$type_where .= "type NOT LIKE 'numeric%' AND ";
$type_where .= "type NOT LIKE 'date%' AND ";
$type_where .= "type NOT LIKE 'time%' AND ";
$type_where .= "type NOT LIKE 'year%' ";
$result = mysqli_query($conn, "SHOW COLUMNS FROM `{$table}` WHERE {$type_where}");
if (!$result) {
return null;
}
$fields = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$fields[] = $row['Field'];
}
}
//Return Primary which is needed for index lookup
//$result = mysqli_query($conn, "SHOW INDEX FROM `{$table}` WHERE KEY_NAME LIKE '%PRIMARY%'"); 1.1.15 updated
$result = mysqli_query($conn, "SHOW INDEX FROM `{$table}`");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$fields[] = $row['Column_name'];
}
}
return (count($fields) > 0) ? $fields : null;
}
/**
* LOAD
* Begins the processing for replace logic
* @param mysql $conn The db connection object
* @param array $list Key value pair of 'search' and 'replace' arrays
* @param array $tables The tables we want to look at
* @param array $fullsearch Search every column reguardless of its data type
* @return array Collection of information gathered during the run.
*/
public static function load($conn, $list = array(), $tables = array(), $fullsearch = false)
{
$report = array(
'scan_tables' => 0,
'scan_rows' => 0,
'scan_cells' => 0,
'updt_tables' => 0,
'updt_rows' => 0,
'updt_cells' => 0,
'errsql' => array(),
'errser' => array(),
'errkey' => array(),
'errsql_sum' => 0,
'errser_sum' => 0,
'errkey_sum' => 0,
'time' => '',
'err_all' => 0
);
$walk_function = create_function('&$str', '$str = "`$str`";');
$profile_start = DUPX_Util::get_microtime();
if (is_array($tables) && !empty($tables)) {
foreach ($tables as $table)
{
$report['scan_tables']++;
$columns = array();
// Get a list of columns in this table
$fields = mysqli_query($conn, 'DESCRIBE ' . $table);
while ($column = mysqli_fetch_array($fields)) {
$columns[$column['Field']] = $column['Key'] == 'PRI' ? true : false;
}
// Count the number of rows we have in the table if large we'll split into blocks
$row_count = mysqli_query($conn, "SELECT COUNT(*) FROM `{$table}`");
$rows_result = mysqli_fetch_array($row_count);
@mysqli_free_result($row_count);
$row_count = $rows_result[0];
if ($row_count == 0) {
DUPX_Log::Info("{$table}^ ({$row_count})");
continue;
}
$page_size = 25000;
$offset = ($page_size + 1);
$pages = ceil($row_count / $page_size);
// Grab the columns of the table. Only grab text based columns because
// they are the only data types that should allow any type of search/replace logic
$colList = '*';
$colMsg = '*';
if (! $fullsearch)
{
$colList = self::getTextColumns($conn, $table);
if ($colList != null && is_array($colList)) {
array_walk($colList, $walk_function);
$colList = implode(',', $colList);
}
$colMsg = (empty($colList)) ? '*' : '~';
}
if (empty($colList))
{
DUPX_Log::Info("{$table}^ ({$row_count})");
continue;
}
else
{
DUPX_Log::Info("{$table}{$colMsg} ({$row_count})");
}
//Paged Records
for ($page = 0; $page < $pages; $page++)
{
$current_row = 0;
$start = $page * $page_size;
$end = $start + $page_size;
$sql = sprintf("SELECT {$colList} FROM `%s` LIMIT %d, %d", $table, $start, $offset);
$data = mysqli_query($conn, $sql);
if (!$data)
$report['errsql'][] = mysqli_error($conn);
$scan_count = ($row_count < $end) ? $row_count : $end;
DUPX_Log::Info("\tScan => {$start} of {$scan_count}", 2);
//Loops every row
while ($row = mysqli_fetch_array($data))
{
$report['scan_rows']++;
$current_row++;
$upd_col = array();
$upd_sql = array();
$where_sql = array();
$upd = false;
$serial_err = 0;
//Loops every cell
foreach ($columns as $column => $primary_key)
{
$report['scan_cells']++;
$edited_data = $data_to_fix = $row[$column];
$base64coverted = false;
$txt_found = false;
//Only replacing string values
if (!empty($row[$column]) && !is_numeric($row[$column]))
{
//Base 64 detection