> $rows Rows. */ public static function append_rows( string $path, array $rows ): void { if ( empty( $rows ) ) { return; } $buf = ''; foreach ( $rows as $row ) { $buf .= self::encode_row( $row ) . "\n"; } self::append( $path, $buf ); } /** * Encode one NDJSON row. * * @param array $row Row. * @throws State_Exception When the row cannot be encoded. */ public static function encode_row( array $row ): string { $json = wp_json_encode( $row, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE ); if ( ! is_string( $json ) ) { throw new State_Exception( esc_html( __( 'Unable to encode a working state row.', '007aj-backup-restore-verifier' ) ) ); } return $json; } /** * Read NDJSON rows starting at a byte offset. * * @param string $path Path. * @param int $offset Byte offset. * @param int $max Max rows. * @param float $deadline Optional microtime deadline (0 = none). * @return array{rows:list>,ends:list,offset:int,eof:bool} * @throws State_Exception On read failure or corrupt row. */ public static function read_rows( string $path, int $offset, int $max, float $deadline = 0.0 ): array { $out = array( 'rows' => array(), 'offset' => $offset, 'eof' => true, ); if ( ! file_exists( $path ) ) { return $out; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $fh = @fopen( $path, 'rb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( false === $fh ) { throw new State_Exception( esc_html( self::io_message( __( 'Unable to open working file for reading', '007aj-backup-restore-verifier' ), $path ) ) ); } if ( $offset > 0 && 0 !== fseek( $fh, $offset ) ) { fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose throw new State_Exception( esc_html( self::io_message( __( 'Unable to seek in working file', '007aj-backup-restore-verifier' ), $path ) ) ); } $rows = array(); $ends = array(); $pos = $offset; $eof = false; while ( count( $rows ) < $max ) { if ( $deadline > 0 && 0 === ( count( $rows ) & 255 ) && count( $rows ) > 0 && microtime( true ) >= $deadline ) { break; } $line = fgets( $fh ); if ( false === $line ) { $eof = true; break; } if ( "\n" !== substr( $line, -1 ) ) { // Partial trailing line (should not happen after journaling) — stop before it. $eof = true; break; } $pos += strlen( $line ); $line = trim( $line ); if ( '' === $line ) { continue; } $row = json_decode( $line, true ); if ( ! is_array( $row ) ) { fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose throw new State_Exception( esc_html( sprintf( /* translators: 1: file, 2: offset */ __( 'Corrupt working state row in %1$s at byte %2$d.', '007aj-backup-restore-verifier' ), basename( $path ), $pos ) ) ); } $rows[] = $row; $ends[] = $pos; } if ( ! $eof ) { $eof = feof( $fh ) || false === fgetc( $fh ); } fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose $out['rows'] = $rows; $out['ends'] = $ends; $out['offset'] = $pos; $out['eof'] = $eof; return $out; } /** * Read raw text lines (without newline) starting at a byte offset. * * @param string $path Path. * @param int $offset Byte offset. * @param int $max Max lines. * @return array{lines:list,offset:int,eof:bool} * @throws State_Exception On read failure. */ public static function read_rows_text( string $path, int $offset, int $max ): array { $out = array( 'lines' => array(), 'offset' => $offset, 'eof' => true, ); if ( ! file_exists( $path ) ) { return $out; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $fh = @fopen( $path, 'rb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( false === $fh ) { throw new State_Exception( esc_html( self::io_message( __( 'Unable to open working file for reading', '007aj-backup-restore-verifier' ), $path ) ) ); } fseek( $fh, $offset ); $pos = $offset; $eof = false; while ( count( $out['lines'] ) < $max ) { $line = fgets( $fh ); if ( false === $line || "\n" !== substr( $line, -1 ) ) { $eof = true; break; } $pos += strlen( $line ); $out['lines'][] = rtrim( $line, "\r\n" ); } fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose $out['offset'] = $pos; $out['eof'] = $eof; return $out; } /** * Write a whole file atomically (temp file + rename). * * @param string $path Path. * @param string $data Data. * @throws State_Exception On failure. */ public static function write_atomic( string $path, string $data ): void { $tmp = $path . '.tmp-' . wp_generate_password( 6, false, false ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents $ok = @file_put_contents( $tmp, $data ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( strlen( $data ) !== $ok ) { wp_delete_file( $tmp ); throw new State_Exception( esc_html( self::io_message( __( 'Unable to write working file (disk full?)', '007aj-backup-restore-verifier' ), $path ) ) ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename if ( ! @rename( $tmp, $path ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.rename_rename wp_delete_file( $tmp ); throw new State_Exception( esc_html( self::io_message( __( 'Unable to replace working file', '007aj-backup-restore-verifier' ), $path ) ) ); } } /** * Truncate a file to a size (no-op when missing or already smaller). * * @param string $path Path. * @param int $size Size. * @throws State_Exception On failure. */ public static function truncate( string $path, int $size ): void { clearstatcache( true, $path ); if ( ! file_exists( $path ) || (int) filesize( $path ) <= $size ) { return; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $fh = @fopen( $path, 'r+b' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( false === $fh || ! ftruncate( $fh, max( 0, $size ) ) ) { if ( false !== $fh ) { fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose } throw new State_Exception( esc_html( self::io_message( __( 'Unable to truncate working file', '007aj-backup-restore-verifier' ), $path ) ) ); } fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose clearstatcache( true, $path ); } /** * Size of a file (0 when missing). * * @param string $path Path. */ public static function size( string $path ): int { clearstatcache( true, $path ); return file_exists( $path ) ? (int) filesize( $path ) : 0; } /** * Roll top-level state files back to their committed sizes. * * @param string $state_dir State dir. * @param array $journal name => committed size. */ public static function rewind( string $state_dir, array $journal ): void { foreach ( self::journaled_names( $state_dir ) as $name ) { $path = $state_dir . '/' . $name; $size = isset( $journal[ $name ] ) ? (int) $journal[ $name ] : 0; self::truncate( $path, $size ); } } /** * Committed sizes of top-level state files. * * @param string $state_dir State dir. * @return array */ public static function journal( string $state_dir ): array { $out = array(); foreach ( self::journaled_names( $state_dir ) as $name ) { $out[ $name ] = self::size( $state_dir . '/' . $name ); } ksort( $out ); return $out; } /** * Files whose committed size is owned by the archive writer (Zip_Writer state in the * cursor). They are rolled back together with the archive, never by this journal, so * there is exactly one record of how much of them is committed. */ public const WRITER_OWNED = array( 'checksums.txt', 'zipcd.bin' ); /** * Journaled file names (*.ndjson, *.txt, *.bin directly in the state dir, except WRITER_OWNED). * * @param string $state_dir State dir. * @return list */ private static function journaled_names( string $state_dir ): array { $names = array(); $dh = is_dir( $state_dir ) ? opendir( $state_dir ) : false; if ( false === $dh ) { return $names; } while ( false !== ( $entry = readdir( $dh ) ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition if ( preg_match( '/^[a-z0-9_.-]+\.(ndjson|txt|bin)$/', $entry ) && ! in_array( $entry, self::WRITER_OWNED, true ) && is_file( $state_dir . '/' . $entry ) ) { $names[] = $entry; } } closedir( $dh ); sort( $names ); return $names; } /** * I/O error text with path and PHP's last error. * * @param string $what Message. * @param string $path Path. */ public static function io_message( string $what, string $path ): string { $last = error_get_last(); $why = is_array( $last ) && ! empty( $last['message'] ) ? ' (' . (string) $last['message'] . ')' : ''; $free = @disk_free_space( dirname( $path ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( false !== $free && $free < 16 * MB_IN_BYTES ) { $why .= ' ' . sprintf( /* translators: %s: free space */ __( '[free disk space: %s]', '007aj-backup-restore-verifier' ), size_format( (int) $free ) ); } return $what . ': ' . $path . $why; } }