-
Notifications
You must be signed in to change notification settings - Fork 500
Expand file tree
/
Copy pathTable.php
More file actions
2144 lines (1812 loc) · 81.5 KB
/
Copy pathTable.php
File metadata and controls
2144 lines (1812 loc) · 81.5 KB
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
namespace DeliciousBrains\WPMDB\Common\Sql;
use DeliciousBrains\WPMDB\Common\Error\ErrorLog;
use DeliciousBrains\WPMDB\Common\Error\HandleRemotePostError;
use DeliciousBrains\WPMDB\Common\Filesystem\Filesystem;
use DeliciousBrains\WPMDB\Common\FormData\FormData;
use DeliciousBrains\WPMDB\Common\FullSite\FullSiteExport;
use DeliciousBrains\WPMDB\Common\Http\Helper;
use DeliciousBrains\WPMDB\Common\Http\Http;
use DeliciousBrains\WPMDB\Common\Http\RemotePost;
use DeliciousBrains\WPMDB\Common\Migration\MigrationHelper;
use DeliciousBrains\WPMDB\Common\MigrationPersistence\Persistence;
use DeliciousBrains\WPMDB\Common\MigrationState\MigrationState;
use DeliciousBrains\WPMDB\Common\MigrationState\MigrationStateManager;
use DeliciousBrains\WPMDB\Common\Multisite\Multisite;
use DeliciousBrains\WPMDB\Common\Properties\DynamicProperties;
use DeliciousBrains\WPMDB\Common\Properties\Properties;
use DeliciousBrains\WPMDB\Common\Replace;
use DeliciousBrains\WPMDB\Common\Util\Util;
use DeliciousBrains\WPMDB\WPMDBDI;
use WP_Error;
class Table
{
/**
* @var int
*/
public $max_insert_string_len = 50000;
/**
* @var mixed|void
*/
public $rows_per_segment;
/**
* @var
*/
public $create_alter_table_query;
/**
* @var Filesystem
*/
public $filesystem;
/**
* @var
*/
public $form_data_container;
/**
* @var FormData
*/
public $form_data;
/**
* @var string
*/
public $query_template = '';
/**
* @var
*/
public $primary_keys = array();
/**
* @var
*/
public $row_tracker;
/**
* @var string
*/
public $query_buffer = '';
/**
* @var string
*/
public $current_chunk = '';
/**
* @var Properties
*/
public $props;
/**
* @var
*/
public $state_data;
/**
* @var
*/
public $first_select;
/**
* @var
*/
public $wpdb;
/**
* @var DynamicProperties
*/
public $dynamic_props;
/**
* @var Replace
*/
public $replace;
/**
* @var Util
*/
private $util;
/**
* @var ErrorLog
*/
private $error_log;
/**
* @var MigrationStateManager
*/
private $migration_state_manager;
/**
* @var TableHelper
*/
private $table_helper;
/**
* @var Multisite
*/
private $multisite;
/**
* @var Http
*/
private $http;
/**
* @var Helper
*/
private $http_helper;
/**
* @var RemotePost
*/
private $remote_post;
/**
* @var
*/
private $query_size;
/**
* @var MigrationHelper
*/
private $migration_helper;
/**
* @var FullSiteExport
*/
private $full_site_export;
/**
* Table constructor.
*
* @param Filesystem $filesystem
* @param Util $util
* @param ErrorLog $error_log
* @param MigrationStateManager $migration_state_manager
* @param FormData $form_data
* @param TableHelper $table_helper
* @param Multisite $multisite
* @param Http $http
* @param Helper $http_helper
* @param RemotePost $remote_post
* @param Properties $properties
* @param Replace $replace
*/
public function __construct(
Filesystem $filesystem,
Util $util,
ErrorLog $error_log,
MigrationStateManager $migration_state_manager,
FormData $form_data,
TableHelper $table_helper,
Multisite $multisite,
Http $http,
Helper $http_helper,
RemotePost $remote_post,
Properties $properties,
Replace $replace,
FullSiteExport $full_site_export
) {
$this->rows_per_segment = apply_filters('wpmdb_rows_per_segment', 100);
$this->dynamic_props = DynamicProperties::getInstance();
$this->form_data = $form_data;
$this->props = $properties;
$this->filesystem = $filesystem;
$this->util = $util;
$this->error_log = $error_log;
$this->migration_state_manager = $migration_state_manager;
$this->table_helper = $table_helper;
$this->multisite = $multisite;
$this->http = $http;
$this->http_helper = $http_helper;
$this->remote_post = $remote_post;
$this->replace = $replace;
$this->full_site_export = $full_site_export;
}
/**
* Returns an array of table names with associated size in kilobytes.
*
* @return mixed
*
* NOTE: Returned array may have been altered by wpmdb_table_sizes filter.
*/
function get_table_sizes()
{
global $wpdb;
static $return;
if (!empty($return)) {
return $return;
}
$return = array();
$sql = $wpdb->prepare(
"SELECT TABLE_NAME AS 'table',
ROUND( ( data_length + index_length ) / 1024, 0 ) AS 'size'
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = %s
AND table_type = %s
ORDER BY TABLE_NAME",
DB_NAME,
'BASE TABLE'
);
$results = $wpdb->get_results($sql, ARRAY_A);
if (!empty($results)) {
foreach ($results as $result) {
if ($this->get_legacy_alter_table_name() == $result['table']) {
continue;
}
$return[$result['table']] = $result['size'];
}
}
// "regular" is passed to the filter as the scope for backwards compatibility (a possible but never used scope was "temp").
return apply_filters('wpmdb_table_sizes', $return, 'regular');
}
/**
* Returns the table name where the alter statements are held during the migration (old "wp_" prefixed style).
*
* @return string
*/
function get_legacy_alter_table_name()
{
static $alter_table_name;
if (!empty($alter_table_name)) {
return $alter_table_name;
}
global $wpdb;
$alter_table_name = apply_filters('wpmdb_alter_table_name', $wpdb->base_prefix . 'wpmdb_alter_statements');
return $alter_table_name;
}
/**
* Returns an array of table names with their associated row counts.
*
* @return array
*/
function get_table_row_count()
{
global $wpdb;
$sql = $wpdb->prepare('SELECT TABLE_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = %s ORDER BY TABLE_NAME', DB_NAME);
$results = $wpdb->get_results($sql, ARRAY_A);
$return = array();
foreach ($results as $result) {
if ($this->get_legacy_alter_table_name() == $result['TABLE_NAME']) {
continue;
}
$return[$result['TABLE_NAME']] = ($result['TABLE_ROWS'] == 0 ? 1 : $result['TABLE_ROWS']);
}
return $return;
}
function format_table_sizes($size)
{
$size *= 1024;
return size_format($size);
}
function get_lower_case_table_names_setting()
{
global $wpdb;
$setting = $wpdb->get_var("SHOW VARIABLES LIKE 'lower_case_table_names'", 1);
return empty($setting) ? '-1' : $setting;
}
public function get_sql_dump_info($migration_type, $info_type)
{
$session_salt = strtolower(wp_generate_password(5, false, false));
$datetime = date('YmdHis');
$ds = ($info_type == 'path' ? DIRECTORY_SEPARATOR : '/');
$dump_name = get_bloginfo() ? strtolower(preg_replace('/\s+/', '', get_bloginfo())) : sanitize_title_with_dashes(DB_NAME);
//Strip out any non-alphanumeric characters
$dump_name = preg_replace("/[^A-Za-z0-9 ]/", '', $dump_name);
$dump_name .= 'export' === $migration_type ? '' : '-' . $migration_type;
$dump_name = apply_filters('wpmdb_export_filename', sprintf('%s-%s',$dump_name, $datetime));
$dump_info = sprintf('%s%s%s-%s.sql', $this->filesystem->get_upload_info($info_type), $ds, $dump_name, $session_salt);
return ($info_type == 'path' ? $this->filesystem->slash_one_direction($dump_info) : $dump_info);
}
/**
* Returns SQL queries used to preserve options in the
* wp_options or wp_sitemeta tables during a migration.
*
* @param array $state_data
* @param array $temp_tables
* @param string $intent
*
* @return string DELETE and INSERT SQL queries separated by a newline character (\n).
*/
function get_preserved_options_queries($state_data, $temp_tables, $intent = '')
{
global $wpdb;
$form_data = $this->form_data->getFormData();
$keep_active_plugins = $form_data['keep_active_plugins'] === '1';
$sql = '';
$sitemeta_table_name = '';
$options_table_names = array();
$temp_prefix = isset($state_data['temp_prefix']) ? $state_data['temp_prefix'] : $this->props->temp_prefix;
$table_prefix = $wpdb->base_prefix;
$prefix = esc_sql($temp_prefix . $table_prefix);
foreach ($temp_tables as $temp_table) {
$table = $wpdb->base_prefix . str_replace($prefix, '', $temp_table);
// Get sitemeta table
if (is_multisite() && $this->table_helper->table_is('sitemeta', $table)) {
$sitemeta_table_name = $temp_table;
}
// Get array of options tables
if ($this->table_helper->table_is('options', $table)) {
$options_table_names[] = $temp_table;
}
}
// Return if multisite but sitemeta and option tables not in migration scope
if (is_multisite() && true === empty($sitemeta_table_name) && true === empty($options_table_names)) {
return $sql;
}
// Return if options tables not in migration scope for non-multisite.
if (!is_multisite() && true === empty($options_table_names)) {
return $sql;
}
$preserved_options = array(
'wpmdb_settings',
'wpmdb_error_log',
'wpmdb_schema_version',
'upload_path',
'upload_url_path',
'blog_public',
'wpmdb_migration_options',
'wpmdb_migration_state',
'wpmdb_remote_response',
'wpmdb_recent_migrations',
'wpmdb_saved_profiles',
'wpmdb_remote_migration_state',
);
$preserved_sitemeta_options = $preserved_options;
if ($keep_active_plugins) {
$preserved_options[] = 'active_plugins';
$preserved_sitemeta_options[] = 'active_sitewide_plugins';
}
if (is_multisite()) {
// Get preserved data in site meta table if being replaced.
if (!empty($sitemeta_table_name)) {
$table = $wpdb->base_prefix . str_replace($prefix, '', $sitemeta_table_name);
$preserved_migration_state_options = $wpdb->get_results(
"SELECT `meta_key` FROM `{$table}` WHERE `meta_key` LIKE '" . MigrationState::OPTION_PREFIX . "%'",
OBJECT_K
);
if (!empty($preserved_migration_state_options)) {
$preserved_sitemeta_options = array_merge($preserved_sitemeta_options, array_keys($preserved_migration_state_options));
}
$preserved_sitemeta_options = apply_filters('wpmdb_preserved_sitemeta_options', $preserved_sitemeta_options, $intent);
$preserved_sitemeta_options_escaped = esc_sql($preserved_sitemeta_options);
$preserved_sitemeta_options_data = $wpdb->get_results(
sprintf(
"SELECT * FROM `{$table}` WHERE `meta_key` IN ('%s')",
implode("','", $preserved_sitemeta_options_escaped)
),
ARRAY_A
);
$preserved_sitemeta_options_data = apply_filters('wpmdb_preserved_sitemeta_options_data', $preserved_sitemeta_options_data, $intent);
// Create preserved data queries for site meta table
foreach ($preserved_sitemeta_options_data as $option) {
$sql .= $wpdb->prepare("DELETE FROM `{$sitemeta_table_name}` WHERE `meta_key` = %s;\n", $option['meta_key']);
$sql .= $wpdb->prepare(
"INSERT INTO `{$sitemeta_table_name}` ( `meta_id`, `site_id`, `meta_key`, `meta_value` ) VALUES ( NULL , %s, %s, %s );\n",
$option['site_id'],
$option['meta_key'],
$option['meta_value']
);
}
}
} else {
$preserved_migration_state_options = $wpdb->get_results(
"SELECT `option_name` FROM `{$wpdb->options}` WHERE `option_name` LIKE '" . MigrationState::OPTION_PREFIX . "%'",
OBJECT_K
);
if (!empty($preserved_migration_state_options)) {
$preserved_options = array_merge($preserved_options, array_keys($preserved_migration_state_options));
}
}
// Get preserved data in options tables if being replaced.
if (!empty($options_table_names)) {
$preserved_options = apply_filters('wpmdb_preserved_options', $preserved_options, $intent);
$preserved_options_escaped = esc_sql($preserved_options);
$preserved_options_data = array();
// Get preserved data in options tables
foreach ($options_table_names as $option_table) {
$table = $wpdb->base_prefix . str_replace($prefix, '', $option_table);
$preserved_options_data[$option_table] = $wpdb->get_results(
sprintf(
"SELECT * FROM `{$table}` WHERE `option_name` IN ('%s')",
implode("','", $preserved_options_escaped)
),
ARRAY_A
);
}
$preserved_options_data = apply_filters('wpmdb_preserved_options_data', $preserved_options_data, $intent);
// Create preserved data queries for options tables
foreach ($preserved_options_data as $key => $value) {
if (false === empty($value)) {
foreach ($value as $option) {
$sql .= $wpdb->prepare(
"DELETE FROM `{$key}` WHERE `option_name` = %s;\n",
$option['option_name']
);
$sql .= $wpdb->prepare(
"INSERT INTO `{$key}` ( `option_id`, `option_name`, `option_value`, `autoload` ) VALUES ( NULL , %s, %s, %s );\n",
$option['option_name'],
$option['option_value'],
$option['autoload']
);
}
}
}
}
return $sql;
}
/**
* Preserves the active_plugins option.
*
* @param array $preserved_options
*
* @return array
*/
function preserve_active_plugins_option($preserved_options)
{
$form_data = $this->form_data->getFormData();
$keep_active_plugins = $form_data['keep_active_plugins'] === '1';
if (empty($keep_active_plugins)) {
$preserved_options[] = 'active_plugins';
}
return $preserved_options;
}
/**
* Preserves WPMDB plugins if the "Keep active plugins" option isn't checked.
*
* @param array $preserved_options_data
*
* @return array
*/
function preserve_wpmdb_plugins($preserved_options_data)
{
$form_data = $this->form_data->getFormData();
$keep_active_plugins = $form_data['keep_active_plugins'] === '1';
if (!empty($keep_active_plugins) || empty($preserved_options_data)) {
return $preserved_options_data;
}
foreach ($preserved_options_data as $table => $data) {
foreach ($data as $key => $option) {
if ('active_plugins' === $option['option_name']) {
global $wpdb;
$table_name = esc_sql($table);
$option_value = Util::unserialize($option['option_value']);
$migrated_plugins = array();
$wpmdb_plugins = array();
if ($result = $wpdb->get_var("SELECT option_value FROM $table_name WHERE option_name = 'active_plugins'")) {
$unserialized = Util::unserialize($result);
if (is_array($unserialized)) {
$migrated_plugins = $unserialized;
}
}
foreach ($option_value as $plugin_key => $plugin) {
if (0 === strpos($plugin, 'wp-migrate-db')) {
$wpmdb_plugins[] = $plugin;
}
}
$merged_plugins = array_unique(array_merge($wpmdb_plugins, $migrated_plugins));
$option['option_value'] = serialize($merged_plugins);
$preserved_options_data[$table][$key] = $option;
break;
}
}
}
return $preserved_options_data;
}
/**
* Change table prefix if needed
*
* @param string $table
*
* @return string
*/
public function prefix_target_table_name($table, $state_data)
{
if($state_data['source_prefix'] === $state_data['destination_prefix']) {
return $table;
}
return Util::prefix_updater($table, $state_data['source_prefix'], $state_data['destination_prefix']);
}
/**
* Loops over data in the provided table to perform a migration.
*
* @TODO this has a memory leak, each iteration of the do/while loop leaks 1k or so of memory
*
* @param string $table
*
* @return mixed
*/
function process_table($table, $fp = null, $state_data = [])
{
global $wpdb;
if (!empty($state_data)) {
$this->state_data = $state_data;
}
$temp_prefix = (isset($state_data['temp_prefix']) ? $state_data['temp_prefix'] : $this->props->temp_prefix);
$site_details = empty($state_data['site_details']) ? array() : $state_data['site_details'];
$subsite_migration = array_key_exists('mst_select_subsite', $state_data) && '1' === $state_data['mst_select_subsite'];
$target_table_name = apply_filters('wpmdb_target_table_name', $table, $state_data, $site_details, $subsite_migration );
if (in_array($state_data['intent'], ['push', 'pull']) && !$subsite_migration && $state_data['stage'] !== 'backup') {
$target_table_name = $this->prefix_target_table_name($target_table_name, $state_data);
}
$temp_table_name = $state_data["intent"] === 'import' ? $target_table_name : $temp_prefix . $target_table_name;
$structure_info = $this->get_structure_info($table, [], $state_data);
$row_start = $this->get_current_row($state_data);
$this->row_tracker = $row_start;
if (!is_array($structure_info)) {
return $structure_info;
}
$this->pre_process_data($table, $target_table_name, $temp_table_name, $fp, $state_data);
$to_search = isset($state_data['find_replace_pairs']['replace_old']) ? $state_data['find_replace_pairs']['replace_old'] : [];
$to_replace = isset($state_data['find_replace_pairs']['replace_new']) ? $state_data['find_replace_pairs']['replace_new'] : [];
$search_replace_regex = isset($state_data['find_replace_pairs']['regex']) ? $state_data['find_replace_pairs']['regex'] : [];
$search_replace_case_sensitive = isset($state_data['find_replace_pairs']['case_sensitive']) ? $state_data['find_replace_pairs']['case_sensitive'] : [];
$replacer = $this->replace->register(array(
'table' => ('find_replace' === $state_data['stage']) ? $temp_table_name : $table,
'search' => $to_search,
'replace' => $to_replace,
'regex' => $search_replace_regex,
'case_sensitive' => $search_replace_case_sensitive,
'intent' => $state_data['intent'],
'base_domain' => $this->multisite->get_domain_replace(),
'site_domain' => $this->multisite->get_domain_current_site(),
'wpmdb' => $this,
'site_details' => $site_details,
));
$table_data = null;
// @TODO this has a memory leak
do {
$select_sql = $this->build_select_query($table, $row_start, $structure_info, $state_data);
$table_data = $wpdb->get_results($select_sql);
if (!is_array($table_data)) {
continue;
}
$this->start_query_buffer($target_table_name, $temp_table_name, $structure_info, $state_data);
// Loop over the results
foreach ($table_data as $row) {
$result = $this->process_row($table, $replacer, $row, $structure_info, $fp, $state_data);
if (!is_bool($result)) {
return $result;
}
}
$this->stow_query_buffer($fp);
$row_start += $this->rows_per_segment;
$select_sql = null;
$result = null;
} while (count($table_data) > 0);
// Finalize and return.
$this->post_process_data($table, $target_table_name, $fp, $state_data);
return $this->transfer_chunk($fp, $state_data);
}
/**
* Parses the provided table structure.
*
* @param array $table_structure
*
* @return array
*/
public function get_structure_info( $table, $table_structure = array(), $state_data = [] ) {
if ( empty( $state_data ) ) {
$state_data = Persistence::getStateData();
}
if ( empty( $table_structure ) ) {
$table_structure = $this->get_table_structure( $table );
}
if (!is_array($table_structure)) {
$this->error_log->log_error($this->error_log->getError());
$return = array('wpmdb_error' => 1, 'body' => $this->error_log->getError());
$result = $this->http->end_ajax(json_encode($return));
return $result;
}
// $defs = mysql defaults, looks up the default for that particular column, used later on to prevent empty inserts values for that column
// $ints = holds a list of the possible integer types so as to not wrap them in quotation marks later in the insert statements
$defs = array();
$ints = array();
$bins = array();
$bits = array();
$points = array();
$field_set = array();
$this->primary_keys = array();
$this->first_select = null;
$use_primary_keys = true;
foreach ( $table_structure as $struct ) {
if (
( 0 === strpos( $struct->Type, 'tinyint' ) ) ||
( 0 === strpos( strtolower( $struct->Type ), 'smallint' ) ) ||
( 0 === strpos( strtolower( $struct->Type ), 'mediumint' ) ) ||
( 0 === strpos( strtolower( $struct->Type ), 'int' ) ) ||
( 0 === strpos( strtolower( $struct->Type ), 'bigint' ) )
) {
$defs[ strtolower( $struct->Field ) ] = ( null === $struct->Default ) ? 'NULL' : $struct->Default;
$ints[ strtolower( $struct->Field ) ] = '1';
} elseif (
0 === strpos( $struct->Type, 'binary' ) ||
apply_filters( 'wpmdb_process_column_as_binary', false, $struct )
) {
$bins[ strtolower( $struct->Field ) ] = '1';
} elseif (
0 === strpos( $struct->Type, 'bit' ) ||
apply_filters( 'wpmdb_process_column_as_bit', false, $struct )
) {
$bits[ strtolower( $struct->Field ) ] = '1';
} elseif ( 0 === strpos( $struct->Type, 'point' ) ) {
$points[ strtolower( $struct->Field ) ] = '1';
}
$field_set[] = $this->table_helper->backquote( $struct->Field );
if ( 'PRI' === $struct->Key && true === $use_primary_keys ) {
if ( false !== strpos( $struct->Type, 'binary' ) ) {
$use_primary_keys = false;
$this->primary_keys = array();
continue;
}
$this->primary_keys[ $struct->Field ] = 0;
}
}
// Now we have the table structure, set primary keys to last data position
// if we've come round for another slice of data.
$this->maybe_update_primary_keys_from_state( $state_data );
return array(
'defs' => $defs,
'ints' => $ints,
'bins' => $bins,
'bits' => $bits,
'field_set' => $field_set,
'points' => $points,
);
}
/**
* Returns the table structure for the provided table.
*
* @param string $table
*
* @return array|bool
*/
function get_table_structure($table)
{
global $wpdb;
$table_structure = false;
if ($this->table_exists($table)) {
$table_structure = $wpdb->get_results('DESCRIBE ' . $this->table_helper->backquote($table));
}
if (!$table_structure) {
$this->error_log->setError(sprintf(__('Failed to retrieve table structure for table \'%s\', please ensure your database is online. (#125)', 'wp-migrate-db'), $table));
return false;
}
return $table_structure;
}
/**
* Checks if a given table exists.
*
* @param $table
*
* @return bool
*/
function table_exists($table)
{
global $wpdb;
$table = esc_sql($table);
if ($wpdb->get_var("SHOW TABLES LIKE '$table'")) {
return true;
}
return false;
}
/**
* Returns the current row, checking the state data.
*
* @return int
*/
function get_current_row($state_data = false)
{
if (!$state_data) {
$state_data = Persistence::getStateData();
}
$current_row = 0;
if (!empty($state_data['current_row'])) {
$temp_current_row = trim($state_data['current_row']);
if (!empty($temp_current_row)) {
$current_row = (int)$temp_current_row;
}
}
$current_row = (0 > $current_row) ? 0 : $current_row;
return $current_row;
}
/**
* If state data contains primary keys, update internal variables used for data position tracking.
*
* @param array $state_data
*
* @return void
*/
private function maybe_update_primary_keys_from_state( $state_data = [] ) {
if ( ! empty( $state_data['primary_keys'] ) ) {
if ( ! Util::is_json( $state_data['primary_keys'] ) ) {
$state_data['primary_keys'] = base64_decode( trim( $state_data['primary_keys'] ) );
}
$decoded_primary_keys = json_decode( stripslashes( $state_data['primary_keys'] ), true );
if ( ! empty( $decoded_primary_keys ) ) {
$this->primary_keys = $decoded_primary_keys;
$this->first_select = false;
}
}
}
/**
* Runs before processing the data in a table.
*
* @param string $table
* @param string $target_table_name
* @param string $temp_table_name
*/
function pre_process_data($table, $target_table_name, $temp_table_name, $fp, $state_data)
{
if (0 !== $this->row_tracker) {
return;
}
if (in_array($state_data['intent'], array('find_replace', 'import'))) {
if ('backup' === $state_data['stage']) {
$this->build_table_header($table, $target_table_name, $temp_table_name, $fp, $state_data);
} elseif ('find_replace' === $state_data['intent']) {
$create = $this->create_temp_table($table);
if (true !== $create) {
$message = sprintf(__('Error creating temporary table. Table "%s" does not exist.', 'wp-migrate-db'), esc_html($table));
return $this->http->end_ajax(
new \WP_Error(
'wpmdb-error-creating-temp-table',
$message
)
);
}
}
} else {
$this->build_table_header($table, $target_table_name, $temp_table_name, $fp, $state_data);
}
/**
* Fires just before processing the data for a table.
*
* @param string $table
* @param string $target_table_name
* @param string $temp_table_name
*/
do_action('wpmdb_pre_process_table_data', $table, $target_table_name, $temp_table_name);
}
/**
* Creates the header for a table in a SQL file.
*
* @param string $table
* @param string $target_table_name
* @param string $temp_table_name
*
* @return null|bool
*/
function build_table_header($table, $target_table_name, $temp_table_name, $fp, $state_data)
{
global $wpdb;
// Don't stow data until after `wpmdb_create_table_query` filter is applied as mysql_compat_filter() can return an error
$stow = '';
$is_backup = false;
$table_to_stow = $temp_table_name;
if ('savefile' === $state_data['intent'] || 'backup' === $state_data['stage']) {
$is_backup = true;
$table_to_stow = $target_table_name;
}
// Add SQL statement to drop existing table
if ($is_backup) {
$stow .= ("\n\n");
$stow .= ("#\n");
$stow .= ('# ' . sprintf(__('Delete any existing table %s', 'wp-migrate-db'), $this->table_helper->backquote($table_to_stow)) . "\n");
$stow .= ("#\n");
$stow .= ("\n");
}
$stow .= ('DROP TABLE IF EXISTS ' . $this->table_helper->backquote($table_to_stow) . ";\n");
// Table structure
// Comment in SQL-file
if ($is_backup) {
$stow .= ("\n\n");
$stow .= ("#\n");
$stow .= ('# ' . sprintf(__('Table structure of table %s', 'wp-migrate-db'), $this->table_helper->backquote($table_to_stow)) . "\n");
$stow .= ("#\n");
$stow .= ("\n");
}
$create_table = $wpdb->get_results('SHOW CREATE TABLE ' . $this->table_helper->backquote($table), ARRAY_N);
if (false === $create_table) {
$this->error_log->setError(__('Failed to generate the create table query, please ensure your database is online. (#126)', 'wp-migrate-db'));
return false;
}
//Replaces ANSI quotes with backticks
$create_table[0][1] = $this->remove_ansi_quotes( $create_table[0][1] );
$create_table[0][1] = str_replace( 'CREATE TABLE `' . $table . '`', 'CREATE TABLE `' . $table_to_stow . '`', $create_table[0][1] );
$create_table[0][1] = str_replace( 'TYPE=', 'ENGINE=', $create_table[0][1] );
$alter_table_query = '';
$create_table[0][1] = $this->process_sql_constraint($create_table[0][1], $target_table_name, $alter_table_query);
$create_table[0][1] = apply_filters('wpmdb_create_table_query', $create_table[0][1], $table_to_stow, $this->dynamic_props->target_db_version, $state_data['intent'], $state_data['stage']);
$stow .= ($create_table[0][1] . ";\n");
$this->stow($stow, false, $fp);
if (!empty($alter_table_query)) {
$alter_table_name = $this->get_alter_table_name();
$insert = sprintf("INSERT INTO %s ( `query` ) VALUES ( '%s' );\n", $this->table_helper->backquote($alter_table_name), esc_sql($alter_table_query));
if ($is_backup) {
$process_chunk_result = $this->process_chunk($insert);
if (true !== $process_chunk_result) {
$result = $this->http->end_ajax($process_chunk_result);
return $result;
}
} else {
$this->stow($insert, false, $fp);
}
}
$alter_data_queries = array();
$alter_data_queries = apply_filters('wpmdb_alter_data_queries', $alter_data_queries, $table_to_stow, $state_data['intent'], $state_data['stage']);
if (!empty($alter_data_queries)) {
$alter_table_name = $this->get_alter_table_name();
$insert = '';
foreach ($alter_data_queries as $alter_data_query) {
$insert .= sprintf("INSERT INTO %s ( `query` ) VALUES ( '%s' );\n", $this->table_helper->backquote($alter_table_name), esc_sql($alter_data_query));
}
if ($is_backup) {
$process_chunk_result = $this->process_chunk($insert);
if (true !== $process_chunk_result) {
$result = $this->http->end_ajax($process_chunk_result);
return $result;
}
} else {
$this->stow($insert, false, $fp);
}
}
// Comment in SQL-file
if ($is_backup) {
$this->stow("\n\n", false, $fp);
$this->stow("#\n", false, $fp);
$this->stow('# ' . sprintf(__('Data contents of table %s', 'wp-migrate-db'), $this->table_helper->backquote($table_to_stow)) . "\n", false, $fp);
$this->stow("#\n", false, $fp);
}
}
function process_sql_constraint($create_query, $table, &$alter_table_query)
{
if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) {
$sql_constraints_query = '';
$nl_nix = "\n";
$nl_win = "\r\n";
$nl_mac = "\r";
if (strpos($create_query, $nl_win) !== false) {
$crlf = $nl_win;
} elseif (strpos($create_query, $nl_mac) !== false) {
$crlf = $nl_mac;
} else {
$crlf = $nl_nix;
}
// Split the query into lines, so we can easily handle it.
// We know lines are separated by $crlf (done few lines above).
$sql_lines = explode($crlf, $create_query);
$sql_count = count($sql_lines);
// lets find first line with constraints
for ($i = 0; $i < $sql_count; $i++) {
if (preg_match(
'@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@',