PluginProbe ʕ •ᴥ•ʔ
Backup Migration / 1.3.0
Backup Migration v1.3.0
2.1.6 2.1.5.2 trunk 1.3.0 1.3.1 1.3.2 1.3.3 1.3.4 1.3.5 1.3.6 1.3.7 1.3.8 1.3.9 1.4.0 1.4.1 1.4.2 1.4.3 1.4.4 1.4.5 1.4.6 1.4.6.1 1.4.7 1.4.8 1.4.9 1.4.9.1 2.0.0 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.5.1
backup-backup / includes / database / even-better-restore-v4.php
backup-backup / includes / database Last commit date
better-backup-v3.php 2 years ago better-backup.php 2 years ago better-restore.php 2 years ago even-better-restore-v3.php 2 years ago even-better-restore-v4.php 2 years ago manager.php 2 years ago search-replace.php 2 years ago smart-sort.php 2 years ago
even-better-restore-v4.php
833 lines
1 <?php
2
3 /**
4 * Author: Mikołaj `iClyde` Chodorowski
5 * Contact: kontakt@iclyde.pl
6 * Package: Backup Migration – WP Plugin
7 */
8
9 // Namespace
10 namespace BMI\Plugin\Database;
11
12 // Use
13 use BMI\Plugin\BMI_Logger AS Logger;
14 use BMI\Plugin\Backup_Migration_Plugin as BMP;
15 use BMI\Plugin\Progress\BMI_ZipProgress AS Progress;
16 use BMI\Plugin\Database\BMI_Search_Replace_Engine as BMISearchReplace;
17
18 // Exit on direct access
19 if (!defined('ABSPATH')) exit;
20
21 /**
22 * Database Restore Enginge v4
23 */
24 class BMI_Even_Better_Database_Restore {
25
26 // Unwanted tables
27 private $unwantedTables = [
28 'wfblockediplog',
29 'wfblocks7',
30 'wfcrawlers',
31 'wffilechanges',
32 'wffilemods',
33 'wfhits',
34 'wfhoover',
35 'wfissues',
36 'wfknownfilelist',
37 'wflivetraffichuman',
38 'wflocs',
39 'wflogins',
40 'wfnotifications',
41 'wfpendingissues',
42 'wfreversecache',
43 'wfsnipcache',
44 'wfstatus',
45 'wftrafficrate',
46 'actionscheduler_logs',
47 'slim_stats',
48 'woocommerce_sessions',
49 'yoast_indexable',
50 'slim_events',
51 'cerber_files',
52 'cerber_traffic',
53 'cerber_log',
54 'cerber_countries',
55 'cerber_blocks',
56 'cerber_acl',
57 'statistics_views',
58 'pcachewpr',
59 'statistics_visitor_relationships',
60 'statistics_visitor',
61 'statistics_visit',
62 'statistics_search',
63 'statistics_pages',
64 'icl_languages_translations',
65 'icl_string_pages',
66 'icl_string_translations',
67 'itsec_log',
68 'actionscheduler_actions',
69 'aepc_logs'
70 ];
71
72 /**
73 * __construct - Make connection
74 *
75 * @return @self
76 */
77 function __construct($storage, $firstDB, &$manifest, &$logger, $splitting, $isCLI) {
78
79 $this->isCLI = $isCLI;
80 $this->splitting = $splitting;
81 $this->storage = $storage;
82 $this->logger = &$logger;
83 $this->manifest = &$manifest;
84 $this->tablemap = BMI_INCLUDES . DIRECTORY_SEPARATOR . 'htaccess' . DIRECTORY_SEPARATOR . '.table_map';
85
86 if ($firstDB) $this->initMessage();
87
88 $this->map = $this->getTableMap();
89 $this->seek = &$this->map['seek'];
90
91 }
92
93 public function start() {
94
95 if ($this->isCLI) {
96
97 while ($nextFile = $this->getNextFile()) {
98 $this->processFile($nextFile);
99 }
100
101 return true;
102
103 } else {
104
105 $nextFile = $this->getNextFile();
106 if ($nextFile === false) return true;
107 else {
108
109 $this->processFile($nextFile);
110
111 return false;
112
113 }
114
115 }
116
117 }
118
119 private function getTableMap() {
120
121 if (file_exists($this->tablemap)) {
122
123 $data = json_decode(file_get_contents($this->tablemap), true);
124 $this->map = $data;
125
126 } else {
127
128 $data = [
129 'tables' => [],
130 'seek' => [
131 'last_seek' => 0,
132 'last_file' => '...',
133 'last_start' => 0,
134 'total_tables' => sizeof(array_diff(scandir($this->storage), ['..', '.'])),
135 'active_plugins' => 'a:1:{i:0;s:31:"backup-backup/backup-backup.php";}'
136 ]
137 ];
138
139 file_put_contents($this->tablemap, json_encode($data));
140
141 }
142
143 return $data;
144
145 }
146
147 private function getTableProgress() {
148
149 $total_tables = $this->seek['total_tables'];
150 $tables_left = sizeof(array_diff(scandir($this->storage), ['..', '.']));
151
152 $finished_tables = ($total_tables - $tables_left) + 1;
153 $percentage = number_format(($finished_tables / $total_tables) * 100, 2);
154
155 $this->logger->progress(50 + ((number_format($percentage, 0) / 2) - 10));
156
157 return $finished_tables . '/' . $total_tables . ' (' . $percentage . '%)';
158
159 }
160
161 private function queryFile(&$objFile, $filePath, $tableName, $realTableName) {
162
163 global $wpdb;
164
165 $seek = &$this->seek['last_seek'];
166 if ($seek == 0) {
167 $seek = 5;
168 $wpdb->query("DROP TABLE IF EXISTS `" . $tableName . "`;");
169
170 $str = __("Started restoration of %table_name% %total_tables% table", 'backup-backup');
171 $str = str_replace('%table_name%', $realTableName, $str);
172 $str = str_replace('%total_tables%', $this->getTableProgress(), $str);
173 $this->logger->log($str, 'STEP');
174
175 // Check if file can be cleaned
176 $this->filterFile($filePath, basename($filePath));
177 }
178
179 $wpdb->suppress_errors();
180
181 $wpdb->query('SET autocommit = 0;');
182 $wpdb->query('SET foreign_key_checks = 0;');
183 $wpdb->query("SET SQL_MODE = '';");
184 $wpdb->query('START TRANSACTION;');
185
186 $sql = '';
187 while (!$objFile->eof()) {
188 $objFile->seek($seek); $seek++;
189 $line = rtrim($objFile->current(), "\n");
190 if (strlen($line) !== 0) {
191 $sql = $line;
192 unset($line);
193 break;
194 }
195 }
196
197 $wpdb->query($sql);
198 unset($sql);
199 $wpdb->query('COMMIT;');
200 $wpdb->query('SET autocommit = 1;');
201 $wpdb->query('SET foreign_key_checks = 1;');
202
203 $str = __("Progress of %table_name%: %progress%", 'backup-backup');
204 $str = str_replace('%table_name%', $realTableName, $str);
205
206 $objFile->seek($objFile->getSize());
207 $total_size = $objFile->key() - 5;
208 $objFile->seek($seek);
209
210 if ($total_size <= 0) $total_size = 1;
211 if (($seek - 5) <= 0) $seek = 6;
212 if ($total_size > 0) $total_size += 1;
213
214 $progress = ($seek - 5) . '/' . $total_size . " (" . number_format(($seek - 5) / $total_size * 100, 2) . "%)";
215 $str = str_replace('%progress%', $progress, $str);
216 $this->logger->log($str, 'INFO');
217
218 $wpdb->show_errors();
219
220 if ($objFile->eof()) {
221 return true;
222 } else {
223 return false;
224 }
225
226 }
227
228 private function addNewTableToMap($from, $to, $file) {
229
230 if (!array_key_exists($from, $this->map['tables'])) {
231 $this->map['tables'][$from] = $to;
232 }
233
234 file_put_contents($this->tablemap, json_encode($this->map));
235
236 }
237
238 private function processFile($file) {
239
240 if ($this->seek['last_seek'] == 0) {
241 $this->seek['last_start'] = microtime(true);
242 }
243
244 $objFile = new \SplFileObject($file);
245
246 $objFile->seek(1);
247 $realTableName = explode('`', $objFile->current())[1];
248
249 $objFile->seek(2);
250 $tmpTableName = explode('`', $objFile->current())[1];
251
252 $finished = $this->queryFile($objFile, $file, $tmpTableName, $realTableName);
253
254 if ($finished && file_exists($file)) {
255 $this->seek['last_seek'] = 0;
256 $this->seek['last_file'] = '...';
257 @unlink($file);
258
259 $totalTime = microtime(true) - intval($this->seek['last_start']);
260 $totalTime = number_format($totalTime, 5);
261
262 $str = __("Table %table_name% restoration took %time% seconds", 'backup-backup');
263 $str = str_replace('%table_name%', $realTableName, $str);
264 $str = str_replace('%time%', $totalTime, $str);
265
266 $this->logger->log($str, 'SUCCESS');
267 $this->seek['last_start'] = 0;
268 }
269
270 $this->addNewTableToMap($tmpTableName, $realTableName, $file);
271
272 return true;
273
274 }
275
276 private function parseDomain($domain, $removeWWW = true) {
277
278 if (substr($domain, 0, 8) == 'https://') $domain = substr($domain, 8);
279 if (substr($domain, 0, 7) == 'http://') $domain = substr($domain, 7);
280 if ($removeWWW === true) {
281 if (substr($domain, 0, 4) == 'www.') $domain = substr($domain, 4);
282 }
283 $domain = untrailingslashit($domain);
284
285 return $domain;
286
287 }
288
289 private function replaceTableNames($tables) {
290
291 global $wpdb;
292
293 $this->logger->log(__('Performing table replacement', 'backup-backup'), 'STEP');
294
295 $wpdb->suppress_errors();
296 foreach ($tables as $oldTable => $newTable) {
297
298 $sql = "DROP TABLE IF EXISTS `" . $newTable . "`;";
299 $wpdb->query($sql);
300
301 $sql = "ALTER TABLE `" . $oldTable . "` RENAME TO `" . $newTable . "`;";
302 $wpdb->query($sql);
303
304 $str = __('Table %old% renamed to %new%', 'backup-backup');
305 $str = str_replace('%old%', $oldTable, $str);
306 $str = str_replace('%new%', $newTable, $str);
307 $this->logger->log($str, 'INFO');
308
309 }
310
311 $wpdb->show_errors();
312 $this->logger->log(__('All tables replaced', 'backup-backup'), 'SUCCESS');
313
314 }
315
316 private function performReplace($step = 0, $tableIndex = 0, $currentPage = 0, $totalPages = 0, $fieldAdjustments = 0) {
317
318 $status = [
319 'step' => $step,
320 'tableIndex' => $tableIndex,
321 'finished' => false,
322 'currentPage' => $currentPage,
323 'totalPages' => $totalPages,
324 'fieldAdjustments' => $fieldAdjustments
325 ];
326
327 require_once BMI_INCLUDES . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'search-replace.php';
328
329 $backupRootDir = $this->manifest->config->ABSPATH;
330 $currentRootDir = ABSPATH;
331
332 $backupDomain = $this->parseDomain($this->manifest->dbdomain);
333 $currentDomain = $this->parseDomain(get_option('siteurl'), false);
334
335 $currentTable = false;
336 $allTables = array_keys($this->map['tables']);
337
338 if ($tableIndex < sizeof($allTables) && array_key_exists($tableIndex, $allTables)) {
339 $currentTable = $allTables[$tableIndex];
340 }
341
342 if ($currentTable == false && !$currentTable) {
343 if ($backupRootDir != $currentRootDir || $currentDomain != $this->parseDomain($backupDomain, false)) {
344 $this->logger->log(__('Search & Replace finished successfully.', 'backup-backup'), 'SUCCESS');
345 }
346
347 $status['finished'] = true;
348 return $status;
349 }
350
351 $replaceEngine = new BMISearchReplace([$currentTable], $currentPage, $totalPages);
352
353 if ($step == 0) {
354 if ($backupRootDir != $currentRootDir || $currentDomain != $this->parseDomain($backupDomain, false)) {
355 $this->logger->log(__('Performing Search & Replace', 'backup-backup'), 'STEP');
356 $pagesize = '?';
357 if (defined('BMI_MAX_SEARCH_REPLACE_PAGE')) $pagesize = BMI_MAX_SEARCH_REPLACE_PAGE;
358 $this->logger->log(__('Page size for that restoration: ', 'backup-backup') . $pagesize, 'INFO');
359 $status['step'] = $step + 1; $step++;
360 } else {
361 $this->logger->log(__('This backup was made on the same site, ommiting search & replace.', 'backup-backup'), 'INFO');
362 $status['finished'] = true;
363 return $status;
364 }
365 }
366
367 if ($step == 1) {
368 $replaceProgress = ($tableIndex + 1) . "/" . sizeof($allTables);
369 $replaceProgressPercentage = number_format((($tableIndex + 1) / sizeof($allTables) * 100), 2);
370 $progressLogT = __('Performing database adjustments for table %progress%: %table_name% (%progress_percentage%)', 'backup-backup');
371 $progressLogT = str_replace('%progress%', $replaceProgress, $progressLogT);
372 $progressLogT = str_replace('%table_name%', $currentTable, $progressLogT);
373 $progressLogT = str_replace('%progress_percentage%', $replaceProgressPercentage . '%', $progressLogT);
374 $this->logger->log($progressLogT, 'STEP');
375
376 $percentageProgress = number_format($replaceProgressPercentage, 0);
377 $this->logger->progress(number_format(90 + ($percentageProgress / 100) * 8, 0));
378
379 if ($backupRootDir != $currentRootDir) {
380
381 $dtables = 0; $drows = 0; $dchange = 0; $dupdates = 0;
382
383 $r = $replaceEngine->perform($backupRootDir, $currentRootDir);
384 $dtables += $r['tables']; $drows += $r['rows']; $dchange += $r['change']; $dupdates += $r['updates'];
385
386 $status['currentPage'] = $r['currentPage'];
387 $status['totalPages'] = $r['totalPages'];
388
389 if ($status['totalPages'] > 0) {
390
391 $info = __("Batch for path adjustment (%page%/%allPages%) updated: %updates% fields.", 'backup-backup');
392 $updates = $dupdates;
393 if ($updates == 0) $updates = 1;
394 $info = str_replace('%page%', $status['currentPage'], $info);
395 $info = str_replace('%allPages%', $status['totalPages'], $info);
396 $info = str_replace('%updates%', $updates, $info);
397 $this->logger->log($info, 'INFO');
398 $status['fieldAdjustments']++;
399
400 }
401
402 if ($status['currentPage'] >= $status['totalPages']) {
403 $status['currentPage'] = 0;
404 $status['totalPages'] = 0;
405 $status['step'] = $step + 1;
406 }
407 return $status;
408
409 } else {
410
411 $status['step'] = $step + 1;
412 $step++;
413
414 }
415 }
416
417 if ($step == 2 || $step == 3 || $step == 4 || $step == 5 || $step == 6 || $step == 7) {
418 if ($currentDomain != $this->parseDomain($backupDomain, false)) {
419 $ssl = is_ssl() == true ? 'https://' : 'http://';
420
421 $dtables = 0; $drows = 0; $dchange = 0; $dupdates = 0;
422
423 $possibleDomainsBackup = [
424 "https://www." . $backupDomain,
425 "http://www." . $backupDomain,
426 "https://" . $backupDomain,
427 "http://" . $backupDomain,
428 'www.' . $backupDomain,
429 $backupDomain
430 ];
431
432 $possibleDomainsCurrent = [
433 $ssl . $currentDomain,
434 $ssl . $currentDomain,
435 $ssl . $currentDomain,
436 $ssl . $currentDomain,
437 $currentDomain,
438 $currentDomain
439 ];
440
441 if ($step == 2) {
442 $r = $replaceEngine->perform($possibleDomainsBackup[0], $possibleDomainsCurrent[0]);
443 $dtables += $r['tables']; $drows += $r['rows']; $dchange += $r['change']; $dupdates += $r['updates'];
444 }
445
446 if ($step == 3) {
447 $r = $replaceEngine->perform($possibleDomainsBackup[1], $possibleDomainsCurrent[1]);
448 $dtables += $r['tables']; $drows += $r['rows']; $dchange += $r['change']; $dupdates += $r['updates'];
449 }
450
451 if ($step == 4) {
452 $r = $replaceEngine->perform($possibleDomainsBackup[2], $possibleDomainsCurrent[2]);
453 $dtables += $r['tables']; $drows += $r['rows']; $dchange += $r['change']; $dupdates += $r['updates'];
454 }
455
456 if ($step == 5) {
457 $r = $replaceEngine->perform($possibleDomainsBackup[3], $possibleDomainsCurrent[3]);
458 $dtables += $r['tables']; $drows += $r['rows']; $dchange += $r['change']; $dupdates += $r['updates'];
459 }
460
461 if ($step == 6) {
462 $r = $replaceEngine->perform($possibleDomainsBackup[4], $possibleDomainsCurrent[4]);
463 $dchange += $r['change']; $dupdates += $r['updates'];
464 }
465
466 if ($step == 7) {
467 if (!(substr($currentDomain, -strlen($backupDomain)) === $backupDomain)) {
468 $r = $replaceEngine->perform($possibleDomainsBackup[5], $possibleDomainsCurrent[5]);
469 $dchange += $r['change']; $dupdates += $r['updates'];
470 }
471 }
472
473 $status['currentPage'] = $r['currentPage'];
474 $status['totalPages'] = $r['totalPages'];
475
476 $variants = [
477 __('variant A', 'backup-backup'),
478 __('variant B', 'backup-backup'),
479 __('variant C', 'backup-backup'),
480 __('variant D', 'backup-backup'),
481 __('variant E', 'backup-backup'),
482 __('variant F', 'backup-backup'),
483 ];
484
485 if ($status['totalPages'] > 0) {
486
487 $info = __("Batch for domain (%variant%) adjustments (%page%/%allPages%) updated: %updates% fields.", 'backup-backup');
488 $updates = $dupdates;
489 if ($updates == 0) $updates = 1;
490 $info = str_replace('%variant%', $variants[$step - 2], $info);
491 $info = str_replace('%page%', $status['currentPage'], $info);
492 $info = str_replace('%allPages%', $status['totalPages'], $info);
493 $info = str_replace('%updates%', $updates, $info);
494 $this->logger->log($info, 'INFO');
495 $status['fieldAdjustments']++;
496
497 } else {
498
499 // $info = __('Domain (%variant%) adjustments are not required for this table.', 'backup-backup');
500 // $info = str_replace('%variant%', $variants[$step - 2], $info);
501 // $this->logger->log($info, 'INFO');
502
503 }
504
505 if ($status['currentPage'] >= $status['totalPages']) {
506 $status['currentPage'] = 0;
507 $status['totalPages'] = 0;
508 $status['step'] = $step + 1;
509 }
510
511 return $status;
512
513 } else {
514
515 $status['currentPage'] = 0;
516 $status['totalPages'] = 0;
517 $status['step'] = 8;
518 $step = 8;
519
520 }
521 }
522
523 if ($step == 8) {
524 if ($fieldAdjustments === 0) {
525 $this->logger->log(__('Adjustments are not required for this table.', 'backup-backup'), 'INFO');
526 }
527
528 $status['step'] = 1;
529 $status['fieldAdjustments'] = 0;
530 $status['tableIndex'] = $tableIndex + 1;
531 return $status;
532 }
533
534 return $status;
535
536 }
537
538 private function try_activate_plugins($plugins, $sucstr_source, $failstr_source, $failed_plugins = []) {
539
540 $plugins_copy = array_values($plugins);
541 $should_continue = false;
542 $activated_plugins = [];
543 $failed_plugins = $failed_plugins;
544 $disallowed_plugins = [
545 'bluehost-wordpress-plugin/bluehost-wordpress-plugin.php',
546 'sg-cachepress/sg-cachepress.php',
547 'wordpress-starter/siteground-wizard.php',
548 'revslider/revslider.php',
549 'easy-soundcloud-shortcode/easy-soundcloud-shortcode.php',
550 'easy-soundcloud-shortcode/EasySoundcloudShortcode.php'
551 ];
552
553 for ($i = 0; $i < sizeof($plugins_copy); ++$i) {
554
555 $plugin_name = $plugins_copy[$i];
556 $plugin_display = $plugin_name;
557
558 $shouldActivate = true;
559
560 if (empty($plugin_name)) {
561 $shouldActivate = false;
562 $plugin_display = '(---)';
563 } else if (strpos($plugin_name, '/') === false) {
564 $shouldActivate = false;
565 }
566
567 $sucstr = str_replace('%plugin_name%', $plugin_display, $sucstr_source);
568 $failstr = str_replace('%plugin_name%', $plugin_display, $failstr_source);
569
570 if ($shouldActivate) {
571 try {
572
573 if (validate_plugin_requirements($plugin_name) && !in_array($plugin_name, $disallowed_plugins)) {
574
575 $resultWP = activate_plugin($plugin_name, '', true, true);
576
577 $this->logger->log($sucstr, 'INFO');
578 $activated_plugins[] = $plugin_name;
579
580 $should_continue = true;
581 break;
582
583 } else {
584
585 if (!in_array($plugin_name, $failed_plugins)) {
586 $failed_plugins[] = $plugin_name;
587 }
588
589 }
590
591 } catch (\Exception $e) {
592
593 if (!in_array($plugin_name, $failed_plugins)) {
594
595 $failed_plugins[] = $plugin_name;
596 error_log(strval($e));
597
598 }
599
600 } catch (\Throwable $e) {
601
602 if (!in_array($plugin_name, $failed_plugins)) {
603
604 $msg = $e->getMessage();
605 if (strpos($msg, 'add_rule()') != false || strpos($msg, 'rewrite.php:143') != false) {
606
607 $activated_plugins[] = $plugin_name;
608 error_log(strval($e));
609
610 } else {
611
612 $failed_plugins[] = $plugin_name;
613 error_log(strval($e));
614
615 }
616
617 }
618
619 }
620
621 } else {
622
623 $this->logger->log($failstr, 'WARN');
624
625 }
626
627 }
628
629 return [ 'failed' => $failed_plugins, 'active' => $activated_plugins, 'should_continue' => $should_continue ];
630
631 }
632
633 private function enablePlugins() {
634
635 global $wpdb;
636
637 $this->logger->log(__('Enabling plugins included in the backup', 'backup-backup'), 'STEP');
638
639 if (is_serialized($this->seek['active_plugins'])) {
640
641 $plugins = unserialize($this->seek['active_plugins']);
642 usort($plugins, function ($a, $b) { return strlen($a) - strlen($b); });
643 $plugins = array_values($plugins);
644
645 $sucstr_source = __('Plugin %plugin_name% enabled successfully.', 'backup-backup');
646 $failstr_source = __('Failed to enable plugin %plugin_name%, trying to not end at fatal error...', 'backup-backup');
647
648 $fullyActive = [];
649 $failed_plugins = [];
650
651 if (!function_exists('activate_plugin')) {
652 require_once(ABSPATH .'/wp-admin/includes/plugin.php');
653 }
654
655 $one_more_time = true;
656 $try_again = true;
657 while ($try_again) {
658
659 $res = $this->try_activate_plugins($plugins, $sucstr_source, $failstr_source, $failed_plugins);
660
661 $fullyActive = array_unique(array_merge($fullyActive, $res['active']));
662 $plugins = array_diff($plugins, $res['active']);
663 $failed_plugins = array_unique(array_diff(array_merge($failed_plugins, $res['failed']), $fullyActive));
664
665 $try_again = $res['should_continue'];
666 if ($try_again == false && $one_more_time == true) {
667 $one_more_time = false;
668 $try_again = true;
669 }
670
671 }
672
673 for ($i = 0; $i < sizeof($failed_plugins); ++$i) {
674
675 $failstr = str_replace('%plugin_name%', $failed_plugins[$i], $failstr_source);
676 $this->logger->log($failstr, 'WARN');
677
678 }
679
680 if (!in_array('backup-backup/backup-backup.php', $fullyActive)) {
681 $fullyActive[] = 'backup-backup/backup-backup.php';
682 }
683
684 update_option('active_plugins', $fullyActive);
685
686 }
687
688 $this->logger->progress(100);
689 $this->logger->log(__('All plugins enabled, you are ready to go :)', 'backup-backup'), 'SUCCESS');
690
691 }
692
693 public function searchReplace($step = 0, $tableIndex = 0, $currentPage = 0, $totalPages = 0, $fieldAdjustments = 0) {
694
695 $this->logger->progress(90);
696 return $this->performReplace($step, $tableIndex, $currentPage, $totalPages, $fieldAdjustments);
697
698 }
699
700 public function alter_tables() {
701
702 $this->logger->progress(98);
703 $this->prepareFinalDatabase();
704 $this->replaceTableNames($this->map['tables']);
705 $this->enablePlugins();
706
707 }
708
709 private function prepareFinalDatabase() {
710
711 global $wpdb;
712
713 $tables = array_keys($this->map['tables']);
714 $unique_prefix = explode('_', $tables[0])[0];
715 $backupPrefix = $this->manifest->config->table_prefix;
716
717 $options_table = $unique_prefix . '_' . $backupPrefix . 'options';
718 if (!in_array($options_table, $tables)) {
719 $tablename = false;
720 for ($i = 0; $i < sizeof($tables); ++$i) {
721 $table = $tables[$i];
722 if (substr($table, -7) == 'options') {
723 $tablename = $table;
724 break;
725 }
726 }
727
728 $options_table = $tablename;
729 }
730
731 if ($options_table != false && in_array($options_table, $tables)) {
732
733 $sql = "DELETE FROM " . $options_table . " WHERE option_name LIKE ('%\_transient\_%')";
734 $wpdb->query($sql);
735
736 $active_plugins = $wpdb->get_results('SELECT option_value FROM `' . $options_table . '` WHERE option_name = "active_plugins"');
737 $active_plugins = $active_plugins[0]->option_value;
738
739 $this->seek['active_plugins'] = $active_plugins;
740
741 update_option('active_plugins', ['backup-backup/backup-backup.php']);
742
743 $ssl = is_ssl() == true ? 'https://' : 'http://';
744 $currentDomain = $ssl . $this->parseDomain(get_option('siteurl'), false);
745
746 $sql = 'UPDATE ' . $options_table . ' SET option_value = %s WHERE option_name = "siteurl"';
747 $wpdb->query($wpdb->prepare($sql, $currentDomain));
748
749 $sql = 'UPDATE ' . $options_table . ' SET option_value = %s WHERE option_name = "home"';
750 $wpdb->query($wpdb->prepare($sql, $currentDomain));
751
752 }
753
754 }
755
756 private function filterFile($path, $name) {
757
758 $blacklist = $this->unwantedTables;
759 $tablename = strtolower(substr($name, 0, -4));
760
761 $shouldBeExcluded = false;
762 for ($i = 0; $i < sizeof($blacklist); ++$i) {
763
764 $rule = strtolower($blacklist[$i]);
765 if (substr($tablename, -(strlen($rule))) == $rule) {
766 $shouldBeExcluded = true;
767 break;
768 }
769
770 }
771
772 if ($shouldBeExcluded == true) {
773
774 $file = new \SplFileObject($path);
775 $file->seek($file->getSize());
776 $total_lines = $file->key() + 1;
777
778 if ($total_lines >= 6) {
779
780 $str = "\n\n\n\n\n";
781
782 $file->seek(5);
783 $str .= trim($file->current());
784
785 $this->logger->log(str_replace('%s', substr($name, 0, -4), __('Cleaning up contents of %s table.', 'backup-backup')), 'INFO');
786 file_put_contents($path, $str);
787
788 $file = null;
789
790 }
791
792 }
793
794 }
795
796 private function getNextFile() {
797
798 if ($this->seek['last_file'] == '...') {
799
800 $nextFile = false;
801
802 $sqlFiles = array_diff(scandir($this->storage), ['..', '.']);
803 $sqlFiles = array_values($sqlFiles);
804
805 if (sizeof($sqlFiles) > 0) {
806 $nextFilePath = $this->storage . DIRECTORY_SEPARATOR . $sqlFiles[0];
807 return $nextFilePath;
808 }
809
810 $this->seek['last_file'] = $nextFile;
811 return $nextFile;
812
813 } else {
814
815 return $this->seek['last_file'];
816
817 }
818
819 }
820
821 private function initMessage() {
822
823 $this->logger->log(__('Successfully detected backup created with v3 engine, importing...', 'backup-backup'), 'INFO');
824 $this->logger->log(__('Restoring database (using v4 engine)...', 'backup-backup'), 'STEP');
825
826 if (file_exists($this->tablemap)) {
827 @unlink($this->tablemap);
828 }
829
830 }
831
832 }
833