'rebuild_index', 'references' => 'rebuild_references', 'duplicates' => 'scan_duplicates', ); public function start( string $kind, string $mode = 'full' ): array { if ( ! isset( self::TYPES[ $kind ] ) ) { throw new \InvalidArgumentException( 'Unknown library scan.' ); } $mode = 'index' === $kind && 'differential' === $mode ? 'differential' : 'full'; $lock = 'frkt_scan_start_' . $kind; if ( ! add_option( $lock, time(), '', false ) ) { if ( time() - (int) get_option( $lock ) < 30 ) { return $this->status( $kind ); } delete_option( $lock ); if ( ! add_option( $lock, time(), '', false ) ) { return $this->status( $kind ); } } try { $current = $this->status( $kind ); if ( in_array( $current['status'], array( 'pending', 'running', 'retrying' ), true ) ) { return $current; } $scope = $this->attachment_scope_bounds( $mode ); $max = $scope['max_id']; $total = $scope['total']; $payload = array( 'kind' => $kind, 'scan_mode' => $mode, 'attachment_scope' => 'wpml_originals', 'scan_usage' => 'index' === $kind && self::usage_available(), 'cursor' => 0, 'max_id' => $max, 'total' => $total, 'processed' => 0, 'phase' => 'index', 'done' => false, ); $id = ( new JobRepository() )->create( self::TYPES[ $kind ], $payload, 'library-scan:' . $kind ); if ( $id <= 0 ) { throw new \RuntimeException( __( 'Could not queue the library scan.', 'foldrocket' ) ); } update_option( 'frkt_scan_' . $kind, $id, false ); ( new JobScheduler() )->dispatch( $id ); return $this->status( $kind ); } finally { delete_option( $lock ); } } public function status( string $kind ): array { $id = (int) get_option( 'frkt_scan_' . $kind, 0 ); $job = $id ? ( new JobRepository() )->find( $id ) : null; // An import that includes usage is also the current reference scan. if ( 'references' === $kind ) { $index_id = (int) get_option( 'frkt_scan_index', 0 ); $index_job = $index_id > $id ? ( new JobRepository() )->find( $index_id ) : null; if ( ! empty( $index_job['payload']['scan_usage'] ) ) { $id = $index_id; $job = $index_job; } } $p = $job['payload'] ?? array(); return array( 'jobId' => $job ? $id : 0, 'includesUsage' => ! empty( $p['scan_usage'] ), 'status' => $job['status'] ?? 'idle', 'progress' => (int) ( $job['progress'] ?? 0 ), 'processed' => (int) ( $p['processed'] ?? 0 ), 'total' => (int) ( $p['total'] ?? 0 ), 'phase' => (string) ( $p['phase'] ?? '' ), 'mode' => (string) ( $p['scan_mode'] ?? 'full' ), 'error' => $job['error'] ?? null, ); } /** The cursor only advances after successful work; retries repeat a bounded, idempotent batch. */ public function step( int $job_id, array $p ): array { global $wpdb; $kind = (string) $p['kind']; if ( $job_id !== (int) get_option( 'frkt_scan_' . $kind, 0 ) ) { throw new \RuntimeException( __( 'This scan was superseded by a newer scan.', 'foldrocket' ) ); } if ( 'duplicates' === $kind && 'compare' === $p['phase'] ) { return ( new DuplicateDetector() )->compare_batch( $job_id, $p ); } if ( 'wpml_originals' !== (string) ( $p['attachment_scope'] ?? '' ) ) { $scope = $this->attachment_scope_bounds( (string) ( $p['scan_mode'] ?? 'full' ) ); $p['total'] = $scope['total']; $p['max_id'] = $scope['max_id']; $p['processed'] = $this->count_scoped_attachments_through( (int) ( $p['cursor'] ?? 0 ), $scope['max_id'] ); $p['attachment_scope'] = 'wpml_originals'; } $scope_join = ''; $scope_where = array(); ( new AssetRepository() )->apply_wpml_original_attachment_filter( $scope_join, $scope_where ); $scope_clause = $scope_where ? ' AND ' . implode( ' AND ', $scope_where ) : ''; $dirty_join = ''; $dirty_clause = ''; if ( 'index' === $kind && 'differential' === (string) ( $p['scan_mode'] ?? '' ) ) { $assets = TableNames::assert_plugin_table( TableNames::assets() ); $site_id = TableNames::site_id(); $dirty_join = $wpdb->prepare( ' LEFT JOIN %i frkt_index_asset ON frkt_index_asset.attachment_id = p.ID AND frkt_index_asset.site_id = %d', $assets, $site_id ); $dirty_clause = " AND (frkt_index_asset.id IS NULL OR frkt_index_asset.hash_fingerprint IS NULL OR p.post_modified > frkt_index_asset.updated_at)"; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Bounded cursor scan must reflect the current library; joins contain only a validated WPML table and a prepared plugin-table identifier. $ids = $wpdb->get_col( $wpdb->prepare( "SELECT p.ID FROM {$wpdb->posts} p {$scope_join} {$dirty_join} WHERE p.post_type = 'attachment' AND p.post_status = 'inherit' AND p.ID > %d AND p.ID <= %d {$scope_clause} {$dirty_clause} ORDER BY p.ID ASC LIMIT 5", (int) $p['cursor'], (int) $p['max_id'] ) ) ?: array(); if ( $wpdb->last_error !== '' ) { throw new \RuntimeException( __( 'Could not read the media library. Please retry the scan.', 'foldrocket' ) ); } if ( ! empty( $p['scan_usage'] ) && ! self::usage_available() ) { $p['scan_usage'] = false; } $started = microtime( true ); foreach ( $ids as $id ) { if ( 'references' === $kind || ( 'index' === $kind && ! empty( $p['scan_usage'] ) ) ) { // The scanner indexes the attachment before recording its references. ( new ReferenceScannerService() )->scan_attachment( (int) $id, false ); } else { ( new AssetIndexer() )->index_now( (int) $id ); } $p['cursor'] = (int) $id; ++$p['processed']; if ( microtime( true ) - $started >= 6 ) { break; } } if ( ! $ids ) { if ( 'duplicates' === $kind ) { ( new DuplicateDetector() )->prepare_snapshot( $job_id, (int) $p['max_id'] ); $p['phase'] = 'compare'; $p['seed_cursor'] = 0; $p['partner_cursor'] = 0; } else { $p['done'] = true; $p['phase'] = 'complete'; } } return $p; } private static function usage_available(): bool { return class_exists( ReferenceScannerService::class ) && FeatureRegistry::is_available( 'usage_detection' ); } /** @return array{total: int, max_id: int} */ private function attachment_scope_bounds( string $mode = 'full' ): array { global $wpdb; $join = ''; $where = array(); ( new AssetRepository() )->apply_wpml_original_attachment_filter( $join, $where ); $scope_clause = $where ? ' AND ' . implode( ' AND ', $where ) : ''; if ( 'differential' === $mode ) { $assets = TableNames::assert_plugin_table( TableNames::assets() ); $site_id = TableNames::site_id(); $join .= $wpdb->prepare( ' LEFT JOIN %i frkt_index_asset ON frkt_index_asset.attachment_id = p.ID AND frkt_index_asset.site_id = %d', $assets, $site_id ); $scope_clause .= " AND (frkt_index_asset.id IS NULL OR frkt_index_asset.hash_fingerprint IS NULL OR p.post_modified > frkt_index_asset.updated_at)"; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Aggregate scan bounds must be current; the optional joins contain only validated or prepared table identifiers. $row = $wpdb->get_row( "SELECT COUNT(*) AS total, COALESCE(MAX(p.ID), 0) AS max_id FROM {$wpdb->posts} p {$join} WHERE p.post_type = 'attachment' AND p.post_status = 'inherit' {$scope_clause}", ARRAY_A ); return array( 'total' => (int) ( $row['total'] ?? 0 ), 'max_id' => (int) ( $row['max_id'] ?? 0 ), ); } private function count_scoped_attachments_through( int $cursor, int $max_id ): int { global $wpdb; if ( $cursor <= 0 || $max_id <= 0 ) { return 0; } $join = ''; $where = array(); ( new AssetRepository() )->apply_wpml_original_attachment_filter( $join, $where ); $scope_clause = $where ? ' AND ' . implode( ' AND ', $where ) : ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Live progress count cannot use a stale cache; the WPML join contains only its validated table identifier. return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} p {$join} WHERE p.post_type = 'attachment' AND p.post_status = 'inherit' AND p.ID <= %d AND p.ID <= %d {$scope_clause}", $cursor, $max_id ) ); } public static function progress( array $p ): int { if ( ! empty( $p['done'] ) ) { return 100; } $index = (int) floor( 100 * (int) $p['processed'] / max( 1, (int) $p['total'] ) ); if ( 'duplicates' === $p['kind'] ) { return 'compare' === $p['phase'] ? min( 99, 50 + (int) ( 49 * ( $p['compared'] ?? 0 ) / max( 1, $p['near_total'] ?? 1 ) ) ) : min( 49, (int) ( $index / 2 ) ); } return min( 99, $index ); } }