Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/wp-staging/Backend/Modules/Jobs/Database.php
+++ b/wp-staging/Backend/Modules/Jobs/Database.php
@@ -7,6 +7,7 @@
use WPStagingCoreUtilsLogger;
use WPStagingCoreWPStaging;
use WPStagingFrameworkCloningProcessCloningDto;
+use WPStagingFrameworkTraitsWithUnfinishedCloneWpConfigGuard;
use WPStagingFrameworkCloningProcessDatabaseDatabaseCloningService;
use WPStagingFrameworkAdapterDatabase as DatabaseAdapter;
use WPStagingFrameworkDatabaseTableService;
@@ -23,6 +24,7 @@
{
use TotalStepsAreNumberOfTables;
use TablePrefixValidator;
+ use WithUnfinishedCloneWpConfigGuard;
@@ -157,6 +159,12 @@
return true;
}
+ $wpConfigPath = trailingslashit($this->options->cloneDir) . 'wp-config.php';
+ if (!$this->guardWpConfigBeforeReset(WPStaging::make(Filesystem::class), $wpConfigPath)) {
+ $this->returnException('Cannot reset staging tables because wp-config.php cannot be guarded: ' . $wpConfigPath);
+ return false;
+ }
+
if ($this->options->databaseResettingStatus === 'pending') {
$this->log('#################### Start Reset Job ####################');
$this->log('DB: Removing all staging database tables.');
--- a/wp-staging/Backend/Modules/Jobs/PreserveDataFirstStep.php
+++ b/wp-staging/Backend/Modules/Jobs/PreserveDataFirstStep.php
@@ -87,12 +87,11 @@
$stagingSites = $this->getStagingSiteOption(Sites::STAGING_SITES_OPTION);
+ $settings = null;
if ($this->options->mainJob === MainJob::UPDATE) {
$settings = $this->getStagingSiteOption("wpstg_settings");
}
- $loginLinkSettings = $this->getStagingSiteOption("wpstg_login_link_settings");
-
$cloneOptions = $this->getStagingSiteOption(CloneOptions::WPSTG_CLONE_SETTINGS_KEY);
@@ -105,7 +104,7 @@
$settingsTableRows = $this->getStagingSiteSettingsTableRows();
- if (!$stagingSites && !$settings && !$cloneOptions && !$backupSchedules && !$loginLinkSettings && empty($remoteStorages) && empty($settingsTableRows)) {
+ if (!$stagingSites && !$settings && !$cloneOptions && !$backupSchedules && empty($remoteStorages) && empty($settingsTableRows)) {
return true;
}
@@ -113,7 +112,6 @@
'stagingSites' => $stagingSites,
'cloneOptions' => $cloneOptions,
'backupSchedules' => $backupSchedules,
- 'loginLinkSettings' => $loginLinkSettings,
'settingsTableRows' => $settingsTableRows,
];
@@ -151,10 +149,6 @@
$this->log("Preserve Data: Failed to get wpstg_clone_options");
}
- if ($loginLinkSettings === false) {
- $this->log("Preserve Data: Failed to get wpstg_login_link_settings");
- }
-
if ($backupSchedules === false) {
$this->log("Preserve Data: Failed to get " . $this->backupSchedulesOption);
}
--- a/wp-staging/Backend/Modules/Jobs/PreserveDataSecondStep.php
+++ b/wp-staging/Backend/Modules/Jobs/PreserveDataSecondStep.php
@@ -111,9 +111,6 @@
}
- $this->preserveStagingOption("wpstg_login_link_settings", $this->preservedData->loginLinkSettings, 'login settings');
-
-
$this->updateCloneOptions();
$this->preserveStagingOption(CloneOptions::WPSTG_CLONE_SETTINGS_KEY, $this->preservedData->cloneOptions, 'clone options');
--- a/wp-staging/Backend/Modules/SystemInfo.php
+++ b/wp-staging/Backend/Modules/SystemInfo.php
@@ -966,7 +966,7 @@
return self::NOT_SET_LABEL;
}
- if (in_array($key, Providers::SENSITIVE_OPTION_KEYS, true)) {
+ if (Providers::isSensitiveOptionKey((string)$key)) {
return self::REMOVED_LABEL;
}
--- a/wp-staging/Backup/Ajax/Backup/PrepareBackup.php
+++ b/wp-staging/Backup/Ajax/Backup/PrepareBackup.php
@@ -56,35 +56,6 @@
- public function ajaxPrepare($data)
- {
- if (!$this->auth->isAuthenticatedRequest()) {
- wp_send_json_error(null, 401);
- }
-
- try {
- $this->processLock->lockProcess();
- } catch (ProcessLockedException $e) {
- wp_send_json_error([
- 'message' => esc_html__('A backup or restore process is already running.', 'wp-staging') . ' ' . $e->getMessage(),
- 'title' => esc_html__('Backup in Progress', 'wp-staging'),
- 'code' => ErrorCode::PROCESS_LOCKED,
- ], $e->getCode());
- }
-
- $response = $this->prepare($data);
-
- if ($response instanceof WP_Error) {
- wp_send_json_error($response->get_error_message(), $response->get_error_code());
- } else {
- wp_send_json_success();
- }
- }
-
-
-
-
-
public function prepare($data = null)
{
if (empty($data) && array_key_exists('wpstgBackupData', $_POST)) {
@@ -117,6 +88,10 @@
$data = $this->discardScheduleIdSentWithTheRequest($data);
}
+ if ($this->isSchedulingWithoutValidProLicense($data)) {
+ return new WP_Error(400, __('You need a valid WP Staging Pro license to create a backup plan.', 'wp-staging'));
+ }
+
try {
$sanitizedData = $this->setupInitialJob($data);
} catch (Exception $e) {
@@ -134,6 +109,19 @@
+ protected function sendProcessLockedError(ProcessLockedException $exception)
+ {
+ wp_send_json_error([
+ 'message' => esc_html__('A backup or restore process is already running.', 'wp-staging') . ' ' . $exception->getMessage(),
+ 'title' => esc_html__('Backup in Progress', 'wp-staging'),
+ 'code' => ErrorCode::PROCESS_LOCKED,
+ ], $exception->getCode());
+ }
+
+
+
+
+
@@ -268,7 +256,7 @@
}
- $data['name'] = substr(sanitize_text_field(html_entity_decode($data['name'])), 0, 100);
+ $data['name'] = mb_substr(sanitize_text_field(html_entity_decode($data['name'])), 0, 100);
$data['name'] = str_replace('\'', ''', $data['name']);
@@ -438,4 +426,20 @@
return true;
}
+
+
+
+
+
+ private function isSchedulingWithoutValidProLicense($data): bool
+ {
+ if (!is_array($data) || empty($data['repeatBackupOnSchedule'])) {
+ return false;
+ }
+
+ return $this->jsBoolean($data['repeatBackupOnSchedule'])
+ && WPStaging::isPro()
+ && class_exists('WPStagingProWPStagingPro')
+ && !WPStagingProWPStagingPro::isValidLicense();
+ }
}
--- a/wp-staging/Backup/Ajax/BackupSizeCalculator.php
+++ b/wp-staging/Backup/Ajax/BackupSizeCalculator.php
@@ -208,7 +208,7 @@
{
$dirToScan = $this->directory->getPluginsDirectory();
$excludeRules = $this->getPluginsExcludeRules();
- $partSize = $this->calculateDirectorySize($dirToScan, PartIdentifier::PLUGIN_PART_IDENTIFIER, $excludeRules);
+ $partSize = $this->calculateDirectorySize($dirToScan, PartIdentifier::PLUGIN_PART_IDENTIFIER, $excludeRules, $this->isSiteHostedOnWordPressCom);
$formatedSize = $this->math->formatSize($partSize);
wp_send_json_success([
@@ -265,7 +265,7 @@
$this->setCurrentPathScanning(PartIdentifier::THEME_PART_IDENTIFIER);
$this->setExcludeRules($excludeRules);
- $this->preScanPath($themesDirectory, true);
+ $this->preScanPath($themesDirectory, $this->isSiteHostedOnWordPressCom);
$totalSize += $this->scannerDto->getFilesystemSize();
}
@@ -318,7 +318,8 @@
- protected function calculateDirectorySize(string $directory, string $partIdentifier, array $excludeRules = []): int
+
+ protected function calculateDirectorySize(string $directory, string $partIdentifier, array $excludeRules = [], bool $processLinks = false): int
{
if (!is_dir($directory)) {
return 0;
@@ -326,7 +327,7 @@
$this->setCurrentPathScanning($partIdentifier);
$this->setExcludeRules($excludeRules);
- $this->preScanPath($directory, true);
+ $this->preScanPath($directory, $processLinks);
return $this->scannerDto->getFilesystemSize();
}
@@ -497,7 +498,7 @@
return;
}
- $this->preScanPath($pathname, true);
+ $this->preScanPath($pathname);
}
--- a/wp-staging/Backup/Ajax/Edit.php
+++ b/wp-staging/Backup/Ajax/Edit.php
@@ -13,6 +13,8 @@
class Edit extends AbstractTemplateComponent
{
+ const MAX_SIZE_WRITE_ATTEMPTS = 10;
+
private $backupMetadataEditor;
@@ -49,13 +51,13 @@
$name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : 'Backup';
- $name = substr(sanitize_text_field(html_entity_decode($name)), 0, 100);
+ $name = mb_substr(sanitize_text_field(html_entity_decode($name)), 0, 100);
$name = htmlentities($name, ENT_QUOTES);
$name = str_replace('\'', ''', $name);
$name = str_replace('\"', '"', $name);
$notes = isset($_POST['notes']) ? sanitize_textarea_field($_POST['notes']) : '';
- $notes = substr($notes, 0, 1000);
+ $notes = mb_substr($notes, 0, 1000);
if (strlen($md5) !== 32) {
wp_send_json([
@@ -86,28 +88,15 @@
$file = new FileObject($backup->getPathname(), FileObject::MODE_APPEND_AND_READ);
$metaData = (new BackupMetadata())->hydrateByFile($file);
- $increment = strlen($name) + strlen($notes);
-
if ($metaData->getIsMultipartBackup()) {
- $this->updateBackupParts($metaData, $name, $notes, $increment, $backup->getFilename());
+ $this->updateBackupParts($metaData, $name, $notes, $backup->getFilename());
return;
}
- $oldNote = $metaData->getNote();
- $oldNoteLength = 2;
- if ($oldNote !== null) {
- $oldNoteLength = strlen($oldNote);
- }
-
- $backupSize = $metaData->getBackupSize();
- $backupSize = $backupSize + $increment - strlen($metaData->getName()) - $oldNoteLength;
- $backupSize = $backupSize - $this->backupMetadataEditor->getLineTerminatorOverhead($file);
-
$metaData->setName($name);
$metaData->setNote($notes);
- $metaData->setBackupSize($backupSize);
- $this->backupMetadataEditor->setBackupMetadata($file, $metaData);
+ $this->writeMetadataUntilSizesHold([['file' => $file, 'metadata' => $metaData]]);
} catch (Exception $e) {
wp_send_json([
'error' => true,
@@ -127,10 +116,8 @@
-
- protected function updateBackupParts($metaData, $name, $notes, $incrementSize, $backupFilename)
+ protected function updateBackupParts($metaData, $name, $notes, $backupFilename)
{
- $backupSize = 0;
$backupParts = [];
foreach ($metaData->getMultipartMetadata()->getBackupParts() as $part) {
$backupPart = $this->backupPathResolver->resolveBackupPartPath($part, $backupFilename);
@@ -140,36 +127,56 @@
$partFile = new FileObject($backupPart, FileObject::MODE_APPEND_AND_READ);
$partMetadata = (new BackupMetadata())->hydrateByFile($partFile);
- $partSize = filesize($backupPart);
-
- $oldNote = $partMetadata->getNote();
- $oldNoteLength = 2;
- if ($oldNote !== null) {
- $oldNoteLength = strlen($oldNote);
- }
+ $partMetadata->setName($name);
+ $partMetadata->setNote($notes);
- $partSize = $partSize + $incrementSize - strlen($partMetadata->getName()) - $oldNoteLength;
- $partSize = $partSize - $this->backupMetadataEditor->getLineTerminatorOverhead($partFile);
- $backupSize += $partSize;
$backupParts[] = [
- 'metadata' => $partMetadata,
'file' => $partFile,
- 'size' => $partSize,
+ 'metadata' => $partMetadata,
];
}
- foreach ($backupParts as $part) {
-
- $partMetadata = $part['metadata'];
- $partMetadata->setName($name);
- $partMetadata->setNote($notes);
- $partMetadata->setBackupSize($backupSize);
+ $this->writeMetadataUntilSizesHold($backupParts);
+ }
- $multipartMetadata = $partMetadata->getMultipartMetadata();
- $multipartMetadata->setPartSize($part['size']);
- $partMetadata->setMultipartMetadata($multipartMetadata);
- $this->backupMetadataEditor->setBackupMetadata($part['file'], $partMetadata);
+
+
+
+
+
+
+ private function writeMetadataUntilSizesHold(array $backupFiles)
+ {
+ $sizes = [];
+ foreach ($backupFiles as $index => $backupFile) {
+ $sizes[$index] = (int)filesize($backupFile['file']->getPathname());
+ }
+
+ for ($attempt = 0; $attempt < self::MAX_SIZE_WRITE_ATTEMPTS; $attempt++) {
+ $measured = [];
+ foreach ($backupFiles as $index => $backupFile) {
+
+ $metadata = $backupFile['metadata'];
+ $metadata->setBackupSize($metadata->getIsMultipartBackup() ? array_sum($sizes) : $sizes[$index]);
+ if ($metadata->getIsMultipartBackup()) {
+ $multipartMetadata = $metadata->getMultipartMetadata();
+ $multipartMetadata->setPartSize($sizes[$index]);
+ $metadata->setMultipartMetadata($multipartMetadata);
+ }
+
+ $this->backupMetadataEditor->setBackupMetadata($backupFile['file'], $metadata);
+ clearstatcache(true, $backupFile['file']->getPathname());
+ $measured[$index] = (int)filesize($backupFile['file']->getPathname());
+ }
+
+ if ($measured === $sizes) {
+ return;
+ }
+
+ $sizes = $measured;
}
+
+ throw new RuntimeException('Cannot determine the size to record in the backup metadata.');
}
}
--- a/wp-staging/Backup/Ajax/Restore/PrepareRestore.php
+++ b/wp-staging/Backup/Ajax/Restore/PrepareRestore.php
@@ -12,7 +12,6 @@
use WPStagingFrameworkFacadesSanitize;
use WPStagingFrameworkFilesystemFilesystem;
use WPStagingFrameworkJobAjaxPrepareJob;
-use WPStagingFrameworkJobExceptionProcessLockedException;
use WPStagingFrameworkJobJobTransientCache;
use WPStagingFrameworkJobProcessLock;
use WPStagingFrameworkJobTraitsWithTmpDatabasePrefix;
@@ -37,27 +36,6 @@
$this->tableService = $tableService;
}
- public function ajaxPrepare($data)
- {
- if (!$this->auth->isAuthenticatedRequest()) {
- wp_send_json_error(null, 401);
- }
-
- try {
- $this->processLock->lockProcess();
- } catch (ProcessLockedException $e) {
- wp_send_json_error($e->getMessage(), $e->getCode());
- }
-
- $response = $this->prepare($data);
-
- if ($response instanceof WP_Error) {
- wp_send_json_error($response->get_error_message(), $response->get_error_code());
- } else {
- wp_send_json_success();
- }
- }
-
public function prepare($data = null)
{
--- a/wp-staging/Backup/Ajax/ScheduleList.php
+++ b/wp-staging/Backup/Ajax/ScheduleList.php
@@ -146,12 +146,12 @@
}
$authProvider = WPStaging::make($authClass);
- if (!method_exists($authProvider, 'getAuthenticationURL')) {
+ if (!method_exists($authProvider, 'getAuthenticationStartURL')) {
wp_send_json_error('This storage provider does not support OAuth reconnect.');
return;
}
- $url = $authProvider->getAuthenticationURL('wpstg_backup');
+ $url = $authProvider->getAuthenticationStartURL('wpstg_backup');
wp_send_json_success(['url' => $url]);
}
--- a/wp-staging/Backup/BackgroundProcessing/Backup/PrepareBackup.php
+++ b/wp-staging/Backup/BackgroundProcessing/Backup/PrepareBackup.php
@@ -12,9 +12,9 @@
use WP_Error;
use WPStagingBackupAjaxBackupPrepareBackup as AjaxPrepareBackup;
use WPStagingBackupDtoJobJobBackupDataDto;
-use WPStagingBackupEntityBackupMetadata;
use WPStagingBackupJobJobBackupProvider;
use WPStagingBackupJobJobsJobBackup;
+use WPStagingBackupServiceServerInitiatedBackupScope;
use WPStagingCoreWPStaging;
use WPStagingFrameworkBackgroundProcessingJobPrepareJob;
use WPStagingFrameworkBackgroundProcessingQueue;
@@ -53,6 +53,8 @@
public function getDefaultDataConfiguration(): array
{
+ $scope = ServerInitiatedBackupScope::forCurrentContext();
+
return [
'isExportingPlugins' => true,
'isExportingMuPlugins' => true,
@@ -74,8 +76,8 @@
'isExcludingUnusedThemes' => false,
'isExcludingLogs' => false,
'isExcludingCaches' => false,
- 'backupType' => is_multisite() ? BackupMetadata::BACKUP_TYPE_MULTISITE : BackupMetadata::BACKUP_TYPE_SINGLE,
- 'subsiteBlogId' => null,
+ 'backupType' => $scope['backupType'],
+ 'subsiteBlogId' => $scope['subsiteBlogId'],
'backupExcludedDirectories' => '',
"isValidateBackupFiles" => false,
];
@@ -112,6 +114,7 @@
$jobDataDto = $job->getJobDataDto();
$jobDataDto->setScheduleId(empty($args['scheduleId']) ? null : (string)$args['scheduleId']);
+ $job->setOwnerJobId((string)$args['jobId']);
if (empty($args['isSyncRequest'])) {
$job->getTransientCache()->startJob((string)$args['jobId'], esc_html__('Backup in Progress', 'wp-staging'), JobTransientCache::JOB_TYPE_BACKUP, (string)$args['jobId']);
--- a/wp-staging/Backup/Dto/Job/JobBackupDataDto.php
+++ b/wp-staging/Backup/Dto/Job/JobBackupDataDto.php
@@ -68,12 +68,21 @@
private $currentFileStartOffset = 0;
+ private $currentFileCrc32Stamp = '';
+
+
private $totalRowsBackup = 0;
private $tableRowsOffset = 0;
+ private $tableLockAttempts = 0;
+
+
+ private $tableLockRetryAt = 0;
+
+
private $sqlCheckpointFile = '';
@@ -89,6 +98,9 @@
private $fileCheckpointIndexBytes = 0;
+ private $databaseCheckpointWrittenBytes = 0;
+
+
private $totalRowsOfTableBeingBackup = 0;
@@ -418,6 +430,38 @@
+ public function getTableLockAttempts()
+ {
+ return (int)$this->tableLockAttempts;
+ }
+
+
+
+
+ public function setTableLockAttempts($tableLockAttempts)
+ {
+ $this->tableLockAttempts = (int)$tableLockAttempts;
+ }
+
+
+
+
+ public function getTableLockRetryAt()
+ {
+ return (int)$this->tableLockRetryAt;
+ }
+
+
+
+
+ public function setTableLockRetryAt($tableLockRetryAt)
+ {
+ $this->tableLockRetryAt = (int)$tableLockRetryAt;
+ }
+
+
+
+
public function getSqlCheckpointFile()
{
return (string)$this->sqlCheckpointFile;
@@ -498,6 +542,22 @@
+ public function getDatabaseCheckpointWrittenBytes()
+ {
+ return (int)$this->databaseCheckpointWrittenBytes;
+ }
+
+
+
+
+ public function setDatabaseCheckpointWrittenBytes($databaseCheckpointWrittenBytes)
+ {
+ $this->databaseCheckpointWrittenBytes = (int)$databaseCheckpointWrittenBytes;
+ }
+
+
+
+
public function getTotalRowsBackup()
{
return (int)$this->totalRowsBackup;
@@ -1249,6 +1309,20 @@
$this->currentFileStartOffset = (int)$currentFileStartOffset;
}
+ public function getCurrentFileCrc32Stamp(): string
+ {
+ return $this->currentFileCrc32Stamp;
+ }
+
+
+
+
+
+ public function setCurrentFileCrc32Stamp(string $currentFileCrc32Stamp)
+ {
+ $this->currentFileCrc32Stamp = $currentFileCrc32Stamp;
+ }
+
--- a/wp-staging/Backup/Dto/Job/JobRestoreDataDto.php
+++ b/wp-staging/Backup/Dto/Job/JobRestoreDataDto.php
@@ -95,6 +95,9 @@
protected $isDatabaseRestoreSkipped = false;
+ protected $skippedViews = [];
+
+
protected $caughtExceptionRetries = 0;
@@ -643,6 +646,36 @@
}
+
+
+ public function getSkippedViews(): array
+ {
+ return $this->skippedViews;
+ }
+
+
+
+
+
+ public function setSkippedViews(array $skippedViews)
+ {
+ $this->skippedViews = $skippedViews;
+ }
+
+
+
+
+
+ public function addSkippedView(string $viewName)
+ {
+ if (in_array($viewName, $this->skippedViews, true)) {
+ return;
+ }
+
+ $this->skippedViews[] = $viewName;
+ }
+
+
public function getCaughtExceptionRetries(): int
--- a/wp-staging/Backup/Dto/Service/ArchiverDto.php
+++ b/wp-staging/Backup/Dto/Service/ArchiverDto.php
@@ -19,6 +19,9 @@
private $fileHeaderSizeInBytes = 0;
+ private $fileCrc32Stamp = '';
+
+
private $writtenBytesTotal = 0;
@@ -84,6 +87,7 @@
$this->setWrittenBytesTotal(0);
$this->indexPositionCreated = [];
$this->setFileHeaderSizeInBytes(0);
+ $this->setFileCrc32Stamp('');
$this->setStartOffset(0);
$this->setIsContinuation(false);
$this->setSourceBytesWrittenTotal(0);
@@ -195,6 +199,20 @@
$this->fileHeaderSizeInBytes = $fileHeaderSizeInBytes;
}
+ public function getFileCrc32Stamp(): string
+ {
+ return $this->fileCrc32Stamp;
+ }
+
+
+
+
+
+ public function setFileCrc32Stamp(string $fileCrc32Stamp)
+ {
+ $this->fileCrc32Stamp = $fileCrc32Stamp;
+ }
+
--- a/wp-staging/Backup/Dto/Task/Restore/Response/RestoreFinishResponseDto.php
+++ b/wp-staging/Backup/Dto/Task/Restore/Response/RestoreFinishResponseDto.php
@@ -17,6 +17,11 @@
+ private $skippedViews = [];
+
+
+
+
public function setIsDatabaseRestoreSkipped(bool $isDatabaseRestoreSkipped)
{
@@ -30,4 +35,13 @@
{
return $this->isDatabaseRestoreSkipped;
}
+
+
+
+
+
+ public function setSkippedViews(array $skippedViews)
+ {
+ $this->skippedViews = $skippedViews;
+ }
}
--- a/wp-staging/Backup/Exceptions/TableLockGivenUpException.php
+++ b/wp-staging/Backup/Exceptions/TableLockGivenUpException.php
@@ -0,0 +1,47 @@
+<?php
+
+namespace WPStagingBackupExceptions;
+
+
+
+
+class TableLockGivenUpException extends BackupRuntimeException
+{
+ const CODE_TABLE_LOCK_GIVEN_UP = 111;
+
+
+
+
+
+
+ public static function forTable(string $table, int $attempts): TableLockGivenUpException
+ {
+ return new self(
+ sprintf(
+ /* translators: 1: database table name, 2: number of lock requests that timed out */
+ __('Table %1$s is held by another query and its lock timed out %2$d times. The backup stopped so the site does not wait behind it; run it again when the site is less busy.', 'wp-staging'),
+ $table,
+ $attempts
+ ),
+ self::CODE_TABLE_LOCK_GIVEN_UP
+ );
+ }
+
+
+
+
+
+
+ public static function forRefusedLock(string $table, string $reason): TableLockGivenUpException
+ {
+ return new self(
+ sprintf(
+ /* translators: 1: database table name, 2: database lock error */
+ __('The backup stopped because table %1$s could not be locked. Database error: %2$s', 'wp-staging'),
+ $table,
+ $reason
+ ),
+ self::CODE_TABLE_LOCK_GIVEN_UP
+ );
+ }
+}
--- a/wp-staging/Backup/Job/Jobs/JobBackup.php
+++ b/wp-staging/Backup/Job/Jobs/JobBackup.php
@@ -12,6 +12,7 @@
use WPStagingBackupDtoJobJobBackupDataDto;
use WPStagingBackupExceptionsMissingBackupPartException;
use WPStagingBackupExceptionsNothingToBackupException;
+use WPStagingBackupExceptionsTableLockGivenUpException;
use WPStagingBackupTaskTasksJobBackupBackupMuPluginsTask;
use WPStagingBackupTaskTasksJobBackupBackupOtherFilesTask;
use WPStagingBackupTaskTasksJobBackupBackupOtherWpRootFilesTask;
@@ -71,6 +72,8 @@
return $this->getUnrecoverableFailResponse($e);
} catch (FileSizeLimitException $e) {
return $this->getUnrecoverableFailResponse($e);
+ } catch (TableLockGivenUpException $e) {
+ return $this->getUnrecoverableFailResponse($e);
} catch (NothingToBackupException $e) {
return $this->getNothingToBackupResponse($e->getMessage());
} catch (Exception $e) {
@@ -135,7 +138,7 @@
$response->setIsRunning(false);
$response->setJobStatus(self::JOB_STATUS_NOTHING_TO_BACKUP);
- $this->jobTransientCache->failJob(esc_html__('Nothing to backup', 'wp-staging'), $message, JobTransientCache::SEVERITY_NOTICE);
+ $this->getTransientCache()->failJob(esc_html__('Nothing to backup', 'wp-staging'), $message, JobTransientCache::SEVERITY_NOTICE);
return $response;
}
--- a/wp-staging/Backup/Service/Archiver.php
+++ b/wp-staging/Backup/Service/Archiver.php
@@ -19,6 +19,7 @@
use WPStagingFrameworkAdapterPhpAdapter;
use WPStagingFrameworkFacadesHooks;
use WPStagingFrameworkFilesystemDiskWriteCheck;
+use WPStagingFrameworkFilesystemFileObject;
use WPStagingFrameworkFilesystemFilesystem;
use WPStagingFrameworkFilesystemPartIdentifier;
use WPStagingFrameworkFilesystemPathIdentifier;
@@ -244,6 +245,36 @@
+ public function recordTempBackupCheckpoint(JobBackupDataDto $jobDataDto, string $checkpointKey)
+ {
+ $backupBytes = $this->measureFileBytes($this->getTempBackup()->getFilePath());
+ $indexBytes = $this->measureFileBytes($this->getTempBackupIndex()->getFilePath());
+
+ $jobDataDto->setFileCheckpointKey($checkpointKey);
+ $jobDataDto->setFileCheckpointBackupBytes($backupBytes);
+ $jobDataDto->setFileCheckpointIndexBytes($indexBytes);
+ }
+
+
+
+
+
+
+ public function rewindTempBackupToCheckpoint(JobBackupDataDto $jobDataDto): int
+ {
+ return $this->truncateToCheckpoint($this->getTempBackup()->getFilePath(), $jobDataDto->getFileCheckpointBackupBytes())
+ + $this->truncateToCheckpoint($this->getTempBackupIndex()->getFilePath(), $jobDataDto->getFileCheckpointIndexBytes());
+ }
+
+
+
+
+
+
+
+
+
+
@@ -275,7 +306,7 @@
$this->archiverDto->setFileHeaderSizeInBytes($fileHeaderSizeInBytes);
} elseif (!$this->isBackupFormatV1()) {
$identifiablePath = $this->pathIdentifier->transformPathToIdentifiable($this->filesystem->maybeNormalizePath($indexPath));
- $this->fileHeader->readFile($fullFilePath, $identifiablePath);
+ $this->readHeaderOfResumedFile($fullFilePath, $identifiablePath);
}
$writtenBytesBefore = $this->archiverDto->getWrittenBytesTotal();
@@ -508,6 +539,7 @@
{
$identifiablePath = $this->pathIdentifier->transformPathToIdentifiable($this->filesystem->maybeNormalizePath($indexPath));
$this->fileHeader->readFile($filePath, $identifiablePath);
+ $this->archiverDto->setFileCrc32Stamp($this->stampCrc32Checksum($this->fileHeader->getCrc32Checksum()));
return $this->tempBackup->append($this->fileHeader->getFileHeader());
}
@@ -518,6 +550,38 @@
+
+
+ private function readHeaderOfResumedFile(string $filePath, string $identifiablePath)
+ {
+ $this->fileHeader->readFile($filePath, $identifiablePath, true);
+
+ $crc32Stamp = $this->archiverDto->getFileCrc32Stamp();
+ $crc32Checksum = (string)strstr($crc32Stamp, ':', true);
+ if ($crc32Checksum !== '' && $crc32Stamp === $this->stampCrc32Checksum($crc32Checksum)) {
+ $this->fileHeader->setCrc32Checksum($crc32Checksum);
+ return;
+ }
+
+ $this->fileHeader->readFile($filePath, $identifiablePath);
+ $this->archiverDto->setFileCrc32Stamp($this->stampCrc32Checksum($this->fileHeader->getCrc32Checksum()));
+ }
+
+
+
+
+
+ private function stampCrc32Checksum(string $crc32Checksum): string
+ {
+ return $crc32Checksum . ':' . $this->fileHeader->getUncompressedSize() . ':' . $this->fileHeader->getModifiedTime();
+ }
+
+
+
+
+
+
+
protected function getDelayForRetry(int $retry): float
{
$delay = 0.1;
@@ -879,6 +943,53 @@
return $bytesWritten;
}
+
+
+
+
+
+
+ private function truncateToCheckpoint(string $filePath, int $checkpointBytes): int
+ {
+ $fileBytes = $this->measureFileBytes($filePath);
+ if ($fileBytes === $checkpointBytes) {
+ return 0;
+ }
+
+ if ($fileBytes < $checkpointBytes) {
+ throw new RuntimeException(sprintf('Backup: %s is shorter than its last checkpoint (%d < %d bytes), so data already added to the backup is missing.', basename($filePath), $fileBytes, $checkpointBytes));
+ }
+
+ $file = new FileObject($filePath, FileObject::MODE_WRITE_UNSAFE);
+ if (!$file->ftruncate($checkpointBytes)) {
+ throw new RuntimeException(sprintf('Backup: Could not discard %s added by a request that did not finish.', size_format($fileBytes - $checkpointBytes)));
+ }
+
+ clearstatcache(true, $filePath);
+
+ return $fileBytes - $checkpointBytes;
+ }
+
+
+
+
+
+
+ private function measureFileBytes(string $filePath): int
+ {
+ clearstatcache(true, $filePath);
+ if (!file_exists($filePath)) {
+ return 0;
+ }
+
+ $bytes = filesize($filePath);
+ if ($bytes === false) {
+ throw new RuntimeException(sprintf('Backup: Could not measure %s to checkpoint what was added to the backup.', basename($filePath)));
+ }
+
+ return $bytes;
+ }
+
private function isBackupFormatV1(): bool
{
--- a/wp-staging/Backup/Service/BackupMetadataEditor.php
+++ b/wp-staging/Backup/Service/BackupMetadataEditor.php
@@ -26,6 +26,11 @@
throw new UnexpectedValueException('Could not find the existing metadata from the backup.');
}
+ $encodedMetadata = json_encode($newMetadata);
+ if ($encodedMetadata === false) {
+ throw new UnexpectedValueException('Could not encode the new metadata of the backup.');
+ }
+
$backupFile->ftruncate($existingMetadataPosition);
$backupFile->fseek($existingMetadataPosition);
@@ -34,7 +39,7 @@
$prepandForSql = '-- ';
}
- $backupFile->fwrite($prepandForSql . json_encode($newMetadata) . BackupHeader::LINE_TERMINATOR);
+ $backupFile->fwrite($prepandForSql . $encodedMetadata . BackupHeader::LINE_TERMINATOR);
}
--- a/wp-staging/Backup/Service/Database/DatabaseImporter.php
+++ b/wp-staging/Backup/Service/Database/DatabaseImporter.php
@@ -122,6 +122,9 @@
private $noticeLogCallable;
+ private $skippedViewCallable;
+
+
private $searchReplace;
@@ -149,6 +152,9 @@
private $tablesExcludedFromSearchReplace = [];
+ private $binaryColumnPositionsByTable = [];
+
+
private $subsiteManager;
@@ -545,6 +551,16 @@
+
+ public function setSkippedViewCallable(callable $callable)
+ {
+ $this->skippedViewCallable = $callable;
+ }
+
+
+
+
+
public function execute()
{
$query = $this->findExecutableQuery();
@@ -743,6 +759,35 @@
}
break;
+ case 1146:
+ $viewName = $this->extractViewNameFromQuery($query);
+ if ($viewName === '') {
+ break;
+ }
+
+ if ($this->tmpDatabasePrefix === self::TMP_DATABASE_PREFIX) {
+ $viewName = str_replace(self::TMP_DATABASE_PREFIX, $this->database->getPrefix(), $viewName);
+ $errorMsg = str_replace(self::TMP_DATABASE_PREFIX, $this->database->getPrefix(), $errorMsg);
+ }
+
+ $warning = 'The database view "%1$s" was skipped because it depends on a table or view that is not present. MySQL returned error %2$d: "%3$s". The remaining database statements will continue.';
+ if (__NAMESPACE__ !== 'WpstgRestorer') {
+ /* translators: 1: database view name, 2: MySQL error code, 3: MySQL error message. */
+ $warning = __('The database view "%1$s" was skipped because it depends on a table or view that is not present. MySQL returned error %2$d: "%3$s". The remaining database statements will continue.', 'wp-staging');
+ }
+
+ $this->logWarning(sprintf($warning, $viewName, $errorNo, $errorMsg), [
+ 'method' => __METHOD__,
+ 'DbFileLine' => $this->getCurrentLine(),
+ 'DbQuery' => $query,
+ ]);
+ if (is_callable($this->skippedViewCallable)) {
+ call_user_func($this->skippedViewCallable, $viewName);
+ }
+
+ $result = true;
+
+ break;
case 1050:
$probedForReplay = true;
$replayedTable = $this->findReplayedEmptyTemporaryTable($query);
@@ -1155,7 +1200,7 @@
$query = "INSERT INTO `$tableName` VALUES (";
- foreach ($valueMatches as $value) {
+ foreach ($valueMatches as $position => $value) {
if (empty($value) || $value === "''") {
$query .= "'', ";
continue;
@@ -1188,8 +1233,8 @@
$value = substr($value, 1, -1);
- if (strpos($value, self::BINARY_FLAG) === 0) {
- $query .= "UNHEX('" . substr($value, strlen(self::BINARY_FLAG)) . "'), ";
+ if ($this->isExportedBinaryValue($value) && isset($this->binaryColumnPositionsOf($tableName)[$position])) {
+ $query .= "UNHEX('" . substr($value, $this->binaryFlagLength) . "'), ";
continue;
}
@@ -1219,6 +1264,203 @@
+ public function rememberBinaryColumnsOf(string $createTableQuery)
+ {
+ $positions = [];
+ $position = 0;
+ foreach ($this->tableDefinitionsOf($createTableQuery) as list($definition, $definitionWithoutLiterals)) {
+ if (strpos($definitionWithoutLiterals, '`') !== 0) {
+ $positions = $this->isTableClause($definitionWithoutLiterals) ? $positions : [];
+ break;
+ }
+
+ if (preg_match('#bINVISIBLEb#i', $definitionWithoutLiterals)) {
+ continue;
+ }
+
+ if (
+ preg_match('#^`(?:[^`]|``)*`s+([a-zA-Z]+(?:([^)]*))?)#', $definitionWithoutLiterals, $type, PREG_OFFSET_CAPTURE)
+ && $this->isBinaryColumnType(substr($definition, $type[1][1], strlen($type[1][0])))
+ ) {
+ $positions[$position] = true;
+ }
+
+ $position++;
+ }
+
+ $tableName = $this->extractTableNameFromQuery(preg_replace('#^CREATE TABLEs+IF NOT EXISTSs+#i', 'CREATE TABLE ', $createTableQuery));
+
+ $this->binaryColumnPositionsByTable[$tableName] = $positions;
+ }
+
+
+
+
+
+ private function isTableClause(string $definition): bool
+ {
+ return preg_match('#^(?:PRIMARY|UNIQUE|KEY|INDEX|FULLTEXT|SPATIAL|CONSTRAINT|CHECK|FOREIGN|PERIOD)b#i', $definition) === 1;
+ }
+
+
+
+
+
+ private function tableDefinitionsOf(string $createTableQuery): array
+ {
+ if (!preg_match('#^CREATE TABLEs+(?:IF NOT EXISTSs+)?(?:`(?:[^`]|``)+`|[a-zA-Z0-9_$]+)s*(#i', $createTableQuery, $tableHead)) {
+ return [];
+ }
+
+ $definitions = [];
+ $definition = '';
+ $definitionWithoutLiterals = '';
+ $depth = 0;
+ $quote = '';
+ $length = strlen($createTableQuery);
+ for ($i = strlen($tableHead[0]); $i < $length; $i++) {
+ $char = $createTableQuery[$i];
+
+ if ($quote !== '') {
+ $definition .= $char;
+ if ($char === '\' && $quote !== '`' && $i + 1 < $length) {
+ $definition .= $createTableQuery[++$i];
+ $definitionWithoutLiterals .= '__';
+ continue;
+ }
+
+ $definitionWithoutLiterals .= $char === $quote ? $char : '_';
+ $quote = $char === $quote ? '' : $quote;
+ continue;
+ }
+
+ if ($char === "'" || $char === '"' || $char === '`') {
+ $quote = $char;
+ } elseif ($char === '(') {
+ $depth++;
+ } elseif ($char === ')' && $depth === 0) {
+ break;
+ } elseif ($char === ')') {
+ $depth--;
+ } elseif ($char === ',' && $depth === 0) {
+ $definitions[] = [trim($definition), trim($definitionWithoutLiterals)];
+ $definition = '';
+ $definitionWithoutLiterals = '';
+ continue;
+ }
+
+ $definition .= $char;
+ $definitionWithoutLiterals .= $char;
+ }
+
+ $definitions[] = [trim($definition), trim($definitionWithoutLiterals)];
+
+ return $definitions;
+ }
+
+
+
+
+ public function getBinaryColumnPositionsByTable(): array
+ {
+ return $this->binaryColumnPositionsByTable;
+ }
+
+
+
+
+
+ public function setBinaryColumnPositionsByTable(array $binaryColumnPositionsByTable)
+ {
+ $this->binaryColumnPositionsByTable = $binaryColumnPositionsByTable;
+ }
+
+
+
+
+
+ private function binaryColumnPositionsOf(string $tableName): array
+ {
+ if (isset($this->binaryColumnPositionsByTable[$tableName])) {
+ return $this->binaryColumnPositionsByTable[$tableName];
+ }
+
+ $positions = $this->readBinaryColumnPositionsOf($tableName);
+ if ($positions === null) {
+ return [];
+ }
+
+ $this->binaryColumnPositionsByTable[$tableName] = $positions;
+
+ return $positions;
+ }
+
+
+
+
+
+ private function readBinaryColumnPositionsOf(string $tableName)
+ {
+ try {
+ $result = $this->client->query("SHOW COLUMNS FROM `$tableName`");
+ } catch (Exception $e) {
+ return null;
+ }
+
+ if ($result === false) {
+ return null;
+ }
+
+ $positions = [];
+ $position = 0;
+ while ($column = $this->client->fetchAssoc($result)) {
+ if (isset($column['Extra']) && stripos($column['Extra'], 'INVISIBLE') !== false) {
+ continue;
+ }
+
+ if ($this->isBinaryColumnType($column['Type'])) {
+ $positions[$position] = true;
+ }
+
+ $position++;
+ }
+
+ $this->client->freeResult($result);
+
+ return $positions;
+ }
+
+
+
+
+
+ private function isBinaryColumnType(string $columnType): bool
+ {
+ $columnType = strtolower($columnType);
+
+ return strpos($columnType, 'binary') !== false || strpos($columnType, 'blob') !== false;
+ }
+
+
+
+
+
+ private function isExportedBinaryValue(string $value): bool
+ {
+ if (strpos($value, self::BINARY_FLAG) !== 0) {
+ return false;
+ }
+
+ $hex = substr($value, $this->binaryFlagLength);
+ $hexLength = strlen($hex);
+
+ return $hexLength % 2 === 0 && strspn($hex, '0123456789abcdefABCDEF') === $hexLength;
+ }
+
+
+
+
+
@@ -1625,15 +1867,23 @@
protected function extractTableNameFromQuery(string $query): string
{
- if (!preg_match('#^(CREATE TABLE|INSERT INTO|DROP TABLE IF EXISTS)s+(?:`([^`]+)`|"([^"]+)"|([a-zA-Z0-9_]+))#i', $query, $matches)) {
+ return $this->extractIdentifierFromQuery($query, '(?:CREATE TABLE|INSERT INTO|DROP TABLE IF EXISTS)');
+ }
+
+ private function extractViewNameFromQuery(string $query): string
+ {
+ return $this->extractIdentifierFromQuery($query, 'CREATEs+(?:ORs+REPLACEs+)?VIEW');
+ }
+
+ private function extractIdentifierFromQuery(string $query, string $statementPattern): string
+ {
+ if (!preg_match('#^' . $statementPattern . 's+(?:`([^`]+)`|"([^"]+)"|([a-zA-Z0-9_]+))#i', $query, $matches)) {
return '';
}
-
-
- foreach ([$matches[2], $matches[3] ?? '', $matches[4] ?? ''] as $tableName) {
- if ($tableName !== '') {
- return $tableName;
+ foreach ([$matches[1], $matches[2] ?? '', $matches[3] ?? ''] as $identifier) {
+ if ($identifier !== '') {
+ return $identifier;
}
}
--- a/wp-staging/Backup/Service/Database/Exporter/RowsExporter.php
+++ b/wp-staging/Backup/Service/Database/Exporter/RowsExporter.php
@@ -15,8 +15,6 @@
use WPStagingFrameworkJobDtoJobDataDto;
use WPStagingVendorPsrLogLoggerInterface;
-use function WPStagingfunctionsdebug_log;
-
class RowsExporter extends AbstractExporter
{
use MySQLRowsGeneratorTrait;
@@ -476,16 +474,10 @@
+
public function lockTable()
{
- try {
- $this->tableService->lockTable($this->tableName);
- } catch (Exception $ex) {
- debug_log("WP STAGING Backup: Could not lock table $this->tableName");
- return false;
- }
-
- return true;
+ $this->tableService->lockTableOrGiveUp($this->tableName);
}
@@ -496,7 +488,6 @@
try {
$this->tableService->unlockTables();
} catch (Exception $ex) {
- debug_log("WP STAGING Backup: Could not unlock tables after locking tables $this->tableName");
return false;
}
--- a/wp-staging/Backup/Service/Database/Exporter/ViewDDLOrder.php
+++ b/wp-staging/Backup/Service/Database/Exporter/ViewDDLOrder.php
@@ -6,6 +6,7 @@
use WPStagingFrameworkDependencyResolverExceptionsCircularReferenceException;
use WPStagingFrameworkDependencyResolverExceptionsMissingReferenceException;
+
class ViewDDLOrder
{
protected $viewsToBeWritten = [];
@@ -36,7 +37,7 @@
}
- if (strpos($queryCurrent, $view) !== false) {
+ if (preg_match('/(?<![w$])' . preg_quote($view, '/') . '(?![w$])/', $queryCurrent) === 1) {
$dependsOn[$viewNameCurrent][] = $view;
}
}
--- a/wp-staging/Backup/Service/FileBackupService.php
+++ b/wp-staging/Backup/Service/FileBackupService.php
@@ -18,7 +18,6 @@
use WPStagingFrameworkAdapterDirectory;
use WPStagingFrameworkJobExceptionDiskNotWritableException;
use WPStagingFrameworkJobExceptionFileSizeLimitException;
-use WPStagingFrameworkFilesystemFileObject;
use WPStagingFrameworkFilesystemFilesystem;
use WPStagingFrameworkFilesystemFilesystemScanner;
use WPStagingFrameworkJobExceptionThresholdException;
@@ -180,6 +179,7 @@
$archiverDto->setWrittenBytesTotal($this->jobDataDto->getFileBeingBackupWrittenBytes());
$archiverDto->setFileHeaderSizeInBytes($this->jobDataDto->getCurrentWrittenFileHeaderBytes());
$archiverDto->setStartOffset($this->jobDataDto->getCurrentFileStartOffset());
+ $archiverDto->setFileCrc32Stamp($this->jobDataDto->getCurrentFileCrc32Stamp());
if ($archiverDto->getWrittenBytesTotal() !== 0) {
$this->logger->debug('Resuming backup of a large file from previous request.');
@@ -246,6 +246,7 @@
$archiverDto = $this->archiver->getDto();
$this->jobDataDto->setFileBeingBackupWrittenBytes($archiverDto->getWrittenBytesTotal());
$this->jobDataDto->setCurrentFileStartOffset($archiverDto->getStartOffset());
+ $this->jobDataDto->setCurrentFileCrc32Stamp($archiverDto->getFileCrc32Stamp());
$this->taskQueue->retry(false);
if ($archiverDto->getFileHeaderSizeInBytes() > 0) {
@@ -426,9 +427,7 @@
return;
}
- $discardedBytes = $this->truncateToCheckpoint($this->archiver->getTempBackup()->getFilePath(), $this->jobDataDto->getFileCheckpointBackupBytes());
- $discardedBytes += $this->truncateToCheckpoint($this->archiver->getTempBackupIndex()->getFilePath(), $this->jobDataDto->getFileCheckpointIndexBytes());
-
+ $discardedBytes = $this->archiver->rewindTempBackupToCheckpoint($this->jobDataDto);
if ($discardedBytes === 0) {
return;
}
@@ -477,8 +476,7 @@
protected function recordFileCheckpoint(): bool
{
try {
- $backupBytes = $this->measureFileBytes($this->archiver->getTempBackup()->getFilePath());
- $indexBytes = $this->measureFileBytes($this->archiver->getTempBackupIndex()->getFilePath());
+ $this->archiver->recordTempBackupCheckpoint($this->jobDataDto, $this->getCurrentArchiveCheckpointKey());
} catch (RuntimeException $e) {
$this->logger->warning($e->getMessage());
$this->jobDataDto->setFileCheckpointKey(self::UNMEASURED_CHECKPOINT_KEY);
@@ -486,10 +484,6 @@
return false;
}
- $this->jobDataDto->setFileCheckpointKey($this->getCurrentArchiveCheckpointKey());
- $this->jobDataDto->setFileCheckpointBackupBytes($backupBytes);
- $this->jobDataDto->setFileCheckpointIndexBytes($indexBytes);
-
return true;
}
@@ -509,51 +503,4 @@
throw new ThresholdException();
}
}
-
-
-
-
-
-
-
- private function truncateToCheckpoint(string $filePath, int $checkpointBytes): int
- {
- $fileBytes = $this->measureFileBytes($filePath);
- if ($fileBytes === $checkpointBytes) {
- return 0;
- }
-
- if ($fileBytes < $checkpointBytes) {
- throw new RuntimeException(sprintf('Backup: %s is shorter than its last checkpoint (%d < %d bytes), so files already added to the backup are missing.', basename($filePath), $fileBytes, $checkpointBytes));
- }
-
- $file = new FileObject($filePath, FileObject::MODE_WRITE_UNSAFE);
- if (!$file->ftruncate($checkpointBytes)) {
- throw new RuntimeException(sprintf('Backup: Could not discard %s of files added by a request that did not finish.', size_format($fileBytes - $checkpointBytes)));
- }
-
- clearstatcache(true, $filePath);
-
- return $fileBytes - $checkpointBytes;
- }
-
-
-
-
-
-
- private function measureFileBytes(string $filePath): int
- {
- clearstatcache(true, $filePath);
- if (!file_exists($filePath)) {
- return 0;
- }
-
- $bytes = filesize($filePath);
- if ($bytes === false) {
- throw new RuntimeException(sprintf('Backup: Could not measure %s to checkpoint the files added to the backup.', basename($filePath)));
- }
-
- return $bytes;
- }
}
--- a/wp-staging/Backup/Service/ServerInitiatedBackupScope.php
+++ b/wp-staging/Backup/Service/ServerInitiatedBackupScope.php
@@ -0,0 +1,53 @@
+<?php
+
+namespace WPStagingBackupService;
+
+use WPStagingBackupEntityBackupMetadata;
+
+
+
+
+
+
+class ServerInitiatedBackupScope
+{
+
+
+
+ public static function forCurrentContext(): array
+ {
+ if (!is_multisite()) {
+ return [
+ 'backupType' => BackupMetadata::BACKUP_TYPE_SINGLE,
+ 'subsiteBlogId' => null,
+ ];
+ }
+
+ if (self::mayBackUpWholeNetwork()) {
+ return [
+ 'backupType' => BackupMetadata::BACKUP_TYPE_MULTISITE,
+ 'subsiteBlogId' => null,
+ ];
+ }
+
+ return [
+ 'backupType' => BackupMetadata::BACKUP_TYPE_NETWORK_SUBSITE,
+ 'subsiteBlogId' => get_current_blog_id(),
+ ];
+ }
+
+ private static function mayBackUpWholeNetwork(): bool
+ {
+ if (is_user_logged_in()) {
+ return is_super_admin();
+ }
+
+ return is_main_site();
+ }
+
+
+ public static function isLimitedToCurrentSite(): bool
+ {
+ return self::forCurrentContext()['backupType'] === BackupMetadata::BACKUP_TYPE_NETWORK_SUBSITE;
+ }
+}
--- a/wp-staging/Backup/Storage/Providers.php
+++ b/wp-staging/Backup/Storage/Providers.php
@@ -107,22 +107,27 @@
- const SENSITIVE_OPTION_KEYS = [
- 'accessKey',
- 'accessToken',
- 'ftpCertContent',
- 'googleClientId',
- 'googleClientSecret',
- 'key',
- 'passphrase',
- 'password',
- 'refreshToken',
- 'secretKey',
+ const CREDENTIAL_OPTION_KEYS = [
+ 'wpstg_google-drive' => ['googleClientId', 'googleClientSecret', 'accessToken', 'refreshToken'],
+ 'wpstg_amazon-s3' => ['accessKey', 'secretKey'],
+ 'wpstg_sftp' => ['username', 'password', 'key', 'passphrase', 'ftpCertContent'],
+ 'wpstg_digitalocean-spaces' => ['accessKey', 'secretKey'],
+ 'wpstg_wasabi-s3' => ['accessKey', 'secretKey'],
+ 'wpstg_generic-s3' => ['accessKey', 'secretKey'],
+ 'wpstg_dropbox' => ['accessToken', 'refreshToken'],
+ 'wpstg_one-drive' => ['accessToken', 'refreshToken'],
+ 'wpstg_pcloud' => ['accessToken'],
+ ];
+
+
+
+
+
+ const UNENCRYPTED_SENSITIVE_OPTION_KEYS = [
'sessionId',
'sharedDriveId',
'uploadId',
'uploadUrl',
- 'username',
];
protected $storages = [];
@@ -502,4 +507,22 @@
delete_option($legacyOptionName);
}
}
+
+
+
+
+ public static function isSensitiveOptionKey(string $key): bool
+ {
+ if (in_array($key, self::UNENCRYPTED_SENSITIVE_OPTION_KEYS, true)) {
+ return true;
+ }
+
+ foreach (self::CREDENTIAL_OPTION_KEYS as $credentialKeys) {
+ if (in_array($key, $credentialKeys, true)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
}
--- a/wp-staging/Backup/Task/Tasks/JobBackup/DatabaseBackupTask.php
+++ b/wp-staging/Backup/Task/Tasks/JobBackup/DatabaseBackupTask.php
@@ -7,6 +7,7 @@
use WPStagingFrameworkDatabaseExporterAbstractExporter;
use WPStagingFrameworkJobDtoStepsDto;
use WPStagingBackupServiceDatabaseExporterDDLExporter;
+use WPStagingBackupExceptionsTableLockGivenUpException;
use WPStagingBackupServiceDatabaseExporterRowsExporter;
use WPStagingBackupTaskBackupTask;
use WPStagingBackupTransferTransferSessionTable;
@@ -15,6 +16,7 @@
use WPStagingBackupServiceDatabaseExporterRowsExporterProvider;
use WPStagingCoreWPStaging;
use WPStagingFrameworkAdapterDirectory;
+use WPStagingFrameworkDatabaseTableService;
use WPStagingFrameworkFacadesHooks;
use WPStagingFrameworkQueueSeekableQueueInterface;
use WPStagingFrameworkUtilsCacheCache;
@@ -35,6 +37,12 @@
];
+ const TABLE_LOCK_ATTEMPTS = 5;
+
+
+ const TABLE_LOCK_RETRY_SECONDS = 30;
+
+
protected $directory;
public function __construct(Directory $directory, LoggerInterface $logger, Cache $cache, StepsDto $stepsDto, SeekableQueueInterface $taskQueue)
@@ -156,50 +164,50 @@
$rowsExporter->setTableRowsOffset($this->jobDataDto->getTableRowsOffset());
$rowsExporter->setTotalRowsExported($this->jobDataDto->getTotalRowsBackup());
-
- $tableLocked = false;
$hasNumericIncrementalPk = false;
+ $tableLocked = false;
try {
$rowsExporter->getPrimaryKey();
$hasNumericIncrementalPk = true;
} catch (Exception $e) {
- $tableLocked = $rowsExporter->lockTable();
+ $retryLater = $this->lockTableOrRetryLater($rowsExporter);
+ if ($retryLater !== null) {
+ return $retryLater;
+ }
+
+ $tableLocked = true;
}
+ try {
- if ($this->jobDataDto->getTableRowsOffset() === 0) {
- $this->jobDataDto->setTotalRowsOfTableBeingBackup($rowsExporter->countTotalRows());
- $this->upsertDatabaseTableInfo(
- $rowsExporter,
- $rowsExporter->getTableBeingBackup(),
- $this->jobDataDto->getTotalRowsOfTableBeingBackup()
- );
+ if ($this->jobDataDto->getTableRowsOffset() === 0) {
+ $this->jobDataDto->setTotalRowsOfTableBeingBackup($rowsExporter->countTotalRows());
+ $this->upsertDatabaseTableInfo(
+ $rowsExporter,
+ $rowsExporter->getTableBeingBackup(),
+ $this->jobDataDto->getTotalRowsOfTableBeingBackup()
+ );
- if ($hasNumericIncrementalPk) {
+ if ($hasNumericIncrementalPk) {
- $rowsExporter->setTableRowsOffset(-PHP_INT_MAX);
+ $rowsExporter->setTableRowsOffset(-PHP_INT_MAX);
+ }
}
- }
- $rowsExporter->setTotalRowsInCurrentTable($this->jobDataDto->getTotalRowsOfTableBeingBackup());
+ $rowsExporter->setTotalRowsInCurrentTable($this->jobDataDto->getTotalRowsOfTableBeingBackup());
- try {
$rowsLeftToBackup = $rowsExporter->backup($this->jobDataDto->getId(), $this->logger);
-
- if ($tableLocked) {
- $rowsExporter->unLockTables();
- }
} catch (Exception $e) {
- if ($tableLocked) {
- $rowsExporter->unLockTables();
- }
-
$this->logger->critical($e->getMessage());
throw $e;
+ } finally {
+ if ($tableLocked) {
+ $this->unlockTable($rowsExporter);
+ }
}
@@ -257,6 +265,122 @@
}
+
+
+
+
+
+
+ private function lockTableOrRetryLater(RowsExporter $rowsExporter)
+ {
+ $table = $rowsExporter->getTableBeingBackup();
+ $this->stopWhenTableLockWasGivenUp($table);
+
+ $retryAt = $this->jobDataDto->getTableLockRetryAt();
+ if ($retryAt > time()) {
+ return $this->retryLaterResponse($table, $retryAt);
+ }
+
+ $this->logger->info(sprintf('Backup database: Requesting a write lock on table %s, waiting up to %d seconds.', $table, TableService::LOCK_WAIT_SECONDS));
+
+ try {
+ $rowsExporter->lockTable();
+ } catch (RuntimeException $refusal) {
+ if ($refusal->getCode() === TableService::LOCK_WAIT_TIMEOUT_ERRNO) {
+ return $this->retryLaterResponse($table, $this->recordRefusedTableLock($table));
+ }
+
+ throw TableLockGivenUpException::forRefusedLock($table, $refusal->getMessage());
+ }
+
+ $this->jobDataDto->setTableLockAttempts(0);
+ $this->jobDataDto->setTableLockRetryAt(0);
+ $this->logger->info(sprintf('Backup database: Locked table %s.', $table));
+
+ return null;
+ }
+
+
+
+
+
+
+
+
+ private function stopWhenTableLockWasGivenUp(string $table)
+ {
+ $attempts = $this->jobDataDto->getTableLockAttempts();
+ if ($attempts < self::TABLE_LOCK_ATTEMPTS) {
+ return;
+ }
+
+ throw TableLockGivenUpException::forTable($table, $attempts);
+ }
+
+
+
+
+
+
+ private function recordRefusedTableLock(string $table): int
+ {
+ $attempts = $this->jobDataDto->getTableLockAttempts() + 1;
+ $this->jobDataDto->setTableLockAttempts($attempts);
+ $this->stopWhenTableLockWasGivenUp($table);
+
+ $retryDelay = self::TABLE_LOCK_RETRY_SECONDS * $attempts;
+ $retryAt = time() + $retryDelay;
+ $this->jobDataDto->setTableLockRetryAt($retryAt);
+ $this->logger->warning(sprintf(
+ 'Backup database: Table %s is held by another query and the lock timed out after %d seconds. Retrying in %d seconds (%d/%d).',
+ $table,
+ TableService::LOCK_WAIT_SECONDS,
+ $retryDelay,
+ $attempts,
+ self::TABLE_LOCK_ATTEMPTS
+ ));
+
+ return $retryAt;
+ }
+
+
+
+
+
+
+
+
+
+ private function retryLaterResponse(string $table, int $retryAt): TaskResponseDto
+ {
+ $retryDelay = $retryAt - time();
+ $response = $this->generateResponse(false);
+ $this->job->getTransientCache()->deferUpload($retryAt, $retryAt);
+ /* translators: 1: database table name, 2: UTC time of the next lock request */
+ $response->setStatusTitle(sprintf(__('Waiting for table %1$s to be released. Next lock request: %2$s UTC.', 'wp-staging'), $table, gmdate('Y-m-d H:i:s', $retryAt)));
+ $response->setRetryAt($retryAt);
+ $response->setRetryDelay($retryDelay);
+ $this->updateTaskProgress($response);
+
+ return $response;
+ }
+
+
+
+
+
+ private function unlockTable(RowsExporter $rowsExporter)
+ {
+ $table = $rowsExporter->getTableBeingBackup();
+ if ($rowsExporter->unLockTables()) {
+ $this->logger->info(sprintf('Backup database: Released the lock on table %s.', $table));
+ return;
+ }
+
+ $this->logger->warning(sprintf('Backup database: Could not release the lock on table %s; the connection releases it when this request ends.', $table));
+ }
+
+
protected function setupDatabaseFilePathName()
--- a/wp-staging/Backup/Task/Tasks/JobBackup/IncludeDatabaseTask.php
+++ b/wp-staging/Backup/Task/Tasks/JobBackup/IncludeDatabaseTask.php
@@ -53,16 +53,19 @@
return $this->generateResponse();
}
+ $this->rewindTempBackupToCheckpointOrRecordBaseline();
+
$archiverDto = $this->archiver->getDto();
- $archiverDto->setWrittenBytesTotal($this->stepsDto->getCurrent());
+ $archiverDto->setWrittenBytesTotal($this->jobDataDto->getDatabaseCheckpointWrittenBytes());
$archiverDto->setFileHeaderSizeInBytes($this->jobDataDto->getCurrentWrittenFileHeaderBytes());
$archiverDto->setStartOffset($this->jobDataDto->getCurrentFileStartOffset());
+ $archiverDto->setFileCrc32Stamp($this->jobDataDto->getCurrentFileCrc32Stamp());
if ($this->archiver->getDto()->getWrittenBytesTotal() !== 0) {
$this->archiver->getDto()->setIndexPositionCreated(true);
}
- $writtenBytesBefore = $this->stepsDto->getCurrent();
+ $writtenBytesBefore = $archiverDto->getWrittenBytesTotal();
$included = false;
try {
$this->archiver->setFileAppendTimeLimit($this->jobDataDto->getFileAppendTimeLimit());
@@ -76,12 +79,15 @@
$this->archiver->getDto()->getFilePath(),
$e->getMessage()
));
+
+ return $this->generateResponse(false);
}
- $archiverDto = $this->archiver->getDto();
+ $this->recordCheckpoint($archiverDto->getWrittenBytesTotal());
$this->stepsDto->setCurrent($archiverDto->getWrittenBytesTotal());
$t