*/ private static $last_write = array(); /** @var array Next log sequence number per job, read from the file once per request. */ private static $seq = array(); /** @var array Last sentence logged per job, so an unchanged step is not logged twice. */ private static $last_text = array(); /** @var array */ private static $appends = array(); public static function stateFile( string $job_id ): string { return Paths::job( $job_id ) . '/progress.json'; } public static function logFile( string $job_id ): string { return Paths::job( $job_id ) . '/progress.log'; } /** * Which of the five phases a stage belongs to. */ public static function phaseFor( string $type, string $stage ): string { $map = array( 'export' => array( 'init' => self::PHASE_DATABASE, 'database' => self::PHASE_DATABASE, 'inventory' => self::PHASE_FILES, 'archive' => self::PHASE_COMPRESSION, 'finalize' => self::PHASE_VERIFICATION, ), 'import' => array( 'upload' => self::PHASE_FILES, 'assemble' => self::PHASE_VERIFICATION, 'extract' => self::PHASE_FILES, 'validate' => self::PHASE_VERIFICATION, 'database' => self::PHASE_DATABASE, 'replace' => self::PHASE_DATABASE, 'files' => self::PHASE_FILES, 'finalize' => self::PHASE_VERIFICATION, ), 'reset' => array( 'prepare' => self::PHASE_DATABASE, 'media' => self::PHASE_FILES, 'plugins' => self::PHASE_FILES, 'themes' => self::PHASE_FILES, 'swap' => self::PHASE_DATABASE, ), ); return $map[ $type ][ $stage ] ?? self::PHASE_FILES; } /** * One sentence on what the job is doing right now, built from the details the stage reports. */ public static function subStep( JobState $job ): string { $d = $job->detail(); $n = static function ( $v ): string { return number_format( (float) $v, 0, '.', ',' ); // fixed separators: this is a log, not a locale-aware page. }; $short = static function ( string $name, int $max = 70 ): string { return strlen( $name ) <= $max ? $name : substr( $name, 0, 24 ) . '…' . substr( $name, -( $max - 25 ) ); }; $kind = $job->type() . ':' . $job->stage(); switch ( $kind ) { case 'export:init': return __( 'Preparing the export…', 'migratex' ); case 'export:database': $total = (int) $job->get( 'db_rows_total', 0 ); if ( isset( $d['table'] ) && '' !== $d['table'] ) { return $total > 0 /* translators: 1: table name, 2: rows done, 3: rows in all (an estimate) */ ? sprintf( __( 'Dumping table: %1$s (%2$s / %3$s rows)', 'migratex' ), $d['table'], $n( $d['rows'] ?? 0 ), $n( $total ) ) /* translators: 1: table name, 2: tables done, 3: tables in all */ : sprintf( __( 'Dumping table: %1$s (%2$s of %3$s tables)', 'migratex' ), $d['table'], $n( $d['tables_done'] ?? 0 ), $n( $d['tables_total'] ?? 0 ) ); } return __( 'Dumping the database…', 'migratex' ); case 'export:inventory': /* translators: 1: number of files found, 2: their size */ return sprintf( __( 'Scanning files: %1$s found (%2$s)', 'migratex' ), $n( $d['files'] ?? 0 ), Format::bytes( (int) ( $d['bytes'] ?? 0 ) ) ); case 'export:archive': if ( ! empty( $d['file'] ) ) { /* translators: 1: file name, 2: files done, 3: files in all, 4: bytes done, 5: bytes in all */ return sprintf( __( 'Archiving %1$s (file %2$s of %3$s, %4$s / %5$s)', 'migratex' ), $short( (string) $d['file'] ), $n( ( $d['files'] ?? 0 ) + 1 ), $n( $d['total_files'] ?? 0 ), Format::bytes( (int) ( $d['bytes'] ?? 0 ) ), Format::bytes( (int) ( $d['total_bytes'] ?? 0 ) ) ); } /* translators: 1: files done, 2: files in all */ return sprintf( __( 'Archiving files (%1$s of %2$s)', 'migratex' ), $n( $d['files'] ?? 0 ), $n( $d['total_files'] ?? 0 ) ); case 'export:finalize': return __( 'Sealing the archive and checking it can be restored…', 'migratex' ); case 'import:upload': if ( ! empty( $d['problem'] ) ) { /* translators: 1: attempt number, 2: what went wrong */ return sprintf( __( 'The source did not answer; trying again (%1$s): %2$s', 'migratex' ), $n( $d['attempt'] ?? 0 ), $d['problem'] ); } /* translators: 1: pieces received, 2: pieces in all, 3: bytes received, 4: bytes in all */ return sprintf( __( 'Receiving the backup: piece %1$s of %2$s (%3$s / %4$s)', 'migratex' ), $n( $d['chunks'] ?? 0 ), $n( $d['total_chunks'] ?? 0 ), Format::bytes( (int) ( $d['bytes'] ?? 0 ) ), Format::bytes( (int) ( $d['total_bytes'] ?? $job->get( 'size', 0 ) ) ) ); case 'import:assemble': /* translators: %s: number of files checked */ return sprintf( __( 'Verifying the backup: %s files checked', 'migratex' ), $n( $d['files'] ?? 0 ) ); case 'import:extract': if ( ! empty( $d['file'] ) ) { /* translators: 1: file name, 2: files extracted */ return sprintf( __( 'Extracting %1$s (%2$s files done)', 'migratex' ), $short( (string) $d['file'] ), $n( $d['files'] ?? 0 ) ); } /* translators: %s: files extracted */ return sprintf( __( 'Extracting files (%s done)', 'migratex' ), $n( $d['files'] ?? 0 ) ); case 'import:validate': return __( 'Checking the backup is compatible with this site…', 'migratex' ); case 'import:database': /* translators: 1: tables created, 2: SQL statements run */ return sprintf( __( 'Restoring the database: %1$s tables, %2$s statements', 'migratex' ), $n( $d['tables'] ?? 0 ), $n( $d['statements'] ?? 0 ) ); case 'import:replace': /* translators: 1: table name, 2: tables done, 3: tables in all */ return sprintf( __( 'Updating addresses in %1$s (table %2$s of %3$s)', 'migratex' ), (string) ( $d['table'] ?? '' ), $n( ( $d['tables_done'] ?? 0 ) + 1 ), $n( $d['tables_total'] ?? 0 ) ); case 'import:files': case 'import:finalize': if ( ! empty( $d['item'] ) ) { /* translators: 1: path, 2: items done, 3: items in all */ return sprintf( __( 'Putting %1$s in place (%2$s of %3$s)', 'migratex' ), $short( (string) $d['item'] ), $n( $d['done'] ?? 0 ), $n( $d['total'] ?? 0 ) ); } return __( 'Switching over to the restored site…', 'migratex' ); case 'reset:prepare': return __( 'Building a fresh database next to the current one…', 'migratex' ); case 'reset:media': /* translators: %s: items removed */ return sprintf( __( 'Removing media: %s items removed', 'migratex' ), $n( $d['removed'] ?? 0 ) ); case 'reset:plugins': case 'reset:themes': /* translators: 1: items removed, 2: items in all */ return sprintf( __( 'Removing: %1$s of %2$s done', 'migratex' ), $n( $d['removed'] ?? 0 ), $n( $d['total'] ?? 0 ) ); case 'reset:swap': return __( 'Switching to the fresh database…', 'migratex' ); } return $job->label(); } /** * Writes the snapshot (replacing the last) and, when the step has changed, a line in the log. * * @param float $overall Overall percent, 0-100, as the runner works it out. * @param bool $force Write now, ignoring the minimum interval (a stage change, the end of a tick). * @param string|null $note A line for the log in place of the automatic one. * @return array What was written. */ public static function publish( JobState $job, float $overall, bool $force = false, ?string $note = null ): array { $id = $job->id(); $now = microtime( true ); $d = $job->detail(); $done = $job->isTerminal() ? ( JobState::COMPLETE === $job->status() ? self::PHASE_COMPLETE : self::PHASE_ERROR ) : self::phaseFor( $job->type(), $job->stage() ); $text = null !== $note ? $note : self::subStep( $job ); $total = (int) ( $d['total_bytes'] ?? 0 ); $state = array( 'job_id' => $id, 'type' => $job->type(), 'status' => $job->status(), 'stage' => $job->stage(), 'phase' => $done, 'sub_step' => $text, 'overall_percent' => round( JobState::COMPLETE === $job->status() ? 100.0 : max( 0.0, min( 100.0, $overall ) ), 1 ), 'phase_percent' => round( JobState::COMPLETE === $job->status() ? 100.0 : max( 0.0, min( 1.0, $job->stageProgress() ) ) * 100, 1 ), 'bytes_processed' => $total > 0 ? (int) ( $d['bytes'] ?? 0 ) : null, 'bytes_total' => $total > 0 ? $total : null, 'timestamp' => (int) $now, 'tick' => $job->tickCount(), ); if ( ! $force && isset( self::$last_write[ $id ] ) && $now - self::$last_write[ $id ] < self::MIN_INTERVAL ) { return $state; } self::$last_write[ $id ] = $now; if ( is_dir( Paths::job( $id ) ) ) { SafeFile::writeAtomic( self::stateFile( $id ), (string) wp_json_encode( $state ) ); // A new sentence is a new line in the log; the same one repeated is not. if ( '' !== $text && ( null !== $note || ( self::$last_text[ $id ] ?? '' ) !== $text ) ) { self::$last_text[ $id ] = $text; self::log( $id, $text ); } } return $state; } /** * Adds a timestamped line to the live log. */ public static function log( string $job_id, string $message, ?int $time = null ): void { if ( 1 !== preg_match( '/^[a-f0-9]{32}$/', $job_id ) || ! is_dir( Paths::job( $job_id ) ) ) { return; } $file = self::logFile( $job_id ); $message = trim( (string) preg_replace( '/[\x00-\x1f\x7f]+/', ' ', $message ) ); // one line, no control characters. $message = substr( $message, 0, 400 ); if ( '' === $message ) { return; } if ( ! isset( self::$seq[ $job_id ] ) ) { self::$seq[ $job_id ] = self::lastSeq( $file ); } ++self::$seq[ $job_id ]; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- a small append, no locking needed: only the one running tick writes. @file_put_contents( $file, self::$seq[ $job_id ] . "\t" . ( $time ?? time() ) . "\t" . $message . "\n", FILE_APPEND ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- a log that cannot be written must not stop the job. self::$appends[ $job_id ] = ( self::$appends[ $job_id ] ?? 0 ) + 1; if ( 0 === self::$appends[ $job_id ] % 25 ) { self::trim( $file ); } } /** * What the browser asks for: the snapshot plus every log line after $since, with the server's own clock so * the page judges "no update for a while" against the server's time, not its own. * * @return array */ public static function snapshot( JobState $job, int $since = 0 ): array { $raw = SafeFile::readJson( self::stateFile( $job->id() ) ); $state = is_array( $raw ) ? $raw : self::derive( $job ); $now = time(); // A finished job is reported as finished whatever the last snapshot says. if ( $job->isTerminal() ) { $state['status'] = $job->status(); $state['phase'] = JobState::COMPLETE === $job->status() ? self::PHASE_COMPLETE : self::PHASE_ERROR; if ( JobState::COMPLETE === $job->status() ) { $state['overall_percent'] = 100.0; $state['phase_percent'] = 100.0; } } $age = max( 0, $now - (int) ( $state['timestamp'] ?? $now ) ); $lines = self::lines( $job->id(), $since ); return $state + array( 'server_time' => $now, 'age' => $age, 'stalled' => ! $job->isTerminal() && $age > self::STALL_AFTER, 'log' => $lines['lines'], 'log_seq' => $lines['last'], ); } /** * A snapshot built from the job's own saved state, for a job that has no progress file (one started * before this existed, or whose file was cleaned up). * * @return array */ public static function derive( JobState $job ): array { $d = $job->detail(); $total = (int) ( $d['total_bytes'] ?? 0 ); return array( 'job_id' => $job->id(), 'type' => $job->type(), 'status' => $job->status(), 'stage' => $job->stage(), 'phase' => self::phaseFor( $job->type(), $job->stage() ), 'sub_step' => self::subStep( $job ), 'overall_percent' => round( $job->progress(), 1 ), 'phase_percent' => round( $job->stageProgress() * 100, 1 ), 'bytes_processed' => $total > 0 ? (int) ( $d['bytes'] ?? 0 ) : null, 'bytes_total' => $total > 0 ? $total : null, 'timestamp' => $job->updatedAt(), 'tick' => $job->tickCount(), ); } /** * @return array{lines:array,last:int} */ private static function lines( string $job_id, int $since ): array { $file = self::logFile( $job_id ); $out = array(); $last = 0; $text = is_file( $file ) ? SafeFile::readText( $file ) : null; foreach ( explode( "\n", (string) $text ) as $line ) { $parts = explode( "\t", $line, 3 ); if ( 3 !== count( $parts ) || ! ctype_digit( $parts[0] ) || ! ctype_digit( $parts[1] ) ) { continue; // a half-written last line, or junk. } $n = (int) $parts[0]; $last = max( $last, $n ); if ( $n > $since ) { $out[] = array( 'n' => $n, 't' => (int) $parts[1], 'm' => $parts[2], ); } } // A poll after a long gap must not be handed a very large reply. return array( 'lines' => array_slice( $out, -300 ), 'last' => $last, ); } private static function lastSeq( string $file ): int { $text = is_file( $file ) ? SafeFile::readText( $file ) : null; if ( null === $text || '' === $text ) { return 0; } $rows = explode( "\n", rtrim( $text ) ); $tail = explode( "\t", (string) end( $rows ), 2 ); return ctype_digit( $tail[0] ) ? (int) $tail[0] : 0; } /** * Keeps the log to LOG_LIMIT bytes by dropping its older half (whole lines only), atomically. */ private static function trim( string $file ): void { clearstatcache( true, $file ); if ( (int) filesize( $file ) <= self::LOG_LIMIT ) { return; } $text = SafeFile::readText( $file ); if ( null === $text ) { return; } $keep = substr( $text, (int) ( strlen( $text ) / 2 ) ); $break = strpos( $keep, "\n" ); $keep = false === $break ? '' : substr( $keep, $break + 1 ); SafeFile::writeAtomic( $file, $keep ); } }