PluginProbe ʕ •ᴥ•ʔ
Backup Migration / 2.1.2
Backup Migration v2.1.2
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 / staging / local.php
backup-backup / includes / staging Last commit date
controller.php 3 months ago local.php 3 months ago tastewp.php 3 months ago
local.php
1007 lines
1 <?php
2
3 // Namespace
4 namespace BMI\Plugin\Staging;
5
6 // Use
7 use BMI\Plugin\Backup_Migration_Plugin as BMP;
8 use BMI\Plugin\Checker\BMI_Checker as Checker;
9 use BMI\Plugin\Database\BMI_Search_Replace_Engine as BMISearchReplace;
10
11 // Exit on direct access
12 if (!defined('ABSPATH')) exit;
13
14 // Require controller
15 require_once BMI_INCLUDES . '/staging/controller.php';
16
17 /**
18 * Subclass of main staging controller (local handler)
19 */
20 class BMI_StagingLocal extends BMI_Staging {
21
22 protected $data = [];
23 protected $step = 0;
24 private $filesList = null;
25 private $dirsList = null;
26 private $rootLength = 0;
27 private $excludedDirectories = [];
28
29 public function __construct($name, $initialize = false) {
30
31 parent::__construct(...func_get_args());
32 if ($initialize) $this->initialization();
33
34 }
35
36 public function continueProcess() {
37
38 if (isset($this->siteConfig['step'])) {
39 $this->step = intval($this->siteConfig['step']);
40 } else {
41 $this->step = null;
42 }
43
44 if (!is_numeric($this->step)) {
45
46 // End with error
47 $this->log(__('Step code was not provided for the request, prevents continuation of the process...'), 'ERROR');
48 $this->log('Step code was not provided for the request, prevents continuation of the process...', 'VERBOSE');
49 $this->log('#201', 'END-CODE');
50 return ['status' => 'error'];
51
52 }
53
54 // Default error
55 $translatedMainError = __('Something unexpected happened, we need to abort the process.', 'backup-backup');
56 $englishMainError = 'Something unexpected happened, we need to abort the process (#207).';
57
58 // Step controller
59 if ($this->step == 1) $this->prepareFilesAndDatabase();
60 else if ($this->step == 2) $this->duplicateDatabase();
61 else if ($this->step == 3) $this->searchReplace();
62 else if ($this->step == 4) $this->databaseFinishedCopyFiles();
63 else if ($this->step == 5) $this->setupWpConfigAndLoginScript();
64 else if ($this->step == 6) $this->performFinish();
65 else if (isset($this->step) && is_numeric($this->step)) $this->sendSuccess();
66 else $this->returnError($translatedMainError, $englishMainError);
67
68 }
69
70 private function getAllLiveTables() {
71
72 global $wpdb;
73 $tables = [];
74
75 $allTables = $wpdb->get_results('SHOW TABLES');
76
77 foreach ($allTables as $table) {
78 foreach ($table as $name) $tables[] = $name;
79 }
80
81 return $tables;
82
83 }
84
85 private function checkIfPrefixCanBeUsed($tables, $prefix) {
86
87 $sizeOfPrefix = strlen($prefix);
88
89 for ($i = 0; $i < sizeof($tables); ++$i) {
90 $name = $tables[$i];
91
92 if (substr($name, 0, $sizeOfPrefix) == $prefix) return false;
93 if (strpos($name, $prefix)) return false;
94 }
95
96 return $prefix;
97
98 }
99
100 private function generateUniquePrefix() {
101 return 'bmstg' . substr(time(), -4) . '_';
102 }
103
104 private function generateDatabasePrefix() {
105
106 $tables = $this->getAllLiveTables();
107 $prefix = $this->generateUniquePrefix();
108
109 $i = 0;
110
111 while ($this->checkIfPrefixCanBeUsed($tables, $prefix) === false && $i <= 3) {
112 sleep(1);
113 $prefix = $this->generateUniquePrefix();
114
115 $i++;
116 }
117
118 if ($i >= 3) return 'error';
119 return $prefix;
120
121 }
122
123 private function createDatabasePrefixAndInitDir() {
124
125 $path = trailingslashit(ABSPATH) . $this->name;
126
127 $this->log(__('Preparing constants and staging details', 'backup-backup'), 'STEP');
128
129 // Directory creation
130 $this->log(__('Creating root directory of new site', 'backup-backup'));
131 if (file_exists($path) && is_dir($path)) {
132 $translated = __('Seems like desired directory of staging site already exist, try with different staging site name.', 'backup-backup');
133 $english = 'Seems like desired directory of staging site already exist, try with different staging site name.';
134 $this->returnError($translated, $english);
135 }
136
137 @mkdir($path, 0755);
138 touch($path . DIRECTORY_SEPARATOR . '.bmi_staging');
139
140 $this->log(__('Path of new website:', 'backup-backup') . ' ' . $path, 'SUCCESS');
141
142 // Generation of database prefix
143 $this->log(__('Generating database prefix', 'backup-backup'));
144 $dbPrefix = $this->generateDatabasePrefix();
145 if ($dbPrefix == 'error') {
146 $translated = __('There was an error during database prefix generation, maybe all generated were already used, try again.', 'backup-backup');
147 $english = 'There was an error during database prefix generation, maybe all generated were already used, try again.';
148 $this->returnError($translated, $english);
149 }
150 $this->log(__('Prefix of new site will be:', 'backup-backup') . ' ' . $dbPrefix, 'SUCCESS');
151
152 $this->config[$this->name]['name'] = $this->name;
153 $this->config[$this->name]['prefix'] = $dbPrefix;
154
155 // Password for first log in
156 $this->log(__('Generating first log in password', 'backup-backup'));
157 $password = $this->getRandomPassword();
158 $this->log(__('Password created and saved.', 'backup-backup'), 'SUCCESS');
159
160 // Set initial configuration
161 $this->log(__('Initializing configuration of the website', 'backup-backup'), 'STEP');
162 $this->initialConfiguration($dbPrefix, $password);
163 $this->log(__('Configuration created', 'backup-backup'), 'SUCCESS');
164
165 }
166
167 private function initialConfiguration($dbPrefix, $password) {
168
169 global $table_prefix;
170
171 $ip = $this->getIpAddress();
172
173 // Basic for all
174 $this->siteConfig['name'] = $this->name; // Name of that staging site
175 $this->siteConfig['url'] = home_url($this->name); // URL to the website
176 $this->siteConfig['root_source'] = trailingslashit(ABSPATH); // ABSPATH of source website
177 $this->siteConfig['root_staging'] = untrailingslashit(ABSPATH) . DIRECTORY_SEPARATOR . $this->name; // ABSPATH of staging site
178 $this->siteConfig['db_prefix'] = $dbPrefix; // Database prefix of that site
179 $this->siteConfig['creation_date'] = time(); // Creation date and time of that staging site
180 $this->siteConfig['password'] = $password; // Password for password-less login
181 $this->siteConfig['creator_ip'] = $ip; // IP of user who created it
182 $this->siteConfig['login_ip'] = $ip; // IP for autologin script (limit password-less login to only that IP)
183 $this->siteConfig['login_user_id'] = get_current_user_id(); // User ID for password less authentication
184 $this->siteConfig['source_home_url'] = home_url(); // Homepage URL of source website
185 $this->siteConfig['source_site_url'] = site_url(); // Website (admin) URL of source website
186 $this->siteConfig['source_db_prefix'] = $table_prefix; // Database prefix of source website
187
188 // TasteWP
189 $this->siteConfig['communication_secret'] = 'local'; // Local if it's not TasteWP website // Secret code to get authless access to website
190 $this->siteConfig['expiration_time'] = 'never'; // Never if it's not TasteWP website // Expiration time of the website
191
192 }
193
194 private function getExcludedFilesAndDirectories($abspath = false) {
195
196 $excludedDirectories = [];
197
198 if ($abspath) {
199 $excludedDirectories = $this->getAllStagingSiteDirectories();
200 }
201
202 $excludedDirectories[] = '.';
203 $excludedDirectories[] = '..';
204 $excludedDirectories[] = 'wp-config.php';
205 $excludedDirectories[] = '.DS_Store';
206 $excludedDirectories[] = '.quarantine';
207 $excludedDirectories[] = '.git';
208 $excludedDirectories[] = '.tmb';
209 $excludedDirectories[] = 'node_modules';
210 $excludedDirectories[] = 'debug.log';
211
212 return $excludedDirectories;
213
214 }
215
216 private function getAbspathFiles($path) {
217
218 $excludedDirectories = $this->getExcludedFilesAndDirectories(true);
219 $topFiles = array_diff(scandir($path), $excludedDirectories);
220
221 return $topFiles;
222
223 }
224
225 private function processFiles($prefixPath, &$files) {
226
227 $dirs = [];
228
229 foreach ($files as $index => $file) {
230 $path = $prefixPath . $file;
231 if (strpos($path, BMI_BACKUPS_ROOT) !== false) continue;
232 if (is_link($path)) continue;
233 if (is_dir($path)) {
234 if (!(is_readable($path) && is_writable($path))) continue;
235 if (file_exists(trailingslashit($path) . '.bmi_staging')) continue;
236 $this->siteConfig['total_size'] += 4096;
237 $this->siteConfig['total_directories'] += 1;
238 fwrite($this->dirsList, $file . "\n");
239 $dirs[] = $path;
240 } else if (is_file($path)) {
241 if (!is_readable($path)) continue;
242 $this->siteConfig['total_size'] += filesize($path);
243 $this->siteConfig['total_files'] += 1;
244 fwrite($this->filesList, $file . "\n");
245 }
246 }
247
248 return $dirs;
249
250 }
251
252 private function processDirectoryRecursively($dir) {
253
254 if (!(is_readable($dir) && is_writable($dir))) return;
255
256 $files = array_diff(scandir($dir), $this->excludedDirectories);
257
258 foreach ($files as $key => $value) {
259 $path = $dir . DIRECTORY_SEPARATOR . $value;
260 if (strpos($path, BMI_BACKUPS_ROOT) !== false) continue;
261 if (is_link($path)) continue;
262 if (is_dir($path)) {
263 $this->siteConfig['total_size'] += 4096;
264 $this->siteConfig['total_directories'] += 1;
265 fwrite($this->dirsList, substr($path, $this->rootLength) . "\n");
266 if (!file_exists(trailingslashit($path) . '.bmi_staging')) {
267 $this->processDirectoryRecursively($path);
268 }
269 } else if (is_file($path)) {
270 if (!is_readable($path)) continue;
271 $this->siteConfig['total_size'] += filesize($path);
272 $this->siteConfig['total_files'] += 1;
273 fwrite($this->filesList, substr($path, $this->rootLength) . "\n");
274 }
275 }
276
277 }
278
279 private function processFilesRecursively($leftDirs) {
280
281 $this->rootLength = strlen(trailingslashit(ABSPATH));
282 $this->excludedDirectories = $this->getExcludedFilesAndDirectories();
283
284 for ($i = 0; $i < sizeof($leftDirs); ++$i) {
285 $this->processDirectoryRecursively($leftDirs[$i]);
286 }
287
288 }
289
290 private function getTablesForDuplication() {
291
292 global $wpdb, $table_prefix;
293
294 $currentPrefixes = $this->getAllStagingSitePrefixes();
295 $relatedTables = [];
296
297
298 $tables = $wpdb->get_results($wpdb->prepare("SELECT (DATA_LENGTH + INDEX_LENGTH) as `size`, TABLE_NAME AS `name` FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s;", array(DB_NAME)));
299 foreach ($tables as $tableObject) {
300
301 $name = $tableObject->name;
302 $size = $tableObject->size;
303
304 if (substr($name, 0, strlen($table_prefix)) != $table_prefix) {
305 $this->log('Ommiting this table: ' . $name, 'verbose');
306 continue;
307 } else {
308 $this->log('Adding this table: ' . $name, 'verbose');
309 }
310
311 $tableOfStagingSite = false;
312 for ($i = 0; $i < sizeof($currentPrefixes); ++$i) {
313 $subPrefix = $currentPrefixes[$i];
314 if ($table_prefix != $subPrefix && substr($name, 0, strlen($subPrefix)) == $subPrefix) {
315 $tableOfStagingSite = true;
316 break;
317 }
318 }
319 if ($tableOfStagingSite) {
320 $this->log('Excluding this table as part of staging site: ' . $name, 'verbose');
321 continue;
322 }
323
324 $this->siteConfig['total_db_size'] += intval($size);
325 $relatedTables[$name] = $this->siteConfig['db_prefix'] . substr($name, strlen($table_prefix));
326
327 }
328
329 return $relatedTables;
330
331 }
332
333 private function updateUserRolesInOptions() {
334
335 global $wpdb;
336
337 // Update option name
338 $newOptionTable = $this->siteConfig['db_prefix'] . 'options';
339 $newOptionName = $this->siteConfig['db_prefix'] . 'user_roles';
340 $oldOptionName = $this->siteConfig['source_db_prefix'] . 'user_roles';
341
342 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
343 $wpdb->query($wpdb->prepare("UPDATE " . BMP::escapeSQLIDentifier($newOptionTable) . " SET `option_name` = %s WHERE `option_name` = %s;", $newOptionName, $oldOptionName));
344
345 if ($wpdb->last_error !== '') {
346 $translated = __('There was an error during update of user roles:', 'backup-backup') . ' ' . $wpdb->last_error;
347 $english = 'There was an error during update of user roles:' . ' ' . $wpdb->last_error;
348 return $this->returnError($translated, $english);
349 }
350
351 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
352 $wpdb->query($wpdb->prepare("DELETE FROM " . BMP::escapeSQLIDentifier($newOptionTable) . " WHERE `option_name` = 'BMI::STORAGE::LOCAL::PATH';"));
353
354 if ($wpdb->last_error !== '') {
355 $translated = __('There was an error during BMI config hard removal:', 'backup-backup') . ' ' . $wpdb->last_error;
356 $english = 'There was an error during BMI config hard removal:' . ' ' . $wpdb->last_error;
357 return $this->returnError($translated, $english);
358 }
359
360 }
361
362 private function duplicateTableAlternative($source, $destination) {
363
364 global $wpdb;
365
366 // Remove failed table if created
367 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
368 $wpdb->query("DROP TABLE IF EXISTS " . BMP::escapeSQLIDentifier($destination) . ";");
369
370 if ($wpdb->last_error !== '') {
371 $translated = __('There was an error during previous destination table removal:', 'backup-backup') . ' ' . $wpdb->last_error;
372 $english = 'There was an error during previous destination table removal:' . ' ' . $wpdb->last_error;
373 return $this->returnError($translated, $english);
374 }
375
376 // Create new table
377 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
378 $wpdb->query("CREATE TABLE " . BMP::escapeSQLIDentifier($destination) . " LIKE " . BMP::escapeSQLIDentifier($source) . ";");
379 if ($wpdb->last_error !== '') {
380 $translated = __('There was an error during database table creation:', 'backup-backup') . ' ' . $wpdb->last_error;
381 $english = 'There was an error during database table creation:' . ' ' . $wpdb->last_error;
382 return $this->returnError($translated, $english);
383 }
384
385 // Duplicate data
386 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
387 $wpdb->query("INSERT INTO " . BMP::escapeSQLIDentifier($destination) . " SELECT * from " . BMP::escapeSQLIDentifier($source) . ";");
388 if ($wpdb->last_error !== '') {
389 $translated = __('There was an error during database table data duplication:', 'backup-backup') . ' ' . $wpdb->last_error;
390 $english = 'There was an error during database table data duplication:' . ' ' . $wpdb->last_error;
391 return $this->returnError($translated, $english);
392 }
393
394 }
395
396 private function duplicateTable($source, $destination) {
397
398 global $wpdb;
399
400 // Create new table
401 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
402 $sourceCreate = $wpdb->get_row("SHOW CREATE TABLE " . BMP::escapeSQLIDentifier($source) . ";");
403 $isTable = isset($sourceCreate->{'Create Table'});
404 if ($isTable) {
405 $sourceCreate->{'Create Table'} = str_ireplace('CREATE TABLE ' . BMP::escapeSQLIDentifier($source), 'CREATE TABLE IF NOT EXISTS ' . BMP::escapeSQLIDentifier($destination), $sourceCreate->{'Create Table'});
406 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL generated from escaped SHOW CREATE TABLE output
407 $wpdb->query($sourceCreate->{'Create Table'});
408 //Insert data
409 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
410 $wpdb->query("INSERT INTO " . BMP::escapeSQLIDentifier($destination) . " SELECT * from " . BMP::escapeSQLIDentifier($source) . ";");
411 } else {
412 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Identifier is safely escaped via escapeSQLIDentifier()
413 $wpdb->query("CREATE TABLE " . BMP::escapeSQLIDentifier($destination) . " AS SELECT * FROM " . BMP::escapeSQLIDentifier($source) . ";");
414 }
415
416
417
418 if ($wpdb->last_error !== '') {
419 $this->duplicateTableAlternative($source, $destination);
420 }
421
422 if ($wpdb->last_error !== '') {
423 $translated = __('There was an error during database table creation:', 'backup-backup') . ' ' . $wpdb->last_error;
424 $english = 'There was an error during database table creation:' . ' ' . $wpdb->last_error;
425 return $this->returnError($translated, $english);
426 }
427
428 }
429
430 private function parseDomain($domain, $removeWWW = true) {
431
432 if (substr($domain, 0, 8) == 'https://') $domain = substr($domain, 8);
433 if (substr($domain, 0, 7) == 'http://') $domain = substr($domain, 7);
434 if ($removeWWW === true) {
435 if (substr($domain, 0, 4) == 'www.') $domain = substr($domain, 4);
436 }
437 $domain = untrailingslashit($domain);
438
439 return $domain;
440
441 }
442
443 private function performSearchReplace($table, $from, $to, $start = 0, $end = 0, $limitColumns = false) {
444
445 $replaceEngine = new BMISearchReplace([$table], $start, $end, true);
446
447 $stats = $replaceEngine->perform($from, $to, $limitColumns);
448
449 $this->siteConfig['totalTables'] += $stats['tables'];
450 $this->siteConfig['totalRows'] += $stats['rows'];
451 $this->siteConfig['totalChanges'] += $stats['change'];
452 $this->siteConfig['totalUpdates'] += $stats['updates'];
453
454 $this->siteConfig['currentTableTotalUpdates'] += $stats['updates'];
455 $this->siteConfig['currentSearchReplacePage'] = $stats['currentPage'];
456 $this->siteConfig['totalSearchReplacePages'] = $stats['totalPages'];
457
458 $replaceEngine = null;
459
460 }
461
462 public function requestDelete() {
463 return $this->abort(true);
464 }
465
466 // Step: 0 (initialization of the staging site, create entry)
467 private function initialization() {
468
469 $this->log('Step 0 - Initialization of the process', 'VERBOSE');
470
471 $this->log(__('Name of subsite:', 'backup-backup') . ' ' . $this->name);
472 $this->log(__('Expected URL of subsite:', 'backup-backup') . ' ' . home_url($this->name));
473
474 $this->printInitialLogs();
475
476 $this->createDatabasePrefixAndInitDir();
477 if ($this->wasError) return;
478
479 // Set progress to do something
480 $this->progress(4);
481
482 // Set next step to be 1
483 $this->setContinuation(1);
484
485 }
486
487 // Step: 1 (preparation of file list and database recipes)
488 private function prepareFilesAndDatabase() {
489
490 // Create list of all files and directories
491 if (!isset($this->siteConfig['batch']) || $this->siteConfig['batch'] == 1) {
492 $this->log(__('Scanning all files on your website, it may take a while...', 'backup-backup'), 'STEP');
493
494 $pathDirsListFile = BMI_TMP . DIRECTORY_SEPARATOR . '.staging_directories';
495 $pathFilesListFile = BMI_TMP . DIRECTORY_SEPARATOR . '.staging_files';
496
497 $this->siteConfig['total_size'] = 0;
498 $this->siteConfig['total_files'] = 0;
499 $this->siteConfig['total_directories'] = 0;
500
501 if (file_exists($pathDirsListFile)) @unlink($pathDirsListFile);
502 if (file_exists($pathFilesListFile)) @unlink($pathFilesListFile);
503
504 $this->filesList = fopen($pathFilesListFile, 'a');
505 $this->dirsList = fopen($pathDirsListFile, 'a');
506
507 $topLevelFiles = $this->getAbspathFiles(ABSPATH);
508 $leftDirs = $this->processFiles(trailingslashit(ABSPATH), $topLevelFiles);
509
510 $this->processFilesRecursively($leftDirs);
511
512 fclose($this->filesList);
513 fclose($this->dirsList);
514
515 $this->log(__('All files scanned and prepared for duplication...', 'backup-backup'), 'SUCCESS');
516 $this->progress(10);
517
518 $this->setContinuation(1, 2);
519 }
520
521 // Display details about scan and check database size
522 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 2) {
523 $this->log(__('Looking for database tables that should be duplicated and their sizes...', 'backup-backup'), 'STEP');
524
525 $this->siteConfig['total_db_size'] = 0;
526 $this->siteConfig['tables'] = $this->getTablesForDuplication();
527 $this->siteConfig['amountOfTables'] = sizeof($this->siteConfig['tables']);
528 $this->siteConfig['sumOfTotalSize'] = intval($this->siteConfig['total_db_size']) + intval($this->siteConfig['total_size']);
529
530 $this->log(__('Amount of files to duplicate:', 'backup-backup') . ' ' . $this->siteConfig['total_files']);
531 $this->log(__('Amount of directories to duplicate:', 'backup-backup') . ' ' . $this->siteConfig['total_directories']);
532 $this->log(__('Amount of tables to duplicate:', 'backup-backup') . ' ' . $this->siteConfig['amountOfTables']);
533 $this->log(__('Size of database to duplicate:', 'backup-backup') . ' ' . BMP::humanSize(intval($this->siteConfig['total_db_size'])));
534 $this->log(__('Size of files to duplicate:', 'backup-backup') . ' ' . BMP::humanSize(intval($this->siteConfig['total_size'])));
535 $this->log(__('Total duplication size:', 'backup-backup') . ' ' . BMP::humanSize($this->siteConfig['sumOfTotalSize']));
536 $this->log(__('Tables prepared for duplication...', 'backup-backup'), 'SUCCESS');
537
538 $this->log(__('Checking if there is enough space for the staging site...', 'backup-backup'), 'STEP');
539 $this->log(__('Space checking may take a while', 'backup-backup'));
540
541 $this->progress(15);
542
543 $this->setContinuation(1, 3);
544 }
545
546 // Check if there is enough space for duplication
547 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 3) {
548 require_once BMI_INCLUDES . '/check/checker.php';
549 $checker = new Checker($this->logger);
550
551 $bytes = intval(intval($this->siteConfig['sumOfTotalSize']) * 1.1);
552 $this->log(str_replace('%s2', BMP::humanSize($bytes), str_replace('%s1', $bytes, __('Checking in total: %s1 bytes (%s2)', 'backup-backup'))));
553
554 if (!$checker->check_free_space($bytes, true)) {
555
556 $translated = __('There is not enough space on your server in order to create staging site.', 'backup-backup');
557 $english = 'There is not enough space on your server in order to create staging site.';
558 return $this->returnError($translated, $english);
559
560 } else {
561
562 $this->log(__("Confirmed, there is more than enough space, checked: ", 'backup-backup') . ($bytes) . __(" bytes", 'backup-backup'), 'SUCCESS');
563
564 }
565
566 $this->progress(20);
567
568 // Set next batch to start step 2
569 $this->log('Setting new step for next request to 2 @ batch 1', 'VERBOSE');
570 $this->setContinuation(2);
571
572 }
573
574 }
575
576 // Step: 2 (duplicate database)
577 private function duplicateDatabase() {
578
579 if (!isset($this->siteConfig['finishedTables'])) {
580 $this->siteConfig['finishedTables'] = [];
581 }
582
583 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 1) {
584 $this->log(__('Duplicating database tables...', 'backup-backup'), 'STEP');
585 }
586
587 $startTime = time();
588 foreach ($this->siteConfig['tables'] as $source_table => $destination_table) {
589
590 $this->duplicateTable($source_table, $destination_table);
591 $this->log(str_replace('%s1', $source_table, str_replace('%s2', $destination_table, __('Table %s1 cloned as %s2', 'backup-backup'))));
592
593 $this->siteConfig['finishedTables'][] = $destination_table;
594 unset($this->siteConfig['tables'][$source_table]);
595
596 $processPercentage = intval((sizeof($this->siteConfig['finishedTables']) / $this->siteConfig['amountOfTables']) * 20);
597 $this->progress(20 + $processPercentage);
598
599 if ((time() - $startTime) >= 4) {
600 $this->setContinuation(2, (intval($this->siteConfig['batch']) + 1));
601 break;
602 }
603
604 }
605
606 if (sizeof($this->siteConfig['tables']) == 0) {
607 unset($this->siteConfig['tables']);
608 }
609
610 if (!isset($this->siteConfig['tables'])) {
611 $this->log(__('All tables were successfully duplicated', 'backup-backup'), 'SUCCESS');
612 $this->setContinuation(3);
613 }
614
615 }
616
617 // Step: 3 (search & replace of new tables)
618 private function searchReplace() {
619
620 require_once BMI_INCLUDES . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'search-replace.php';
621
622 // Domain
623 $sourceURL = $this->parseDomain($this->siteConfig['source_home_url']);
624 $destinationURL = $this->parseDomain($this->siteConfig['url']);
625
626 // Paths
627 $sourceABSPATH = untrailingslashit($this->siteConfig['root_source']);
628 $destinationABSPATH = untrailingslashit($this->siteConfig['root_staging']);
629
630 // Items to be replaced
631 $replaces = [
632 ['from' => $sourceABSPATH, 'to' => $destinationABSPATH],
633 ['from' => $sourceURL, 'to' => $destinationURL],
634 ['from' => $this->siteConfig['source_db_prefix'], 'to' => $this->siteConfig['db_prefix']]
635 ];
636
637 $variants = [
638 __("Batch for path adjustment (%s/%s) updated: %s fields.", 'backup-backup'),
639 __("Batch for domain adjustments (%s/%s) updated: %s fields.", 'backup-backup'),
640 __("Batch for prefix key adjustments (%s/%s) updated: %s fields.", 'backup-backup')
641 ];
642
643 $variantsEmpty = [
644 __("Path replacements are not required for table: %s", 'backup-backup'),
645 __("Domain replacements are not required for table: %s", 'backup-backup'),
646 __("Prefix key replacements are not required for table: %s", 'backup-backup')
647 ];
648
649 // Table for replacement
650 if (isset($this->siteConfig['finishedTables']) && sizeof($this->siteConfig['finishedTables']) > 0) {
651
652 // Get first table from duplicated tables
653 $table = $this->siteConfig['finishedTables'][0];
654
655 } else {
656
657 // All tables processed, search replace finished
658 unset($this->siteConfig['finishedTables']);
659 $this->setContinuation(4);
660
661 }
662
663 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 1) {
664 $this->log(__('Performing database search replace on duplicated tables...', 'backup-backup'), 'STEP');
665
666 $pagesize = '?';
667 if (defined('BMI_MAX_SEARCH_REPLACE_PAGE')) $pagesize = BMI_MAX_SEARCH_REPLACE_PAGE;
668 $this->log(__('Page size for that process: ', 'backup-backup') . $pagesize, 'INFO');
669
670 $this->siteConfig['totalTables'] = 0;
671 $this->siteConfig['totalRows'] = 0;
672 $this->siteConfig['totalChanges'] = 0;
673 $this->siteConfig['totalUpdates'] = 0;
674
675 $this->siteConfig['currentSearchReplaceItem'] = 0;
676 $this->siteConfig['currentTableTotalUpdates'] = 0;
677 $this->siteConfig['currentSearchReplacePage'] = 0;
678 $this->siteConfig['totalSearchReplacePages'] = 0;
679
680 $this->setContinuation(3, 2);
681 }
682
683 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 2) {
684
685 // Give details of current process
686 if ($this->siteConfig['currentSearchReplaceItem'] == 0 && $this->siteConfig['currentSearchReplacePage'] == 0) {
687 $this->log(sprintf(__('Performing search replace for table: %s', 'backup-backup'), $table), 'STEP');
688 }
689
690 // Control time of the process
691 $startTime = time();
692 $tableCompleted = false;
693 $maxExecutionTime = 5;
694
695 for ($i = $this->siteConfig['currentSearchReplaceItem']; $i < sizeof($replaces); ++$i) {
696
697 $this->siteConfig['currentSearchReplaceItem'] = $i;
698 if ((time() - $startTime) >= $maxExecutionTime) break;
699 $tableCompleted = false;
700
701 $from = $replaces[$i]['from'];
702 $to = $replaces[$i]['to'];
703
704 while ($tableCompleted === false && (time() - $startTime) < $maxExecutionTime) {
705
706 // Progress
707 $start = $this->siteConfig['currentSearchReplacePage'];
708 $end = $this->siteConfig['totalSearchReplacePages'];
709
710 // Path replace for current table
711 if ($i == 2) {
712 if (strpos($table, 'usermeta') !== false) {
713 $this->performSearchReplace($table, $from, $to, $start, $end, ['meta_key']);
714 }
715 } else {
716 $this->performSearchReplace($table, $from, $to, $start, $end);
717 }
718
719 // Handle batch logs
720 if ($this->siteConfig['currentTableTotalUpdates'] == 0 && $this->siteConfig['totalSearchReplacePages'] == 0) {
721 $this->log(sprintf($variantsEmpty[$i], $table), 'INFO');
722 } else {
723 $st = $this->siteConfig['currentSearchReplacePage'];
724 $en = $this->siteConfig['totalSearchReplacePages'];
725 $this->log(sprintf($variants[$i], $st, $en, $this->siteConfig['currentTableTotalUpdates']));
726 $this->siteConfig['currentTableTotalUpdates'] = 0;
727 }
728
729 // Done of that table
730 if ($this->siteConfig['currentSearchReplacePage'] >= $this->siteConfig['totalSearchReplacePages']) {
731 if ($i >= sizeof($replaces) - 1) {
732 unset($this->siteConfig['finishedTables'][0]);
733 $this->siteConfig['finishedTables'] = array_values($this->siteConfig['finishedTables']);
734 $this->log(sprintf(__('Search replace for table %s finished', 'backup-backup'), $table), 'SUCCESS');
735 $this->siteConfig['currentSearchReplaceItem'] = 0;
736
737 $processPercentage = intval((($this->siteConfig['amountOfTables'] - sizeof($this->siteConfig['finishedTables'])) / $this->siteConfig['amountOfTables']) * 20);
738 $this->progress(40 + $processPercentage);
739 }
740
741 $this->siteConfig['currentTableTotalUpdates'] = 0;
742 $this->siteConfig['currentSearchReplacePage'] = 0;
743 $this->siteConfig['totalSearchReplacePages'] = 0;
744 $tableCompleted = true;
745 }
746
747 }
748
749 if (!$tableCompleted) break;
750
751 }
752
753 if ($tableCompleted && sizeof($this->siteConfig['finishedTables']) == 0) $this->setContinuation(3, 3); // If path replacement finished
754 else $this->setContinuation(3, 2); // If path raplecement didnt finish, continue next batch (time exceed 5 seconds)
755
756 }
757
758 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 3) $this->setContinuation(4);
759
760 }
761
762 // Step: 4 (summary of S&R and file duplication)
763 private function databaseFinishedCopyFiles() {
764
765 $totalBatchExecution = 5; // 5 seconds
766 $milestoneUpdate = 500; // per 500 files/directories
767 $batchLimit = $milestoneUpdate + 1; // Limit of files/directories per batch
768
769 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 1) {
770
771 // Remove unused variables
772 unset($this->siteConfig['currentSearchReplaceItem']);
773 unset($this->siteConfig['currentTableTotalUpdates']);
774 unset($this->siteConfig['currentSearchReplacePage']);
775 unset($this->siteConfig['totalSearchReplacePages']);
776
777 // Display summary of search replace
778 $this->log(__('Displaying summary of search replace process', 'backup-backup'), 'STEP');
779 $this->log(sprintf(__('Search replace processed %s tables in total', 'backup-backup'), $this->siteConfig['totalTables']));
780 $this->log(sprintf(__('In total it processed %s rows', 'backup-backup'), $this->siteConfig['totalRows']));
781 $this->log(sprintf(__('After all it changed only %s columns', 'backup-backup'), $this->siteConfig['totalChanges']));
782 $this->log(sprintf(__('Which results in %s changes in total of all cells', 'backup-backup'), $this->siteConfig['totalUpdates']));
783
784 // Remove unused variables
785 unset($this->siteConfig['totalTables']);
786 unset($this->siteConfig['totalRows']);
787 unset($this->siteConfig['totalChanges']);
788 unset($this->siteConfig['totalUpdates']);
789
790 // Update user roles in options table
791 $this->updateUserRolesInOptions();
792
793 $this->log(__('Search replace of all tables finished successfully', 'backup-backup'), 'SUCCESS');
794
795 // Go to new process without new batch request
796 $this->siteConfig['batch'] = 2;
797
798 }
799
800 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 2) {
801
802 if (!isset($this->siteConfig['dirSeek']) || $this->siteConfig['dirSeek'] == 0) {
803 $this->log(__('Duplication of directories to staging site', 'backup-backup'), 'STEP');
804 $this->siteConfig['dirSeek'] = 0;
805 }
806
807 $pathDirsListFile = BMI_TMP . DIRECTORY_SEPARATOR . '.staging_directories';
808
809 $file = new \SplFileObject($pathDirsListFile);
810 $file->seek($file->getSize());
811
812 $startTime = time();
813 $currentSeekedElements = 0;
814 $totalLines = $file->key() + 1;
815 $stagingRoot = trailingslashit($this->siteConfig['root_staging']);
816 $file->seek($this->siteConfig['dirSeek']);
817
818 while (!$file->eof()) {
819
820 if ((time() - $startTime) > $totalBatchExecution || $currentSeekedElements > $batchLimit) break;
821
822 $file->seek($this->siteConfig['dirSeek']);
823 $path = $stagingRoot . trim($file->current());
824
825 if (!(file_exists($path) && is_dir($path))) @mkdir($path);
826 if ($this->siteConfig['dirSeek'] % $milestoneUpdate === 0 && $this->siteConfig['dirSeek'] != 0) {
827 $processPercentageTotal = number_format(($this->siteConfig['dirSeek'] / $this->siteConfig['total_directories']) * 100, 2);
828 $this->log(sprintf(
829 __('Directory creation milestone: %s/%s (%s)', 'backup-backup'),
830 $this->siteConfig['dirSeek'],
831 $this->siteConfig['total_directories'],
832 $processPercentageTotal . '%'
833 ));
834 $processPercentage = intval(($this->siteConfig['dirSeek'] / $this->siteConfig['total_directories']) * 5);
835 $this->progress(60 + $processPercentage);
836 }
837
838 $this->siteConfig['dirSeek']++;
839 $currentSeekedElements++;
840
841 }
842
843 if ($this->siteConfig['dirSeek'] >= $this->siteConfig['total_directories']) {
844 unlink($pathDirsListFile);
845 unset($this->siteConfig['dirSeek']);
846 $this->log(sprintf(
847 __('Directory creation milestone: %s/%s (%s)', 'backup-backup'),
848 $this->siteConfig['total_directories'],
849 $this->siteConfig['total_directories'],
850 '100%'
851 ));
852 $this->progress(65);
853 $this->setContinuation(4, 3);
854 } else {
855 $this->setContinuation(4, 2);
856 }
857
858 }
859
860 if (isset($this->siteConfig['batch']) && $this->siteConfig['batch'] == 3) {
861
862 if (!isset($this->siteConfig['fileSeek']) || $this->siteConfig['fileSeek'] == 0) {
863 $this->log(__('Duplication of files to staging site', 'backup-backup'), 'STEP');
864 $this->log(__('Duplication of files make take a while', 'backup-backup'));
865 $this->log(__('Disclaimer: ZIP Archives are not getting cloned on staging sites', 'backup-backup'), 'WARN');
866 $this->siteConfig['fileSeek'] = 0;
867 }
868
869 $pathFilesListFile = BMI_TMP . DIRECTORY_SEPARATOR . '.staging_files';
870
871 $file = new \SplFileObject($pathFilesListFile);
872 $file->seek($file->getSize());
873
874 $startTime = time();
875 $currentSeekedElements = 0;
876 $totalLines = $file->key() + 1;
877 $sourceRoot = trailingslashit($this->siteConfig['root_source']);
878 $stagingRoot = trailingslashit($this->siteConfig['root_staging']);
879 $file->seek($this->siteConfig['fileSeek']);
880 $disallowedExtensions = ['zip', 'tar', 'gz', 'tmp', 'rar', '7z'];
881
882 while (!$file->eof()) {
883
884 if ((time() - $startTime) > $totalBatchExecution || $currentSeekedElements > $batchLimit) break;
885
886 $file->seek($this->siteConfig['fileSeek']);
887 $path = trim($file->current());
888
889 if (file_exists($sourceRoot . $path) && !file_exists($stagingRoot . $path)) {
890 $arrayWithExtension = explode('.', $path);
891 $ext = strtolower(array_pop($arrayWithExtension));
892 if (!in_array($ext, $disallowedExtensions) && strpos($path, 'backup-migration-config.php') === false) {
893 @copy($sourceRoot . $path, $stagingRoot . $path);
894 }
895 }
896
897 if ($this->siteConfig['fileSeek'] % $milestoneUpdate === 0 && $this->siteConfig['fileSeek'] != 0) {
898 $processPercentageTotal = number_format(($this->siteConfig['fileSeek'] / $this->siteConfig['total_files']) * 100, 2);
899 $this->log(sprintf(
900 __('File duplication milestone: %s/%s (%s)', 'backup-backup'),
901 $this->siteConfig['fileSeek'],
902 $this->siteConfig['total_files'],
903 $processPercentageTotal . '%'
904 ));
905 $processPercentage = intval(($this->siteConfig['fileSeek'] / $this->siteConfig['total_files']) * 25);
906 $this->progress(65 + $processPercentage);
907 }
908
909 $this->siteConfig['fileSeek']++;
910 $currentSeekedElements++;
911
912 }
913
914 if ($this->siteConfig['fileSeek'] >= $this->siteConfig['total_files']) {
915 unlink($pathFilesListFile);
916 unset($this->siteConfig['fileSeek']);
917 $this->log(sprintf(
918 __('File duplication milestone: %s/%s (%s)', 'backup-backup'),
919 $this->siteConfig['total_files'],
920 $this->siteConfig['total_files'],
921 '100%'
922 ));
923 $this->progress(90);
924 $this->setContinuation(5);
925 } else {
926 $this->setContinuation(4, 3);
927 }
928
929 }
930
931 }
932
933 // Step: 5 (setup passwordless login script and paste adjusted wp-config)
934 private function setupWpConfigAndLoginScript() {
935
936 $this->copyOverPasswordLessScript();
937
938 $this->log(__('Inserting wp-config.php file for staging site', 'backup-backup'), 'STEP');
939
940 $sourceWPConfig = trailingslashit($this->siteConfig['root_source']) . 'wp-config.php';
941 $destinationWPConfig = trailingslashit($this->siteConfig['root_staging']) . 'wp-config.php';
942
943 $previousPrefix = $this->siteConfig['source_db_prefix'];
944 $destinationPrefix = $this->siteConfig['db_prefix'];
945
946 $previousRoot = untrailingslashit($this->siteConfig['root_source']);
947 $destinationRoot = untrailingslashit($this->siteConfig['root_staging']);
948
949 $sourceURL = $this->parseDomain($this->siteConfig['source_home_url']);
950 $destinationURL = $this->parseDomain($this->siteConfig['url']);
951
952 $wpconfig = file_get_contents($sourceWPConfig);
953
954 // Table Prefix
955 $this->log(__('Replacing table prefix in wp-config.php', 'backup-backup'));
956 if (strpos($wpconfig, '"' . $previousPrefix . '";') !== false) {
957 $wpconfig = str_replace('"' . $previousPrefix . '";', '"' . $destinationPrefix . '";', $wpconfig);
958 } elseif (strpos($wpconfig, "'" . $previousPrefix . "';") !== false) {
959 $wpconfig = str_replace("'" . $previousPrefix . "';", "'" . $destinationPrefix . "';", $wpconfig);
960 }
961
962 // Paths e.g. for wp_debug_log
963 $this->log(__('Adjusting paths in wp-config.php', 'backup-backup'));
964 if (strpos($wpconfig, '"' . $previousRoot . '";') !== false) {
965 $wpconfig = str_replace('"' . $previousRoot . '";', '"' . $destinationRoot . '";', $wpconfig);
966 } elseif (strpos($wpconfig, "'" . $previousRoot . "';") !== false) {
967 $wpconfig = str_replace("'" . $previousRoot . "';", "'" . $destinationRoot . "';", $wpconfig);
968 }
969
970 // Paths e.g. for wp_home & wp_siteurl
971 $this->log(__('Adjusting domains in wp-config.php', 'backup-backup'));
972 $wpconfig = explode("\n", $wpconfig);
973 for ($i = 0; $i < sizeof($wpconfig); ++$i) {
974
975 $line = $wpconfig[$i];
976
977 if (strpos($line, 'WP_SITEURL') !== false || strpos($line, 'WP_HOME') !== false) {
978 $wpconfig[$i] = str_replace($sourceURL, $destinationURL, $line);
979 }
980
981 }
982
983 $wpconfig = implode("\n", $wpconfig);
984
985 file_put_contents($destinationWPConfig, $wpconfig);
986 $this->log(__('File adjustments for wp-config.php finished successfully', 'backup-backup'), 'SUCCESS');
987
988 $this->setContinuation(6);
989
990 }
991
992 // Step: 6 (cleanup and misc)
993 private function performFinish() {
994
995 $this->cleanup();
996 $this->setContinuation(7);
997
998 }
999
1000 public function __destruct() {
1001
1002 parent::__destruct();
1003
1004 }
1005
1006 }
1007