Plugin Directory

Changeset 3817595


Ignore:
Timestamp:
11/23/2026 06:44:32 AM (2 days ago)
Author:
mdfirdousahmed
Message:

Release 1.0.1

Location:
sitezip
Files:
2 added
32 edited
1 copied

Legend:

Unmodified
Added
Removed
  • sitezip/tags/1.0.1/admin/css/admin.css

    r3800592 r3817595  
    490490/* Measuring: each part lights up in turn while a sheen sweeps across, like a scan. */
    491491.sitezip-bar.is-loading {
     492        /* Keep the sweeping sheen inside the bar, not across the card edge. */
     493        border-radius: 4px;
     494        overflow: hidden;
    492495        position: relative;
    493496}
  • sitezip/tags/1.0.1/admin/js/app.js

    r3800592 r3817595  
    6161                        'import': __( 'Importing database', 'sitezip' ),
    6262                        replace: __( 'Updating site address', 'sitezip' ),
     63                        code: __( 'Putting plugins and themes in place', 'sitezip' ),
    6364                        swap: __( 'Switching database', 'sitezip' ),
    6465                        done: __( 'Done', 'sitezip' )
    … …  
    733734                                                } );
    734735                                        }
    735                                 }, [ job.type === 'restore' ? __( 'Cancel restore', 'sitezip' ) : __( 'Cancel backup', 'sitezip' ) ] )
     736                                }, [ job.type === 'restore' ? __( 'Cancel restore', 'sitezip' ) : __( 'Cancel backup', 'sitezip' ) ] ),
     737                                debugButton( 'button' )
    736738                        ]
    737739                } );
    … …  
    13221324
    13231325        /**
    1324          * Ask the server for a one-time link, then start the download with it.
    1325          * The link works once, for this user, for two minutes.
     1326         * Ask the server for a link, then start the download with it. It must
     1327         * be started within two minutes; after that it keeps working for this
     1328         * user so the browser can resume a large download.
    13261329         */
    13271330        function startDownload( backup, button ) {
    … …  
    18561859        }
    18571860
    1858         function copyText( text ) {
     1861        /**
     1862         * A button that copies a full debug report (server facts, loopback
     1863         * tests, the latest job's log and exact position) for a support request.
     1864         */
     1865        function debugButton( cls ) {
     1866                return el( 'button', {
     1867                        type: 'button',
     1868                        class: cls,
     1869                        onClick: function ( e ) {
     1870                                var btn = e.currentTarget;
     1871                                btn.disabled = true;
     1872                                request( '/diagnostics' ).then( function ( data ) {
     1873                                        copyText(
     1874                                                'SiteZip debug report — ' + new Date().toISOString() + '\n' +
     1875                                                'Browser: ' + window.navigator.userAgent + '\n\n' +
     1876                                                JSON.stringify( data, null, 2 ),
     1877                                                __( 'Debug report copied. Paste it into your support request.', 'sitezip' )
     1878                                        );
     1879                                } ).then( function () {
     1880                                        btn.disabled = false;
     1881                                }, function () {
     1882                                        btn.disabled = false;
     1883                                } );
     1884                        }
     1885                }, [ __( 'Copy debug report', 'sitezip' ) ] );
     1886        }
     1887
     1888        function copyText( text, message ) {
    18591889                var done = function () {
    1860                         notify( __( 'Log copied.', 'sitezip' ) );
     1890                        notify( message || __( 'Log copied.', 'sitezip' ) );
    18611891                };
    18621892                if ( window.navigator.clipboard && window.isSecureContext ) {
    … …  
    18931923                                        }
    18941924                                }, [ __( 'Copy all', 'sitezip' ) ] ) : null,
     1925                                debugButton( 'button-link sitezip-copy' ),
    18951926                                el( 'button', { type: 'button', class: 'sitezip-toast-close', 'aria-label': __( 'Close', 'sitezip' ), onClick: function () { toggleActivity( false ); } }, [ '×' ] )
    18961927                        ] )
  • sitezip/tags/1.0.1/includes/Admin/AdminPage.php

    r3800592 r3817595  
    235235         */
    236236        private function deactivate_assets() {
    237                 $backups = BackupStore::all();
    238                 $folder  = PathGuard::find_backups_dir();
    239                 $bytes   = 0;
    240                 foreach ( $backups as $backup ) {
    241                         $bytes += (int) $backup['size'];
    242                 }
     237                // Only a count and a size: never open every archive on the Plugins screen.
     238                list( $count, $bytes ) = BackupStore::totals();
     239                $folder                = PathGuard::find_backups_dir();
    243240
    244241                wp_enqueue_style( 'sitezip-deactivate', SITEZIP_URL . 'admin/css/admin.css', array(), SITEZIP_VERSION . '.' . filemtime( SITEZIP_DIR . 'admin/css/admin.css' ) );
    … …  
    251248                                'plugin'  => plugin_basename( SITEZIP_FILE ),
    252249                                'nonce'   => wp_create_nonce( Plugin::PURGE_NONCE ),
    253                                 'count'   => count( $backups ),
     250                                'count'   => $count,
    254251                                'size'    => size_format( $bytes ),
    255252                                'folder'  => $folder ? 'wp-content/' . basename( $folder ) : 'wp-content',
    … …  
    317314         * The backups folder is denied to the web server, so this is the only
    318315         * way to fetch an archive. It needs an administrator's login and a
    319          * one-time link made seconds earlier by the Download button (see
    320          * DownloadLinks): the link works once, for that user, for two minutes.
     316         * link made seconds earlier by the Download button (see DownloadLinks):
     317         * it must be first used within two minutes, by that user, and then
     318         * keeps working for 12 hours so a big download can resume.
    321319         *
    322320         * @return void
    … …  
    328326
    329327                $token = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- the one-time token is stronger than a nonce.
    330                 $file  = DownloadLinks::consume( $token, get_current_user_id() );
     328                $file  = DownloadLinks::redeem( $token, get_current_user_id() );
    331329                if ( false === $file ) {
    332330                        wp_die(
    … …  
    355353                }
    356354
     355                clearstatcache( true, $path );
     356                $size  = (int) filesize( $path );
     357                $start = 0;
     358                $end   = $size - 1;
     359
     360                // Resume: answer "Range: bytes=START-[END]" with just that part, so
     361                // a dropped multi-gigabyte download continues instead of failing.
     362                $range = isset( $_SERVER['HTTP_RANGE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_RANGE'] ) ) : '';
     363                if ( '' !== $range ) {
     364                        if ( ! preg_match( '/^bytes=(\d*)-(\d*)$/', trim( $range ), $m ) || ( '' === $m[1] && '' === $m[2] ) ) {
     365                                $m = null;
     366                        } elseif ( '' === $m[1] ) {
     367                                $start = max( 0, $size - (int) $m[2] ); // Last N bytes.
     368                        } else {
     369                                $start = (int) $m[1];
     370                                $end   = '' === $m[2] ? $end : min( $end, (int) $m[2] );
     371                        }
     372                        if ( ! $m || $start > $end || $start >= $size ) {
     373                                status_header( 416 );
     374                                header( 'Content-Range: bytes */' . $size );
     375                                exit;
     376                        }
     377                        status_header( 206 );
     378                        header( 'Content-Range: bytes ' . $start . '-' . $end . '/' . $size );
     379                }
     380
    357381                nocache_headers();
    358382                header( 'Content-Type: application/zip' );
    359383                header( 'Content-Disposition: attachment; filename="' . str_replace( array( '"', "\r", "\n" ), '', basename( $path ) ) . '"' );
    360                 header( 'Content-Length: ' . filesize( $path ) );
     384                header( 'Content-Length: ' . ( $end - $start + 1 ) );
     385                header( 'Accept-Ranges: bytes' );
     386                // Same file, same validator: lets the browser check a resume matches.
     387                header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', (int) filemtime( $path ) ) . ' GMT' );
    361388                header( 'X-Content-Type-Options: nosniff' );
    362389                header( 'Referrer-Policy: no-referrer' );
    363390                header( 'X-Robots-Tag: noindex, nofollow' );
     391                // Stop nginx and similar proxies from buffering gigabytes first.
     392                header( 'X-Accel-Buffering: no' );
    364393
    365394                $handle = fopen( $path, 'rb' );
    366395                if ( $handle ) {
    367                         while ( ! feof( $handle ) && ! connection_aborted() ) {
    368                                 echo fread( $handle, 4194304 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary file download.
     396                        fseek( $handle, $start );
     397                        $left = $end - $start + 1;
     398                        while ( $left > 0 && ! feof( $handle ) && ! connection_aborted() ) {
     399                                $chunk = fread( $handle, (int) min( 4194304, $left ) );
     400                                if ( false === $chunk || '' === $chunk ) {
     401                                        break;
     402                                }
     403                                $left -= strlen( $chunk );
     404                                echo $chunk; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary file download.
    369405                                flush();
    370406                        }
  • sitezip/tags/1.0.1/includes/Backup/BackupStore.php

    r3800592 r3817595  
    136136                $site  = self::sanitize_name( $site );
    137137
    138                 return ( '' !== $site ? $site : 'site' ) . '-' . wp_date( 'Y-m-d-His' );
     138                // A random ending, so backup names cannot be guessed from the date.
     139                return ( '' !== $site ? $site : 'site' ) . '-' . wp_date( 'Y-m-d-His' ) . '-' . bin2hex( random_bytes( 3 ) );
    139140        }
    140141
    … …  
    226227
    227228        /**
    228          * Every archive in the backups folder, newest first.
    229          *
    230          * @return array[]
     229         * How many backups there are and their total size, without opening any.
     230         *
     231         * @return array [ count, bytes ].
     232         */
     233        public static function totals() {
     234                $dir   = PathGuard::backups_dir();
     235                $count = 0;
     236                $bytes = 0;
     237                if ( ! is_wp_error( $dir ) ) {
     238                        foreach ( (array) @scandir( $dir ) as $file ) {
     239                                if ( self::is_valid_filename( $file ) && is_file( $dir . $file ) && ! is_link( $dir . $file ) ) {
     240                                        ++$count;
     241                                        $bytes += (int) filesize( $dir . $file );
     242                                }
     243                        }
     244                }
     245                return array( $count, $bytes );
     246        }
     247
     248        /**
     249         * Every backup in the folder, newest first, with manifest details.
     250         *
     251         * @return array
    231252         */
    232253        public static function all() {
    … …  
    256277                                'size'     => $size,
    257278                                'modified' => gmdate( 'c', $mtime ),
    258                                 'created'  => ( $manifest && ! empty( $manifest['created'] ) ) ? $manifest['created'] : gmdate( 'c', $mtime ),
    259                                 'site_url' => ( $manifest && ! empty( $manifest['home_url'] ) ) ? $manifest['home_url'] : '',
     279                                // From inside the zip: only well-formed strings reach the page.
     280                                'created'  => ( $manifest && ! empty( $manifest['created'] ) && is_string( $manifest['created'] ) && false !== strtotime( $manifest['created'] ) ) ? $manifest['created'] : gmdate( 'c', $mtime ),
     281                                'site_url' => ( $manifest && ! empty( $manifest['home_url'] ) && is_string( $manifest['home_url'] ) ) ? esc_url_raw( $manifest['home_url'] ) : '',
    260282                                'valid'    => (bool) $manifest,
    261283                                'options'  => ( $manifest && ! empty( $manifest['options'] ) && is_array( $manifest['options'] ) ) ? $manifest['options'] : null,
  • sitezip/tags/1.0.1/includes/Backup/JobRunner.php

    r3800592 r3817595  
    199199                        return new \WP_Error( 'sitezip_job', __( 'Could not create the restore job.', 'sitezip' ) );
    200200                }
     201                \SiteZip\Restore\RestoreGuard::install();
    201202
    202203                $this->store->log(
    … …  
    592593
    593594                if ( 'restore' === $job['type'] ) {
     595                        \SiteZip\Restore\RestoreGuard::remove();
    594596                        $this->check_site( $job_id, isset( $job['state']['dropins_skipped'] ) ? (array) $job['state']['dropins_skipped'] : array() );
    595597                }
    … …  
    685687
    686688                if ( 'restore' === $job['type'] ) {
     689                        \SiteZip\Restore\RestoreGuard::remove();
    687690                        RestoreRunner::drop_temp_tables();
    688691                        return;
  • sitezip/tags/1.0.1/includes/Backup/Source/DatabaseSource.php

    r3800592 r3817595  
    251251                        return "`comment_id` NOT IN (SELECT `comment_ID` FROM `{$wpdb->comments}` WHERE `comment_approved` IN ('spam','trash'))";
    252252                }
    253                 if ( ! empty( $o['skip_transients'] ) && $table === $wpdb->options ) {
    254                         return "`option_name` NOT LIKE '\\_transient\\_%' AND `option_name` NOT LIKE '\\_site\\_transient\\_%'";
     253                if ( $table === $wpdb->options ) {
     254                        // Cloud keys, the Google sign-in and its tokens belong to this
     255                        // site, never in a backup file that may be shared or moved.
     256                        $secret = "`option_name` NOT IN ('sitezip_cloud','sitezip_gdrive_folders','sitezip_cloud_tune') AND `option_name` NOT LIKE '\\_transient\\_sitezip\\_g%' AND `option_name` NOT LIKE '\\_transient\\_timeout\\_sitezip\\_g%'";
     257                        if ( ! empty( $o['skip_transients'] ) ) {
     258                                return $secret . " AND `option_name` NOT LIKE '\\_transient\\_%' AND `option_name` NOT LIKE '\\_site\\_transient\\_%'";
     259                        }
     260                        return $secret;
    255261                }
    256262
  • sitezip/tags/1.0.1/includes/Plugin.php

    r3800592 r3817595  
    7171                add_action( 'wp_ajax_nopriv_sitezip_ping', array( __CLASS__, 'pong' ) );
    7272                add_action( 'sitezip_run_job', array( $this, 'handle_cron' ), 10, 1 );
     73                add_action( 'admin_init', array( '\\SiteZip\\Restore\\RestoreGuard', 'sweep' ) );
    7374        }
    7475
    … …  
    135136        public static function deactivate() {
    136137                wp_unschedule_hook( 'sitezip_run_job' );
     138                \SiteZip\Restore\RestoreGuard::remove();
    137139
    138140                // phpcs:disable WordPress.Security.NonceVerification.Recommended -- verified immediately below.
  • sitezip/tags/1.0.1/includes/Rest/RestController.php

    r3800592 r3817595  
    495495                                'cron_next'      => wp_next_scheduled( 'sitezip_run_job', array( (int) $job['id'] ) ),
    496496                                'log_tail'       => array_slice( $log, -15 ),
     497                                'position'       => self::job_position( $job ),
    497498                        );
    498499                }
    … …  
    535536
    536537        /**
     538         * Where a job is inside its work: stage cursor, byte counts and, while
     539         * files are being unpacked, the archive entry it is on. A restore that
     540         * stalls at the same percent is almost always stuck on that one entry.
     541         *
     542         * @param array $job Job row.
     543         * @return array
     544         */
     545        private static function job_position( array $job ) {
     546                $state = is_array( $job['state'] ) ? $job['state'] : array();
     547                $out   = array();
     548                foreach ( array( 'file', 'stage', 'cursor', 'entries', 'bytes_done', 'bytes_total', 'dropins_skipped' ) as $key ) {
     549                        if ( isset( $state[ $key ] ) ) {
     550                                $out[ $key ] = $state[ $key ];
     551                        }
     552                }
     553                if ( isset( $state['tables'] ) && is_array( $state['tables'] ) ) {
     554                        $out['tables_imported'] = count( $state['tables'] );
     555                }
     556                if ( isset( $state['manifest']['home_url'] ) ) {
     557                        $out['backup_of'] = $state['manifest']['home_url'];
     558                }
     559
     560                if ( 'restore' === $job['type'] && 'extract' === $job['stage'] && isset( $state['file'], $state['cursor'] ) && is_numeric( $state['cursor'] ) && class_exists( '\ZipArchive' ) ) {
     561                        $path = BackupStore::path( $state['file'] );
     562                        $zip  = new \ZipArchive();
     563                        if ( ! is_wp_error( $path ) && true === $zip->open( $path ) ) {
     564                                $stat = $zip->statIndex( (int) $state['cursor'] );
     565                                if ( $stat ) {
     566                                        $out['current_entry'] = array(
     567                                                'name'            => $stat['name'],
     568                                                'size'            => size_format( (int) $stat['size'] ),
     569                                                'compressed_size' => size_format( (int) $stat['comp_size'] ),
     570                                        );
     571                                }
     572                                $zip->close();
     573                        }
     574                }
     575
     576                return $out;
     577        }
     578
     579        /**
    537580         * Poll a job.
    538581         *
  • sitezip/tags/1.0.1/includes/Restore/ArchiveReader.php

    r3800592 r3817595  
    3333
    3434        /**
     35         * Staging folder for code, or ''.
     36         *
     37         * @var string
     38         */
     39        private $code_root = '';
     40
     41        /**
     42         * Top-level wp-content folders holding code the running site executes.
     43         *
     44         * Their files are unpacked into a staging folder and only moved into
     45         * place at the end. Written in place, a plugin caught half way (new
     46         * files next to old ones from a different version) fatals every
     47         * request to the site, including the ones driving this restore.
     48         */
     49        const CODE_FOLDERS = array( 'plugins', 'themes', 'mu-plugins' );
     50
     51        /**
    3552         * Extract entries until the deadline.
    3653         *
    … …  
    4158         * @param float  $deadline     Stop-by timestamp.
    4259         * @param string $index_path   File from build_index(), or ''.
     60         * @param string $code_root    Staging folder for plugins, themes and
     61         *                             must-use plugins, or '' to write them in
     62         *                             place. See move_staged().
    4363         * @return array|\WP_Error Keys: cursor, done, written, rejected, total.
    4464         */
    45         public function extract_batch( $zip_path, $content_root, $sql_root, $cursor, $deadline, $index_path = '' ) {
     65        public function extract_batch( $zip_path, $content_root, $sql_root, $cursor, $deadline, $index_path = '', $code_root = '' ) {
     66                $this->code_root = $code_root;
     67                if ( '' !== $code_root && ! is_dir( $code_root ) && ! wp_mkdir_p( $code_root ) ) {
     68                        return new \WP_Error( 'sitezip_staging', __( 'Could not create the folder for staging plugins and themes.', 'sitezip' ) );
     69                }
    4670                $records = ( '' !== $index_path && is_readable( $index_path ) ) ? (string) file_get_contents( $index_path ) : '';
    4771
    … …  
    136160                        // The same file is already there (the usual case when restoring
    137161                        // onto the site the backup came from): skip the rewrite.
    138                         if ( $mtime && self::same_file( $target['path'], $stat, $mtime ) ) {
     162                        // Only plain media may be skipped: code is always rewritten, so a
     163                        // tampered file with a faked size and date cannot survive.
     164                        if ( $mtime && ! isset( $target['live'] ) && self::skippable( $entry ) && self::same_file( $target['path'], $stat, $mtime ) ) {
    139165                                $bytes += (int) $stat['size'];
    140166                                continue;
    … …  
    152178                                continue;
    153179                        }
    154                         $copied = stream_copy_to_stream( $stream, $out );
     180                        // Never more than the archive declared for this entry.
     181                        $copied = stream_copy_to_stream( $stream, $out, (int) $stat['size'] + 1 );
    155182                        fclose( $stream );
    156183                        fclose( $out );
    … …  
    189216
    190217        /**
     218         * Move staged code files into wp-content, until done or the deadline.
     219         *
     220         * Each file is a rename on the same disk, so the whole set lands in
     221         * well under a second for a typical site. A request killed part way
     222         * leaves the rest in the staging folder, and the next call resumes.
     223         *
     224         * @param string $code_root    Staging folder.
     225         * @param string $content_root wp-content.
     226         * @param float  $deadline     Stop-by timestamp.
     227         * @return array Keys: done, moved, rejected.
     228         */
     229        public static function move_staged( $code_root, $content_root, $deadline ) {
     230                $code_root    = untrailingslashit( $code_root );
     231                $content_root = untrailingslashit( $content_root );
     232                $moved        = 0;
     233                $rejected     = 0;
     234
     235                if ( ! is_dir( $code_root ) ) {
     236                        return array( 'done' => true, 'moved' => 0, 'rejected' => 0 );
     237                }
     238
     239                while ( microtime( true ) < $deadline ) {
     240                        // Collected first: moving files while iterating their folder is unreliable.
     241                        $batch = array();
     242                        $files = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $code_root, \FilesystemIterator::SKIP_DOTS ) );
     243                        foreach ( $files as $file ) {
     244                                if ( $file->isFile() || $file->isLink() ) {
     245                                        $batch[] = $file->getPathname();
     246                                        if ( count( $batch ) >= 500 ) {
     247                                                break;
     248                                        }
     249                                }
     250                        }
     251                        if ( ! $batch ) {
     252                                return array( 'done' => true, 'moved' => $moved, 'rejected' => $rejected );
     253                        }
     254
     255                        foreach ( $batch as $src ) {
     256                                $relative = substr( $src, strlen( $code_root ) + 1 );
     257                                $dest     = $content_root . '/' . $relative;
     258                                $dir      = dirname( $dest );
     259
     260                                $ok = ! is_link( $src )
     261                                        && ( is_dir( $dir ) || wp_mkdir_p( $dir ) )
     262                                        && PathGuard::is_inside( $dir, $content_root )
     263                                        && ! is_link( $dest )
     264                                        && ! is_dir( $dest );
     265                                if ( $ok && ! @rename( $src, $dest ) ) {
     266                                        $ok = @copy( $src, $dest );
     267                                        if ( $ok ) {
     268                                                @touch( $dest, (int) filemtime( $src ) );
     269                                        }
     270                                }
     271                                @unlink( $src );
     272                                if ( $ok ) {
     273                                        $moved++;
     274                                } else {
     275                                        $rejected++;
     276                                }
     277                                if ( microtime( true ) >= $deadline ) {
     278                                        break;
     279                                }
     280                        }
     281                }
     282
     283                return array( 'done' => false, 'moved' => $moved, 'rejected' => $rejected );
     284        }
     285
     286        /**
    191287         * Bytes per entry in the index file: 32-bit time, 64-bit size.
    192288         */
    … …  
    239335                }
    240336
     337                // A damaged or doctored archive must not make us read past its end
     338                // or allocate gigabytes.
     339                if ( $start < 0 || $len < 0 || $len > 268435456 || $start + $len > $size || $count < 0 ) {
     340                        fclose( $fh );
     341                        return false;
     342                }
    241343                fseek( $fh, $start );
    242344                $cd = $len > 0 ? (string) fread( $fh, $len ) : '';
    … …  
    261363                        $x    = $pos + 46 + $lens['name'];
    262364                        $xend = $x + $lens['extra'];
     365                        if ( $xend + $lens['comment'] > $n ) {
     366                                return false;
     367                        }
    263368                        while ( $x + 4 <= $xend ) {
    264369                                $field = unpack( 'vid/vsize', $cd, $x );
     370                                if ( $x + 4 + $field['size'] > $xend ) {
     371                                        break;
     372                                }
    265373                                if ( 0x5455 === $field['id'] && $field['size'] >= 5 && ( ord( $cd[ $x + 4 ] ) & 1 ) ) {
    266374                                        $time = unpack( 'V', $cd, $x + 5 )[1];
    … …  
    300408
    301409        /**
     410         * File types a restore may leave in place when they look unchanged:
     411         * plain media in uploads only. Anything that can run (PHP, scripts,
     412         * HTML, SVG, server config) is always rewritten from the backup.
     413         */
     414        const SKIPPABLE = array( 'jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'heic', 'bmp', 'tif', 'tiff', 'ico', 'mp4', 'm4v', 'mov', 'webm', 'mkv', 'avi', 'mp3', 'm4a', 'wav', 'ogg', 'flac', 'pdf', 'zip', 'woff', 'woff2', 'ttf', 'otf', 'eot' );
     415
     416        /**
     417         * Whether an entry may be skipped when the file on disk looks the same.
     418         *
     419         * @param string $entry Normalised entry name.
     420         * @return bool
     421         */
     422        private static function skippable( $entry ) {
     423                $entry = strtolower( $entry );
     424                if ( 0 !== strpos( $entry, 'wp-content/uploads/' ) ) {
     425                        return false;
     426                }
     427                $ext = pathinfo( $entry, PATHINFO_EXTENSION );
     428                // "photo.php.jpg" style names are rewritten too.
     429                return in_array( $ext, self::SKIPPABLE, true ) && 1 === substr_count( basename( $entry ), '.' );
     430        }
     431
     432        /**
    302433         * Whether a regular file on disk already matches an archive entry, by
    303434         * size and exact modification time. Only file metadata is read, so
    … …  
    310441         */
    311442        private static function same_file( $path, array $stat, $mtime ) {
     443                if ( ! isset( $stat['size'] ) ) {
     444                        return false;
     445                }
    312446                if ( ! is_file( $path ) || (int) filesize( $path ) !== (int) $stat['size'] ) {
    313447                        return false;
    … …  
    334468                if ( 0 === strpos( $entry, 'wp-content/' ) ) {
    335469                        $relative = substr( $entry, strlen( 'wp-content/' ) );
     470                        // Compared in lower case: macOS and Windows disks treat
     471                        // "Plugins" and "plugins" as the same folder.
     472                        $lower = strtolower( $relative );
    336473                        // Restoring wp-config.php is never legitimate: it is not in the
    337474                        // archive, and an injected one would hand over the database.
    338                         if ( '' === $relative || 'wp-config.php' === basename( $relative ) ) {
     475                        if ( '' === $relative || 'wp-config.php' === basename( $lower ) ) {
    339476                                return false;
    340477                        }
    … …  
    342479                        // Server-specific drop-ins from the old host would break this
    343480                        // one (backups from older versions may still contain them).
    344                         $host = \SiteZip\Backup\Source\FilesSource::host_specific( $relative );
     481                        $host = \SiteZip\Backup\Source\FilesSource::host_specific( $lower );
    345482                        if ( '' !== $host ) {
    346483                                if ( 'dropin' === $host ) {
    … …  
    352489                        // Never overwrite the code that is running this restore, and
    353490                        // never write into the backups folder.
    354                         $own_plugin = 'plugins/' . basename( dirname( SITEZIP_FILE ) ) . '/';
    355                         $top_level  = strtok( $relative, '/' );
    356                         if ( 0 === strpos( $relative, $own_plugin ) || preg_match( PathGuard::BACKUPS_FOLDER_PATTERN, $top_level ) ) {
     491                        $own_plugin = strtolower( 'plugins/' . basename( dirname( SITEZIP_FILE ) ) . '/' );
     492                        $top_level  = strtok( $lower, '/' );
     493                        if ( 0 === strpos( $lower, $own_plugin ) || preg_match( PathGuard::BACKUPS_FOLDER_PATTERN, $top_level ) ) {
    357494                                return null;
     495                        }
     496
     497                        if ( '' !== $this->code_root && in_array( $top_level, self::CODE_FOLDERS, true ) && false !== strpos( $relative, '/' ) ) {
     498                                return array(
     499                                        'path' => trailingslashit( $this->code_root ) . $relative,
     500                                        'root' => $this->code_root,
     501                                        'live' => trailingslashit( $content_root ) . $relative,
     502                                );
    358503                        }
    359504
  • sitezip/tags/1.0.1/includes/Restore/RestoreRunner.php

    r3800592 r3817595  
    3333
    3434        const TEMP_PREFIX = 'sbtmp_';
     35
     36        /** Longest SQL statement accepted from a dump (bytes). */
     37        const MAX_STATEMENT = 67108864;
     38
     39        /**
     40         * Words that may come before "(" in a CREATE TABLE from SHOW CREATE TABLE.
     41         */
     42        const CREATE_WORDS = array(
     43                'tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint', 'decimal', 'dec', 'numeric', 'fixed', 'float', 'double', 'real', 'bit',
     44                'char', 'varchar', 'binary', 'varbinary', 'tinytext', 'text', 'mediumtext', 'longtext', 'tinyblob', 'blob', 'mediumblob', 'longblob',
     45                'enum', 'set', 'datetime', 'timestamp', 'time', 'year', 'date',
     46                'key', 'index', 'unique', 'fulltext', 'spatial',
     47                'current_timestamp', 'now', 'localtime', 'localtimestamp', 'current_date', 'curdate', 'current_time', 'curtime', 'utc_timestamp', 'uuid',
     48                // MySQL 8 writes expression defaults as DEFAULT (...).
     49                'default',
     50                // MariaDB writes JSON columns as longtext with this check.
     51                'check', 'json_valid',
     52        );
    3553        const OLD_PREFIX  = 'sbold_';
    3654
    … …  
    105123                                        $result = $this->replace_step( $state, $job_id, $deadline );
    106124                                        break;
     125                                case 'code':
     126                                        $result = $this->code_step( $state, $job_id, $deadline );
     127                                        break;
    107128                                case 'swap':
    108129                                        $result = $this->swap( $state, $job_id );
    … …  
    179200                if ( is_multisite() || ! empty( $manifest['multisite'] ) ) {
    180201                        return new \WP_Error( 'sitezip_multisite', __( 'Restoring multisite networks is not supported.', 'sitezip' ) );
     202                }
     203                foreach ( array( 'prefix', 'home_url', 'site_url', 'content_dir', 'charset' ) as $field ) {
     204                        if ( isset( $manifest[ $field ] ) && ! is_string( $manifest[ $field ] ) ) {
     205                                return new \WP_Error( 'sitezip_manifest', __( 'The backup manifest is damaged.', 'sitezip' ) );
     206                        }
     207                }
     208                if ( isset( $manifest['smart'] ) && ( ! is_array( $manifest['smart'] ) || ! isset( $manifest['smart']['chain'], $manifest['smart']['tables'] ) || ! is_array( $manifest['smart']['chain'] ) || ! is_array( $manifest['smart']['tables'] ) ) ) {
     209                        return new \WP_Error( 'sitezip_manifest', __( 'The backup manifest is damaged.', 'sitezip' ) );
     210                }
     211                if ( empty( $manifest['home_url'] ) ) {
     212                        return new \WP_Error( 'sitezip_manifest', __( 'The backup manifest is damaged.', 'sitezip' ) );
    181213                }
    182214                if ( empty( $manifest['prefix'] ) || ! preg_match( '/^[A-Za-z0-9_]+$/', $manifest['prefix'] ) ) {
    … …  
    278310                }
    279311
    280                 $result = ( new ArchiveReader() )->extract_batch( $path, WP_CONTENT_DIR, $state['dir'] . 'sql', (int) $state['cursor'], $deadline, $state['dir'] . 'index.bin' );
     312                $result = ( new ArchiveReader() )->extract_batch( $path, WP_CONTENT_DIR, $state['dir'] . 'sql', (int) $state['cursor'], $deadline, $state['dir'] . 'index.bin', $state['dir'] . 'code' );
    281313                if ( is_wp_error( $result ) ) {
    282314                        return $result;
    … …  
    367399                $wpdb->query( "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'" );
    368400                if ( preg_match( '/^[A-Za-z0-9_]+$/', $state['manifest']['charset'] ) ) {
    369                         $wpdb->query( "SET NAMES '" . $state['manifest']['charset'] . "'" );
     401                        // Only single-byte-safe charsets: with gbk, big5, sjis and the like,
     402                        // MySQL and this plugin's checks could read a string differently.
     403                        $charset = in_array( strtolower( $state['manifest']['charset'] ), array( 'utf8mb4', 'utf8', 'utf8mb3', 'latin1' ), true ) ? $state['manifest']['charset'] : 'utf8mb4';
     404                        $wpdb->query( "SET NAMES '" . $charset . "'" );
    370405                }
    371406
    … …  
    392427
    393428                while ( microtime( true ) < $deadline ) {
    394                         $line = fgets( $handle );
     429                        $line = fgets( $handle, self::MAX_STATEMENT );
    395430                        if ( false === $line ) {
    396431                                $cursor['done'] += filesize( $file ) - (int) $cursor['pos'];
    … …  
    409444
    410445                        $statement .= $line;
     446                        // This plugin never writes a statement anywhere near this size.
     447                        if ( strlen( $statement ) > self::MAX_STATEMENT ) {
     448                                $wpdb->query( 'ROLLBACK' );
     449                                fclose( $handle );
     450                                return new \WP_Error( 'sitezip_sql_statement', __( 'The database dump contains an unexpected statement.', 'sitezip' ) );
     451                        }
    411452
    412453                        // Values are escaped by the same driver that replays them, so no
    … …  
    414455                        // ending in ";" is always a real statement boundary.
    415456                        if ( ';' !== substr( rtrim( $line, "\r\n" ), -1 ) ) {
     457                                continue;
     458                        }
     459
     460                        // This server's own job table is never taken from a backup.
     461                        if ( preg_match( '/^(?:DROP TABLE IF EXISTS|CREATE TABLE|INSERT INTO) `([A-Za-z0-9_]+)`/', $statement, $jm ) && $this->local_name( $jm[1], $state ) === JobStore::table() ) {
     462                                $new_pos         = ftell( $handle );
     463                                $cursor['done'] += $new_pos - (int) $cursor['pos'];
     464                                $cursor['pos']   = $new_pos;
     465                                $statement       = '';
    416466                                continue;
    417467                        }
    … …  
    497547                        );
    498548                        $sql = preg_replace( '/CONSTRAINT `[^`]*` (FOREIGN KEY)/', '$1', $sql );
     549                        $sql = $this->fit_server( $sql );
    499550                }
    500551
    501552                return $match[1] . ' `' . $temp . '`' . substr( $sql, strlen( $match[0] ) );
     553        }
     554
     555        /** @var array|null This server's character sets, collations and engines. */
     556        private $server = null;
     557
     558        /**
     559         * Make a CREATE TABLE from another kind of server work on this one.
     560         *
     561         * MySQL 8 writes utf8mb4_0900_ai_ci, which MariaDB does not know;
     562         * MariaDB 11 writes utf8mb4_uca1400_ai_ci and utf8mb3, which MySQL does
     563         * not know; MariaDB's Aria engine does not exist on MySQL. Anything
     564         * this server lacks is swapped for the closest thing it has.
     565         *
     566         * @param string $sql CREATE TABLE statement.
     567         * @return string
     568         */
     569        private function fit_server( $sql ) {
     570                global $wpdb;
     571                if ( null === $this->server ) {
     572                        $this->server = array(
     573                                'cs'    => array(),
     574                                'co'    => array(),
     575                                'en'    => array(),
     576                                'maria' => false !== stripos( (string) $wpdb->get_var( 'SELECT VERSION()' ), 'mariadb' ),
     577                        );
     578                        foreach ( (array) $wpdb->get_col( 'SHOW CHARACTER SET', 0 ) as $v ) {
     579                                $this->server['cs'][ strtolower( $v ) ] = true;
     580                        }
     581                        foreach ( (array) $wpdb->get_col( 'SHOW COLLATION', 0 ) as $v ) {
     582                                $this->server['co'][ strtolower( $v ) ] = true;
     583                        }
     584                        foreach ( (array) $wpdb->get_results( 'SHOW ENGINES', ARRAY_N ) as $row ) {
     585                                if ( isset( $row[0], $row[1] ) && in_array( strtoupper( $row[1] ), array( 'YES', 'DEFAULT' ), true ) ) {
     586                                        $this->server['en'][ strtolower( $row[0] ) ] = true;
     587                                }
     588                        }
     589                }
     590                $srv = $this->server;
     591                // Could not read what the server supports: leave the statement as is.
     592                if ( ! $srv['cs'] || ! $srv['co'] ) {
     593                        return $sql;
     594                }
     595
     596                $charset = function ( $cs ) use ( $srv ) {
     597                        $cs = strtolower( $cs );
     598                        if ( isset( $srv['cs'][ $cs ] ) ) {
     599                                return $cs;
     600                        }
     601                        if ( in_array( $cs, array( 'utf8mb3', 'utf8' ), true ) ) {
     602                                return isset( $srv['cs']['utf8mb3'] ) ? 'utf8mb3' : 'utf8';
     603                        }
     604                        return 'utf8mb4';
     605                };
     606
     607                $sql = preg_replace_callback(
     608                        '/\b(CHARACTER SET|CHARSET)(\s*=?\s*)([A-Za-z0-9_]+)/i',
     609                        function ( $m ) use ( $charset ) {
     610                                return $m[1] . $m[2] . $charset( $m[3] );
     611                        },
     612                        $sql
     613                );
     614
     615                $sql = preg_replace_callback(
     616                        '/\bCOLLATE(\s*=?\s*)([A-Za-z0-9_]+)/i',
     617                        function ( $m ) use ( $srv, $charset ) {
     618                                $co = strtolower( $m[2] );
     619                                if ( isset( $srv['co'][ $co ] ) ) {
     620                                        return $m[0];
     621                                }
     622                                $cs   = $charset( strtok( $co, '_' ) );
     623                                $tail = substr( $co, strpos( $co, '_' ) );
     624                                $try  = array( $cs . $tail, $cs . '_unicode_520_ci', $cs . '_unicode_ci', $cs . '_general_ci' );
     625                                // A binary collation stays binary.
     626                                if ( '_bin' === substr( $co, -4 ) ) {
     627                                        array_unshift( $try, $cs . '_bin' );
     628                                }
     629                                foreach ( $try as $c ) {
     630                                        if ( isset( $srv['co'][ $c ] ) ) {
     631                                                return 'COLLATE' . $m[1] . $c;
     632                                        }
     633                                }
     634                                return 'COLLATE' . $m[1] . 'utf8mb4_general_ci';
     635                        },
     636                        $sql
     637                );
     638
     639                // MariaDB writes "DEFAULT uuid()"; MySQL needs "DEFAULT (uuid())".
     640                if ( ! $srv['maria'] ) {
     641                        $sql = preg_replace( '/\bDEFAULT\s+(?!(?:current_timestamp|now|localtime|localtimestamp)\s*\()([A-Za-z_]+\(\))/i', 'DEFAULT ($1)', $sql );
     642                }
     643
     644                if ( $srv['en'] && preg_match( '/\bENGINE\s*=\s*([A-Za-z0-9_]+)/i', $sql, $m ) && ! isset( $srv['en'][ strtolower( $m[1] ) ] ) ) {
     645                        $sql = str_replace( $m[0], 'ENGINE=InnoDB', $sql );
     646                        // Aria-only table options.
     647                        $sql = preg_replace( '/\s(?:PAGE_CHECKSUM|TRANSACTIONAL)\s*=\s*[01]\b/i', '', $sql );
     648                }
     649
     650                return $sql;
    502651        }
    503652
    … …  
    516665         */
    517666        public static function is_safe_statement( $type, $sql ) {
     667                if ( ! is_string( $sql ) ) {
     668                        return false;
     669                }
    518670                $bare = self::strip_strings( $sql );
    519671                if ( false === $bare ) {
    … …  
    546698                }
    547699
    548                 // CREATE TABLE, as written by SHOW CREATE TABLE.
    549                 return ! preg_match( '/\b(?:SELECT|UNION|LOAD_FILE|DATA\s+DIRECTORY|INDEX\s+DIRECTORY|CONNECTION|INTO\s+(?:OUT|DUMP)FILE)\b|ENGINE\s*=\s*(?:FEDERATED|CONNECT|MERGE|MRG_MYISAM)\b/i', $bare );
     700                // CREATE TABLE, as written by SHOW CREATE TABLE: column definitions,
     701                // keys and table options only. Names are blanked so they cannot hide
     702                // words, then nothing that runs code or reads data may remain.
     703                $body = substr( preg_replace( '/`(?:[^`]|``)*`/', '``', $bare ), strlen( 'CREATE TABLE ``' ) );
     704                if ( preg_match( '/\b(?:SELECT|UNION|TABLE|VALUES|ROW|WITH|AS|LOAD_FILE|DATA\s+DIRECTORY|INDEX\s+DIRECTORY|CONNECTION|INTO|PARTITION|SLEEP|BENCHMARK)\b|ENGINE\s*=\s*(?:FEDERATED|CONNECT|MERGE|MRG_MYISAM)\b/i', $body ) ) {
     705                        return false;
     706                }
     707                // Every "word(" must be a column type, a key, or the current time:
     708                // no other function (and so no expression default) is accepted.
     709                preg_match_all( '/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/', $body, $calls );
     710                foreach ( $calls[1] as $word ) {
     711                        if ( ! in_array( strtolower( $word ), self::CREATE_WORDS, true ) ) {
     712                                return false;
     713                        }
     714                }
     715                return true;
    550716        }
    551717
    … …  
    563729                $i   = 0;
    564730                while ( $i < $n ) {
    565                         $j    = strcspn( $sql, "'", $i );
     731                        $j    = strcspn( $sql, "'`\"#/-", $i );
    566732                        $out .= substr( $sql, $i, $j );
    567733                        $i   += $j;
    … …  
    569735                                break;
    570736                        }
     737                        $c = $sql[ $i ];
     738                        if ( '"' === $c || '#' === $c ) {
     739                                // This plugin's dumps never use either outside a string or a
     740                                // name; MySQL would read them as a string or a comment.
     741                                return false;
     742                        }
     743                        if ( '/' === $c || '-' === $c ) {
     744                                $pair = substr( $sql, $i, 2 );
     745                                if ( '/*' === $pair || '--' === $pair ) {
     746                                        return false;
     747                                }
     748                                $out .= $c;
     749                                ++$i;
     750                                continue;
     751                        }
     752                        if ( '`' === $c ) {
     753                                // A name: kept as written, its content never read as SQL.
     754                                $end = $i + 1;
     755                                while ( true ) {
     756                                        $end += strcspn( $sql, '`', $end );
     757                                        if ( $end >= $n ) {
     758                                                return false;
     759                                        }
     760                                        if ( $end + 1 < $n && '`' === $sql[ $end + 1 ] ) {
     761                                                $end += 2;
     762                                                continue;
     763                                        }
     764                                        break;
     765                                }
     766                                $out .= substr( $sql, $i, $end - $i + 1 );
     767                                $i    = $end + 1;
     768                                continue;
     769                        }
     770                        // A string: replaced by '' so its content is never read as SQL.
    571771                        $out .= "''";
    572772                        ++$i;
    … …  
    630830                $pairs = array();
    631831                foreach ( array( 'home_url', 'site_url', 'content_dir' ) as $key ) {
    632                         $old = untrailingslashit( (string) $state['manifest'][ $key ] );
    633                         $new = untrailingslashit( (string) $state['target'][ $key ] );
    634                         if ( '' === $old || $old === $new ) {
    635                                 continue;
    636                         }
    637                         $pairs[ $old ] = $new;
    638                         // The same value as it appears inside JSON.
    639                         $pairs[ str_replace( '/', '\\/', $old ) ] = str_replace( '/', '\\/', $new );
     832                        $pairs += SearchReplace::pairs_for(
     833                                untrailingslashit( (string) $state['manifest'][ $key ] ),
     834                                untrailingslashit( (string) $state['target'][ $key ] ),
     835                                'content_dir' !== $key
     836                        );
    640837                }
    641838
    … …  
    653850
    654851                if ( $result['done'] ) {
    655                         $state['stage']  = 'swap';
     852                        $state['stage']  = 'code';
    656853                        $state['cursor'] = array();
    657854                        if ( ! $replacer->is_empty() ) {
    … …  
    673870
    674871        /**
     872         * Move the staged plugins, themes and must-use plugins into place.
     873         *
     874         * Runs straight before the database swap, so the new code and the new
     875         * database go live within the same request.
     876         *
     877         * @param array $state    Job state.
     878         * @param int   $job_id   Job ID.
     879         * @param float $deadline Stop-by timestamp.
     880         * @return true
     881         */
     882        private function code_step( array &$state, $job_id, $deadline ) {
     883                // Check everything the swap needs before any live code changes, so
     884                // a restore that cannot finish leaves the site's plugins as they were.
     885                if ( empty( $state['code_checked'] ) ) {
     886                        $ready = $this->swap_ready( $state );
     887                        if ( is_wp_error( $ready ) ) {
     888                                return $ready;
     889                        }
     890                        $state['code_checked'] = true;
     891                }
     892
     893                $result = ArchiveReader::move_staged( $state['dir'] . 'code', WP_CONTENT_DIR, $deadline );
     894
     895                $state['code_moved'] = ( isset( $state['code_moved'] ) ? (int) $state['code_moved'] : 0 ) + $result['moved'];
     896                if ( $result['rejected'] ) {
     897                        $this->store->log(
     898                                $job_id,
     899                                sprintf(
     900                                        /* translators: %d: number of files. */
     901                                        __( 'Could not put %d plugin or theme files in place.', 'sitezip' ),
     902                                        $result['rejected']
     903                                )
     904                        );
     905                }
     906                if ( $result['done'] ) {
     907                        $state['stage']    = 'swap';
     908                        $state['progress'] = 99;
     909                        if ( $state['code_moved'] ) {
     910                                $this->store->log(
     911                                        $job_id,
     912                                        sprintf(
     913                                                /* translators: %s: number of files. */
     914                                                __( 'Plugins and themes put in place (%s files).', 'sitezip' ),
     915                                                number_format_i18n( $state['code_moved'] )
     916                                        )
     917                                );
     918                        }
     919                }
     920
     921                return true;
     922        }
     923
     924        /**
     925         * Whether the imported database is complete enough to swap in.
     926         *
     927         * @param array $state Job state.
     928         * @return true|\WP_Error
     929         */
     930        private function swap_ready( array $state ) {
     931                global $wpdb;
     932
     933                $prefix = $state['target']['prefix'];
     934                if ( empty( $state['tables'][ $prefix . 'options' ] ) ) {
     935                        return new \WP_Error( 'sitezip_no_options', __( 'The backup database has no options table, so it cannot be restored.', 'sitezip' ) );
     936                }
     937
     938                $existing = array_flip( (array) $wpdb->get_col( 'SHOW TABLES' ) );
     939                foreach ( array_keys( $state['tables'] ) as $real ) {
     940                        if ( ! isset( $existing[ self::TEMP_PREFIX . $real ] ) ) {
     941                                return new \WP_Error(
     942                                        'sitezip_missing_temp',
     943                                        sprintf(
     944                                                /* translators: %s: table name. */
     945                                                __( 'The imported copy of %s is missing.', 'sitezip' ),
     946                                                $real
     947                                        )
     948                                );
     949                        }
     950                }
     951
     952                return true;
     953        }
     954
     955        /**
    675956         * Fix prefix-dependent rows, then swap every table in at once.
    676957         *
    … …  
    705986                }
    706987
     988                // This site's own address, whatever the dump says: a doctored backup
     989                // must not be able to send the site (or its health check) elsewhere.
     990                $wpdb->update( $options, array( 'option_value' => $state['target']['home_url'] ), array( 'option_name' => 'home' ) );
     991                $wpdb->update( $options, array( 'option_value' => $state['target']['site_url'] ), array( 'option_name' => 'siteurl' ) );
     992
    707993                // Locks and cron claims copied from the source site mean nothing here.
    708994                $wpdb->query( "DELETE FROM `{$options}` WHERE option_name LIKE 'sitezip\\_lock\\_%' OR option_name IN ('_transient_doing_cron', 'core_updater.lock')" );
  • sitezip/tags/1.0.1/includes/Restore/SearchReplace.php

    r3800592 r3817595  
    4949
    5050        /**
     51         * Search => replacement pairs that move one value to another.
     52         *
     53         * A site's content often holds its address in more than one form:
     54         * Local and many hosts save http:// links on an https:// site or the
     55         * other way round, and themes write protocol-relative //host URLs.
     56         * Every form is pointed at the new address; strtr() tries the longest
     57         * search first, so a full URL never gets half-replaced by the shorter
     58         * //host form. Each pair is added again as it appears inside JSON.
     59         *
     60         * @param string $old    Old value, no trailing slash.
     61         * @param string $new    New value, no trailing slash.
     62         * @param bool   $is_url Whether the values are URLs.
     63         * @return array
     64         */
     65        public static function pairs_for( $old, $new, $is_url ) {
     66                if ( '' === $old || $old === $new ) {
     67                        return array();
     68                }
     69
     70                $pairs = array( $old => $new );
     71                if ( $is_url && preg_match( '#^https?:(//.+)$#i', $old, $m ) ) {
     72                        $new_relative = preg_replace( '#^https?:#i', '', $new );
     73                        $pairs        = array(
     74                                'http:' . $m[1]  => $new,
     75                                'https:' . $m[1] => $new,
     76                                $m[1]            => $new_relative,
     77                        );
     78                }
     79
     80                foreach ( $pairs as $search => $replace ) {
     81                        $pairs[ str_replace( '/', '\\/', $search ) ] = str_replace( '/', '\\/', $replace );
     82                }
     83
     84                // An unchanged pair (same host, only the scheme differs) is harmless
     85                // but would make every row look like a match.
     86                foreach ( $pairs as $search => $replace ) {
     87                        if ( $search === $replace ) {
     88                                unset( $pairs[ $search ] );
     89                        }
     90                }
     91
     92                return $pairs;
     93        }
     94
     95        /**
    5196         * Whether there is anything to replace.
    5297         *
    … …  
    67112         * @return string
    68113         */
     114        /** @var int How deep inside nested serialized strings we are. */
     115        private $depth = 0;
     116
    69117        public function replace_value( $value ) {
    70118                if ( ! $this->contains_search( $value ) ) {
    71119                        return $value;
    72120                }
    73                 if ( $this->looks_serialized( $value ) ) {
    74                         return $this->replace_serialized( $value );
     121                // Serialized data nested this deep is not real; stop recursing.
     122                if ( $this->depth < 64 && $this->looks_serialized( $value ) ) {
     123                        ++$this->depth;
     124                        $out = $this->replace_serialized( $value );
     125                        --$this->depth;
     126                        return $out;
    75127                }
    76128
  • sitezip/tags/1.0.1/includes/Security/DownloadLinks.php

    r3800592 r3817595  
    1212/**
    1313 * A link is made only when an administrator clicks Download. It is tied to
    14  * one file and one user, works once, and expires after two minutes. Only a
    15  * hash of the token is stored, so reading the database does not reveal a
     14 * one file and one user and must be started within two minutes. Once
     15 * started it keeps working for that user for a while, so the browser can
     16 * resume a multi-gigabyte download after a dropped connection. Only a hash
     17 * of the token is stored, so reading the database does not reveal a
    1618 * usable link.
    1719 */
    … …  
    2224         */
    2325        const TTL = 120;
     26
     27        /**
     28         * Seconds a started link keeps working, for resumed downloads.
     29         */
     30        const RESUME_TTL = 43200;
    2431
    2532        /**
    … …  
    5057
    5158        /**
    52          * Use up a token. Returns its file name, or false if the token is
    53          * unknown, expired, already used, or belongs to someone else.
     59         * Redeem a token. Returns its file name, or false if the token is
     60         * unknown, expired, or belongs to someone else. The first use starts
     61         * the resume window; later uses (a browser resuming) keep working
     62         * until it ends.
    5463         *
    5564         * @param string $token   Token from the URL.
    … …  
    5766         * @return string|false
    5867         */
    59         public static function consume( $token, $user_id ) {
     68        public static function redeem( $token, $user_id ) {
    6069                if ( ! is_string( $token ) || ! preg_match( '/^[a-f0-9]{64}$/', $token ) ) {
    6170                        return false;
    … …  
    6675                        return false;
    6776                }
    68 
    69                 // Deleting is the gate: if two requests race, only the one that
    70                 // actually removes the token may continue.
    71                 if ( ! delete_transient( $key ) ) {
     77                if ( ! $user_id || (int) $data['user'] !== (int) $user_id ) {
    7278                        return false;
    7379                }
    74                 if ( (int) $data['user'] !== (int) $user_id || ! $user_id ) {
    75                         return false;
     80                if ( empty( $data['started'] ) ) {
     81                        $data['started'] = time();
     82                        set_transient( $key, $data, self::RESUME_TTL );
    7683                }
    7784
  • sitezip/tags/1.0.1/includes/Security/PathGuard.php

    r3800592 r3817595  
    182182                        return new \WP_Error( 'sitezip_mkdir', __( 'Could not create a temporary folder for this job.', 'sitezip' ) );
    183183                }
     184                // Holds database dumps while a job runs: same deny rules as the parent.
     185                self::protect( $dir );
    184186
    185187                return trailingslashit( $dir );
  • sitezip/tags/1.0.1/readme.txt

    r3800592 r3817595  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.0.0
     7Stable tag: 1.0.1
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    6666== Changelog ==
    6767
     68= 1.0.1 =
     69* New: restore a backup made on MySQL onto MariaDB, and the other way round. Collations, table engines and column defaults the other server does not understand are converted automatically.
     70* New: Copy debug report button, and the restore screen shows which step it is on.
     71* Improved: plugin and theme code is staged and the database is checked before any code is replaced, so a failed restore leaves the site as it was.
     72* Improved: the old site address is replaced in every form (http, https, escaped), not only the one saved in the backup.
     73* Improved: Backup contents now shows what is in the backup and what is left out, with sizes and file counts.
     74* Fix: large backup downloads no longer fail part way; downloads can resume.
     75* Security: restore accepts only the exact database statements SiteZip writes, and only safe character sets.
     76* Security: a restored backup can no longer change this site's address.
     77* Security: plugin and theme files are always rewritten on restore, never skipped as "unchanged".
     78* Security: damaged or doctored backup files are rejected cleanly instead of using up memory.
     79* Security: backup file names are harder to guess, and the temporary folder is protected from web access.
     80
    6881= 1.0.0 =
    6982* First release.
  • sitezip/tags/1.0.1/sitezip.php

    r3800592 r3817595  
    33 * Plugin Name:       SiteZip – Backup & Restore
    44 * Description:       Simple full-site backup, export and import: database and wp-content compressed into one .zip of any size, with safe restore.
    5  * Version:           1.0.0
     5 * Version:           1.0.1
    66 * Requires at least: 5.8
    77 * Requires PHP:      7.4
    … …  
    1717defined( 'ABSPATH' ) || exit;
    1818
    19 define( 'SITEZIP_VERSION', '1.0.0' );
     19define( 'SITEZIP_VERSION', '1.0.1' );
    2020define( 'SITEZIP_FILE', __FILE__ );
    2121define( 'SITEZIP_DIR', plugin_dir_path( __FILE__ ) );
  • sitezip/tags/1.0.1/uninstall.php

    r3800592 r3817595  
    2525
    2626wp_unschedule_hook( 'sitezip_run_job' );
     27
     28// The restore guard, if a restore was running when SiteZip was removed.
     29if ( defined( 'WPMU_PLUGIN_DIR' ) && is_file( WPMU_PLUGIN_DIR . '/sitezip-restore-guard.php' ) ) {
     30        wp_delete_file( WPMU_PLUGIN_DIR . '/sitezip-restore-guard.php' );
     31}
  • sitezip/trunk/admin/css/admin.css

    r3800592 r3817595  
    490490/* Measuring: each part lights up in turn while a sheen sweeps across, like a scan. */
    491491.sitezip-bar.is-loading {
     492        /* Keep the sweeping sheen inside the bar, not across the card edge. */
     493        border-radius: 4px;
     494        overflow: hidden;
    492495        position: relative;
    493496}
  • sitezip/trunk/admin/js/app.js

    r3800592 r3817595  
    6161                        'import': __( 'Importing database', 'sitezip' ),
    6262                        replace: __( 'Updating site address', 'sitezip' ),
     63                        code: __( 'Putting plugins and themes in place', 'sitezip' ),
    6364                        swap: __( 'Switching database', 'sitezip' ),
    6465                        done: __( 'Done', 'sitezip' )
    … …  
    733734                                                } );
    734735                                        }
    735                                 }, [ job.type === 'restore' ? __( 'Cancel restore', 'sitezip' ) : __( 'Cancel backup', 'sitezip' ) ] )
     736                                }, [ job.type === 'restore' ? __( 'Cancel restore', 'sitezip' ) : __( 'Cancel backup', 'sitezip' ) ] ),
     737                                debugButton( 'button' )
    736738                        ]
    737739                } );
    … …  
    13221324
    13231325        /**
    1324          * Ask the server for a one-time link, then start the download with it.
    1325          * The link works once, for this user, for two minutes.
     1326         * Ask the server for a link, then start the download with it. It must
     1327         * be started within two minutes; after that it keeps working for this
     1328         * user so the browser can resume a large download.
    13261329         */
    13271330        function startDownload( backup, button ) {
    … …  
    18561859        }
    18571860
    1858         function copyText( text ) {
     1861        /**
     1862         * A button that copies a full debug report (server facts, loopback
     1863         * tests, the latest job's log and exact position) for a support request.
     1864         */
     1865        function debugButton( cls ) {
     1866                return el( 'button', {
     1867                        type: 'button',
     1868                        class: cls,
     1869                        onClick: function ( e ) {
     1870                                var btn = e.currentTarget;
     1871                                btn.disabled = true;
     1872                                request( '/diagnostics' ).then( function ( data ) {
     1873                                        copyText(
     1874                                                'SiteZip debug report — ' + new Date().toISOString() + '\n' +
     1875                                                'Browser: ' + window.navigator.userAgent + '\n\n' +
     1876                                                JSON.stringify( data, null, 2 ),
     1877                                                __( 'Debug report copied. Paste it into your support request.', 'sitezip' )
     1878                                        );
     1879                                } ).then( function () {
     1880                                        btn.disabled = false;
     1881                                }, function () {
     1882                                        btn.disabled = false;
     1883                                } );
     1884                        }
     1885                }, [ __( 'Copy debug report', 'sitezip' ) ] );
     1886        }
     1887
     1888        function copyText( text, message ) {
    18591889                var done = function () {
    1860                         notify( __( 'Log copied.', 'sitezip' ) );
     1890                        notify( message || __( 'Log copied.', 'sitezip' ) );
    18611891                };
    18621892                if ( window.navigator.clipboard && window.isSecureContext ) {
    … …  
    18931923                                        }
    18941924                                }, [ __( 'Copy all', 'sitezip' ) ] ) : null,
     1925                                debugButton( 'button-link sitezip-copy' ),
    18951926                                el( 'button', { type: 'button', class: 'sitezip-toast-close', 'aria-label': __( 'Close', 'sitezip' ), onClick: function () { toggleActivity( false ); } }, [ '×' ] )
    18961927                        ] )
  • sitezip/trunk/includes/Admin/AdminPage.php

    r3800592 r3817595  
    235235         */
    236236        private function deactivate_assets() {
    237                 $backups = BackupStore::all();
    238                 $folder  = PathGuard::find_backups_dir();
    239                 $bytes   = 0;
    240                 foreach ( $backups as $backup ) {
    241                         $bytes += (int) $backup['size'];
    242                 }
     237                // Only a count and a size: never open every archive on the Plugins screen.
     238                list( $count, $bytes ) = BackupStore::totals();
     239                $folder                = PathGuard::find_backups_dir();
    243240
    244241                wp_enqueue_style( 'sitezip-deactivate', SITEZIP_URL . 'admin/css/admin.css', array(), SITEZIP_VERSION . '.' . filemtime( SITEZIP_DIR . 'admin/css/admin.css' ) );
    … …  
    251248                                'plugin'  => plugin_basename( SITEZIP_FILE ),
    252249                                'nonce'   => wp_create_nonce( Plugin::PURGE_NONCE ),
    253                                 'count'   => count( $backups ),
     250                                'count'   => $count,
    254251                                'size'    => size_format( $bytes ),
    255252                                'folder'  => $folder ? 'wp-content/' . basename( $folder ) : 'wp-content',
    … …  
    317314         * The backups folder is denied to the web server, so this is the only
    318315         * way to fetch an archive. It needs an administrator's login and a
    319          * one-time link made seconds earlier by the Download button (see
    320          * DownloadLinks): the link works once, for that user, for two minutes.
     316         * link made seconds earlier by the Download button (see DownloadLinks):
     317         * it must be first used within two minutes, by that user, and then
     318         * keeps working for 12 hours so a big download can resume.
    321319         *
    322320         * @return void
    … …  
    328326
    329327                $token = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- the one-time token is stronger than a nonce.
    330                 $file  = DownloadLinks::consume( $token, get_current_user_id() );
     328                $file  = DownloadLinks::redeem( $token, get_current_user_id() );
    331329                if ( false === $file ) {
    332330                        wp_die(
    … …  
    355353                }
    356354
     355                clearstatcache( true, $path );
     356                $size  = (int) filesize( $path );
     357                $start = 0;
     358                $end   = $size - 1;
     359
     360                // Resume: answer "Range: bytes=START-[END]" with just that part, so
     361                // a dropped multi-gigabyte download continues instead of failing.
     362                $range = isset( $_SERVER['HTTP_RANGE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_RANGE'] ) ) : '';
     363                if ( '' !== $range ) {
     364                        if ( ! preg_match( '/^bytes=(\d*)-(\d*)$/', trim( $range ), $m ) || ( '' === $m[1] && '' === $m[2] ) ) {
     365                                $m = null;
     366                        } elseif ( '' === $m[1] ) {
     367                                $start = max( 0, $size - (int) $m[2] ); // Last N bytes.
     368                        } else {
     369                                $start = (int) $m[1];
     370                                $end   = '' === $m[2] ? $end : min( $end, (int) $m[2] );
     371                        }
     372                        if ( ! $m || $start > $end || $start >= $size ) {
     373                                status_header( 416 );
     374                                header( 'Content-Range: bytes */' . $size );
     375                                exit;
     376                        }
     377                        status_header( 206 );
     378                        header( 'Content-Range: bytes ' . $start . '-' . $end . '/' . $size );
     379                }
     380
    357381                nocache_headers();
    358382                header( 'Content-Type: application/zip' );
    359383                header( 'Content-Disposition: attachment; filename="' . str_replace( array( '"', "\r", "\n" ), '', basename( $path ) ) . '"' );
    360                 header( 'Content-Length: ' . filesize( $path ) );
     384                header( 'Content-Length: ' . ( $end - $start + 1 ) );
     385                header( 'Accept-Ranges: bytes' );
     386                // Same file, same validator: lets the browser check a resume matches.
     387                header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', (int) filemtime( $path ) ) . ' GMT' );
    361388                header( 'X-Content-Type-Options: nosniff' );
    362389                header( 'Referrer-Policy: no-referrer' );
    363390                header( 'X-Robots-Tag: noindex, nofollow' );
     391                // Stop nginx and similar proxies from buffering gigabytes first.
     392                header( 'X-Accel-Buffering: no' );
    364393
    365394                $handle = fopen( $path, 'rb' );
    366395                if ( $handle ) {
    367                         while ( ! feof( $handle ) && ! connection_aborted() ) {
    368                                 echo fread( $handle, 4194304 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary file download.
     396                        fseek( $handle, $start );
     397                        $left = $end - $start + 1;
     398                        while ( $left > 0 && ! feof( $handle ) && ! connection_aborted() ) {
     399                                $chunk = fread( $handle, (int) min( 4194304, $left ) );
     400                                if ( false === $chunk || '' === $chunk ) {
     401                                        break;
     402                                }
     403                                $left -= strlen( $chunk );
     404                                echo $chunk; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary file download.
    369405                                flush();
    370406                        }
  • sitezip/trunk/includes/Backup/BackupStore.php

    r3800592 r3817595  
    136136                $site  = self::sanitize_name( $site );
    137137
    138                 return ( '' !== $site ? $site : 'site' ) . '-' . wp_date( 'Y-m-d-His' );
     138                // A random ending, so backup names cannot be guessed from the date.
     139                return ( '' !== $site ? $site : 'site' ) . '-' . wp_date( 'Y-m-d-His' ) . '-' . bin2hex( random_bytes( 3 ) );
    139140        }
    140141
    … …  
    226227
    227228        /**
    228          * Every archive in the backups folder, newest first.
    229          *
    230          * @return array[]
     229         * How many backups there are and their total size, without opening any.
     230         *
     231         * @return array [ count, bytes ].
     232         */
     233        public static function totals() {
     234                $dir   = PathGuard::backups_dir();
     235                $count = 0;
     236                $bytes = 0;
     237                if ( ! is_wp_error( $dir ) ) {
     238                        foreach ( (array) @scandir( $dir ) as $file ) {
     239                                if ( self::is_valid_filename( $file ) && is_file( $dir . $file ) && ! is_link( $dir . $file ) ) {
     240                                        ++$count;
     241                                        $bytes += (int) filesize( $dir . $file );
     242                                }
     243                        }
     244                }
     245                return array( $count, $bytes );
     246        }
     247
     248        /**
     249         * Every backup in the folder, newest first, with manifest details.
     250         *
     251         * @return array
    231252         */
    232253        public static function all() {
    … …  
    256277                                'size'     => $size,
    257278                                'modified' => gmdate( 'c', $mtime ),
    258                                 'created'  => ( $manifest && ! empty( $manifest['created'] ) ) ? $manifest['created'] : gmdate( 'c', $mtime ),
    259                                 'site_url' => ( $manifest && ! empty( $manifest['home_url'] ) ) ? $manifest['home_url'] : '',
     279                                // From inside the zip: only well-formed strings reach the page.
     280                                'created'  => ( $manifest && ! empty( $manifest['created'] ) && is_string( $manifest['created'] ) && false !== strtotime( $manifest['created'] ) ) ? $manifest['created'] : gmdate( 'c', $mtime ),
     281                                'site_url' => ( $manifest && ! empty( $manifest['home_url'] ) && is_string( $manifest['home_url'] ) ) ? esc_url_raw( $manifest['home_url'] ) : '',
    260282                                'valid'    => (bool) $manifest,
    261283                                'options'  => ( $manifest && ! empty( $manifest['options'] ) && is_array( $manifest['options'] ) ) ? $manifest['options'] : null,
  • sitezip/trunk/includes/Backup/JobRunner.php

    r3800592 r3817595  
    199199                        return new \WP_Error( 'sitezip_job', __( 'Could not create the restore job.', 'sitezip' ) );
    200200                }
     201                \SiteZip\Restore\RestoreGuard::install();
    201202
    202203                $this->store->log(
    … …  
    592593
    593594                if ( 'restore' === $job['type'] ) {
     595                        \SiteZip\Restore\RestoreGuard::remove();
    594596                        $this->check_site( $job_id, isset( $job['state']['dropins_skipped'] ) ? (array) $job['state']['dropins_skipped'] : array() );
    595597                }
    … …  
    685687
    686688                if ( 'restore' === $job['type'] ) {
     689                        \SiteZip\Restore\RestoreGuard::remove();
    687690                        RestoreRunner::drop_temp_tables();
    688691                        return;
  • sitezip/trunk/includes/Backup/Source/DatabaseSource.php

    r3800592 r3817595  
    251251                        return "`comment_id` NOT IN (SELECT `comment_ID` FROM `{$wpdb->comments}` WHERE `comment_approved` IN ('spam','trash'))";
    252252                }
    253                 if ( ! empty( $o['skip_transients'] ) && $table === $wpdb->options ) {
    254                         return "`option_name` NOT LIKE '\\_transient\\_%' AND `option_name` NOT LIKE '\\_site\\_transient\\_%'";
     253                if ( $table === $wpdb->options ) {
     254                        // Cloud keys, the Google sign-in and its tokens belong to this
     255                        // site, never in a backup file that may be shared or moved.
     256                        $secret = "`option_name` NOT IN ('sitezip_cloud','sitezip_gdrive_folders','sitezip_cloud_tune') AND `option_name` NOT LIKE '\\_transient\\_sitezip\\_g%' AND `option_name` NOT LIKE '\\_transient\\_timeout\\_sitezip\\_g%'";
     257                        if ( ! empty( $o['skip_transients'] ) ) {
     258                                return $secret . " AND `option_name` NOT LIKE '\\_transient\\_%' AND `option_name` NOT LIKE '\\_site\\_transient\\_%'";
     259                        }
     260                        return $secret;
    255261                }
    256262
  • sitezip/trunk/includes/Plugin.php

    r3800592 r3817595  
    7171                add_action( 'wp_ajax_nopriv_sitezip_ping', array( __CLASS__, 'pong' ) );
    7272                add_action( 'sitezip_run_job', array( $this, 'handle_cron' ), 10, 1 );
     73                add_action( 'admin_init', array( '\\SiteZip\\Restore\\RestoreGuard', 'sweep' ) );
    7374        }
    7475
    … …  
    135136        public static function deactivate() {
    136137                wp_unschedule_hook( 'sitezip_run_job' );
     138                \SiteZip\Restore\RestoreGuard::remove();
    137139
    138140                // phpcs:disable WordPress.Security.NonceVerification.Recommended -- verified immediately below.
  • sitezip/trunk/includes/Rest/RestController.php

    r3800592 r3817595  
    495495                                'cron_next'      => wp_next_scheduled( 'sitezip_run_job', array( (int) $job['id'] ) ),
    496496                                'log_tail'       => array_slice( $log, -15 ),
     497                                'position'       => self::job_position( $job ),
    497498                        );
    498499                }
    … …  
    535536
    536537        /**
     538         * Where a job is inside its work: stage cursor, byte counts and, while
     539         * files are being unpacked, the archive entry it is on. A restore that
     540         * stalls at the same percent is almost always stuck on that one entry.
     541         *
     542         * @param array $job Job row.
     543         * @return array
     544         */
     545        private static function job_position( array $job ) {
     546                $state = is_array( $job['state'] ) ? $job['state'] : array();
     547                $out   = array();
     548                foreach ( array( 'file', 'stage', 'cursor', 'entries', 'bytes_done', 'bytes_total', 'dropins_skipped' ) as $key ) {
     549                        if ( isset( $state[ $key ] ) ) {
     550                                $out[ $key ] = $state[ $key ];
     551                        }
     552                }
     553                if ( isset( $state['tables'] ) && is_array( $state['tables'] ) ) {
     554                        $out['tables_imported'] = count( $state['tables'] );
     555                }
     556                if ( isset( $state['manifest']['home_url'] ) ) {
     557                        $out['backup_of'] = $state['manifest']['home_url'];
     558                }
     559
     560                if ( 'restore' === $job['type'] && 'extract' === $job['stage'] && isset( $state['file'], $state['cursor'] ) && is_numeric( $state['cursor'] ) && class_exists( '\ZipArchive' ) ) {
     561                        $path = BackupStore::path( $state['file'] );
     562                        $zip  = new \ZipArchive();
     563                        if ( ! is_wp_error( $path ) && true === $zip->open( $path ) ) {
     564                                $stat = $zip->statIndex( (int) $state['cursor'] );
     565                                if ( $stat ) {
     566                                        $out['current_entry'] = array(
     567                                                'name'            => $stat['name'],
     568                                                'size'            => size_format( (int) $stat['size'] ),
     569                                                'compressed_size' => size_format( (int) $stat['comp_size'] ),
     570                                        );
     571                                }
     572                                $zip->close();
     573                        }
     574                }
     575
     576                return $out;
     577        }
     578
     579        /**
    537580         * Poll a job.
    538581         *
  • sitezip/trunk/includes/Restore/ArchiveReader.php

    r3800592 r3817595  
    3333
    3434        /**
     35         * Staging folder for code, or ''.
     36         *
     37         * @var string
     38         */
     39        private $code_root = '';
     40
     41        /**
     42         * Top-level wp-content folders holding code the running site executes.
     43         *
     44         * Their files are unpacked into a staging folder and only moved into
     45         * place at the end. Written in place, a plugin caught half way (new
     46         * files next to old ones from a different version) fatals every
     47         * request to the site, including the ones driving this restore.
     48         */
     49        const CODE_FOLDERS = array( 'plugins', 'themes', 'mu-plugins' );
     50
     51        /**
    3552         * Extract entries until the deadline.
    3653         *
    … …  
    4158         * @param float  $deadline     Stop-by timestamp.
    4259         * @param string $index_path   File from build_index(), or ''.
     60         * @param string $code_root    Staging folder for plugins, themes and
     61         *                             must-use plugins, or '' to write them in
     62         *                             place. See move_staged().
    4363         * @return array|\WP_Error Keys: cursor, done, written, rejected, total.
    4464         */
    45         public function extract_batch( $zip_path, $content_root, $sql_root, $cursor, $deadline, $index_path = '' ) {
     65        public function extract_batch( $zip_path, $content_root, $sql_root, $cursor, $deadline, $index_path = '', $code_root = '' ) {
     66                $this->code_root = $code_root;
     67                if ( '' !== $code_root && ! is_dir( $code_root ) && ! wp_mkdir_p( $code_root ) ) {
     68                        return new \WP_Error( 'sitezip_staging', __( 'Could not create the folder for staging plugins and themes.', 'sitezip' ) );
     69                }
    4670                $records = ( '' !== $index_path && is_readable( $index_path ) ) ? (string) file_get_contents( $index_path ) : '';
    4771
    … …  
    136160                        // The same file is already there (the usual case when restoring
    137161                        // onto the site the backup came from): skip the rewrite.
    138                         if ( $mtime && self::same_file( $target['path'], $stat, $mtime ) ) {
     162                        // Only plain media may be skipped: code is always rewritten, so a
     163                        // tampered file with a faked size and date cannot survive.
     164                        if ( $mtime && ! isset( $target['live'] ) && self::skippable( $entry ) && self::same_file( $target['path'], $stat, $mtime ) ) {
    139165                                $bytes += (int) $stat['size'];
    140166                                continue;
    … …  
    152178                                continue;
    153179                        }
    154                         $copied = stream_copy_to_stream( $stream, $out );
     180                        // Never more than the archive declared for this entry.
     181                        $copied = stream_copy_to_stream( $stream, $out, (int) $stat['size'] + 1 );
    155182                        fclose( $stream );
    156183                        fclose( $out );
    … …  
    189216
    190217        /**
     218         * Move staged code files into wp-content, until done or the deadline.
     219         *
     220         * Each file is a rename on the same disk, so the whole set lands in
     221         * well under a second for a typical site. A request killed part way
     222         * leaves the rest in the staging folder, and the next call resumes.
     223         *
     224         * @param string $code_root    Staging folder.
     225         * @param string $content_root wp-content.
     226         * @param float  $deadline     Stop-by timestamp.
     227         * @return array Keys: done, moved, rejected.
     228         */
     229        public static function move_staged( $code_root, $content_root, $deadline ) {
     230                $code_root    = untrailingslashit( $code_root );
     231                $content_root = untrailingslashit( $content_root );
     232                $moved        = 0;
     233                $rejected     = 0;
     234
     235                if ( ! is_dir( $code_root ) ) {
     236                        return array( 'done' => true, 'moved' => 0, 'rejected' => 0 );
     237                }
     238
     239                while ( microtime( true ) < $deadline ) {
     240                        // Collected first: moving files while iterating their folder is unreliable.
     241                        $batch = array();
     242                        $files = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $code_root, \FilesystemIterator::SKIP_DOTS ) );
     243                        foreach ( $files as $file ) {
     244                                if ( $file->isFile() || $file->isLink() ) {
     245                                        $batch[] = $file->getPathname();
     246                                        if ( count( $batch ) >= 500 ) {
     247                                                break;
     248                                        }
     249                                }
     250                        }
     251                        if ( ! $batch ) {
     252                                return array( 'done' => true, 'moved' => $moved, 'rejected' => $rejected );
     253                        }
     254
     255                        foreach ( $batch as $src ) {
     256                                $relative = substr( $src, strlen( $code_root ) + 1 );
     257                                $dest     = $content_root . '/' . $relative;
     258                                $dir      = dirname( $dest );
     259
     260                                $ok = ! is_link( $src )
     261                                        && ( is_dir( $dir ) || wp_mkdir_p( $dir ) )
     262                                        && PathGuard::is_inside( $dir, $content_root )
     263                                        && ! is_link( $dest )
     264                                        && ! is_dir( $dest );
     265                                if ( $ok && ! @rename( $src, $dest ) ) {
     266                                        $ok = @copy( $src, $dest );
     267                                        if ( $ok ) {
     268                                                @touch( $dest, (int) filemtime( $src ) );
     269                                        }
     270                                }
     271                                @unlink( $src );
     272                                if ( $ok ) {
     273                                        $moved++;
     274                                } else {
     275                                        $rejected++;
     276                                }
     277                                if ( microtime( true ) >= $deadline ) {
     278                                        break;
     279                                }
     280                        }
     281                }
     282
     283                return array( 'done' => false, 'moved' => $moved, 'rejected' => $rejected );
     284        }
     285
     286        /**
    191287         * Bytes per entry in the index file: 32-bit time, 64-bit size.
    192288         */
    … …  
    239335                }
    240336
     337                // A damaged or doctored archive must not make us read past its end
     338                // or allocate gigabytes.
     339                if ( $start < 0 || $len < 0 || $len > 268435456 || $start + $len > $size || $count < 0 ) {
     340                        fclose( $fh );
     341                        return false;
     342                }
    241343                fseek( $fh, $start );
    242344                $cd = $len > 0 ? (string) fread( $fh, $len ) : '';
    … …  
    261363                        $x    = $pos + 46 + $lens['name'];
    262364                        $xend = $x + $lens['extra'];
     365                        if ( $xend + $lens['comment'] > $n ) {
     366                                return false;
     367                        }
    263368                        while ( $x + 4 <= $xend ) {
    264369                                $field = unpack( 'vid/vsize', $cd, $x );
     370                                if ( $x + 4 + $field['size'] > $xend ) {
     371                                        break;
     372                                }
    265373                                if ( 0x5455 === $field['id'] && $field['size'] >= 5 && ( ord( $cd[ $x + 4 ] ) & 1 ) ) {
    266374                                        $time = unpack( 'V', $cd, $x + 5 )[1];
    … …  
    300408
    301409        /**
     410         * File types a restore may leave in place when they look unchanged:
     411         * plain media in uploads only. Anything that can run (PHP, scripts,
     412         * HTML, SVG, server config) is always rewritten from the backup.
     413         */
     414        const SKIPPABLE = array( 'jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'heic', 'bmp', 'tif', 'tiff', 'ico', 'mp4', 'm4v', 'mov', 'webm', 'mkv', 'avi', 'mp3', 'm4a', 'wav', 'ogg', 'flac', 'pdf', 'zip', 'woff', 'woff2', 'ttf', 'otf', 'eot' );
     415
     416        /**
     417         * Whether an entry may be skipped when the file on disk looks the same.
     418         *
     419         * @param string $entry Normalised entry name.
     420         * @return bool
     421         */
     422        private static function skippable( $entry ) {
     423                $entry = strtolower( $entry );
     424                if ( 0 !== strpos( $entry, 'wp-content/uploads/' ) ) {
     425                        return false;
     426                }
     427                $ext = pathinfo( $entry, PATHINFO_EXTENSION );
     428                // "photo.php.jpg" style names are rewritten too.
     429                return in_array( $ext, self::SKIPPABLE, true ) && 1 === substr_count( basename( $entry ), '.' );
     430        }
     431
     432        /**
    302433         * Whether a regular file on disk already matches an archive entry, by
    303434         * size and exact modification time. Only file metadata is read, so
    … …  
    310441         */
    311442        private static function same_file( $path, array $stat, $mtime ) {
     443                if ( ! isset( $stat['size'] ) ) {
     444                        return false;
     445                }
    312446                if ( ! is_file( $path ) || (int) filesize( $path ) !== (int) $stat['size'] ) {
    313447                        return false;
    … …  
    334468                if ( 0 === strpos( $entry, 'wp-content/' ) ) {
    335469                        $relative = substr( $entry, strlen( 'wp-content/' ) );
     470                        // Compared in lower case: macOS and Windows disks treat
     471                        // "Plugins" and "plugins" as the same folder.
     472                        $lower = strtolower( $relative );
    336473                        // Restoring wp-config.php is never legitimate: it is not in the
    337474                        // archive, and an injected one would hand over the database.
    338                         if ( '' === $relative || 'wp-config.php' === basename( $relative ) ) {
     475                        if ( '' === $relative || 'wp-config.php' === basename( $lower ) ) {
    339476                                return false;
    340477                        }
    … …  
    342479                        // Server-specific drop-ins from the old host would break this
    343480                        // one (backups from older versions may still contain them).
    344                         $host = \SiteZip\Backup\Source\FilesSource::host_specific( $relative );
     481                        $host = \SiteZip\Backup\Source\FilesSource::host_specific( $lower );
    345482                        if ( '' !== $host ) {
    346483                                if ( 'dropin' === $host ) {
    … …  
    352489                        // Never overwrite the code that is running this restore, and
    353490                        // never write into the backups folder.
    354                         $own_plugin = 'plugins/' . basename( dirname( SITEZIP_FILE ) ) . '/';
    355                         $top_level  = strtok( $relative, '/' );
    356                         if ( 0 === strpos( $relative, $own_plugin ) || preg_match( PathGuard::BACKUPS_FOLDER_PATTERN, $top_level ) ) {
     491                        $own_plugin = strtolower( 'plugins/' . basename( dirname( SITEZIP_FILE ) ) . '/' );
     492                        $top_level  = strtok( $lower, '/' );
     493                        if ( 0 === strpos( $lower, $own_plugin ) || preg_match( PathGuard::BACKUPS_FOLDER_PATTERN, $top_level ) ) {
    357494                                return null;
     495                        }
     496
     497                        if ( '' !== $this->code_root && in_array( $top_level, self::CODE_FOLDERS, true ) && false !== strpos( $relative, '/' ) ) {
     498                                return array(
     499                                        'path' => trailingslashit( $this->code_root ) . $relative,
     500                                        'root' => $this->code_root,
     501                                        'live' => trailingslashit( $content_root ) . $relative,
     502                                );
    358503                        }
    359504
  • sitezip/trunk/includes/Restore/RestoreRunner.php

    r3800592 r3817595  
    3333
    3434        const TEMP_PREFIX = 'sbtmp_';
     35
     36        /** Longest SQL statement accepted from a dump (bytes). */
     37        const MAX_STATEMENT = 67108864;
     38
     39        /**
     40         * Words that may come before "(" in a CREATE TABLE from SHOW CREATE TABLE.
     41         */
     42        const CREATE_WORDS = array(
     43                'tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint', 'decimal', 'dec', 'numeric', 'fixed', 'float', 'double', 'real', 'bit',
     44                'char', 'varchar', 'binary', 'varbinary', 'tinytext', 'text', 'mediumtext', 'longtext', 'tinyblob', 'blob', 'mediumblob', 'longblob',
     45                'enum', 'set', 'datetime', 'timestamp', 'time', 'year', 'date',
     46                'key', 'index', 'unique', 'fulltext', 'spatial',
     47                'current_timestamp', 'now', 'localtime', 'localtimestamp', 'current_date', 'curdate', 'current_time', 'curtime', 'utc_timestamp', 'uuid',
     48                // MySQL 8 writes expression defaults as DEFAULT (...).
     49                'default',
     50                // MariaDB writes JSON columns as longtext with this check.
     51                'check', 'json_valid',
     52        );
    3553        const OLD_PREFIX  = 'sbold_';
    3654
    … …  
    105123                                        $result = $this->replace_step( $state, $job_id, $deadline );
    106124                                        break;
     125                                case 'code':
     126                                        $result = $this->code_step( $state, $job_id, $deadline );
     127                                        break;
    107128                                case 'swap':
    108129                                        $result = $this->swap( $state, $job_id );
    … …  
    179200                if ( is_multisite() || ! empty( $manifest['multisite'] ) ) {
    180201                        return new \WP_Error( 'sitezip_multisite', __( 'Restoring multisite networks is not supported.', 'sitezip' ) );
     202                }
     203                foreach ( array( 'prefix', 'home_url', 'site_url', 'content_dir', 'charset' ) as $field ) {
     204                        if ( isset( $manifest[ $field ] ) && ! is_string( $manifest[ $field ] ) ) {
     205                                return new \WP_Error( 'sitezip_manifest', __( 'The backup manifest is damaged.', 'sitezip' ) );
     206                        }
     207                }
     208                if ( isset( $manifest['smart'] ) && ( ! is_array( $manifest['smart'] ) || ! isset( $manifest['smart']['chain'], $manifest['smart']['tables'] ) || ! is_array( $manifest['smart']['chain'] ) || ! is_array( $manifest['smart']['tables'] ) ) ) {
     209                        return new \WP_Error( 'sitezip_manifest', __( 'The backup manifest is damaged.', 'sitezip' ) );
     210                }
     211                if ( empty( $manifest['home_url'] ) ) {
     212                        return new \WP_Error( 'sitezip_manifest', __( 'The backup manifest is damaged.', 'sitezip' ) );
    181213                }
    182214                if ( empty( $manifest['prefix'] ) || ! preg_match( '/^[A-Za-z0-9_]+$/', $manifest['prefix'] ) ) {
    … …  
    278310                }
    279311
    280                 $result = ( new ArchiveReader() )->extract_batch( $path, WP_CONTENT_DIR, $state['dir'] . 'sql', (int) $state['cursor'], $deadline, $state['dir'] . 'index.bin' );
     312                $result = ( new ArchiveReader() )->extract_batch( $path, WP_CONTENT_DIR, $state['dir'] . 'sql', (int) $state['cursor'], $deadline, $state['dir'] . 'index.bin', $state['dir'] . 'code' );
    281313                if ( is_wp_error( $result ) ) {
    282314                        return $result;
    … …  
    367399                $wpdb->query( "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'" );
    368400                if ( preg_match( '/^[A-Za-z0-9_]+$/', $state['manifest']['charset'] ) ) {
    369                         $wpdb->query( "SET NAMES '" . $state['manifest']['charset'] . "'" );
     401                        // Only single-byte-safe charsets: with gbk, big5, sjis and the like,
     402                        // MySQL and this plugin's checks could read a string differently.
     403                        $charset = in_array( strtolower( $state['manifest']['charset'] ), array( 'utf8mb4', 'utf8', 'utf8mb3', 'latin1' ), true ) ? $state['manifest']['charset'] : 'utf8mb4';
     404                        $wpdb->query( "SET NAMES '" . $charset . "'" );
    370405                }
    371406
    … …  
    392427
    393428                while ( microtime( true ) < $deadline ) {
    394                         $line = fgets( $handle );
     429                        $line = fgets( $handle, self::MAX_STATEMENT );
    395430                        if ( false === $line ) {
    396431                                $cursor['done'] += filesize( $file ) - (int) $cursor['pos'];
    … …  
    409444
    410445                        $statement .= $line;
     446                        // This plugin never writes a statement anywhere near this size.
     447                        if ( strlen( $statement ) > self::MAX_STATEMENT ) {
     448                                $wpdb->query( 'ROLLBACK' );
     449                                fclose( $handle );
     450                                return new \WP_Error( 'sitezip_sql_statement', __( 'The database dump contains an unexpected statement.', 'sitezip' ) );
     451                        }
    411452
    412453                        // Values are escaped by the same driver that replays them, so no
    … …  
    414455                        // ending in ";" is always a real statement boundary.
    415456                        if ( ';' !== substr( rtrim( $line, "\r\n" ), -1 ) ) {
     457                                continue;
     458                        }
     459
     460                        // This server's own job table is never taken from a backup.
     461                        if ( preg_match( '/^(?:DROP TABLE IF EXISTS|CREATE TABLE|INSERT INTO) `([A-Za-z0-9_]+)`/', $statement, $jm ) && $this->local_name( $jm[1], $state ) === JobStore::table() ) {
     462                                $new_pos         = ftell( $handle );
     463                                $cursor['done'] += $new_pos - (int) $cursor['pos'];
     464                                $cursor['pos']   = $new_pos;
     465                                $statement       = '';
    416466                                continue;
    417467                        }
    … …  
    497547                        );
    498548                        $sql = preg_replace( '/CONSTRAINT `[^`]*` (FOREIGN KEY)/', '$1', $sql );
     549                        $sql = $this->fit_server( $sql );
    499550                }
    500551
    501552                return $match[1] . ' `' . $temp . '`' . substr( $sql, strlen( $match[0] ) );
     553        }
     554
     555        /** @var array|null This server's character sets, collations and engines. */
     556        private $server = null;
     557
     558        /**
     559         * Make a CREATE TABLE from another kind of server work on this one.
     560         *
     561         * MySQL 8 writes utf8mb4_0900_ai_ci, which MariaDB does not know;
     562         * MariaDB 11 writes utf8mb4_uca1400_ai_ci and utf8mb3, which MySQL does
     563         * not know; MariaDB's Aria engine does not exist on MySQL. Anything
     564         * this server lacks is swapped for the closest thing it has.
     565         *
     566         * @param string $sql CREATE TABLE statement.
     567         * @return string
     568         */
     569        private function fit_server( $sql ) {
     570                global $wpdb;
     571                if ( null === $this->server ) {
     572                        $this->server = array(
     573                                'cs'    => array(),
     574                                'co'    => array(),
     575                                'en'    => array(),
     576                                'maria' => false !== stripos( (string) $wpdb->get_var( 'SELECT VERSION()' ), 'mariadb' ),
     577                        );
     578                        foreach ( (array) $wpdb->get_col( 'SHOW CHARACTER SET', 0 ) as $v ) {
     579                                $this->server['cs'][ strtolower( $v ) ] = true;
     580                        }
     581                        foreach ( (array) $wpdb->get_col( 'SHOW COLLATION', 0 ) as $v ) {
     582                                $this->server['co'][ strtolower( $v ) ] = true;
     583                        }
     584                        foreach ( (array) $wpdb->get_results( 'SHOW ENGINES', ARRAY_N ) as $row ) {
     585                                if ( isset( $row[0], $row[1] ) && in_array( strtoupper( $row[1] ), array( 'YES', 'DEFAULT' ), true ) ) {
     586                                        $this->server['en'][ strtolower( $row[0] ) ] = true;
     587                                }
     588                        }
     589                }
     590                $srv = $this->server;
     591                // Could not read what the server supports: leave the statement as is.
     592                if ( ! $srv['cs'] || ! $srv['co'] ) {
     593                        return $sql;
     594                }
     595
     596                $charset = function ( $cs ) use ( $srv ) {
     597                        $cs = strtolower( $cs );
     598                        if ( isset( $srv['cs'][ $cs ] ) ) {
     599                                return $cs;
     600                        }
     601                        if ( in_array( $cs, array( 'utf8mb3', 'utf8' ), true ) ) {
     602                                return isset( $srv['cs']['utf8mb3'] ) ? 'utf8mb3' : 'utf8';
     603                        }
     604                        return 'utf8mb4';
     605                };
     606
     607                $sql = preg_replace_callback(
     608                        '/\b(CHARACTER SET|CHARSET)(\s*=?\s*)([A-Za-z0-9_]+)/i',
     609                        function ( $m ) use ( $charset ) {
     610                                return $m[1] . $m[2] . $charset( $m[3] );
     611                        },
     612                        $sql
     613                );
     614
     615                $sql = preg_replace_callback(
     616                        '/\bCOLLATE(\s*=?\s*)([A-Za-z0-9_]+)/i',
     617                        function ( $m ) use ( $srv, $charset ) {
     618                                $co = strtolower( $m[2] );
     619                                if ( isset( $srv['co'][ $co ] ) ) {
     620                                        return $m[0];
     621                                }
     622                                $cs   = $charset( strtok( $co, '_' ) );
     623                                $tail = substr( $co, strpos( $co, '_' ) );
     624                                $try  = array( $cs . $tail, $cs . '_unicode_520_ci', $cs . '_unicode_ci', $cs . '_general_ci' );
     625                                // A binary collation stays binary.
     626                                if ( '_bin' === substr( $co, -4 ) ) {
     627                                        array_unshift( $try, $cs . '_bin' );
     628                                }
     629                                foreach ( $try as $c ) {
     630                                        if ( isset( $srv['co'][ $c ] ) ) {
     631                                                return 'COLLATE' . $m[1] . $c;
     632                                        }
     633                                }
     634                                return 'COLLATE' . $m[1] . 'utf8mb4_general_ci';
     635                        },
     636                        $sql
     637                );
     638
     639                // MariaDB writes "DEFAULT uuid()"; MySQL needs "DEFAULT (uuid())".
     640                if ( ! $srv['maria'] ) {
     641                        $sql = preg_replace( '/\bDEFAULT\s+(?!(?:current_timestamp|now|localtime|localtimestamp)\s*\()([A-Za-z_]+\(\))/i', 'DEFAULT ($1)', $sql );
     642                }
     643
     644                if ( $srv['en'] && preg_match( '/\bENGINE\s*=\s*([A-Za-z0-9_]+)/i', $sql, $m ) && ! isset( $srv['en'][ strtolower( $m[1] ) ] ) ) {
     645                        $sql = str_replace( $m[0], 'ENGINE=InnoDB', $sql );
     646                        // Aria-only table options.
     647                        $sql = preg_replace( '/\s(?:PAGE_CHECKSUM|TRANSACTIONAL)\s*=\s*[01]\b/i', '', $sql );
     648                }
     649
     650                return $sql;
    502651        }
    503652
    … …  
    516665         */
    517666        public static function is_safe_statement( $type, $sql ) {
     667                if ( ! is_string( $sql ) ) {
     668                        return false;
     669                }
    518670                $bare = self::strip_strings( $sql );
    519671                if ( false === $bare ) {
    … …  
    546698                }
    547699
    548                 // CREATE TABLE, as written by SHOW CREATE TABLE.
    549                 return ! preg_match( '/\b(?:SELECT|UNION|LOAD_FILE|DATA\s+DIRECTORY|INDEX\s+DIRECTORY|CONNECTION|INTO\s+(?:OUT|DUMP)FILE)\b|ENGINE\s*=\s*(?:FEDERATED|CONNECT|MERGE|MRG_MYISAM)\b/i', $bare );
     700                // CREATE TABLE, as written by SHOW CREATE TABLE: column definitions,
     701                // keys and table options only. Names are blanked so they cannot hide
     702                // words, then nothing that runs code or reads data may remain.
     703                $body = substr( preg_replace( '/`(?:[^`]|``)*`/', '``', $bare ), strlen( 'CREATE TABLE ``' ) );
     704                if ( preg_match( '/\b(?:SELECT|UNION|TABLE|VALUES|ROW|WITH|AS|LOAD_FILE|DATA\s+DIRECTORY|INDEX\s+DIRECTORY|CONNECTION|INTO|PARTITION|SLEEP|BENCHMARK)\b|ENGINE\s*=\s*(?:FEDERATED|CONNECT|MERGE|MRG_MYISAM)\b/i', $body ) ) {
     705                        return false;
     706                }
     707                // Every "word(" must be a column type, a key, or the current time:
     708                // no other function (and so no expression default) is accepted.
     709                preg_match_all( '/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/', $body, $calls );
     710                foreach ( $calls[1] as $word ) {
     711                        if ( ! in_array( strtolower( $word ), self::CREATE_WORDS, true ) ) {
     712                                return false;
     713                        }
     714                }
     715                return true;
    550716        }
    551717
    … …  
    563729                $i   = 0;
    564730                while ( $i < $n ) {
    565                         $j    = strcspn( $sql, "'", $i );
     731                        $j    = strcspn( $sql, "'`\"#/-", $i );
    566732                        $out .= substr( $sql, $i, $j );
    567733                        $i   += $j;
    … …  
    569735                                break;
    570736                        }
     737                        $c = $sql[ $i ];
     738                        if ( '"' === $c || '#' === $c ) {
     739                                // This plugin's dumps never use either outside a string or a
     740                                // name; MySQL would read them as a string or a comment.
     741                                return false;
     742                        }
     743                        if ( '/' === $c || '-' === $c ) {
     744                                $pair = substr( $sql, $i, 2 );
     745                                if ( '/*' === $pair || '--' === $pair ) {
     746                                        return false;
     747                                }
     748                                $out .= $c;
     749                                ++$i;
     750                                continue;
     751                        }
     752                        if ( '`' === $c ) {
     753                                // A name: kept as written, its content never read as SQL.
     754                                $end = $i + 1;
     755                                while ( true ) {
     756                                        $end += strcspn( $sql, '`', $end );
     757                                        if ( $end >= $n ) {
     758                                                return false;
     759                                        }
     760                                        if ( $end + 1 < $n && '`' === $sql[ $end + 1 ] ) {
     761                                                $end += 2;
     762                                                continue;
     763                                        }
     764                                        break;
     765                                }
     766                                $out .= substr( $sql, $i, $end - $i + 1 );
     767                                $i    = $end + 1;
     768                                continue;
     769                        }
     770                        // A string: replaced by '' so its content is never read as SQL.
    571771                        $out .= "''";
    572772                        ++$i;
    … …  
    630830                $pairs = array();
    631831                foreach ( array( 'home_url', 'site_url', 'content_dir' ) as $key ) {
    632                         $old = untrailingslashit( (string) $state['manifest'][ $key ] );
    633                         $new = untrailingslashit( (string) $state['target'][ $key ] );
    634                         if ( '' === $old || $old === $new ) {
    635                                 continue;
    636                         }
    637                         $pairs[ $old ] = $new;
    638                         // The same value as it appears inside JSON.
    639                         $pairs[ str_replace( '/', '\\/', $old ) ] = str_replace( '/', '\\/', $new );
     832                        $pairs += SearchReplace::pairs_for(
     833                                untrailingslashit( (string) $state['manifest'][ $key ] ),
     834                                untrailingslashit( (string) $state['target'][ $key ] ),
     835                                'content_dir' !== $key
     836                        );
    640837                }
    641838
    … …  
    653850
    654851                if ( $result['done'] ) {
    655                         $state['stage']  = 'swap';
     852                        $state['stage']  = 'code';
    656853                        $state['cursor'] = array();
    657854                        if ( ! $replacer->is_empty() ) {
    … …  
    673870
    674871        /**
     872         * Move the staged plugins, themes and must-use plugins into place.
     873         *
     874         * Runs straight before the database swap, so the new code and the new
     875         * database go live within the same request.
     876         *
     877         * @param array $state    Job state.
     878         * @param int   $job_id   Job ID.
     879         * @param float $deadline Stop-by timestamp.
     880         * @return true
     881         */
     882        private function code_step( array &$state, $job_id, $deadline ) {
     883                // Check everything the swap needs before any live code changes, so
     884                // a restore that cannot finish leaves the site's plugins as they were.
     885                if ( empty( $state['code_checked'] ) ) {
     886                        $ready = $this->swap_ready( $state );
     887                        if ( is_wp_error( $ready ) ) {
     888                                return $ready;
     889                        }
     890                        $state['code_checked'] = true;
     891                }
     892
     893                $result = ArchiveReader::move_staged( $state['dir'] . 'code', WP_CONTENT_DIR, $deadline );
     894
     895                $state['code_moved'] = ( isset( $state['code_moved'] ) ? (int) $state['code_moved'] : 0 ) + $result['moved'];
     896                if ( $result['rejected'] ) {
     897                        $this->store->log(
     898                                $job_id,
     899                                sprintf(
     900                                        /* translators: %d: number of files. */
     901                                        __( 'Could not put %d plugin or theme files in place.', 'sitezip' ),
     902                                        $result['rejected']
     903                                )
     904                        );
     905                }
     906                if ( $result['done'] ) {
     907                        $state['stage']    = 'swap';
     908                        $state['progress'] = 99;
     909                        if ( $state['code_moved'] ) {
     910                                $this->store->log(
     911                                        $job_id,
     912                                        sprintf(
     913                                                /* translators: %s: number of files. */
     914                                                __( 'Plugins and themes put in place (%s files).', 'sitezip' ),
     915                                                number_format_i18n( $state['code_moved'] )
     916                                        )
     917                                );
     918                        }
     919                }
     920
     921                return true;
     922        }
     923
     924        /**
     925         * Whether the imported database is complete enough to swap in.
     926         *
     927         * @param array $state Job state.
     928         * @return true|\WP_Error
     929         */
     930        private function swap_ready( array $state ) {
     931                global $wpdb;
     932
     933                $prefix = $state['target']['prefix'];
     934                if ( empty( $state['tables'][ $prefix . 'options' ] ) ) {
     935                        return new \WP_Error( 'sitezip_no_options', __( 'The backup database has no options table, so it cannot be restored.', 'sitezip' ) );
     936                }
     937
     938                $existing = array_flip( (array) $wpdb->get_col( 'SHOW TABLES' ) );
     939                foreach ( array_keys( $state['tables'] ) as $real ) {
     940                        if ( ! isset( $existing[ self::TEMP_PREFIX . $real ] ) ) {
     941                                return new \WP_Error(
     942                                        'sitezip_missing_temp',
     943                                        sprintf(
     944                                                /* translators: %s: table name. */
     945                                                __( 'The imported copy of %s is missing.', 'sitezip' ),
     946                                                $real
     947                                        )
     948                                );
     949                        }
     950                }
     951
     952                return true;
     953        }
     954
     955        /**
    675956         * Fix prefix-dependent rows, then swap every table in at once.
    676957         *
    … …  
    705986                }
    706987
     988                // This site's own address, whatever the dump says: a doctored backup
     989                // must not be able to send the site (or its health check) elsewhere.
     990                $wpdb->update( $options, array( 'option_value' => $state['target']['home_url'] ), array( 'option_name' => 'home' ) );
     991                $wpdb->update( $options, array( 'option_value' => $state['target']['site_url'] ), array( 'option_name' => 'siteurl' ) );
     992
    707993                // Locks and cron claims copied from the source site mean nothing here.
    708994                $wpdb->query( "DELETE FROM `{$options}` WHERE option_name LIKE 'sitezip\\_lock\\_%' OR option_name IN ('_transient_doing_cron', 'core_updater.lock')" );
  • sitezip/trunk/includes/Restore/SearchReplace.php

    r3800592 r3817595  
    4949
    5050        /**
     51         * Search => replacement pairs that move one value to another.
     52         *
     53         * A site's content often holds its address in more than one form:
     54         * Local and many hosts save http:// links on an https:// site or the
     55         * other way round, and themes write protocol-relative //host URLs.
     56         * Every form is pointed at the new address; strtr() tries the longest
     57         * search first, so a full URL never gets half-replaced by the shorter
     58         * //host form. Each pair is added again as it appears inside JSON.
     59         *
     60         * @param string $old    Old value, no trailing slash.
     61         * @param string $new    New value, no trailing slash.
     62         * @param bool   $is_url Whether the values are URLs.
     63         * @return array
     64         */
     65        public static function pairs_for( $old, $new, $is_url ) {
     66                if ( '' === $old || $old === $new ) {
     67                        return array();
     68                }
     69
     70                $pairs = array( $old => $new );
     71                if ( $is_url && preg_match( '#^https?:(//.+)$#i', $old, $m ) ) {
     72                        $new_relative = preg_replace( '#^https?:#i', '', $new );
     73                        $pairs        = array(
     74                                'http:' . $m[1]  => $new,
     75                                'https:' . $m[1] => $new,
     76                                $m[1]            => $new_relative,
     77                        );
     78                }
     79
     80                foreach ( $pairs as $search => $replace ) {
     81                        $pairs[ str_replace( '/', '\\/', $search ) ] = str_replace( '/', '\\/', $replace );
     82                }
     83
     84                // An unchanged pair (same host, only the scheme differs) is harmless
     85                // but would make every row look like a match.
     86                foreach ( $pairs as $search => $replace ) {
     87                        if ( $search === $replace ) {
     88                                unset( $pairs[ $search ] );
     89                        }
     90                }
     91
     92                return $pairs;
     93        }
     94
     95        /**
    5196         * Whether there is anything to replace.
    5297         *
    … …  
    67112         * @return string
    68113         */
     114        /** @var int How deep inside nested serialized strings we are. */
     115        private $depth = 0;
     116
    69117        public function replace_value( $value ) {
    70118                if ( ! $this->contains_search( $value ) ) {
    71119                        return $value;
    72120                }
    73                 if ( $this->looks_serialized( $value ) ) {
    74                         return $this->replace_serialized( $value );
     121                // Serialized data nested this deep is not real; stop recursing.
     122                if ( $this->depth < 64 && $this->looks_serialized( $value ) ) {
     123                        ++$this->depth;
     124                        $out = $this->replace_serialized( $value );
     125                        --$this->depth;
     126                        return $out;
    75127                }
    76128
  • sitezip/trunk/includes/Security/DownloadLinks.php

    r3800592 r3817595  
    1212/**
    1313 * A link is made only when an administrator clicks Download. It is tied to
    14  * one file and one user, works once, and expires after two minutes. Only a
    15  * hash of the token is stored, so reading the database does not reveal a
     14 * one file and one user and must be started within two minutes. Once
     15 * started it keeps working for that user for a while, so the browser can
     16 * resume a multi-gigabyte download after a dropped connection. Only a hash
     17 * of the token is stored, so reading the database does not reveal a
    1618 * usable link.
    1719 */
    … …  
    2224         */
    2325        const TTL = 120;
     26
     27        /**
     28         * Seconds a started link keeps working, for resumed downloads.
     29         */
     30        const RESUME_TTL = 43200;
    2431
    2532        /**
    … …  
    5057
    5158        /**
    52          * Use up a token. Returns its file name, or false if the token is
    53          * unknown, expired, already used, or belongs to someone else.
     59         * Redeem a token. Returns its file name, or false if the token is
     60         * unknown, expired, or belongs to someone else. The first use starts
     61         * the resume window; later uses (a browser resuming) keep working
     62         * until it ends.
    5463         *
    5564         * @param string $token   Token from the URL.
    … …  
    5766         * @return string|false
    5867         */
    59         public static function consume( $token, $user_id ) {
     68        public static function redeem( $token, $user_id ) {
    6069                if ( ! is_string( $token ) || ! preg_match( '/^[a-f0-9]{64}$/', $token ) ) {
    6170                        return false;
    … …  
    6675                        return false;
    6776                }
    68 
    69                 // Deleting is the gate: if two requests race, only the one that
    70                 // actually removes the token may continue.
    71                 if ( ! delete_transient( $key ) ) {
     77                if ( ! $user_id || (int) $data['user'] !== (int) $user_id ) {
    7278                        return false;
    7379                }
    74                 if ( (int) $data['user'] !== (int) $user_id || ! $user_id ) {
    75                         return false;
     80                if ( empty( $data['started'] ) ) {
     81                        $data['started'] = time();
     82                        set_transient( $key, $data, self::RESUME_TTL );
    7683                }
    7784
  • sitezip/trunk/includes/Security/PathGuard.php

    r3800592 r3817595  
    182182                        return new \WP_Error( 'sitezip_mkdir', __( 'Could not create a temporary folder for this job.', 'sitezip' ) );
    183183                }
     184                // Holds database dumps while a job runs: same deny rules as the parent.
     185                self::protect( $dir );
    184186
    185187                return trailingslashit( $dir );
  • sitezip/trunk/readme.txt

    r3800592 r3817595  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.0.0
     7Stable tag: 1.0.1
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    6666== Changelog ==
    6767
     68= 1.0.1 =
     69* New: restore a backup made on MySQL onto MariaDB, and the other way round. Collations, table engines and column defaults the other server does not understand are converted automatically.
     70* New: Copy debug report button, and the restore screen shows which step it is on.
     71* Improved: plugin and theme code is staged and the database is checked before any code is replaced, so a failed restore leaves the site as it was.
     72* Improved: the old site address is replaced in every form (http, https, escaped), not only the one saved in the backup.
     73* Improved: Backup contents now shows what is in the backup and what is left out, with sizes and file counts.
     74* Fix: large backup downloads no longer fail part way; downloads can resume.
     75* Security: restore accepts only the exact database statements SiteZip writes, and only safe character sets.
     76* Security: a restored backup can no longer change this site's address.
     77* Security: plugin and theme files are always rewritten on restore, never skipped as "unchanged".
     78* Security: damaged or doctored backup files are rejected cleanly instead of using up memory.
     79* Security: backup file names are harder to guess, and the temporary folder is protected from web access.
     80
    6881= 1.0.0 =
    6982* First release.
  • sitezip/trunk/sitezip.php

    r3800592 r3817595  
    33 * Plugin Name:       SiteZip – Backup & Restore
    44 * Description:       Simple full-site backup, export and import: database and wp-content compressed into one .zip of any size, with safe restore.
    5  * Version:           1.0.0
     5 * Version:           1.0.1
    66 * Requires at least: 5.8
    77 * Requires PHP:      7.4
    … …  
    1717defined( 'ABSPATH' ) || exit;
    1818
    19 define( 'SITEZIP_VERSION', '1.0.0' );
     19define( 'SITEZIP_VERSION', '1.0.1' );
    2020define( 'SITEZIP_FILE', __FILE__ );
    2121define( 'SITEZIP_DIR', plugin_dir_path( __FILE__ ) );
  • sitezip/trunk/uninstall.php

    r3800592 r3817595  
    2525
    2626wp_unschedule_hook( 'sitezip_run_job' );
     27
     28// The restore guard, if a restore was running when SiteZip was removed.
     29if ( defined( 'WPMU_PLUGIN_DIR' ) && is_file( WPMU_PLUGIN_DIR . '/sitezip-restore-guard.php' ) ) {
     30        wp_delete_file( WPMU_PLUGIN_DIR . '/sitezip-restore-guard.php' );
     31}
Note: See TracChangeset for help on using the changeset viewer.