items->delete_orphan_rows(); } $ids = $this->page_after( $after_id ); $rebuilt = 0; foreach ( $ids as $id ) { if ( $this->rebuild_attachment( $id ) ) { ++$rebuilt; } } $next = count( $ids ) === self::PAGE_SIZE ? (int) end( $ids ) : 0; if ( 0 === $next ) { $this->stats->recalculate(); } return array( 'rebuilt' => $rebuilt, 'next' => $next, ); } /** * Rebuilds one attachment's records. * * @param int $id Attachment ID. * @return bool Whether records were written. */ public function rebuild_attachment( int $id ): bool { $file = (string) get_attached_file( $id ); if ( '' === $file || ! is_file( $file ) ) { return false; } $state = $this->state->get( $id ); // WebP and AVIF copies are made at their own time; their rows keep it. $converted_at = ''; foreach ( $this->items->for_attachment( $id ) as $row ) { if ( ! empty( $row['is_derivative'] ) ) { $converted_at = max( $converted_at, (string) $row['updated_at'] ); } } $meta = wp_get_attachment_metadata( $id ); $meta = is_array( $meta ) ? $meta : array(); $files = $this->files_of( $file, $meta ); $master = $files['original'] ?? $files['full']; $relinked = $this->relink_backup( $id, $master, $state ); if ( null !== $relinked ) { $state = $relinked; } if ( array() === $state ) { return false; } if ( in_array( $state['status'] ?? '', array( 'failed', 'skipped' ), true ) ) { return false; } $format = str_replace( 'image/', '', (string) get_post_mime_type( $id ) ); $backup = is_array( $state['backup'] ?? null ) ? $state['backup'] : null; $any = false; $rows = array(); foreach ( $files as $name => $path ) { $bytes = (int) filesize( $path ); $size = wp_getimagesize( $path ); $width = false === $size ? 0 : (int) $size[0]; $height = false === $size ? 0 : (int) $size[1]; $before = $state['baseline'][ $name ] ?? null; $was_bytes = is_array( $before ) ? (int) $before['bytes'] : $bytes; if ( null !== $backup && $path === $master && ! is_array( $before ) ) { $was_bytes = max( $bytes, (int) $backup['bytes'] ); } $restored = 'restored' === ( $state['status'] ?? '' ); $status = $restored ? 'restored' : ( $bytes < $was_bytes ? 'optimized' : 'already_optimal' ); $any = $any || 'optimized' === $status; $rows[] = array( 'size_name' => (string) $name, 'format' => $format, 'bytes_before' => $was_bytes, 'bytes_after' => $bytes, 'w_before' => is_array( $before ) ? (int) $before['width'] : $width, 'h_before' => is_array( $before ) ? (int) $before['height'] : $height, 'w_after' => $width, 'h_after' => $height, 'method' => (string) ( $state['methods'][ $name ]['method'] ?? ( $restored ? 'restore' : '' ) ), 'quality' => $state['methods'][ $name ]['quality'] ?? null, 'status' => $status, 'error_code' => '', 'backup_path' => $path === $master && null !== $backup ? (string) $backup['path'] : '', 'checksum' => (string) hash_file( 'sha256', $path ), ); } $this->items->replace( $id, $rows ); if ( ! in_array( $state['status'] ?? '', array( 'optimized', 'already_optimal', 'restored' ), true ) ) { $state['status'] = $any ? 'optimized' : 'already_optimal'; } $this->state->save( $id, $state ); $this->rebuild_derivatives( $id, $files, $master !== $files['full'] ? $master : '' ); // A rebuild is not processing, so the rows keep the date of the last real run. if ( ! empty( $state['updated_at'] ) ) { $this->items->set_processed_at( $id, (string) $state['updated_at'] ); } if ( '' !== $converted_at ) { $this->items->set_processed_at( $id, $converted_at, true ); } return true; } /** * Recreates derivative records from the copies found beside each file. * * @param int $id Attachment ID. * @param array $files Size name to path. * @param string $exclude Unserved master. * @return void */ private function rebuild_derivatives( int $id, array $files, string $exclude ): void { $known = $this->derivatives->records( $id ); $records = array(); $rows = array(); foreach ( $files as $name => $path ) { if ( $path === $exclude ) { continue; } foreach ( self::DERIVATIVES as $format ) { $copy = Derivatives::path_for( $path, $format ); if ( ! is_file( $copy ) ) { continue; } $size = wp_getimagesize( $copy ); $width = false === $size ? 0 : (int) $size[0]; $height = false === $size ? 0 : (int) $size[1]; $bytes = (int) filesize( $copy ); $before = (int) filesize( $path ); $sha = (string) hash_file( 'sha256', $copy ); // A copy that has not changed keeps how it was made. $old = $known[ $format ][ $name ] ?? array(); $same = ( $old['sha256'] ?? '' ) === $sha; $method = $same ? (string) ( $old['method'] ?? '' ) : ''; $quality = $same && isset( $old['quality'] ) ? (int) $old['quality'] : null; $before = $same && isset( $old['before'] ) ? (int) $old['before'] : $before; $records[ $format ][ $name ] = array( 'path' => Paths::relative( $copy ), 'source' => wp_basename( $path ), 'bytes' => $bytes, 'before' => $before, 'width' => $width, 'height' => $height, 'quality' => $quality, 'method' => $method, 'sha256' => $sha, ); $rows[] = array( 'size_name' => (string) $name, 'format' => $format, 'bytes_before' => $before, 'bytes_after' => $bytes, 'w_before' => $width, 'h_before' => $height, 'w_after' => $width, 'h_after' => $height, 'method' => $method, 'quality' => $quality, 'status' => 'optimized', 'error_code' => '', 'backup_path' => '', 'checksum' => $sha, ); } } $this->derivatives->save( $id, $records, $rows ); } /** * Reconnects a backup found on disk when the state has lost track of it. * * @param int $id Attachment ID. * @param string $master Master path. * @param array $state Attachment state. * @return array|null New state, or null when nothing changed. */ private function relink_backup( int $id, string $master, array $state ): ?array { if ( isset( $state['backup'] ) ) { return null; } $base = $this->backups->base_dir(); $matches = glob( $base . '/*/*/' . $id . '-' . (string) preg_replace( '/([*?\[\]])/', '[$1]', wp_basename( $master ) ) ); if ( false === $matches || array() === $matches ) { return null; } $path = (string) $matches[0]; if ( ! Paths::is_inside( $path, array( $base ) ) ) { return null; } $state['backup'] = array( 'path' => substr( $path, strlen( $base ) + 1 ), 'master' => Paths::relative( $master ), 'bytes' => (int) filesize( $path ), 'sha256' => (string) hash_file( 'sha256', $path ), 'created_at' => gmdate( 'Y-m-d H:i:s', (int) filemtime( $path ) ), 'method' => '', 'quality' => null, ); $state['master'] = Paths::relative( $master ); $state['master_bytes'] = (int) filesize( $master ); return $state; } /** * Lists an attachment's files. * * @param string $file Main file. * @param array $meta Attachment metadata. * @return array Size name to path. */ private function files_of( string $file, array $meta ): array { $dir = dirname( $file ); $files = array( 'full' => $file ); if ( ! empty( $meta['original_image'] ) && is_file( $dir . '/' . wp_basename( (string) $meta['original_image'] ) ) ) { $files['original'] = $dir . '/' . wp_basename( (string) $meta['original_image'] ); } foreach ( is_array( $meta['sizes'] ?? null ) ? $meta['sizes'] : array() as $name => $size ) { $path = $dir . '/' . wp_basename( (string) ( $size['file'] ?? '' ) ); if ( ! empty( $size['file'] ) && is_file( $path ) ) { $files[ (string) $name ] = $path; } } return $files; } /** * Returns the next page of attachment IDs. * * @param int $after_id Exclusive lower bound. * @return int[] */ private function page_after( int $after_id ): array { global $wpdb; $placeholders = implode( ',', array_fill( 0, count( LibraryScanner::SUPPORTED_MIMES ), '%s' ) ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- ID-keyed paging; placeholders are generated above. $ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_mime_type IN ({$placeholders}) AND ID > %d ORDER BY ID ASC LIMIT %d", array_merge( LibraryScanner::SUPPORTED_MIMES, array( $after_id, self::PAGE_SIZE ) ) ) ); // phpcs:enable return array_map( 'intval', is_array( $ids ) ? $ids : array() ); } }