strlen( $a ); } ); foreach ( $roots as $top => $root ) { if ( $abs === $root || 0 === strpos( $abs, $root . '/' ) ) { return 'wp-content/' . $top . substr( $abs, strlen( $root ) ); } } $content = wp_normalize_path( self::content_dir() ); if ( $abs === $content || 0 === strpos( $abs, $content . '/' ) ) { return 'wp-content' . substr( $abs, strlen( $content ) ); } return ''; } /** * Every folder a files backup, a clone or a check has to walk, as content-relative prefix => absolute path. * Plugins, mu-plugins, themes and uploads are asked from WordPress (they can live outside the content * folder), so each is walked at its real place under its own prefix ("plugins", "themes", ...). The content * folder itself is walked last, without those four, under the empty prefix. A folder that happens to be * called "plugins" inside the content folder but is not the site's real plugins folder is left out, so one * relative name never means two different places. * * @return array */ public static function content_scan_roots(): array { $roots = array(); foreach ( array( 'plugins', 'mu-plugins', 'themes', 'uploads' ) as $top ) { $dir = self::content_root_for( $top ); if ( '' !== $dir && is_dir( $dir ) ) { $roots[ $top ] = $dir; } } $roots[''] = untrailingslashit( self::content_dir() ); return $roots; } /** * Walks every file of the site's content folders (see content_scan_roots()). Yields * content-relative path => SplFileInfo, directories included, exactly like a recursive directory * iterator would, so callers keep their own filtering. Throws what the iterator throws. * * @return \Generator */ public static function each_content_file(): \Generator { $roots = self::content_scan_roots(); $others = array(); foreach ( array( 'plugins', 'mu-plugins', 'themes', 'uploads' ) as $top ) { $others[] = wp_normalize_path( untrailingslashit( self::content_dir() ) . '/' . $top ); if ( isset( $roots[ $top ] ) ) { $others[] = wp_normalize_path( $roots[ $top ] ); } } $others = array_values( array_unique( $others ) ); foreach ( $roots as $prefix => $dir ) { $base = wp_normalize_path( $dir ); $it = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $dir, \RecursiveDirectoryIterator::SKIP_DOTS ), \RecursiveIteratorIterator::SELF_FIRST ); foreach ( $it as $item ) { $path = wp_normalize_path( $item->getPathname() ); if ( '' === $prefix ) { foreach ( $others as $skip ) { if ( $path === $skip || 0 === strpos( $path, $skip . '/' ) ) { continue 2; } } } $rel = ltrim( substr( $path, strlen( $base ) ), '/' ); yield ( '' === $prefix ? $rel : $prefix . '/' . $rel ) => $item; } } } // ========================================================================= // DNS / IP (IPv4 and IPv6) // ========================================================================= /** Cloudflare's published edge ranges, IPv4. The single copy: the paid Cloudflare code reads it from here. */ const CF_IPV4_RANGES = array( '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', ); /** Cloudflare's published edge ranges, IPv6. */ const CF_IPV6_RANGES = array( '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', ); /** * Address records of a host, both families. A CNAME chain is followed by the resolver. * Filter `wardpair_dns_records` lets a host (or a test) supply the answer: * return array( 'v4' => [..], 'v6' => [..] ) to use it. * * @return array{v4: string[], v6: string[]} */ public static function dns_ips( string $host ): array { static $cache = array(); $host = strtolower( trim( $host ) ); if ( '' === $host ) { return array( 'v4' => array(), 'v6' => array() ); } if ( isset( $cache[ $host ] ) ) { return $cache[ $host ]; } $out = array( 'v4' => array(), 'v6' => array() ); $pre = apply_filters( 'wardpair_dns_records', null, $host ); if ( is_array( $pre ) ) { $out['v4'] = array_values( array_filter( (array) ( $pre['v4'] ?? array() ) ) ); $out['v6'] = array_values( array_filter( (array) ( $pre['v6'] ?? array() ) ) ); return $cache[ $host ] = $out; } if ( function_exists( 'dns_get_record' ) ) { foreach ( (array) @dns_get_record( $host, DNS_A | DNS_AAAA ) as $r ) { if ( ! empty( $r['ip'] ) ) { $out['v4'][] = (string) $r['ip']; } elseif ( ! empty( $r['ipv6'] ) ) { $out['v6'][] = (string) $r['ipv6']; } } } if ( ! $out['v4'] ) { // Some hosts block dns_get_record(): the system resolver still answers for IPv4. foreach ( (array) @gethostbynamel( $host ) as $ip ) { if ( false !== filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { $out['v4'][] = $ip; } } } $out['v4'] = array_values( array_unique( $out['v4'] ) ); $out['v6'] = array_values( array_unique( $out['v6'] ) ); return $cache[ $host ] = $out; } /** * One connectable address for a host name or IP literal. IPv4 first (what the plugin has * always pinned), IPv6 when the name has no IPv4 record. '' when nothing resolves. */ public static function resolve_ip( string $host_or_ip ): string { $h = trim( $host_or_ip ); if ( false !== filter_var( $h, FILTER_VALIDATE_IP ) ) { return $h; } $ips = self::dns_ips( $h ); return $ips['v4'][0] ?? ( $ips['v6'][0] ?? '' ); } /** Same address, whatever the text form (IPv6 can be written many ways). */ public static function same_ip( string $a, string $b ): bool { $pa = @inet_pton( trim( $a ) ); $pb = @inet_pton( trim( $b ) ); return false !== $pa && false !== $pb && $pa === $pb; } public static function ip_in_list( string $ip, array $list ): bool { foreach ( $list as $candidate ) { if ( self::same_ip( $ip, (string) $candidate ) ) { return true; } } return false; } /** Cloudflare edge address, either family. */ public static function is_cloudflare_edge_ip( string $ip ): bool { if ( false === filter_var( $ip, FILTER_VALIDATE_IP ) ) { return false; } $ranges = false === strpos( $ip, ':' ) ? self::CF_IPV4_RANGES : self::CF_IPV6_RANGES; foreach ( $ranges as $cidr ) { if ( self::ip_in_cidr( $ip, $cidr ) ) { return true; } } return false; } /** Host part for fsockopen()/stream_socket_client(): IPv6 literals need brackets. */ public static function socket_host( string $ip ): string { return ( false !== strpos( $ip, ':' ) && '[' !== substr( $ip, 0, 1 ) ) ? '[' . $ip . ']' : $ip; } // ========================================================================= // HOST MEMORY // ========================================================================= /** * Memory cap the hosting container puts on this site (cgroup v2 or v1), in bytes. * Returns 0 when there is no cap or it cannot be read. * * PHP's memory_limit does not reflect this cap. A process that goes over it is * ended by the kernel with no PHP error and no shutdown handler, so long jobs * must size their work from this number as well as from memory_limit. */ public static function container_memory_limit(): int { foreach ( array( '/sys/fs/cgroup/memory.max', '/sys/fs/cgroup/memory/memory.limit_in_bytes' ) as $file ) { if ( ! @is_readable( $file ) ) { continue; } $raw = trim( (string) @file_get_contents( $file ) ); if ( '' === $raw || ! ctype_digit( $raw ) ) { continue; // "max" means no cap on cgroup v2. } $bytes = (int) $raw; // cgroup v1 reports a huge number when there is no cap. if ( $bytes > 0 && $bytes < 64 * 1024 * 1024 * 1024 ) { return $bytes; } } return 0; } /** * The memory this site can really use: the lower of PHP's memory_limit and the * container cap. 0 means unlimited / unknown. */ public static function effective_memory_limit(): int { $php = (string) ini_get( 'memory_limit' ); $php = ( '' === $php || '-1' === $php ) ? 0 : (int) wp_convert_hr_to_bytes( $php ); $box = self::container_memory_limit(); if ( $php > 0 && $box > 0 ) { return min( $php, $box ); } return $php > 0 ? $php : $box; } // ========================================================================= // DB SEARCH-REPLACE // ========================================================================= /** * Serialization-safe search-replace across the WordPress database. * * Handles: wp_options, wp_postmeta, wp_usermeta, wp_posts (content + guid), * wp_comments (content + author URL), wp_commentmeta, wp_termmeta, * wp_term_taxonomy (description), and a generic fallback scan of any * other table (covers third-party/custom plugin tables — WooCommerce, * form plugins, page builders, etc.) so failover coverage matches the * comprehensive scan already done at initial clone time. * * Skips: * - siteurl, home (callers write these directly after this runs) * - wardpair_* (plugin state must never be overwritten by URL ops) * - Transients (no point replacing URLs in expiring cache keys) * * Serialized values are unserialized → recursively replaced → re-serialized, * which automatically recalculates the s:LENGTH byte-count prefixes. * A naive str_replace on raw serialized data would corrupt those lengths. * * @param string $old URL to find (trailing slash stripped automatically). * @param string $new Replacement URL (trailing slash stripped automatically). * @return int Total number of DB rows updated. */ /** * Escape a value for a hand-written SQL string literal WITHOUT the * wpdb placeholder token. * * esc_sql() routes through wpdb::_real_escape(), which swaps every literal * "%" for a "{<64 hex chars>}" placeholder that only wpdb::query() strips * back out. A value written into a .sql file with esc_sql() therefore * carries those tokens into the dump, and the restore (which runs through * mysqli_query(), not wpdb::query()) stores them verbatim: "width:100%" * becomes "width:100{3f9a...}" and the page breaks. */ /** * Proxy ranges whose forwarded-client-IP headers can be believed. * Cloudflare's published edge ranges (https://www.cloudflare.com/ips, last * changed 2023-09-28). Another reverse proxy in front of the site (nginx, * Varnish, a load balancer) is added with the filter wardpair_trusted_proxies * or the constant WARDPAIR_TRUSTED_PROXIES (array or comma list of IPs/CIDRs). */ public static function trusted_proxies(): array { $list = array( '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', ); if ( defined( 'WARDPAIR_TRUSTED_PROXIES' ) ) { $extra = WARDPAIR_TRUSTED_PROXIES; $extra = is_array( $extra ) ? $extra : array_map( 'trim', explode( ',', (string) $extra ) ); $list = array_merge( $list, array_filter( $extra ) ); } $list = apply_filters( 'wardpair_trusted_proxies', $list ); return is_array( $list ) ? $list : array(); } /** Is $ip inside $cidr (or equal to it when no mask is given)? IPv4 and IPv6. */ public static function ip_in_cidr( string $ip, string $cidr ): bool { $bin = @inet_pton( $ip ); if ( false === $bin ) { return false; } $parts = explode( '/', $cidr, 2 ); $net = @inet_pton( $parts[0] ); if ( false === $net || strlen( $net ) !== strlen( $bin ) ) { return false; } $bits = isset( $parts[1] ) ? (int) $parts[1] : strlen( $net ) * 8; if ( $bits < 0 || $bits > strlen( $net ) * 8 ) { return false; } $bytes = intdiv( $bits, 8 ); if ( $bytes > 0 && substr( $bin, 0, $bytes ) !== substr( $net, 0, $bytes ) ) { return false; } $rest = $bits % 8; if ( 0 === $rest ) { return true; } $mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF; return ( ord( $bin[ $bytes ] ) & $mask ) === ( ord( $net[ $bytes ] ) & $mask ); } private static function ip_is_trusted_proxy( string $ip ): bool { foreach ( self::trusted_proxies() as $range ) { if ( self::ip_in_cidr( $ip, (string) $range ) ) { return true; } } return false; } /** * The address of the machine that is really making this request. * * REMOTE_ADDR is the right answer when the request reaches PHP directly. Behind * Cloudflare it is a Cloudflare edge address shared by thousands of visitors, so a * per-IP limit would count everyone together. A forwarded header (CF-Connecting-IP, * X-Forwarded-For) is believed ONLY when the connection itself comes from a proxy we * trust (see trusted_proxies()); from anyone else those headers are ignored, so they * cannot be used to dodge a limit. */ public static function client_ip(): string { $remote = isset( $_SERVER['REMOTE_ADDR'] ) ? trim( sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) ) : ''; if ( '' === $remote || ! filter_var( $remote, FILTER_VALIDATE_IP ) ) { return ''; } if ( ! self::ip_is_trusted_proxy( $remote ) ) { return $remote; } $cf = isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ? trim( sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) ) : ''; if ( '' !== $cf && filter_var( $cf, FILTER_VALIDATE_IP ) ) { return $cf; } // X-Forwarded-For: walk from the right, skipping our own proxies; the first // address that is not one of them is the client the outermost proxy saw. if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { $chain = array_reverse( array_map( 'trim', explode( ',', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) ) ); foreach ( $chain as $hop ) { if ( filter_var( $hop, FILTER_VALIDATE_IP ) && ! self::ip_is_trusted_proxy( $hop ) ) { return $hop; } } } return $remote; } /** * unserialize() with object creation switched off. * * Serialized data from the other site (or from the database during a URL * rewrite) must never be allowed to instantiate arbitrary classes: that is * what PHP object-injection attacks rely on, and a compromised partner site * would otherwise be able to attack this one through a synced option. * Objects that do appear become __PHP_Incomplete_Class, which serializes back * to the original class name, so values pass through unchanged. * Filter wardpair_unserialize_allowed_classes lists classes that may be built. * * Same contract as @unserialize(): false on failure. */ public static function unserialize_flat( $data ) { if ( ! is_string( $data ) ) { return false; } $allowed = apply_filters( 'wardpair_unserialize_allowed_classes', array( 'stdClass' ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Object creation is restricted with allowed_classes. return @unserialize( trim( $data ), array( 'allowed_classes' => is_array( $allowed ) ? $allowed : false ) ); } /** * Repair one Wardpair setting that was stored as serialized text instead of an array (a restore * once wrote it back through update_option() as a raw string). Leaves everything else alone. * * @return bool True when the option was repaired. */ public static function heal_flattened_option( string $name ): bool { if ( 0 !== strpos( $name, 'wardpair_' ) ) { return false; } $val = get_option( $name ); if ( ! is_string( $val ) || ! is_serialized( $val ) ) { return false; } $fixed = self::safe_unserialize( $val ); if ( ! is_array( $fixed ) ) { return false; } update_option( $name, $fixed ); return true; } /** * One-time sweep over Wardpair's own settings, repairing any that a past clone flattened. * Runs once per site; the cause is fixed, so there is nothing to repeat. */ public static function heal_flattened_options(): void { if ( get_option( 'wardpair_flat_heal_v1' ) ) { return; } global $wpdb; $names = (array) $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM %i WHERE option_name LIKE %s AND option_value LIKE %s", $wpdb->options, 'wardpair\\_%', 's:%:"a:%' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery foreach ( $names as $name ) { self::heal_flattened_option( (string) $name ); } update_option( 'wardpair_flat_heal_v1', 1, false ); } /** maybe_unserialize() without object creation. See unserialize_flat(). */ public static function safe_unserialize( $value ) { if ( is_string( $value ) && is_serialized( $value ) ) { return self::unserialize_flat( $value ); } return $value; } /** * Is this a safe path relative to a base directory? * * Checks path SEGMENTS, not substrings. The old test rejected any name that * contained two dots, so a perfectly normal file such as "photo..jpg" or * "report v1..2.pdf" was refused with no retry and never reached the other * site. Only a segment that IS ".." (or "."), an absolute path, a backslash, * a drive letter or a NUL byte is traversal. */ public static function relative_path_ok( $relative ): bool { if ( ! is_string( $relative ) || '' === $relative || strlen( $relative ) > 512 ) { return false; } if ( false !== strpos( $relative, "\0" ) || false !== strpos( $relative, '\\' ) ) { return false; } if ( '/' === $relative[0] || preg_match( '#^[a-zA-Z]:#', $relative ) ) { return false; } foreach ( explode( '/', $relative ) as $segment ) { if ( '' === $segment || '.' === $segment || '..' === $segment ) { return false; } } return true; } /** * After symlinks are resolved, does $path still sit inside $base? * $path may not exist yet (a file about to be written), so its parent * directory is resolved instead. */ public static function path_inside( string $path, string $base ): bool { $real_base = realpath( $base ); if ( false === $real_base ) { return false; } $probe = file_exists( $path ) ? $path : dirname( $path ); $real = realpath( $probe ); if ( false === $real ) { return false; } return $real === $real_base || 0 === strpos( $real, rtrim( $real_base, '/\\' ) . DIRECTORY_SEPARATOR ); } /** * May a folder be created at $dir? Checked BEFORE wp_mkdir_p(): the nearest folder that already * exists on the way down (symlinks followed) must sit inside $base, so a pre-existing link cannot * make the new folders appear somewhere else. */ public static function dir_target_ok( string $dir, string $base ): bool { $real_base = realpath( $base ); if ( false === $real_base ) { return false; } $probe = rtrim( $dir, '/\\' ); while ( '' !== $probe && ! file_exists( $probe ) && ! is_link( $probe ) ) { $parent = dirname( $probe ); if ( $parent === $probe ) { return false; } $probe = $parent; } $real = realpath( $probe ); if ( false === $real ) { return false; // Dangling link or unreadable path. } return $real === $real_base || 0 === strpos( $real, rtrim( $real_base, '/\\' ) . DIRECTORY_SEPARATOR ); } /** * Create $dir only if dir_target_ok() allows it: the check runs first, so nothing is created when an * existing symbolic link would send the new folders somewhere else. */ public static function mkdir_inside( string $dir, string $base ): bool { if ( ! self::dir_target_ok( $dir, $base ) ) { return false; } return is_dir( $dir ) || wp_mkdir_p( $dir ); } /** * May a file be written to $dest? Stricter than path_inside() alone: * the folder it lands in must resolve (symlinks followed) to somewhere inside $base, * AND the destination must not itself be a symbolic link, because writing to * a link would put the data wherever the link points, which could be outside $base. */ public static function write_target_ok( string $dest, string $base ): bool { if ( is_link( $dest ) ) { return false; } return self::path_inside( $dest, $base ); } /** * Server-executable file names (shell.php, shell.php.jpg, x.phtml, x.phar). * WordPress never lets the media library create these, so one arriving in * uploads over the sync link is not media and is not carried across. * Filter: wardpair_allow_executables_in_uploads. */ public static function is_executable_name( string $relative ): bool { if ( apply_filters( 'wardpair_allow_executables_in_uploads', false ) ) { return false; } return (bool) preg_match( '/\.(?:php\d*|phtml|pht|phps|phar)(?:\.|$)/i', basename( $relative ) ); } /** * Every table that belongs to THIS WordPress install. * * "SHOW TABLES LIKE 'wp_%'" is not that: the prefix is a LIKE pattern (the * underscore matches any character), and a second install in the same * database with a longer prefix (wp_shop_) also starts with "wp_". Backing up * those tables copies another site's data; wiping or search-and-replacing * them damages it. A neighbouring install is recognised by owning its own * options + posts + postmeta tables under a longer prefix, and its tables are * left out. * * @param string $prefix Defaults to this site's $wpdb->prefix. * @return string[] */ public static function tables_for_prefix( string $prefix = '' ): array { global $wpdb; if ( '' === $prefix ) { $prefix = $wpdb->prefix; } $all = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $prefix ) . '%' ) ); if ( ! is_array( $all ) || empty( $all ) ) { return array(); } $have = array_flip( $all ); $plen = strlen( $prefix ); $foreign = array(); foreach ( $all as $t ) { if ( 'options' !== substr( $t, -7 ) ) { continue; } $mid = substr( $t, $plen, -7 ); if ( false === $mid || '' === $mid || '_' !== substr( $mid, -1 ) ) { continue; } $other = $prefix . $mid; if ( isset( $have[ $other . 'posts' ], $have[ $other . 'postmeta' ] ) ) { $foreign[] = $other; } } if ( empty( $foreign ) ) { return array_values( $all ); } return array_values( array_filter( $all, function ( $t ) use ( $foreign ) { foreach ( $foreign as $f ) { if ( 0 === strpos( $t, $f ) ) { return false; } } return true; } ) ); } /** This install's tables. See tables_for_prefix(). */ public static function own_tables(): array { return self::tables_for_prefix(); } // ─── Restoring a backup made under another table prefix ─────────────────── // // A backup taken on a site whose tables start with a different prefix (wpny_ vs wp_) is imported // under its own names, next to this site's tables, and only then renamed to this site's prefix, // exactly the way the site-to-site copy does it. Nothing of this site is touched until the import // has finished. /** Names of the tables a prefix-converting import has put into this database (so a crashed attempt can be cleaned up). */ const PREFIX_IMPORT_OPTION = 'wardpair_prefix_import_tables'; /** * Read a SQL dump once: which tables it creates, and which table prefix its WordPress core tables use. * * The prefix is the shortest one that has all of {prefix}options, {prefix}posts and {prefix}users in the * dump, so a plugin table such as wp_foo_options is never mistaken for the core options table. * * @param string $path A plain (already decrypted) dump. * @param bool $compressed True for gzip. * @return array{prefix:string,tables:string[],bytes:int}|WP_Error */ public static function scan_dump( string $path, bool $compressed ) { $wardpair_limits = Sentinel_Limits::raise( 300 ); $fh = $compressed ? @gzopen( $path, 'rb' ) : @fopen( $path, 'rb' ); if ( ! $fh ) { return new WP_Error( 'dump_unreadable', __( 'The database dump cannot be opened.', 'wardpair' ) ); } $read = $compressed ? 'gzread' : 'fread'; $eof = $compressed ? 'gzeof' : 'feof'; $close = $compressed ? 'gzclose' : 'fclose'; $tables = array(); $bytes = 0; $tail = ''; while ( ! $eof( $fh ) ) { $chunk = $read( $fh, 1048576 ); if ( false === $chunk ) { $close( $fh ); return new WP_Error( 'dump_corrupt', __( 'The database dump is corrupt or cut short.', 'wardpair' ) ); } if ( '' === $chunk ) { break; } $bytes += strlen( $chunk ); $buf = $tail . $chunk; // Anchored to the start of a line: the dump writes each CREATE TABLE on its own line. if ( preg_match_all( '/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`([^`]+)`/im', $buf, $m ) ) { foreach ( $m[1] as $t ) { $tables[ $t ] = true; } } $tail = substr( $buf, -512 ); } $close( $fh ); if ( 0 === $bytes ) { return new WP_Error( 'dump_empty', __( 'The database dump is empty.', 'wardpair' ) ); } $names = array_keys( $tables ); $have = array_flip( $names ); $prefix = null; foreach ( $names as $t ) { if ( 'options' !== substr( $t, -7 ) ) { continue; } $p = substr( $t, 0, -7 ); if ( ! isset( $have[ $p . 'posts' ], $have[ $p . 'users' ] ) ) { continue; } if ( null === $prefix || strlen( $p ) < strlen( $prefix ) ) { $prefix = $p; } } if ( null === $prefix ) { return new WP_Error( 'dump_prefix', __( 'The database dump has no WordPress core tables (options, posts, users). It is incomplete, or it is not a WordPress backup.', 'wardpair' ) ); } return array( 'prefix' => $prefix, 'tables' => $names, 'bytes' => $bytes ); } /** Old table name => name under this site's prefix, for every dump table that carries the dump's prefix. */ public static function prefix_rename_map( array $tables, string $old, string $new ): array { $map = array(); foreach ( $tables as $t ) { $t = (string) $t; if ( '' !== $old && 0 !== strpos( $t, $old ) ) { continue; } $map[ $t ] = $new . substr( $t, strlen( $old ) ); } return $map; } /** * Tables the import would overwrite: names from the dump that already exist here and were not put there by * an earlier, interrupted import of ours. */ public static function prefix_conflicts( array $map ): array { global $wpdb; $existing = array_flip( (array) $wpdb->get_col( 'SHOW TABLES' ) ); $mine = array_flip( (array) get_option( self::PREFIX_IMPORT_OPTION, array() ) ); $clash = array(); foreach ( array_keys( $map ) as $t ) { if ( isset( $existing[ $t ] ) && ! isset( $mine[ $t ] ) ) { $clash[] = $t; } } return $clash; } public static function begin_prefix_import( array $map ): void { $names = array_values( array_unique( array_merge( (array) get_option( self::PREFIX_IMPORT_OPTION, array() ), array_keys( $map ) ) ) ); update_option( self::PREFIX_IMPORT_OPTION, $names, false ); } public static function end_prefix_import(): void { delete_option( self::PREFIX_IMPORT_OPTION ); } /** Drop tables by exact name (used to remove an imported copy that was not swapped in). */ public static function drop_tables( array $names ): void { global $wpdb; $wpdb->query( 'SET FOREIGN_KEY_CHECKS=0' ); foreach ( $names as $t ) { // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', (string) $t ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared } $wpdb->query( 'SET FOREIGN_KEY_CHECKS=1' ); } /** * Rename the imported tables to this site's prefix, replacing any table already there under the new name. * * @return array{renamed:int,failed:string[],options_ok:bool} */ public static function swap_in_prefixed_tables( array $map ): array { global $wpdb; $renamed = 0; $failed = array(); $existing = array_flip( (array) $wpdb->get_col( 'SHOW TABLES' ) ); $wpdb->query( 'SET FOREIGN_KEY_CHECKS=0' ); foreach ( $map as $old => $new ) { if ( $old === $new || ! isset( $existing[ $old ] ) ) { continue; } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $new ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. if ( false === $wpdb->query( $wpdb->prepare( 'RENAME TABLE %i TO %i', $old, $new ) ) ) { $failed[] = $old; } else { // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $renamed++; } } $wpdb->query( 'SET FOREIGN_KEY_CHECKS=1' ); // Same as the site-to-site copy: reconnect after a mass rename. $wpdb->flush(); $wpdb->db_connect(); wp_cache_flush(); $options_ok = ( $wpdb->prefix . 'options' === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $wpdb->prefix . 'options' ) ) ) ); return array( 'renamed' => $renamed, 'failed' => $failed, 'options_ok' => $options_ok ); } /** * Rename the rows whose NAME is built from the table prefix: usermeta {prefix}capabilities, * {prefix}user_level and friends, and the options row {prefix}user_roles. Other options that merely start * with "wp_" (wp_page_for_privacy_policy and so on) have nothing to do with the prefix and are left alone. * * @return string Short summary for the log. */ public static function fix_prefix_bound_rows( string $old, string $new ): string { global $wpdb; if ( '' === $old || $old === $new ) { return ''; } $cut = strlen( $old ) + 1; $like_old = $wpdb->esc_like( $old ) . '%'; $like_new = $wpdb->esc_like( $new ) . '%'; if ( 0 === strpos( $new, $old ) ) { // The new prefix starts with the old one: keep rows that already carry the new prefix. $meta_fixed = $wpdb->query( $wpdb->prepare( "UPDATE IGNORE {$wpdb->usermeta} SET meta_key = CONCAT(%s, SUBSTRING(meta_key, %d)) WHERE meta_key LIKE %s AND meta_key NOT LIKE %s", $new, $cut, $like_old, $like_new ) ); $meta_left = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s AND meta_key NOT LIKE %s", $like_old, $like_new ) ); } else { $meta_fixed = $wpdb->query( $wpdb->prepare( "UPDATE IGNORE {$wpdb->usermeta} SET meta_key = CONCAT(%s, SUBSTRING(meta_key, %d)) WHERE meta_key LIKE %s", $new, $cut, $like_old ) ); // Rows that collided with an existing new-prefix key are stale copies. $meta_left = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s", $like_old ) ); } $old_key = $old . 'user_roles'; $new_key = $new . 'user_roles'; $opt_fixed = 0; $has_old = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name = %s", $old_key ) ); if ( $has_old > 0 && $old_key !== $new_key ) { // The imported backup is authoritative: drop any stale target, then rename. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s", $new_key ) ); $r = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_name = %s WHERE option_name = %s", $new_key, $old_key ) ); $opt_fixed = ( false === $r ) ? 0 : (int) $r; } wp_cache_flush(); return sprintf( '%d usermeta row(s) renamed, %d stale removed, %d roles option renamed', (int) $meta_fixed, (int) $meta_left, $opt_fixed ); } /** * Make sure the restored site can still resolve an administrator (without {prefix}user_roles and an * administrator's {prefix}capabilities every user has no rights and wp-admin refuses access), and repair it if not. * * @return string Short summary for the log; starts with "FAILED" when no administrator could be found. */ public static function verify_roles_after_prefix_change( string $prefix ): string { global $wpdb; $roles_key = $prefix . 'user_roles'; $caps_key = $prefix . 'capabilities'; $repairs = array(); $adm_like = '%' . $wpdb->esc_like( '"administrator"' ) . '%'; $roles_raw = (string) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $roles_key ) ); if ( '' === $roles_raw || false === strpos( $roles_raw, '"administrator"' ) ) { $other = $wpdb->get_row( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND option_name <> %s AND option_value LIKE %s LIMIT 1", '%' . $wpdb->esc_like( 'user_roles' ), $roles_key, $adm_like ), ARRAY_A ); $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s", $roles_key ) ); if ( $other ) { $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_name = %s WHERE option_name = %s", $roles_key, $other['option_name'] ) ); $repairs[] = "roles option recovered from '{$other['option_name']}'"; } else { require_once ABSPATH . 'wp-admin/includes/schema.php'; wp_cache_flush(); populate_roles(); $repairs[] = 'roles option missing, default roles rebuilt'; } } $admins = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value LIKE %s", $caps_key, $adm_like ) ); if ( 0 === $admins ) { $wpdb->query( $wpdb->prepare( "UPDATE IGNORE {$wpdb->usermeta} SET meta_key = CONCAT(%s, 'capabilities') WHERE meta_key LIKE %s AND meta_key <> %s AND meta_value LIKE %s", $prefix, '%' . $wpdb->esc_like( '_capabilities' ), $caps_key, $adm_like ) ); $admins = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value LIKE %s", $caps_key, $adm_like ) ); if ( $admins > 0 ) { $repairs[] = 'administrator capabilities re-keyed to this prefix'; } } wp_cache_delete( 'alloptions', 'options' ); wp_cache_flush(); if ( 0 === $admins ) { return "FAILED: no administrator found under '{$caps_key}'. wp-admin will refuse access until this is fixed."; } return empty( $repairs ) ? "role check passed ({$admins} administrator(s))" : 'role check repaired: ' . implode( '; ', $repairs ); } // ─── Keeping this site's own live state through a manual restore ────────── // // A manual restore replaces the whole database with the backup's. The plugin's status tables (events, // pings, sync log, partner commits) and its backup list describe THIS site as it is now (who it is // paired with, what it has synced, which backup files really exist). They are copied aside before the // import and put back afterwards, so a restore never shows a connection or history that belonged to // the moment the backup was made. The activity log is kept too, so the restore's own log (and any error it // recorded) is still there afterwards instead of being replaced by the backup's copy. const KEEP_TABLE_PREFIX = 'swpkeep_'; /** Plugin tables (without the "wardpair_" part) that describe this site's live state. */ public static function kept_plugin_tables(): array { return array( 'events', 'pings', 'sync_log', 'commits', 'backups', 'activity_logs' ); } /** * Names of option rows that make up this plugin's housekeeping (running jobs and their locks). * One list, shared by the database dump, the ZIP dump and the restore, so they cannot drift apart. */ const JOB_OPTION_PATTERN = 'filejob|dbjob|dbreuse|clonesnap|extract|ziprestore|zip_extract_lock|replay|prefix_import'; /** * Regular expression (same syntax for MySQL REGEXP and PCRE, no delimiters) for option rows a dump must leave out. * * A normal backup carries none of Wardpair's own state, nor the Freemius account and license data: who this site is paired with, the shared secret, * Cloudflare and backup-key settings, sync progress, locks. That state describes the site as it is NOW and * must never be written into a file that can be restored later, downloaded, or moved to another site. * The site-to-site copy still sends everything except running jobs, as before. * * @param bool $for_clone True for the site-to-site copy. */ public static function backup_option_regex( bool $for_clone ): string { if ( $for_clone ) { return '^wardpair_(' . self::JOB_OPTION_PATTERN . ')_'; } // Freemius (fs_*) keeps this site's own account, install and license data. It belongs to the site the // backup is restored onto, never to the site the backup came from. return '^((_site)?_transient_(timeout_)?)?(wardpair|fs)_'; } /** * True for the plugin's own status tables (events, pings, sync log, commits, backup list, activity log). * A normal backup keeps their structure but none of their rows. */ public static function is_state_table( string $table ): bool { global $wpdb; foreach ( self::kept_plugin_tables() as $name ) { if ( $table === $wpdb->prefix . 'wardpair_' . $name ) { return true; } } return false; } /** Copy the live-state tables aside (structure and rows). Safe to call again: old copies are replaced. */ public static function keep_plugin_tables(): void { global $wpdb; $existing = array_flip( (array) $wpdb->get_col( 'SHOW TABLES' ) ); foreach ( self::kept_plugin_tables() as $name ) { $live = $wpdb->prefix . 'wardpair_' . $name; $copy = self::KEEP_TABLE_PREFIX . $name; // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $copy ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( ! isset( $existing[ $live ] ) ) { continue; } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. if ( false === $wpdb->query( $wpdb->prepare( 'CREATE TABLE %i LIKE %i', $copy, $live ) ) || false === $wpdb->query( $wpdb->prepare( 'INSERT INTO %i SELECT * FROM %i', $copy, $live ) ) ) { $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $copy ) ); } // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared } } /** * Put the kept tables back in place of whatever the restore brought in. Backup files that were created * while the restore ran (its own safety copies) are added to the kept backup list first. Idempotent: * only copies that still exist are used. * * @return string Names of the tables put back, comma separated. */ public static function return_plugin_tables(): string { global $wpdb; $existing = array_flip( (array) $wpdb->get_col( 'SHOW TABLES' ) ); $done = array(); foreach ( self::kept_plugin_tables() as $name ) { $copy = self::KEEP_TABLE_PREFIX . $name; if ( ! isset( $existing[ $copy ] ) ) { continue; } $live = $wpdb->prefix . 'wardpair_' . $name; if ( 'backups' === $name && isset( $existing[ $live ] ) ) { self::merge_new_backup_rows( $live, $copy ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $live ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. if ( false !== $wpdb->query( $wpdb->prepare( 'RENAME TABLE %i TO %i', $copy, $live ) ) ) { $done[] = $name; } // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared } return implode( ',', $done ); } /** Discard the copies without putting them back (the database was rolled back instead). */ public static function drop_kept_tables(): void { global $wpdb; foreach ( self::kept_plugin_tables() as $name ) { // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. The WHERE, ORDER BY and column lists are built inside the plugin from fixed strings, column names read from the database, and escaped or integer-cast values. $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', self::KEEP_TABLE_PREFIX . $name ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared } } /** Rows of the restored backup list whose file is really on disk and that the kept list does not have yet. */ private static function merge_new_backup_rows( string $restored, string $kept ): void { global $wpdb; if ( ! defined( 'WARDPAIR_BACKUP_DIR' ) ) { return; } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT filename, size_bytes, type, notes, created_at FROM %i', $restored ), ARRAY_A ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( empty( $rows ) ) { return; } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table or column name taken from the plugin's own table list or the database's own metadata; identifiers cannot be bound as placeholders before WordPress 6.2. $have = array_flip( (array) $wpdb->get_col( $wpdb->prepare( 'SELECT filename FROM %i', $kept ) ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared foreach ( $rows as $r ) { if ( isset( $have[ $r['filename'] ] ) || ! is_file( WARDPAIR_BACKUP_DIR . '/' . $r['filename'] ) ) { continue; } $wpdb->insert( $kept, $r ); } } /** * Escape percent signs in a fixed SQL fragment so it can be joined into a wpdb::prepare() format string. * Only for fragments the plugin builds from its own constants and database metadata (never request data); * every value and identifier is still bound with %s, %d and %i. */ public static function lit( string $fragment ): string { return str_replace( '%', '%%', $fragment ); } /** * Rows of $table where any of $columns contains $needle. Every identifier goes through %i and the * LIKE pattern through %s (after esc_like()). Rows matching in more than one column are returned once. * * @param string $table Table name. * @param string[] $columns Column names to search. * @param string $needle Text to look for. * @return array[] */ public static function rows_containing( string $table, array $columns, string $needle ): array { global $wpdb; $like = '%' . $wpdb->esc_like( $needle ) . '%'; $seen = array(); $out = array(); // One fixed statement per column (instead of one long OR chain), so no SQL text is ever assembled. foreach ( $columns as $col ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Search-and-replace across the site's own tables. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE %i LIKE %s', $table, (string) $col, $like ), ARRAY_A ); foreach ( (array) $rows as $row ) { $key = md5( wp_json_encode( $row ) ); if ( ! isset( $seen[ $key ] ) ) { $seen[ $key ] = true; $out[] = $row; } } } return $out; } /** * Describe a table's columns (DESCRIBE with the name bound as an identifier). * * @return array[] */ public static function describe_table( string $table ): array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Reads the live table structure. $cols = $wpdb->get_results( $wpdb->prepare( 'DESCRIBE %i', $table ), ARRAY_A ); return is_array( $cols ) ? $cols : array(); } public static function sql_escape( $value ): string { global $wpdb; $escaped = esc_sql( (string) $value ); if ( is_object( $wpdb ) && method_exists( $wpdb, 'remove_placeholder_escape' ) ) { return $wpdb->remove_placeholder_escape( $escaped ); } return preg_replace( '/\{[0-9a-f]{64}\}/', '%', $escaped ); } public static function search_replace_db( string $old, string $new ): int { global $wpdb; $old = untrailingslashit( $old ); $new = untrailingslashit( $new ); if ( empty( $old ) || empty( $new ) || $old === $new ) { return 0; } $count = 0; $like_old = '%' . $wpdb->esc_like( $old ) . '%'; // ── wp_options ──────────────────────────────────────────────────────── $opt_rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_value LIKE %s AND option_name NOT IN ('siteurl','home') AND option_name NOT LIKE %s AND option_name NOT LIKE %s AND option_name NOT LIKE %s", $like_old, $wpdb->esc_like( 'wardpair_' ) . '%', $wpdb->esc_like( '_transient' ) . '%', $wpdb->esc_like( '_site_transient' ) . '%' ), ARRAY_A ); foreach ( $opt_rows as $row ) { $updated = self::replace_value( $old, $new, $row['option_value'] ); if ( $updated !== $row['option_value'] ) { $wpdb->update( $wpdb->options, array( 'option_value' => $updated ), array( 'option_name' => $row['option_name'] ), array( '%s' ), array( '%s' ) ); $count++; } } // ── wp_postmeta ─────────────────────────────────────────────────────── $pmeta_rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_id, meta_value FROM {$wpdb->postmeta} WHERE meta_value LIKE %s", $like_old ), ARRAY_A ); foreach ( $pmeta_rows as $row ) { $updated = self::replace_value( $old, $new, $row['meta_value'] ); if ( $updated !== $row['meta_value'] ) { $wpdb->update( $wpdb->postmeta, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- This is the column name in a $wpdb->update() data array, not a meta query. array( 'meta_value' => $updated ), array( 'meta_id' => (int) $row['meta_id'] ), array( '%s' ), array( '%d' ) ); $count++; } } // ── wp_usermeta ─────────────────────────────────────────────────────── $umeta_rows = $wpdb->get_results( $wpdb->prepare( "SELECT umeta_id, meta_value FROM {$wpdb->usermeta} WHERE meta_value LIKE %s", $like_old ), ARRAY_A ); foreach ( $umeta_rows as $row ) { $updated = self::replace_value( $old, $new, $row['meta_value'] ); if ( $updated !== $row['meta_value'] ) { $wpdb->update( $wpdb->usermeta, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- This is the column name in a $wpdb->update() data array, not a meta query. array( 'meta_value' => $updated ), array( 'umeta_id' => (int) $row['umeta_id'] ), array( '%s' ), array( '%d' ) ); $count++; } } // ── wp_posts — post_content and guid ────────────────────────────────── $post_rows = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_content, guid FROM {$wpdb->posts} WHERE post_content LIKE %s OR guid LIKE %s", $like_old, $like_old ), ARRAY_A ); foreach ( $post_rows as $row ) { // post_content: may contain serialized blocks — use replace_value. $new_content = self::replace_value( $old, $new, $row['post_content'] ); // guid: never serialized — plain str_replace is correct. $new_guid = str_replace( $old, $new, $row['guid'] ); if ( $new_content !== $row['post_content'] || $new_guid !== $row['guid'] ) { $wpdb->update( $wpdb->posts, array( 'post_content' => $new_content, 'guid' => $new_guid ), array( 'ID' => (int) $row['ID'] ), array( '%s', '%s' ), array( '%d' ) ); $count++; } } // ── wp_comments — comment_content and comment_author_url ─────────────── $comment_rows = $wpdb->get_results( $wpdb->prepare( "SELECT comment_ID, comment_content, comment_author_url FROM {$wpdb->comments} WHERE comment_content LIKE %s OR comment_author_url LIKE %s", $like_old, $like_old ), ARRAY_A ); foreach ( $comment_rows as $row ) { $new_content = self::replace_value( $old, $new, $row['comment_content'] ); $new_url = str_replace( $old, $new, $row['comment_author_url'] ); if ( $new_content !== $row['comment_content'] || $new_url !== $row['comment_author_url'] ) { $wpdb->update( $wpdb->comments, array( 'comment_content' => $new_content, 'comment_author_url' => $new_url ), array( 'comment_ID' => (int) $row['comment_ID'] ), array( '%s', '%s' ), array( '%d' ) ); $count++; } } // ── wp_commentmeta ──────────────────────────────────────────────────── $cmeta_rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_id, meta_value FROM {$wpdb->commentmeta} WHERE meta_value LIKE %s", $like_old ), ARRAY_A ); foreach ( $cmeta_rows as $row ) { $updated = self::replace_value( $old, $new, $row['meta_value'] ); if ( $updated !== $row['meta_value'] ) { $wpdb->update( $wpdb->commentmeta, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- This is the column name in a $wpdb->update() data array, not a meta query. array( 'meta_value' => $updated ), array( 'meta_id' => (int) $row['meta_id'] ), array( '%s' ), array( '%d' ) ); $count++; } } // ── wp_termmeta ─────────────────────────────────────────────────────── $tmeta_rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_id, meta_value FROM {$wpdb->termmeta} WHERE meta_value LIKE %s", $like_old ), ARRAY_A ); foreach ( $tmeta_rows as $row ) { $updated = self::replace_value( $old, $new, $row['meta_value'] ); if ( $updated !== $row['meta_value'] ) { $wpdb->update( $wpdb->termmeta, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- This is the column name in a $wpdb->update() data array, not a meta query. array( 'meta_value' => $updated ), array( 'meta_id' => (int) $row['meta_id'] ), array( '%s' ), array( '%d' ) ); $count++; } } // ── wp_term_taxonomy — description ────────────────────────────────────── $tt_rows = $wpdb->get_results( $wpdb->prepare( "SELECT term_taxonomy_id, description FROM {$wpdb->term_taxonomy} WHERE description LIKE %s", $like_old ), ARRAY_A ); foreach ( $tt_rows as $row ) { $updated = self::replace_value( $old, $new, $row['description'] ); if ( $updated !== $row['description'] ) { $wpdb->update( $wpdb->term_taxonomy, array( 'description' => $updated ), array( 'term_taxonomy_id' => (int) $row['term_taxonomy_id'] ), array( '%s' ), array( '%d' ) ); $count++; } } // ── Everything else — third-party/custom tables ───────────────────────── // WooCommerce order tables, form-plugin submissions, page-builder custom // tables, redirect plugins, etc. can all store URLs outside the core // tables above. Scan the rest of the database generically so a real // cutover is as thorough as the initial clone, which already does this. $count += self::generic_table_scan( $old, $new ); return $count; } /** * Generic fallback scan of any table not explicitly handled above — * covers third-party plugin tables. Uses the same serialization-safe * replace as the explicit table handlers. Tables without a primary key * are matched on their full original row (all columns) as a composite * key, since there's no single column guaranteed unique to update by. * * @return int Rows updated. */ private static function generic_table_scan( string $old, string $new ): int { global $wpdb; $known_tables = array( $wpdb->options, $wpdb->postmeta, $wpdb->usermeta, $wpdb->posts, $wpdb->comments, $wpdb->commentmeta, $wpdb->termmeta, $wpdb->term_taxonomy, ); $tables = self::own_tables(); // Never rewrite a neighbouring install's data. $like = '%' . $wpdb->esc_like( $old ) . '%'; $updated = 0; foreach ( $tables as $table ) { // Skip core tables already handled explicitly above, and skip // Wardpair's own tables — plugin state must never be rewritten. if ( in_array( $table, $known_tables, true ) || false !== strpos( $table, 'wardpair' ) ) { continue; } $col_results = self::describe_table( $table ); $columns = array(); $pk = null; foreach ( $col_results as $col ) { $type = strtolower( $col['Type'] ); if ( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false || strpos( $type, 'blob' ) !== false || strpos( $type, 'binary' ) !== false ) { $columns[] = $col['Field']; } if ( 'PRI' === $col['Key'] && ! $pk ) { $pk = $col['Field']; } } if ( empty( $columns ) ) { continue; } $rows = self::rows_containing( $table, $columns, $old ); foreach ( $rows as $row ) { $update_data = array(); foreach ( $columns as $column ) { $original = $row[ $column ] ?? ''; if ( ! is_string( $original ) || strpos( $original, $old ) === false ) { continue; } $replaced = self::replace_value( $old, $new, $original ); if ( $replaced !== $original ) { $update_data[ $column ] = $replaced; } } if ( empty( $update_data ) ) { continue; } if ( $pk ) { $wpdb->update( $table, $update_data, array( $pk => $row[ $pk ] ) ); } else { // No primary key — match the exact original row instead. // Safe as long as the row (all columns together) is unique, // which holds for the overwhelming majority of PK-less // WordPress tables (e.g. wp_options-style lookup tables). $original_row = array(); foreach ( $col_results as $col ) { $field = $col['Field']; if ( isset( $row[ $field ] ) ) { $original_row[ $field ] = $row[ $field ]; } } $wpdb->update( $table, $update_data, $original_row ); } $updated++; } } return $updated; } // ========================================================================= // PRIVATE HELPERS // ========================================================================= /** * Replace $old → $new inside a raw DB value. * * If the value is valid serialized data, it is unserialized, all nested * strings/keys are replaced recursively, then re-serialized (which * automatically fixes the s:LENGTH byte-count prefixes). * * Falls back to plain str_replace for non-serialized values. * * @param string $old String to find. * @param string $new Replacement string. * @param string $value Raw DB value (may be serialized). * @return string Replaced value, safe to write back to DB. */ private static function replace_value( string $old, string $new, string $value ): string { if ( strpos( $value, $old ) === false ) { return $value; // fast-path — nothing to replace } // Attempt unserialize. @ suppresses notices on broken data. // We distinguish real false from failure by checking serialize(false). $unserialized = self::unserialize_flat( $value ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Re-serializes a value after a search-and-replace so serialized string lengths stay correct; the input is only ever unserialized without creating objects (see Sentinel_Utils::unserialize_flat()). if ( false !== $unserialized || $value === serialize( false ) ) { $replaced = self::deep_replace( $old, $new, $unserialized ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Re-serializes a value after a search-and-replace so serialized string lengths stay correct; the input is only ever unserialized without creating objects (see Sentinel_Utils::unserialize_flat()). return serialize( $replaced ); } // Plain (non-serialized) string. return str_replace( $old, $new, $value ); } /** * Recursively replace $old → $new inside any nested data structure. * * Handles strings, arrays (including string keys), and objects. * Scalars (int, float, bool, null) are returned unchanged. * * @param string $old * @param string $new * @param mixed $data * @return mixed */ private static function deep_replace( string $old, string $new, $data ) { if ( is_string( $data ) ) { return str_replace( $old, $new, $data ); } if ( is_array( $data ) ) { $result = array(); foreach ( $data as $k => $v ) { // Array keys can also contain URLs (some plugins do this). $new_k = is_string( $k ) ? str_replace( $old, $new, $k ) : $k; $result[ $new_k ] = self::deep_replace( $old, $new, $v ); } return $result; } if ( is_object( $data ) ) { // A class we refused to build (see unserialize_flat) cannot be edited, and writing // to its properties raises errors on newer PHP. It is passed through unchanged. if ( $data instanceof __PHP_Incomplete_Class ) { return $data; } foreach ( get_object_vars( $data ) as $prop => $val ) { $data->$prop = self::deep_replace( $old, $new, $val ); } return $data; } // int, float, bool, null — nothing to replace. return $data; } }