prefix . 'pixelkeep_items'; } /** * Returns an attachment's rows. * * @param int $attachment_id Attachment ID. * @return array> */ public function for_attachment( int $attachment_id ): array { global $wpdb; $table = $this->table(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE attachment_id = %d ORDER BY id ASC", $attachment_id ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * Replaces an attachment's rows. * * @param int $attachment_id Attachment ID. * @param array> $rows New rows. * @return array{before: int, after: int, files: int} Change in totals, for Stats. */ public function replace( int $attachment_id, array $rows ): array { global $wpdb; $table = $this->table(); $now = current_time( 'mysql', true ); $existing = array(); $delta = array( 'before' => 0, 'after' => 0, 'files' => 0, ); foreach ( $this->originals_for( $attachment_id ) as $row ) { $existing[ $row['size_name'] . '|' . $row['format'] ] = $row; $delta['before'] -= (int) $row['bytes_before']; $delta['after'] -= (int) $row['bytes_after']; --$delta['files']; } foreach ( $rows as $row ) { $key = $row['size_name'] . '|' . $row['format']; $row['updated_at'] = $now; if ( isset( $existing[ $key ] ) ) { $wpdb->update( $table, $row, array( 'id' => (int) $existing[ $key ]['id'] ) ); unset( $existing[ $key ] ); } else { $row['attachment_id'] = $attachment_id; $row['created_at'] = $now; $wpdb->insert( $table, $row ); } $delta['before'] += (int) $row['bytes_before']; $delta['after'] += (int) $row['bytes_after']; ++$delta['files']; } foreach ( $existing as $stale ) { $wpdb->delete( $table, array( 'id' => (int) $stale['id'] ) ); } return $delta; } /** * Removes an attachment's rows. * * @param int $attachment_id Attachment ID. * @return array{before: int, after: int, files: int} Change in totals, for Stats. */ public function delete_attachment( int $attachment_id ): array { $this->delete_derivatives( $attachment_id ); return $this->replace( $attachment_id, array() ); } /** * Replaces an attachment's derivative rows. Derivatives never count toward savings totals. * * @param int $attachment_id Attachment ID. * @param array> $rows New rows. * @return void */ public function replace_derivatives( int $attachment_id, array $rows ): void { global $wpdb; $this->delete_derivatives( $attachment_id ); $now = current_time( 'mysql', true ); foreach ( $rows as $row ) { $row['attachment_id'] = $attachment_id; $row['is_derivative'] = 1; $row['created_at'] = $now; $row['updated_at'] = $now; $wpdb->insert( $this->table(), $row ); } } /** * Removes an attachment's derivative rows. * * @param int $attachment_id Attachment ID. * @return void */ public function delete_derivatives( int $attachment_id ): void { global $wpdb; $wpdb->delete( $this->table(), array( 'attachment_id' => $attachment_id, 'is_derivative' => 1, ) ); } /** * Counts the images that have a derivative in a format. * * @param string $format `webp` or `avif`. * @return int */ public function count_images_with_format( string $format ): int { global $wpdb; $table = $this->table(); return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT attachment_id) FROM {$table} WHERE is_derivative = 1 AND format = %s", $format ) ); } /** * Returns an attachment's rows for its own files, without derivatives. * * @param int $attachment_id Attachment ID. * @return array> */ public function originals_for( int $attachment_id ): array { return array_values( array_filter( $this->for_attachment( $attachment_id ), static fn( $row ) => 0 === (int) $row['is_derivative'] ) ); } /** * Sums all rows. * * @return array{bytes_before: int, bytes_after: int, files: int} */ public function totals(): array { global $wpdb; $table = $this->table(); $row = $wpdb->get_row( "SELECT COALESCE(SUM(bytes_before),0) AS b, COALESCE(SUM(bytes_after),0) AS a, COUNT(*) AS c FROM {$table} WHERE is_derivative = 0", ARRAY_A ); return array( 'bytes_before' => (int) ( $row['b'] ?? 0 ), 'bytes_after' => (int) ( $row['a'] ?? 0 ), 'files' => (int) ( $row['c'] ?? 0 ), ); } /** * Sums one attachment's rows. * * @param int $attachment_id Attachment ID. * @return array{before: int, after: int} */ public function attachment_totals( int $attachment_id ): array { $before = 0; $after = 0; foreach ( $this->originals_for( $attachment_id ) as $row ) { $before += (int) $row['bytes_before']; $after += (int) $row['bytes_after']; } return array( 'before' => $before, 'after' => $after, ); } /** * Returns the most recently updated attachments with their totals. * * @param int $limit Maximum number of attachments. * @return array> */ public function recent_attachments( int $limit = 10 ): array { global $wpdb; $table = $this->table(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT attachment_id, SUM(bytes_before) AS bytes_before, SUM(bytes_after) AS bytes_after, MAX(updated_at) AS updated_at, COUNT(*) AS files FROM {$table} WHERE is_derivative = 0 GROUP BY attachment_id ORDER BY MAX(updated_at) DESC LIMIT %d", $limit ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * Returns one page of rows for the History screen. * * @param int $page 1-based page. * @param int $per_page Rows per page. * @param array $filters Keys: status, format, search. * @return array{rows: array>, total: int} */ public function paginate( int $page, int $per_page, array $filters = array() ): array { global $wpdb; $table = $this->table(); $where = $this->filter_clause( $filters ); $offset = max( 0, ( $page - 1 ) * $per_page ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT i.*, p.post_title FROM {$table} i LEFT JOIN {$wpdb->posts} p ON p.ID = i.attachment_id WHERE {$where} ORDER BY i.updated_at DESC, i.id DESC LIMIT %d OFFSET %d", $per_page, $offset ), ARRAY_A ); $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} i LEFT JOIN {$wpdb->posts} p ON p.ID = i.attachment_id WHERE {$where}" ); return array( 'rows' => is_array( $rows ) ? $rows : array(), 'total' => $total, ); } /** * Returns rows for export, oldest ID first, a page at a time. * * @param array $filters Keys: status, format, search. * @param int $after_id Exclusive lower bound. * @param int $limit Maximum rows. * @return array> */ public function export_page( array $filters, int $after_id, int $limit ): array { global $wpdb; $table = $this->table(); $where = $this->filter_clause( $filters ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT i.*, p.post_title FROM {$table} i LEFT JOIN {$wpdb->posts} p ON p.ID = i.attachment_id WHERE {$where} AND i.id > %d ORDER BY i.id ASC LIMIT %d", $after_id, $limit ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * Returns the space saved per day, for images last processed on that day. * * @param int $days Days back from today. * @return array Date (UTC) to totals, with every day present. */ public function daily_totals( int $days ): array { global $wpdb; $table = $this->table(); $today = time(); $totals = array(); for ( $i = $days - 1; $i >= 0; $i-- ) { $totals[ gmdate( 'Y-m-d', $today - $i * DAY_IN_SECONDS ) ] = array( 'saved' => 0, 'images' => 0, ); } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT DATE(updated_at) AS day, SUM(bytes_before - bytes_after) AS saved, COUNT(DISTINCT attachment_id) AS images FROM {$table} WHERE is_derivative = 0 AND updated_at >= %s GROUP BY DATE(updated_at)", gmdate( 'Y-m-d 00:00:00', $today - ( $days - 1 ) * DAY_IN_SECONDS ) ), ARRAY_A ); foreach ( is_array( $rows ) ? $rows : array() as $row ) { if ( isset( $totals[ $row['day'] ] ) ) { $totals[ $row['day'] ] = array( 'saved' => max( 0, (int) $row['saved'] ), 'images' => (int) $row['images'], ); } } return $totals; } /** * Sets when an attachment was last processed, for records rebuilt after the fact. * * @param int $id Attachment ID. * @param string $date MySQL date in UTC. * @param bool $derivative Whether to set the WebP and AVIF rows instead of the main ones. * @return void */ public function set_processed_at( int $id, string $date, bool $derivative = false ): void { global $wpdb; $table = $this->table(); $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET updated_at = %s WHERE attachment_id = %d AND is_derivative = %d", $date, $id, $derivative ? 1 : 0 ) ); } /** * Removes records of attachments that no longer exist. * * @return void */ public function delete_orphan_rows(): void { global $wpdb; $table = $this->table(); $wpdb->query( "DELETE i FROM {$table} i LEFT JOIN {$wpdb->posts} p ON p.ID = i.attachment_id WHERE p.ID IS NULL" ); } /** * Builds the WHERE clause for history filters. * * @param array $filters Keys: status, format, search. * @return string Safe SQL. */ private function filter_clause( array $filters ): string { global $wpdb; $parts = array( '1=1' ); if ( ! empty( $filters['status'] ) ) { $parts[] = $wpdb->prepare( 'i.status = %s', $filters['status'] ); } if ( ! empty( $filters['format'] ) ) { $parts[] = $wpdb->prepare( 'i.format = %s', $filters['format'] ); } if ( ! empty( $filters['search'] ) ) { $like = '%' . $wpdb->esc_like( $filters['search'] ) . '%'; if ( ctype_digit( $filters['search'] ) ) { $parts[] = $wpdb->prepare( '(p.post_title LIKE %s OR i.attachment_id = %d)', $like, (int) $filters['search'] ); } else { $parts[] = $wpdb->prepare( '(p.post_title LIKE %s OR i.size_name LIKE %s)', $like, $like ); } } return implode( ' AND ', $parts ); } /** * Returns attachments whose backups were created before a date. * * @param string $cutoff MySQL UTC datetime. * @param int $limit Maximum rows. * @return int[] Attachment IDs. */ public function attachments_with_backup_before( string $cutoff, int $limit ): array { global $wpdb; $table = $this->table(); $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE backup_path <> '' AND created_at < %s LIMIT %d", $cutoff, $limit ) ); return array_map( 'intval', is_array( $ids ) ? $ids : array() ); } /** * Returns attachments that have a backup, starting after an ID. * * @param int $after_id Exclusive lower bound. * @param int $limit Maximum rows. * @return int[] Attachment IDs. */ public function attachments_with_backup( int $after_id, int $limit ): array { global $wpdb; $table = $this->table(); $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE backup_path <> '' AND attachment_id > %d ORDER BY attachment_id ASC LIMIT %d", $after_id, $limit ) ); return array_map( 'intval', is_array( $ids ) ? $ids : array() ); } /** * Returns every attachment that has rows, starting after an ID. * * @param int $after_id Exclusive lower bound. * @param int $limit Maximum IDs. * @return int[] */ public function attachments_with_rows( int $after_id, int $limit ): array { global $wpdb; $table = $this->table(); $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT attachment_id FROM {$table} WHERE attachment_id > %d ORDER BY attachment_id ASC LIMIT %d", $after_id, $limit ) ); return array_map( 'intval', is_array( $ids ) ? $ids : array() ); } /** * Clears the backup path on an attachment's rows. * * @param int $attachment_id Attachment ID. * @return void */ public function clear_backup_path( int $attachment_id ): void { global $wpdb; $wpdb->update( $this->table(), array( 'backup_path' => '' ), array( 'attachment_id' => $attachment_id ) ); } }