fail_and_cleanup( $job_id, $cursor, $config, __( 'Multisite is not supported.', '007aj-backup-restore-verifier' ) ); } if ( ! Working_Dir::ensure() ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'Unable to create protected working directory.', '007aj-backup-restore-verifier' ) ); } $job_dir = Working_Dir::ensure_job( $job_id ); // Map init → validate for restore jobs. if ( Job_States::PHASE_INIT === $phase ) { $phase = Job_States::PHASE_VALIDATE; } try { $state_dir = State_Files::dir( $job_dir ); State_Files::rewind( $state_dir, isset( $cursor['jr'] ) && is_array( $cursor['jr'] ) ? $cursor['jr'] : array() ); $cursor['job_dir'] = $job_dir; switch ( $phase ) { case Job_States::PHASE_VALIDATE: $result = $this->phase_validate( $job_id, $job_dir, $cursor, $config, $deadline ); break; case Job_States::PHASE_MAINTAIN: $result = $this->phase_maintain( $job_id, $cursor, $config ); break; case Job_States::PHASE_SNAPSHOT: $result = $this->phase_snapshot( $job_id, $job_dir, $cursor, $config, $deadline ); break; case Job_States::PHASE_APPLY_FILES: $result = $this->phase_apply_files( $job_id, $job_dir, $cursor, $config, $deadline ); break; case Job_States::PHASE_APPLY_DB: $result = $this->phase_apply_db( $job_id, $job_dir, $cursor, $config, $deadline ); break; case Job_States::PHASE_VERIFY: $result = $this->phase_verify( $job_id, $job_dir, $cursor, $config ); break; case Job_States::PHASE_ROLLBACK: $result = $this->phase_rollback( $job_id, $cursor, $deadline ); break; default: $result = $this->fail_and_cleanup( $job_id, $cursor, $config, sprintf( /* translators: %s: phase name */ __( 'Unknown restore phase: %s', '007aj-backup-restore-verifier' ), $phase ) ); } if ( Job_States::STATUS_RUNNING === ( $result['status'] ?? '' ) && isset( $result['cursor'] ) && is_array( $result['cursor'] ) ) { $result['cursor']['jr'] = State_Files::journal( $state_dir ); } return $result; } catch ( \Throwable $e ) { $message = Job_Error::describe( $e, $phase ); Logger::error( $job_id, 'Restore exception: ' . $message ); if ( Job_States::PHASE_ROLLBACK === $phase ) { // Rollback itself failed: stop here and report both errors. Maintenance::exit(); return array( 'status' => Job_States::STATUS_FAILED, 'error' => (string) ( $cursor['fail_error'] ?? '' ) . ' — ' . sprintf( /* translators: %s: error */ __( 'rollback failed: %s', '007aj-backup-restore-verifier' ), $message ), 'cursor' => $this->slim( $cursor ), ); } return $this->fail_and_cleanup( $job_id, $cursor, $config, $message, $phase ); } } /** * Validate the artifact (and every archive of a chain) across ticks. * * @param int $job_id Job id. * @param string $job_dir Job dir. * @param array $cursor Cursor. * @param array $config Config. * @param float $deadline Deadline. * @return array{status:string,phase?:string,progress_pct?:int,cursor?:array,error?:string} */ private function phase_validate( int $job_id, string $job_dir, array $cursor, array $config, float $deadline ): array { if ( empty( $cursor['steps'] ) ) { Logger::info( $job_id, 'Restore validate.' ); $artifact_id = (int) ( $config['artifact_id'] ?? 0 ); if ( $artifact_id <= 0 ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'Missing artifact_id for restore.', '007aj-backup-restore-verifier' ) ); } $repo = new Job_Repository(); $art = $repo->get_artifact( $artifact_id ); if ( null === $art ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'Artifact not found.', '007aj-backup-restore-verifier' ) ); } $zip_path = (string) ( $art['path'] ?? '' ); $storage = realpath( Working_Dir::storage() ); if ( false === $storage || '' === $zip_path ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'Local storage unavailable.', '007aj-backup-restore-verifier' ) ); } $real = realpath( $zip_path ); if ( false === $real || ! Path_Guard::is_under( $real, $storage ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'Artifact path failed storage jail check.', '007aj-backup-restore-verifier' ) ); } $cursor['zip_path'] = $real; $cursor['artifact_id'] = $artifact_id; $cursor['snapshot_taken'] = false; $cursor['maintenance'] = false; /** * Filter the restore plan before validation. * * An extension may expand the restore into an ordered list of archives * (incremental chain). Return shape: array{ * ok:bool, * error?:string, * cursor?:array small values only, * steps?:list full archive first, * zip_path?:string tip archive (database dump source) * } * * @param array $plan Default ok plan. * @param array $cursor Cursor. * @param array $config Config. * @param array $art Artifact row. */ $plan = apply_filters( 'brverify_restore_plan', array( 'ok' => true, 'cursor' => $cursor, ), $cursor, $config, $art ); if ( ! is_array( $plan ) || empty( $plan['ok'] ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, (string) ( is_array( $plan ) ? ( $plan['error'] ?? __( 'Restore chain validation failed.', '007aj-backup-restore-verifier' ) ) : __( 'Restore chain validation failed.', '007aj-backup-restore-verifier' ) ) ); } if ( isset( $plan['cursor'] ) && is_array( $plan['cursor'] ) ) { $cursor = $plan['cursor']; } if ( isset( $plan['zip_path'] ) && is_string( $plan['zip_path'] ) && '' !== $plan['zip_path'] ) { $cursor['zip_path'] = $plan['zip_path']; } $steps = array(); if ( isset( $plan['steps'] ) && is_array( $plan['steps'] ) ) { foreach ( $plan['steps'] as $st ) { $sz = is_array( $st ) ? realpath( (string) ( $st['zip'] ?? '' ) ) : false; if ( false === $sz || ! Path_Guard::is_under( $sz, $storage ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'Chain archive path failed storage jail check.', '007aj-backup-restore-verifier' ) ); } $steps[] = array( 'zip' => $sz, 'mode' => 'incremental' === (string) ( $st['mode'] ?? '' ) ? 'incremental' : 'full', 'sha256' => (string) ( $st['sha256'] ?? '' ), ); } } if ( empty( $steps ) ) { $steps[] = array( 'zip' => (string) $cursor['zip_path'], 'mode' => 'full', 'sha256' => '', ); } $cursor['steps'] = $steps; $cursor['va'] = array( 'i' => 0, 'st' => array(), 'ok' => 0, ); } $steps = $cursor['steps']; $va = $cursor['va']; while ( (int) $va['i'] < count( $steps ) ) { $i = (int) $va['i']; $check = new Archive_Check( State_Files::dir( $job_dir ) . '/check-' . $i ); $st = (array) $va['st']; if ( empty( $st ) && '' !== (string) $steps[ $i ]['sha256'] ) { $st['sha256'] = (string) $steps[ $i ]['sha256']; } try { $st = $check->step( (string) $steps[ $i ]['zip'], $st, $deadline - 0.5 ); } catch ( State_Exception $e ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, count( $steps ) > 1 ? basename( (string) $steps[ $i ]['zip'] ) . ': ' . $e->getMessage() : $e->getMessage() ); } if ( empty( $st['done'] ) ) { $va['st'] = $st; $cursor['va'] = $va; return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_VALIDATE, 'progress_pct' => 2 + (int) floor( 7 * ( $i / count( $steps ) ) ), 'cursor' => $cursor, ); } $va['ok'] = (int) $va['ok'] + (int) ( $st['ok'] ?? 0 ); $va['i'] = $i + 1; $va['st'] = array(); if ( $i === count( $steps ) - 1 ) { $manifest = $check->manifest(); $cursor['tip_check'] = $i; $cursor['has_db'] = ! empty( $st['sp']['database/dump.sql'] ) || ! empty( $st['sp']['database/dump.sql.rpenc'] ); $cursor['manifest_components'] = isset( $manifest['components'] ) && is_array( $manifest['components'] ) ? $manifest['components'] : null; $cursor['manifest_format'] = (string) ( $manifest['format'] ?? '' ); } if ( microtime( true ) >= $deadline - 0.5 && (int) $va['i'] < count( $steps ) ) { $cursor['va'] = $va; return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_VALIDATE, 'progress_pct' => 2 + (int) floor( 7 * ( (int) $va['i'] / count( $steps ) ) ), 'cursor' => $cursor, ); } } $components = $this->resolve_components( $config, array( 'components' => $cursor['manifest_components'] ?? null ) ); if ( ! $this->any_component( $components ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'No restore components selected.', '007aj-backup-restore-verifier' ) ); } $cursor['components'] = $components; $cursor['validated_at'] = time(); $cursor['checked'] = (int) $va['ok']; unset( $cursor['va'] ); Logger::info( $job_id, sprintf( 'Validated artifact #%d (%d checksummed members in %d archive(s)). Components: %s', (int) ( $cursor['artifact_id'] ?? 0 ), (int) $cursor['checked'], count( $steps ), wp_json_encode( $components ) ) ); return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_MAINTAIN, 'progress_pct' => 10, 'cursor' => $cursor, ); } /** * Enter maintenance mode. * * @param int $job_id Job id. * @param array $cursor Cursor. * @param array $config Config. * @return array{status:string,phase?:string,progress_pct?:int,cursor?:array,error?:string} */ private function phase_maintain( int $job_id, array $cursor, array $config ): array { /** * Whether this restore should write .maintenance (Phase L). Default true. * * An add-on that must keep admin-ajax reachable across ticks (site migrator swaps * core tables) may return false; nothing changes for the default restore. * * @param bool $use Use maintenance mode. * @param int $job_id Job id. * @param array $config Job config. */ if ( ! apply_filters( 'brverify_restore_use_maintenance', true, $job_id, $config ) ) { Logger::info( $job_id, 'Maintenance mode skipped for this restore (add-on request).' ); $cursor['maintenance'] = false; return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_SNAPSHOT, 'progress_pct' => 15, 'cursor' => $cursor, ); } $result = Maintenance::enter( $job_id ); if ( empty( $result['ok'] ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, (string) ( $result['error'] ?? __( 'Maintenance enter failed.', '007aj-backup-restore-verifier' ) ) ); } $cursor['maintenance'] = true; Logger::info( $job_id, 'Entered maintenance mode.' ); if ( $this->should_force_fail( $config, 'maintain' ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, 'Forced failure after maintain (test).' ); } return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_SNAPSHOT, 'progress_pct' => 15, 'cursor' => $cursor, ); } /** * Pre-restore snapshot. * * @param int $job_id Job id. * @param string $job_dir Job dir. * @param array $cursor Cursor. * @param array $config Config. * @param float $deadline Deadline. * @return array{status:string,phase?:string,progress_pct?:int,cursor?:array,error?:string} */ private function phase_snapshot( int $job_id, string $job_dir, array $cursor, array $config, float $deadline ): array { $components = isset( $cursor['components'] ) && is_array( $cursor['components'] ) ? $cursor['components'] : array(); $snap = new Snapshot(); $result = $snap->tick( $job_id, $job_dir, $cursor, $components, $deadline ); if ( ! empty( $result['error'] ) ) { return $this->fail_and_cleanup( $job_id, $result['cursor'], $config, (string) $result['error'] ); } $cursor = $result['cursor']; if ( empty( $result['done'] ) ) { return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_SNAPSHOT, 'progress_pct' => 25, 'cursor' => $cursor, ); } $cursor['snapshot_taken'] = true; if ( $this->should_force_fail( $config, 'snapshot' ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, 'Forced failure after snapshot (test).' ); } return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_APPLY_FILES, 'progress_pct' => 35, 'cursor' => $cursor, ); } /** * Apply file components. * * @param int $job_id Job id. * @param string $job_dir Job dir. * @param array $cursor Cursor. * @param array $config Config. * @param float $deadline Deadline. * @return array{status:string,phase?:string,progress_pct?:int,cursor?:array,error?:string} */ private function phase_apply_files( int $job_id, string $job_dir, array $cursor, array $config, float $deadline ): array { $components = isset( $cursor['components'] ) && is_array( $cursor['components'] ) ? $cursor['components'] : array(); $needs_files = ! empty( $components['plugins'] ) || ! empty( $components['themes'] ) || ! empty( $components['uploads'] ); if ( ! $needs_files ) { Logger::info( $job_id, 'Skipping file apply (no file components selected).' ); return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_APPLY_DB, 'progress_pct' => 70, 'cursor' => $cursor, ); } $zip_path = (string) ( $cursor['zip_path'] ?? '' ); $applier = new File_Applier(); $result = $applier->tick( $job_id, $job_dir, $zip_path, $cursor, $components, $deadline ); if ( ! empty( $result['error'] ) ) { return $this->fail_and_cleanup( $job_id, $result['cursor'], $config, (string) $result['error'] ); } $cursor = $result['cursor']; $pct = 35 + (int) floor( 30 * File_Applier::progress( $cursor ) ); if ( empty( $result['done'] ) ) { return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_APPLY_FILES, 'progress_pct' => $pct, 'cursor' => $cursor, ); } if ( $this->should_force_fail( $config, 'apply_files' ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, 'Forced failure after apply_files (test).' ); } return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_APPLY_DB, 'progress_pct' => 70, 'cursor' => $cursor, ); } /** * Apply database dump from the artifact (when selected). * * @param int $job_id Job id. * @param string $job_dir Job dir. * @param array $cursor Cursor. * @param array $config Config. * @param float $deadline Deadline. * @return array{status:string,phase?:string,progress_pct?:int,cursor?:array,error?:string} */ private function phase_apply_db( int $job_id, string $job_dir, array $cursor, array $config, float $deadline ): array { $components = isset( $cursor['components'] ) && is_array( $cursor['components'] ) ? $cursor['components'] : array(); if ( empty( $components['database'] ) ) { Logger::info( $job_id, 'Skipping DB apply (database component not selected).' ); return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_VERIFY, 'progress_pct' => 90, 'cursor' => $cursor, ); } // Extract database/dump.sql from the archive (streamed, resumable). if ( empty( $cursor['restore_dump_path'] ) ) { $extracted = $this->extract_dump( $job_id, $job_dir, (string) ( $cursor['zip_path'] ?? '' ), $cursor, $config, $deadline ); if ( ! empty( $extracted['error'] ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, (string) $extracted['error'] ); } if ( empty( $extracted['path'] ) ) { return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_APPLY_DB, 'progress_pct' => 72, 'cursor' => $cursor, ); } unset( $cursor['dx'] ); $cursor['restore_dump_path'] = (string) $extracted['path']; $cursor['db_apply_offset'] = 0; $cursor['db_apply_stmts'] = 0; } // A dump prepared by an add-on from this archive (e.g. a migration) must come from the // database member that passed validation, and the archive must be unchanged since. if ( ! empty( $cursor['restore_dump_source'] ) && empty( $cursor['dump_ok'] ) ) { $src_ok = false; $tip_check = new Archive_Check( State_Files::dir( $job_dir ) . '/check-' . (int) ( $cursor['tip_check'] ?? -1 ) ); try { $tip_check->assert_unchanged( (string) ( $cursor['zip_path'] ?? '' ) ); $want = $tip_check->expected( (string) ( $cursor['restore_dump_source']['member'] ?? '' ) ); $src_ok = null !== $want && hash_equals( $want, strtolower( (string) ( $cursor['restore_dump_source']['sha256'] ?? '' ) ) ); } catch ( State_Exception $e ) { $src_ok = false; } if ( ! $src_ok ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'The prepared database was not made from the validated backup archive; nothing was applied to the database.', '007aj-backup-restore-verifier' ) ); } } // A dump supplied by an add-on with a known SHA-256 (e.g. a prepared migration) is // checked before the first statement runs, across as many ticks as it needs. if ( ! empty( $cursor['restore_dump_sha256'] ) && empty( $cursor['dump_ok'] ) ) { $dh = isset( $cursor['dh'] ) && is_array( $cursor['dh'] ) ? $cursor['dh'] : array(); $hash = \BRVerify\Backup\Backup_Driver::hash_file_resumable( (string) $cursor['restore_dump_path'], $dh, $deadline ); if ( '' === $hash ) { $cursor['dh'] = $dh; return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_APPLY_DB, 'progress_pct' => 72, 'cursor' => $cursor, ); } unset( $cursor['dh'] ); if ( ! hash_equals( strtolower( (string) $cursor['restore_dump_sha256'] ), $hash ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, __( 'The prepared database file changed after it was checked; nothing was applied to the database.', '007aj-backup-restore-verifier' ) ); } $cursor['dump_ok'] = 1; } $cursor['db_touched'] = true; $applier = new Db_Applier(); $result = $applier->tick( $job_id, (string) $cursor['restore_dump_path'], $cursor, $deadline ); if ( ! empty( $result['error'] ) ) { return $this->fail_and_cleanup( $job_id, $result['cursor'], $config, (string) $result['error'] ); } $cursor = $result['cursor']; if ( empty( $result['done'] ) ) { $size = (int) @filesize( (string) $cursor['restore_dump_path'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_APPLY_DB, 'progress_pct' => 72 + (int) floor( 17 * ( $size > 0 ? min( 1, (int) $cursor['db_apply_offset'] / $size ) : 0 ) ), 'cursor' => $cursor, ); } if ( $this->should_force_fail( $config, 'apply_db' ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, 'Forced failure after apply_db (test).' ); } return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_VERIFY, 'progress_pct' => 90, 'cursor' => $cursor, ); } /** * Post-apply integrity spot checks + exit maintenance. * * @param int $job_id Job id. * @param string $job_dir Job dir. * @param array $cursor Cursor. * @param array $config Config. * @return array{status:string,phase?:string,progress_pct?:int,cursor?:array,result?:array,error?:string} */ private function phase_verify( int $job_id, string $job_dir, array $cursor, array $config ): array { unset( $job_dir ); if ( $this->should_force_fail( $config, 'verify' ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, 'Forced failure at verify (test).' ); } $components = isset( $cursor['components'] ) && is_array( $cursor['components'] ) ? $cursor['components'] : array(); $spot = $this->spot_check_files( $cursor, $components ); if ( empty( $spot['ok'] ) ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, (string) ( $spot['error'] ?? __( 'Post-restore integrity check failed.', '007aj-backup-restore-verifier' ) ) ); } /** * Filter post-apply verification (Phase L). Return array{ok:false,error:string} to fail * the restore, which triggers the standard snapshot rollback. * * @param array $check Default array( 'ok' => true ). * @param int $job_id Job id. * @param array $cursor Cursor. * @param array $config Job config. */ $extra = apply_filters( 'brverify_restore_verify', array( 'ok' => true ), $job_id, $cursor, $config ); if ( is_array( $extra ) && isset( $extra['ok'] ) && ! $extra['ok'] ) { return $this->fail_and_cleanup( $job_id, $cursor, $config, (string) ( $extra['error'] ?? __( 'Post-restore verification failed.', '007aj-backup-restore-verifier' ) ) ); } $exit = Maintenance::exit(); if ( empty( $exit['ok'] ) ) { Logger::warning( $job_id, (string) ( $exit['error'] ?? 'Maintenance clear warning.' ) ); } $cursor['maintenance'] = false; // Cleanup scratch (keep storage artifact). $job_scratch = (string) ( $cursor['job_dir'] ?? '' ); if ( '' !== $job_scratch ) { Working_Dir::rrmdir( $job_scratch ); } $cursor = $this->slim( $cursor ); $result = array( 'artifact_id' => (int) ( $cursor['artifact_id'] ?? 0 ), 'components' => $components, 'applied_files' => (int) ( $cursor['applied_files'] ?? 0 ), 'db_stmts' => (int) ( $cursor['db_apply_stmts'] ?? 0 ), 'spot_checked' => (int) ( $spot['checked'] ?? 0 ), ); Logger::info( $job_id, 'Restore completed successfully.' ); /** * Fires after a restore finished and maintenance mode was cleared (Phase L). * * @param int $job_id Job id. * @param array $cursor Cursor. * @param array $config Job config. * @param array $result Result summary. */ do_action( 'brverify_restore_completed', $job_id, $cursor, $config, $result ); return array( 'status' => Job_States::STATUS_COMPLETED, 'phase' => Job_States::PHASE_VERIFY, 'progress_pct' => 100, 'cursor' => $cursor, 'result' => $result, ); } /** * Fail path. Before any live data was touched: clear maintenance and fail. * After the snapshot: switch to the rollback phase, which restores files and * database over as many ticks as needed and then fails with this message. * * @param int $job_id Job id. * @param array $cursor Cursor. * @param array $config Config. * @param string $message Error. * @param string $phase Phase where it happened. * @return array{status:string,error?:string,phase?:string,cursor:array,result?:array} */ private function fail_and_cleanup( int $job_id, array $cursor, array $config, string $message, string $phase = '' ): array { unset( $config ); if ( '' !== $phase ) { $message = Job_Error::with_phase( $message, $phase ); } if ( ! empty( $cursor['snapshot_taken'] ) ) { Logger::warning( $job_id, 'Restore failed after snapshot — rolling back: ' . $message ); $cursor['fail_error'] = $message; $cursor['rb'] = array( 'st' => 'files' ); return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_ROLLBACK, 'progress_pct' => 90, 'cursor' => $cursor, ); } $exit = Maintenance::exit(); if ( empty( $exit['ok'] ) ) { Logger::error( $job_id, (string) ( $exit['error'] ?? 'Failed clearing maintenance.' ) ); } else { Logger::info( $job_id, 'Maintenance mode cleared.' ); } return array( 'status' => Job_States::STATUS_FAILED, 'error' => $message, 'cursor' => $this->slim( $cursor ), 'result' => array( 'rollback' => array( 'files' => null, 'db' => null, ), 'maintenance_clear' => ! empty( $exit['ok'] ), ), ); } /** * Rollback phase: snapshot files, then snapshot database, then fail. * * @param int $job_id Job id. * @param array $cursor Cursor. * @param float $deadline Deadline. * @return array{status:string,phase?:string,progress_pct?:int,error?:string,cursor:array,result?:array} */ private function phase_rollback( int $job_id, array $cursor, float $deadline ): array { $rb = isset( $cursor['rb'] ) && is_array( $cursor['rb'] ) ? $cursor['rb'] : array( 'st' => 'files' ); $components = isset( $cursor['components'] ) && is_array( $cursor['components'] ) ? $cursor['components'] : array(); $running = static function ( array $cursor, array $rb, int $pct ): array { $cursor['rb'] = $rb; return array( 'status' => Job_States::STATUS_RUNNING, 'phase' => Job_States::PHASE_ROLLBACK, 'progress_pct' => $pct, 'cursor' => $cursor, ); }; if ( 'files' === $rb['st'] ) { $res = ( new Snapshot() )->rollback_files_step( $job_id, $cursor, $deadline ); $rb['files'] = (int) $res['restored']; if ( empty( $res['done'] ) ) { return $running( $cursor, $rb, 92 ); } $rb['st'] = 'db'; $rb['c'] = array( 'db_apply_offset' => 0, 'db_apply_stmts' => 0, ); } if ( 'db' === $rb['st'] ) { $snap_db = (string) ( $cursor['snapshot_db_path'] ?? '' ); if ( ! empty( $components['database'] ) && '' !== $snap_db && is_readable( $snap_db ) && ! empty( $cursor['db_touched'] ) ) { $tick = ( new Db_Applier() )->tick( $job_id, $snap_db, (array) $rb['c'], $deadline ); $rb['c'] = $tick['cursor']; if ( ! empty( $tick['error'] ) ) { $rb['db_error'] = (string) $tick['error']; Logger::error( $job_id, 'DB rollback failed: ' . (string) $tick['error'] ); } elseif ( empty( $tick['done'] ) ) { return $running( $cursor, $rb, 95 ); } else { Logger::info( $job_id, 'DB rollback from snapshot completed.' ); } } $rb['st'] = 'done'; } $exit = Maintenance::exit(); $cursor['maintenance'] = false; if ( empty( $exit['ok'] ) ) { Logger::error( $job_id, (string) ( $exit['error'] ?? 'Failed clearing maintenance.' ) ); } else { Logger::info( $job_id, 'Maintenance mode cleared.' ); } $message = (string) ( $cursor['fail_error'] ?? __( 'Restore failed.', '007aj-backup-restore-verifier' ) ); if ( ! empty( $rb['db_error'] ) ) { $message .= ' — ' . sprintf( /* translators: %s: error */ __( 'database rollback failed: %s', '007aj-backup-restore-verifier' ), (string) $rb['db_error'] ); } return array( 'status' => Job_States::STATUS_FAILED, 'error' => $message, 'cursor' => $this->slim( $cursor ), 'result' => array( 'rollback' => array( 'files' => array( 'ok' => true, 'restored' => (int) ( $rb['files'] ?? 0 ), ), 'db' => empty( $cursor['db_touched'] ) ? null : array( 'ok' => empty( $rb['db_error'] ), 'error' => (string) ( $rb['db_error'] ?? '' ), 'stmts' => (int) ( $rb['c']['db_apply_stmts'] ?? 0 ), ), ), 'maintenance_clear' => ! empty( $exit['ok'] ), ), ); } /** * Small cursor kept on a finished job. * * @param array $cursor Cursor. * @return array */ private function slim( array $cursor ): array { $keep = array( 'artifact_id', 'components', 'applied_files', 'db_apply_stmts', 'checked', 'snapshot_taken', 'maintenance', 'fail_error', 'zip_path', 'job_dir', 'snapshot_dir', 'snapshot_db_path', 'migrate', 'chain_steps' ); return array_intersect_key( $cursor, array_flip( $keep ) ); } /** * Extract the database dump from the archive into the job dir (streamed, resumable). * Returns array{path} when ready, array{} to continue next tick, array{error} on failure. * * @param int $job_id Job id. * @param string $job_dir Job dir. * @param string $zip_path Zip path. * @param array $cursor Cursor (by reference: "dx" resume state). * @param array $config Config. * @param float $deadline Deadline. * @return array{path?:string,error?:string} */ private function extract_dump( int $job_id, string $job_dir, string $zip_path, array &$cursor = array(), array $config = array(), float $deadline = 0.0 ): array { // Defence in depth: the database is only taken from the archive that passed validation, unchanged since. $tip_check = new Archive_Check( State_Files::dir( $job_dir ) . '/check-' . (int) ( $cursor['tip_check'] ?? -1 ) ); try { $tip_check->assert_unchanged( $zip_path ); } catch ( State_Exception $e ) { return array( 'error' => $e->getMessage() ); } /** * Let an add-on supply the plaintext dump itself (the extended edition decrypts an * encrypted database dump). Return null to use normal extraction, array{path:string} * to use that file as the dump, or array{error:string} to fail the restore cleanly. * * @param array|null $override Null (not handled). * @param int $job_id Job id. * @param string $job_dir Job scratch dir. * @param string $zip_path Archive path. * @param array $cursor Job cursor. * @param array $config Job config. * @param float $deadline Tick deadline; return array( 'pending' => true ) to continue next tick. */ if ( empty( $cursor['dx'] ) ) { $override = apply_filters( 'brverify_restore_dump_path', null, $job_id, $job_dir, $zip_path, $cursor, $config, $deadline ); if ( is_array( $override ) ) { if ( ! empty( $override['error'] ) ) { return array( 'error' => (string) $override['error'] ); } if ( ! empty( $override['pending'] ) ) { return array(); // Add-on step not finished (e.g. resumable decryption); called again next tick. } if ( ! empty( $override['path'] ) && is_readable( (string) $override['path'] ) ) { Logger::info( $job_id, 'Database dump supplied by add-on for apply.' ); return array( 'path' => (string) $override['path'] ); } } } $reader = new Zip_Reader( $zip_path ); try { $dx = isset( $cursor['dx'] ) && is_array( $cursor['dx'] ) ? $cursor['dx'] : array(); if ( empty( $dx['e'] ) ) { $found = $reader->find_many( array( 'database/dump.sql', 'database/dump.sql.rpenc' ) ); if ( empty( $found['database/dump.sql'] ) ) { if ( ! empty( $found['database/dump.sql.rpenc'] ) ) { return array( 'error' => __( 'The database in this backup is encrypted and cannot be restored by this plugin because the encryption module is not available.', '007aj-backup-restore-verifier' ) ); } return array( 'error' => __( 'database/dump.sql missing from artifact.', '007aj-backup-restore-verifier' ) ); } $dx = array( 'e' => $found['database/dump.sql'], 'rs' => array(), ); } $db_dir = trailingslashit( $job_dir ) . 'restore-db'; if ( ! is_dir( $db_dir ) ) { wp_mkdir_p( $db_dir ); Working_Dir::harden( $db_dir ); } $path = trailingslashit( $db_dir ) . 'dump.sql'; $from = (int) ( $dx['rs']['done'] ?? 0 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $out = @fopen( $path, $from > 0 ? 'cb' : 'wb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( false === $out ) { return array( 'error' => State_Files::io_message( __( 'Failed writing extracted dump.sql', '007aj-backup-restore-verifier' ), $path ) ); } if ( $from > 0 ) { ftruncate( $out, $from ); fseek( $out, $from ); } try { $res = $reader->stream( (array) $dx['e'], static function ( string $b ) use ( $out, $path ): void { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite if ( strlen( $b ) !== fwrite( $out, $b ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite throw new State_Exception( esc_html( State_Files::io_message( __( 'Short write while extracting dump.sql (disk full?)', '007aj-backup-restore-verifier' ), $path ) ) ); } }, (array) $dx['rs'], $deadline ); } finally { fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose } if ( empty( $res['done'] ) ) { $dx['rs'] = $res['resume']; $cursor['dx'] = $dx; return array(); } $want = $tip_check->expected( 'database/dump.sql' ); if ( null === $want || ! hash_equals( $want, (string) ( $res['sha256'] ?? '' ) ) ) { wp_delete_file( $path ); return array( 'error' => __( 'database/dump.sql does not match its validated checksum; restore stopped.', '007aj-backup-restore-verifier' ) ); } } finally { $reader->close(); } Logger::info( $job_id, 'Extracted database/dump.sql for apply.' ); return array( 'path' => $path ); } /** * Spot-check restored files against the tip archive's checksum list. * * @param array $cursor Cursor. * @param array $components Components. * @return array{ok:bool,checked?:int,error?:string} */ private function spot_check_files( array $cursor, array $components ): array { $needs_files = ! empty( $components['plugins'] ) || ! empty( $components['themes'] ) || ! empty( $components['uploads'] ); if ( ! $needs_files || ! isset( $cursor['tip_check'] ) ) { return array( 'ok' => true, 'checked' => 0, ); } $sums = trailingslashit( (string) ( $cursor['job_dir'] ?? '' ) ) . 'state/check-' . (int) $cursor['tip_check'] . '/sums.txt'; if ( ! is_readable( $sums ) ) { return array( 'ok' => true, 'checked' => 0, ); } $targets = ( new Snapshot() )->component_targets( $components ); $checked = 0; $off = 0; $seen = 0; while ( $checked < 25 && $seen < 5000 ) { $r = State_Files::read_rows_text( $sums, $off, 500 ); if ( empty( $r['lines'] ) ) { break; } $off = $r['offset']; foreach ( $r['lines'] as $line ) { ++$seen; if ( ! preg_match( '/^([a-f0-9]{64})\s+(files\/.+)$/', $line, $m ) ) { continue; } if ( apply_filters( 'brverify_restore_skip_member', false, $m[2], 0, $cursor ) ) { continue; } foreach ( $targets as $rel_prefix => $abs_root ) { $prefix = 'files/' . $rel_prefix . '/'; if ( ! \brverify_str_starts_with( $m[2], $prefix ) ) { continue; } $root_real = realpath( $abs_root ); $path = false === $root_real ? '' : $root_real . '/' . substr( $m[2], strlen( $prefix ) ); // Large files were already hash-checked while being restored; keep this check inside one request. if ( '' !== $path && is_readable( $path ) && (int) @filesize( $path ) <= 33554432 ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $actual = hash_file( 'sha256', $path ); if ( ! is_string( $actual ) || ! hash_equals( $m[1], $actual ) ) { return array( 'ok' => false, 'error' => sprintf( /* translators: %s: path */ __( 'Post-restore checksum mismatch: %s', '007aj-backup-restore-verifier' ), $m[2] ), ); } ++$checked; } break; } if ( $checked >= 25 ) { break 2; } } if ( $r['eof'] ) { break; } } return array( 'ok' => true, 'checked' => $checked, ); } /** * Merge requested components with manifest availability. * * @param array $config Config. * @param array $manifest Manifest. * @return array{database:bool,plugins:bool,themes:bool,uploads:bool} */ private function resolve_components( array $config, array $manifest ): array { $available = isset( $manifest['components'] ) && is_array( $manifest['components'] ) ? $manifest['components'] : array( 'database' => true, 'plugins' => true, 'themes' => true, 'uploads' => true, ); $requested = isset( $config['components'] ) && is_array( $config['components'] ) ? $config['components'] : $available; return array( 'database' => ! empty( $requested['database'] ) && ! empty( $available['database'] ), 'plugins' => ! empty( $requested['plugins'] ) && ! empty( $available['plugins'] ), 'themes' => ! empty( $requested['themes'] ) && ! empty( $available['themes'] ), 'uploads' => ! empty( $requested['uploads'] ) && ! empty( $available['uploads'] ), ); } /** * @param array $components Components. */ private function any_component( array $components ): bool { foreach ( $components as $on ) { if ( $on ) { return true; } } return false; } /** * Test hook: force failure after a named phase. * * @param array $config Config. * @param string $phase Phase key. */ private function should_force_fail( array $config, string $phase ): bool { $forced = isset( $config['force_fail_after'] ) ? (string) $config['force_fail_after'] : ''; return '' !== $forced && $forced === $phase; } }