/ (unchanged live files are * hardlinked, so only changed files use extra disk). The swap then renames whole entries: * each live entry moves to wp-content/.replica-old-/ and the staged entry takes its * place. Renames inside one filesystem are instant and atomic. Every rename is written to a * journal first, so an interrupted swap can be finished or reversed. * * Never touched: Site Replica itself, the storage folder, our guard mu-plugins, * wp-config.php, drop-ins (object-cache.php etc.) and anything outside the roots. * * @package AccessNow\Replica */ namespace AccessNow\Replica\Restore; use AccessNow\Replica\Sets\Damaged_File; use AccessNow\Replica\Sets\Set_Files; use AccessNow\Replica\Storage; use AccessNow\Replica\Util\Fs; use AccessNow\Replica\Util\Paths; defined( 'ABSPATH' ) || exit; // Exception messages are plain text: they are escaped where shown (esc_html() in PHP, textContent in admin.js). // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped /** * Restore file operations. */ final class Files { /** * Drop-ins: host-specific, never restored. */ const DROPINS = array( 'advanced-cache.php', 'object-cache.php', 'db.php', 'db-error.php', 'install.php', 'maintenance.php', 'php-error.php', 'fatal-error-handler.php', 'sunrise.php', 'blog-deleted.php', 'blog-inactive.php', 'blog-suspended.php' ); /** * Our own mu-plugin files (kept across the swap). */ const OWN_MU = array( 'accessnow-replica-compat.php', 'accessnow-replica-mail-guard.php' ); /** * Folders this plugin used to live in, so a backup taken before it was renamed cannot restore * a second copy of it alongside this one. */ const LEGACY_DIRS = array( 'site-replica' ); /** * Live files up to this size (and every script) are hashed before an unchanged one is reused. */ const LINK_CHECK_BYTES = 1048576; /** * Destination directory for a set root. * * @param string $root Root key. * @return string|null */ public static function dest_root( $root ) { switch ( $root ) { case 'content': return Paths::content_dir(); case 'uploads': return Paths::uploads_dir(); case 'plugins': return Paths::plugins_dir(); case 'mu-plugins': return Paths::mu_plugins_dir(); case 'themes': return Paths::themes_dir(); } return null; } /** * Staging directory for a job. * * @param string $job_id Job ID. */ public static function staging( $job_id ) { return Paths::content_dir() . '/.replica-staging-' . $job_id; } /** * Directory that receives the replaced live entries (rollback copy). * * @param string $job_id Job ID. */ public static function old_dir( $job_id ) { return Paths::content_dir() . '/.replica-old-' . $job_id; } /** * The unit a file belongs to for swapping: [root, relative unit path] or null when it * must not be restored. * * Units: top-level entries of each root, except plugins and mu-plugins, which are * swapped per plugin (so Site Replica itself is never replaced). * * @param string $root Root key. * @param string $rel Relative path. * @return string|null Unit path relative to the root. */ public static function unit( $root, $rel ) { $parts = explode( '/', $rel ); $top = $parts[0]; if ( 0 === strpos( $top, '.replica-' ) || 0 === strpos( $top, 'accessnow-replica-' ) ) { return null; } // This plugin's own folder, under any name it has ever had. A backup taken before the // plugin was renamed still contains plugins/site-replica; restoring that on top of an // install running the new folder would put a second copy of this plugin on disk, and both // would run. $own_plugin = array_merge( array( dirname( ACCESSNOW_REPLICA_BASENAME ) ), self::LEGACY_DIRS ); if ( 'content' === $root ) { if ( 1 === count( $parts ) && in_array( $top, self::DROPINS, true ) ) { return null; } if ( in_array( $top, array( 'plugins', 'mu-plugins' ), true ) ) { if ( ! isset( $parts[1] ) ) { return $top; // The folder itself (created in staging, never swapped whole). } if ( ( 'plugins' === $top && in_array( $parts[1], $own_plugin, true ) ) || ( 'mu-plugins' === $top && in_array( $parts[1], self::OWN_MU, true ) ) ) { return null; } return $top . '/' . $parts[1]; } return $top; } if ( 'plugins' === $root && in_array( $top, $own_plugin, true ) ) { return null; } if ( 'mu-plugins' === $root && in_array( $top, self::OWN_MU, true ) ) { return null; } return $top; } /** * Stages one indexed file from the set. Returns 'linked', 'copied', 'skipped', or 'case_clash' * when this disk ignores case and a file with the same name in another case is already staged. * * @param string $job_id Job ID. * @param string $set_dir Set dir. * @param array $row Index row. * @throws \RuntimeException On write failure. */ public static function stage( $job_id, $set_dir, array $row ) { $rel = isset( $row['p64'] ) ? (string) base64_decode( $row['p64'] ) : (string) ( $row['p'] ?? '' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode $rel = Fs::clean_relative( $rel ); if ( null === $rel || null === self::unit( $row['r'], $rel ) || null === self::dest_root( $row['r'] ) ) { return 'skipped'; } $target = self::staging( $job_id ) . '/' . $row['r'] . '/' . $rel; if ( 'd' === $row['t'] ) { if ( ! is_dir( $target ) ) { wp_mkdir_p( $target ); } return 'skipped'; } if ( 'f' !== $row['t'] ) { return 'skipped'; // Symlinks are not recreated. } if ( ! is_dir( dirname( $target ) ) && ! wp_mkdir_p( dirname( $target ) ) ) { throw new \RuntimeException( 'Could not create a staging folder in wp-content. Check permissions.' ); } if ( file_exists( $target ) ) { if ( ! Fs::exact_entry_exists( $target ) ) { // Another file whose name differs only in upper/lower case, on a disk that can't hold both. return 'case_clash'; } @unlink( $target ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- Our own earlier attempt. } // Unchanged live file: hardlink it instead of copying. Size and time alone can be kept by an // edit (malware often resets the time), so a script or a small file must also have the bytes // the backup recorded; large media go by size and time, so a restore doesn't read them all. $live = self::dest_root( $row['r'] ) . '/' . $rel; clearstatcache( true, $live ); if ( is_file( $live ) && ! is_link( $live ) && (int) filesize( $live ) === (int) $row['s'] && (int) filemtime( $live ) === (int) $row['m'] && ( ( (int) $row['s'] > self::LINK_CHECK_BYTES && ! Set_Files::is_script( $row ) ) || Set_Files::matches( $live, $row ) ) && @link( $live, $target ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return 'linked'; } // From the set, whichever format it is in (Set_Files: stored under its checksum, or as a copy). try { $copied = Set_Files::copy_out( $set_dir, $row, $target ); } catch ( Damaged_File $e ) { // The backup itself is damaged: stop before the swap, with this site untouched. throw new \RuntimeException( sprintf( 'The backup is damaged: %s Nothing on this site has been changed. Restore another backup, or make a new one.', $e->getMessage() ) ); } catch ( \RuntimeException $e ) { return 'skipped'; // A path or checksum that is not allowed. } if ( ! $copied ) { throw new \RuntimeException( sprintf( 'Could not copy %s into the staging folder. Is the disk full?', $rel ) ); } @touch( $target, (int) $row['m'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_touch return 'copied'; } /** * Builds the swap list: which live entries are replaced, added or moved away. * * @param string $job_id Job ID. * @param array $roots Set root keys. * @return array[] [live, staged|null, old]. */ public static function swap_plan( $job_id, array $roots ) { $plan = array(); $staging = self::staging( $job_id ); $old = self::old_dir( $job_id ); foreach ( $roots as $root ) { $dest = self::dest_root( $root ); if ( null === $dest || ! is_dir( $staging . '/' . $root ) ) { continue; } $units = array(); foreach ( self::list_dir( $staging . '/' . $root ) as $name ) { if ( 'content' === $root && in_array( $name, array( 'plugins', 'mu-plugins' ), true ) ) { foreach ( self::list_dir( $staging . '/' . $root . '/' . $name ) as $sub ) { $units[ $name . '/' . $sub ] = true; } continue; } $units[ $name ] = true; } foreach ( array_keys( $units ) as $unit ) { if ( null === self::unit( $root, $unit ) ) { continue; } $plan[] = array( 'live' => $dest . '/' . $unit, 'staged' => $staging . '/' . $root . '/' . $unit, 'old' => $old . '/' . $root . '/' . $unit, ); } // Plugins that exist only here are moved away too (an exact copy); the restore plan lists // them first. Must-use plugins that exist only here are kept: they are usually the host's // own (managed hosts install several) or this site's, like a local mail catcher, and a // backup deliberately leaves some out. if ( 'content' === $root ) { foreach ( array( 'plugins' => Paths::plugins_dir() ) as $name => $dir ) { if ( ! is_dir( $staging . '/content/' . $name ) ) { continue; } foreach ( self::list_dir( $dir ) as $sub ) { if ( isset( $units[ $name . '/' . $sub ] ) || null === self::unit( 'content', $name . '/' . $sub ) || 'index.php' === $sub ) { continue; } $plan[] = array( 'live' => untrailingslashit( wp_normalize_path( $dir ) ) . '/' . $sub, 'staged' => null, 'old' => $old . '/content/' . $name . '/' . $sub, ); } } } } return $plan; } /** * Keeps media that exists only on this site: files in the live uploads folder that the staged * copy doesn't have are hardlinked (or copied) into it, so the swap, which replaces whole * folders, doesn't take them away. Resumable: returns the cursor to continue from, or null. * * @param string $job_id Job ID. * @param array $roots Set root keys. * @param string $after Cursor from the previous call ('' to start). * @param float $deadline microtime(true) to stop by. * @return array{next: string|null, kept: int} */ public static function keep_live_uploads( $job_id, array $roots, $after, $deadline ) { $live = untrailingslashit( wp_normalize_path( Paths::uploads_dir() ) ); $content = untrailingslashit( wp_normalize_path( Paths::content_dir() ) ); $staging = self::staging( $job_id ); if ( in_array( 'uploads', $roots, true ) ) { $staged = $staging . '/uploads'; $whole = false; // Swapped per top-level folder (uploads/2026). } elseif ( in_array( 'content', $roots, true ) && 0 === strpos( $live . '/', $content . '/' ) ) { $staged = $staging . '/content/' . substr( $live, strlen( $content ) + 1 ); $whole = true; // Swapped as one folder. } else { return array( 'next' => null, 'kept' => 0 ); } if ( ! is_dir( $staged ) || ! is_dir( $live ) ) { return array( 'next' => null, 'kept' => 0 ); // The backup has no uploads: nothing is swapped. } $walker = new \AccessNow\Replica\Files\Walker( 'uploads', $live ); $batch = $walker->walk( (string) $after, 2000, $deadline ); $kept = 0; foreach ( $batch['entries'] as $entry ) { $rel = Set_Files::relative( $entry ); if ( null === $rel || ! empty( $entry['err'] ) ) { continue; } $top = explode( '/', $rel )[0]; if ( ! $whole && ! is_dir( $staged . '/' . $top ) ) { continue; // That folder isn't in the backup, so the swap leaves it alone anyway. } $target = $staged . '/' . $rel; if ( 'd' === $entry['t'] ) { if ( ! file_exists( $target ) ) { wp_mkdir_p( $target ); } continue; } if ( 'f' !== $entry['t'] || file_exists( $target ) || is_link( $target ) ) { continue; // The backup's own copy wins. } if ( ! is_dir( dirname( $target ) ) ) { wp_mkdir_p( dirname( $target ) ); } $source = $live . '/' . $rel; if ( @link( $source, $target ) || @copy( $source, $target ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged ++$kept; } } return array( 'next' => $batch['next'], 'kept' => $kept ); } /** * Plugins on this site that the backup doesn't have, which a full restore removes (the restore * plan lists them). Empty when the backup has no plugins folder, since nothing is swapped then. * * @param string $set_dir Set dir. * @return string[] Plugin folder (or single-file plugin) names. */ public static function plugins_only_here( $set_dir ) { $in_set = array(); $fh = @fopen( $set_dir . 'index/files.jsonl', 'rb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( ! $fh ) { return array(); } while ( false !== ( $line = fgets( $fh ) ) ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition $row = json_decode( $line, true ); if ( ! is_array( $row ) ) { continue; } $rel = (string) Set_Files::relative( $row ); if ( 'content' === ( $row['r'] ?? '' ) && 0 === strpos( $rel, 'plugins/' ) ) { $in_set[ explode( '/', $rel )[1] ?? '' ] = true; } elseif ( 'plugins' === ( $row['r'] ?? '' ) ) { $in_set[ explode( '/', $rel )[0] ] = true; } } fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose unset( $in_set[''] ); if ( ! $in_set ) { return array(); } $gone = array(); foreach ( self::list_dir( Paths::plugins_dir() ) as $sub ) { if ( ! isset( $in_set[ $sub ] ) && 'index.php' !== $sub && null !== self::unit( 'content', 'plugins/' . $sub ) ) { $gone[] = $sub; } } return $gone; } /** * The plugin, theme or must-use plugin folder a path is inside, relative to its root * (plugins/foo for the content root, foo for the plugins root), or null when it is not inside * one: a single-file plugin, a top-level must-use plugin, media, or this plugin itself. * * The restore replaces each such folder whole, the way a plugin update does, so a file this site * has inside a folder the backup also has, and the backup doesn't, is removed. * * @param string $root Root key. * @param string $rel Path relative to the root. * @return string|null */ public static function replaced_folder( $root, $rel ) { $parts = explode( '/', (string) $rel ); if ( 'content' === $root ) { if ( count( $parts ) < 3 || ! in_array( $parts[0], array( 'plugins', 'mu-plugins', 'themes' ), true ) || '' === $parts[1] ) { return null; } $folder = $parts[0] . '/' . $parts[1]; } elseif ( in_array( $root, array( 'plugins', 'mu-plugins', 'themes' ), true ) ) { if ( count( $parts ) < 2 || '' === $parts[0] ) { return null; } $folder = $parts[0]; } else { return null; } return null === self::unit( $root, $folder ) ? null : $folder; } /** * Files and folders this site has inside the plugin, theme and must-use plugin folders the backup * also has, which the backup doesn't: the restore replaces those folders whole, so it removes * them (Roll back puts them back). A folder the backup has nothing inside is listed once, with a * trailing slash, instead of file by file. * * @param string $set_dir Set dir. * @param int $limit Most entries to list (the count covers them all). * @param array|null $dirs Root key => live directory (tests); null for this site's. * @return array{list: array[], count: int} list: {path (from wp-content's point of view), part (the swap unit, as the restore plan's parts name it)}. */ public static function removed_in_folders( $set_dir, $limit = 200, $dirs = null ) { $out = array( 'list' => array(), 'count' => 0, ); $fh = @fopen( $set_dir . 'index/files.jsonl', 'rb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( ! $fh ) { return $out; } // What the backup has inside those folders: every file and folder, and each file's folders. $folders = array(); $have = array(); while ( false !== ( $line = fgets( $fh ) ) ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition $row = json_decode( $line, true ); if ( ! is_array( $row ) || ! isset( $row['r'] ) || ! in_array( $row['t'] ?? '', array( 'f', 'd' ), true ) ) { continue; // Links are not recreated, so a link here is removed like any other file. } $root = (string) $row['r']; $rel = Set_Files::relative( $row ); $top = null === $rel ? null : self::replaced_folder( $root, $rel ); if ( null === $top ) { continue; } $folders[ $root ][ $top ] = true; for ( $p = $rel; strlen( $p ) > strlen( $top ) && ! isset( $have[ $root . '/' . $p ] ); $p = dirname( $p ) ) { $have[ $root . '/' . $p ] = true; } } fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose ksort( $folders ); foreach ( $folders as $root => $tops ) { $base = null === $dirs ? self::dest_root( $root ) : ( $dirs[ $root ] ?? null ); if ( null === $base ) { continue; } $tops = array_keys( $tops ); sort( $tops ); foreach ( $tops as $top ) { $live = untrailingslashit( wp_normalize_path( $base ) ) . '/' . $top; if ( is_dir( $live ) && ! is_link( $live ) ) { self::walk_extra( $root, $live, $top, $have, $limit, $out ); } } } return $out; } /** * One folder's part of removed_in_folders(). * * @param string $root Root key. * @param string $dir Live folder. * @param string $rel Its path relative to the root. * @param array $have What the backup has (root/rel => true). * @param int $limit Most entries to list. * @param array $out Result, added to. */ private static function walk_extra( $root, $dir, $rel, array $have, $limit, array &$out ) { foreach ( self::list_dir( $dir ) as $name ) { $path = $dir . '/' . $name; $sub = $rel . '/' . $name; $folder = is_dir( $path ) && ! is_link( $path ); if ( isset( $have[ $root . '/' . $sub ] ) ) { if ( $folder ) { self::walk_extra( $root, $path, $sub, $have, $limit, $out ); } continue; } ++$out['count']; if ( count( $out['list'] ) < $limit ) { $out['list'][] = array( 'path' => ( 'content' === $root ? '' : $root . '/' ) . $sub . ( $folder ? '/' : '' ), 'part' => $root . '/' . self::unit( $root, $sub ), ); } } } /** * Performs the swap, journalling each rename first. Returns the journal path. * * @param string $job_dir Job directory. * @param array[] $plan Swap plan. * @throws \RuntimeException On failure (after reversing what was done). */ public static function swap( $job_dir, array $plan ) { $journal = $job_dir . 'swap-journal.jsonl'; foreach ( $plan as $entry ) { $ops = array(); if ( file_exists( $entry['live'] ) || is_link( $entry['live'] ) ) { $ops[] = array( $entry['live'], $entry['old'] ); } if ( null !== $entry['staged'] ) { $ops[] = array( $entry['staged'], $entry['live'] ); } foreach ( $ops as $op ) { if ( ! is_dir( dirname( $op[1] ) ) ) { wp_mkdir_p( dirname( $op[1] ) ); } file_put_contents( $journal, wp_json_encode( array( 'from' => $op[0], 'to' => $op[1] ) ) . "\n", FILE_APPEND | LOCK_EX ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents if ( ! @rename( $op[0], $op[1] ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.rename_rename self::reverse( $journal ); throw new \RuntimeException( sprintf( 'Could not move %s. The files were put back as they were.', $op[0] ) ); } } } return $journal; } /** * Reverses a swap journal (newest first). Safe to repeat. * * @param string $journal Journal path. */ public static function reverse( $journal ) { if ( ! is_file( $journal ) ) { return; } $lines = array_reverse( (array) file( $journal, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ) ); foreach ( $lines as $line ) { $op = json_decode( $line, true ); if ( ! is_array( $op ) ) { continue; } if ( ( file_exists( $op['to'] ) || is_link( $op['to'] ) ) && ! file_exists( $op['from'] ) ) { if ( ! is_dir( dirname( $op['from'] ) ) ) { wp_mkdir_p( dirname( $op['from'] ) ); } @rename( $op['to'], $op['from'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.rename_rename } } @rename( $journal, $journal . '.reversed' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.rename_rename } /** * Entries of a directory (no dots). * * @param string $dir Directory. * @return string[] */ private static function list_dir( $dir ) { $names = @scandir( $dir ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return is_array( $names ) ? array_values( array_diff( $names, array( '.', '..' ) ) ) : array(); } /** * Deletes a directory tree inside wp-content we created (staging or old). * * @param string $dir Directory. */ public static function delete_tree( $dir ) { $base = basename( $dir ); if ( 0 === strpos( $base, '.replica-staging-' ) || 0 === strpos( $base, '.replica-old-' ) ) { Fs::rrmdir( $dir ); } } /** * Writes a small mu-plugin (creating the folder if needed). * * @param string $name File name (one of OWN_MU). * @param string $code PHP code. */ public static function write_mu( $name, $code ) { if ( ! in_array( $name, self::OWN_MU, true ) ) { return; } $dir = Paths::mu_plugins_dir(); if ( ! is_dir( $dir ) ) { wp_mkdir_p( $dir ); } Storage::write_atomic( $dir . '/' . $name, $code ); } /** * Removes one of our mu-plugins. * * @param string $name File name. */ public static function remove_mu( $name ) { $file = Paths::mu_plugins_dir() . '/' . $name; if ( in_array( $name, self::OWN_MU, true ) && is_file( $file ) ) { @unlink( $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink } } }