get_param('status')) { $statuses = array_filter(array_map('trim', explode(',', (string) $request->get_param('status')))); $filters['status'] = count($statuses) > 1 ? array_values($statuses) : reset($statuses); } if ($request->get_param('tool_type')) { $filters['tool_type'] = $request->get_param('tool_type'); } if ($request->get_param('created_by')) { $filters['created_by'] = $request->get_param('created_by'); } $per_page = $request->get_param('per_page') ?: 20; $page = $request->get_param('page') ?: 1; $offset = ($page - 1) * $per_page; $jobs = $this->job_manager->getJobs($filters, $per_page, $offset); $total = $this->job_manager->getJobCount($filters); $prepared_jobs = []; foreach ($jobs as $job) { $prepared_jobs[] = $this->prepare_job_for_response($job); } $response = new WP_REST_Response([ 'success' => true, 'data' => $prepared_jobs, 'pagination' => [ 'total' => $total, 'per_page' => $per_page, 'current_page' => $page, 'total_pages' => ceil($total / $per_page) ] ]); $response->header('X-WP-Total', $total); $response->header('X-WP-TotalPages', ceil($total / $per_page)); return $response; } catch (\Exception $e) { return $this->failure($e, 'Jobs list could not be loaded', 'jobs_fetch_error', __('The jobs could not be loaded.', 'ai-product-tools'), 500, []); } } /** * Get specific job * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function get_job(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error( 'job_not_found', __('Job not found', 'ai-product-tools'), ['status' => 404] ); } $job_data = $this->prepare_job_for_response($job); $progress_details = $this->job_executor->getJobProgress($job_id); foreach (['started_at', 'estimated_completion'] as $time_key) { if (isset($progress_details[$time_key])) { $progress_details[$time_key] = UtcTimestamp::fromStored($progress_details[$time_key], false); } } $job_data['progress_details'] = $progress_details; $job_data['log_statistics'] = $this->logger->getLogStatistics($job_id); return new WP_REST_Response([ 'success' => true, 'data' => $job_data ]); } catch (\Exception $e) { return $this->failure($e, 'Job could not be loaded', 'job_fetch_error', __('The job could not be loaded.', 'ai-product-tools'), 500, ['job_id' => (int) $request->get_param('id')]); } } /** * Get job logs * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function get_job_logs(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error( 'job_not_found', __('Job not found', 'ai-product-tools'), ['status' => 404] ); } $filters = []; if ($request->get_param('level')) { $filters['level'] = $request->get_param('level'); } elseif (!rest_sanitize_boolean($request->get_param('details'))) { $filters['exclude_level'] = 'debug'; } if ($request->get_param('type')) { $filters['type'] = $request->get_param('type'); } $filters['limit'] = $request->get_param('per_page') ?: 50; $filters['offset'] = (($request->get_param('page') ?: 1) - 1) * $filters['limit']; $logs = $this->logger->getJobLogs($job_id, $filters); $product_ids = []; foreach ($logs as $log) { if (is_array($log->context) && isset($log->context['product_id'])) { $product_ids[] = (int) $log->context['product_id']; } } $viewable_product_ids = array_values(array_filter( array_unique($product_ids), static function ($product_id) { return current_user_can('edit_post', $product_id); } )); $product_names = empty($viewable_product_ids) ? [] : (new ProductIdentityResolver())->resolve($viewable_product_ids); $prepared_logs = []; foreach ($logs as $log) { $context = is_array($log->context) ? JobLogger::redactSensitiveContext($log->context) : $log->context; if (is_array($context) && isset($context['product_id'])) { $name = $product_names[(int) $context['product_id']]['name'] ?? ''; if ($name !== '') { $context['product_name'] = $name; } } $prepared_logs[] = [ 'id' => $log->id, 'level' => $log->level, 'message' => $log->message, 'context' => $context, 'created_at' => UtcTimestamp::fromStored($log->created_at, false) ]; } return new WP_REST_Response([ 'success' => true, 'data' => $prepared_logs, 'statistics' => $this->logger->getLogStatistics($job_id) ]); } catch (\Exception $e) { return $this->failure($e, 'Job log could not be loaded', 'logs_fetch_error', __('The job log could not be loaded.', 'ai-product-tools'), 500, ['job_id' => (int) $request->get_param('id')]); } } /** * Get filter options for job creation * * @param WP_REST_Request $request Request object * @return WP_REST_Response Response object */ public function get_filter_options(WP_REST_Request $request) { try { $categories = get_terms([ 'taxonomy' => 'product_cat', 'hide_empty' => true, 'orderby' => 'count', 'order' => 'DESC', 'number' => 10 ]); $formatted_categories = []; foreach ($categories as $category) { $formatted_categories[] = [ 'id' => $category->term_id, 'name' => $category->name, 'count' => $category->count ]; } $tags = get_terms([ 'taxonomy' => 'product_tag', 'hide_empty' => true, 'orderby' => 'count', 'order' => 'DESC', 'number' => 10 ]); $formatted_tags = []; foreach ($tags as $tag) { $formatted_tags[] = [ 'id' => $tag->term_id, 'name' => $tag->name, 'count' => $tag->count ]; } $product_types = [ ['id' => 'simple', 'name' => 'Simple Product'], ['id' => 'variable', 'name' => 'Variable Product'], ['id' => 'grouped', 'name' => 'Grouped Product'], ['id' => 'external', 'name' => 'External/Affiliate Product'] ]; $stock_statuses = [ ['id' => 'all', 'name' => 'All Stock Statuses'], ['id' => 'instock', 'name' => 'In Stock'], ['id' => 'outofstock', 'name' => 'Out of Stock'], ['id' => 'onbackorder', 'name' => 'On Backorder'] ]; $product_statuses = [ ['id' => 'publish', 'name' => __('Published', 'ai-product-tools')], ['id' => 'draft', 'name' => __('Draft', 'ai-product-tools')], ['id' => 'pending', 'name' => __('Pending review', 'ai-product-tools')], ['id' => 'private', 'name' => __('Private', 'ai-product-tools')] ]; return new WP_REST_Response([ 'success' => true, 'data' => [ 'categories' => $formatted_categories, 'tags' => $formatted_tags, 'product_types' => $product_types, 'stock_statuses' => $stock_statuses, 'product_statuses' => $product_statuses ] ]); } catch (\Exception $e) { return $this->failure($e, 'Filter options could not be loaded', 'filter_options_error', __('The filter options could not be loaded.', 'ai-product-tools'), 500, []); } } /** * Get list jobs arguments * * @return array Arguments schema */ private function get_list_jobs_args() { return [ 'status' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ($param) { $statuses = array_filter(array_map('trim', explode(',', (string) $param))); if (empty($statuses)) { return false; } foreach ($statuses as $status) { if (!in_array($status, AutomationJob::VALID_STATUSES, true)) { return false; } } return true; } ], 'tool_type' => [ 'required' => false, 'type' => 'string', 'enum' => AutomationJob::VALID_TOOL_TYPES, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg' ], 'created_by' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint' ], 'per_page' => [ 'required' => false, 'type' => 'integer', 'default' => 20, 'minimum' => 1, 'maximum' => 100, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ], 'page' => [ 'required' => false, 'type' => 'integer', 'default' => 1, 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ] ]; } /** * Get job logs arguments * * @return array Arguments schema */ private function get_job_logs_args() { return [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ], 'level' => [ 'required' => false, 'type' => 'string', 'enum' => ['info', 'warning', 'error', 'debug'], 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg' ], 'details' => [ 'required' => false, 'type' => 'boolean', 'default' => false, 'description' => 'Include debug-level log lines when no level filter is given.', 'sanitize_callback' => 'rest_sanitize_boolean' ], 'type' => [ 'required' => false, 'type' => 'string', 'description' => 'Logical error category (AI_PROVIDER, WC_UPDATE, NETWORK, AUTH, RATE_LIMIT, VALIDATION, DB, SYSTEM)', 'sanitize_callback' => 'sanitize_text_field' ], 'per_page' => [ 'required' => false, 'type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 1000, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ], 'page' => [ 'required' => false, 'type' => 'integer', 'default' => 1, 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ] ]; } /** * Lightweight monitor endpoint for real-time job progress * - Cached for a few seconds to avoid DB pressure * - Returns progress, counts, time estimations and current processing items (up to 3) */ public function get_job_monitor(\WP_REST_Request $request) { try { global $wpdb; $job_id = (int) $request->get_param('id'); $rl = $this->check_automation_rate_limit('monitor_' . $job_id, AutomationConstants::RATE_LIMIT_MONITOR_WINDOW); if (is_wp_error($rl)) { return $rl; } // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query for ownership verification $owner_id = (int) $wpdb->get_var( $wpdb->prepare("SELECT created_by FROM {$wpdb->prefix}aipt_automation_jobs WHERE id = %d", $job_id) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching if ($owner_id <= 0) { return new \WP_Error('job_not_found', __('Job not found', 'ai-product-tools'), ['status' => 404]); } $cache_key = 'aipt_job_monitor_' . $job_id; $cached = get_transient($cache_key); if (is_array($cached)) { return new \WP_REST_Response(['success' => true, 'data' => $this->withProcessingTitles($cached)]); } $job = $this->job_manager->getJob($job_id); if (!$job) { return new \WP_Error('job_not_found', __('Job not found', 'ai-product-tools'), ['status' => 404]); } if ($job->status !== 'running') { $data = [ 'id' => (int) $job->id, 'status' => $job->status, 'progress_percent' => (int) $job->progress, 'processed_products' => (int) $job->processed_products, 'total_products' => (int) $job->total_products, 'failed_products' => (int) $job->failed_products, 'started_at' => UtcTimestamp::fromStored($job->started_at, false), 'estimated_completion' => null, 'estimated_completion_capped' => false, 'elapsed_seconds' => null, 'elapsed_human' => null, 'remaining_seconds' => null, 'remaining_human' => null, 'current_processing' => [ 'count' => 0, 'items' => [] ], 'updated_at' => gmdate('Y-m-d\TH:i:s\Z'), ]; set_transient($cache_key, $data, 5); return new \WP_REST_Response(['success' => true, 'data' => $data]); } $progress = $this->job_executor->getJobProgress($job_id); $started_at_ts = $job->started_at ? JobTime::toTimestamp($job->started_at) : null; $now = time(); $elapsed_seconds = $started_at_ts ? max(0, $now - $started_at_ts) : null; $eta_str = $progress['estimated_completion'] ?? null; $eta_ts = $eta_str ? strtotime($eta_str) : null; $remaining_seconds = ($eta_ts && $eta_ts > $now) ? ($eta_ts - $now) : null; $human = function($seconds) { if ($seconds === null) return null; if ($seconds < 60) return '~' . $seconds . 's'; $m = floor($seconds / 60); if ($m < 60) return '~' . $m . ' min'; $h = floor($m / 60); $rm = $m % 60; return '~' . $h . 'h ' . ($rm ? $rm . 'm' : ''); }; $job_products_table = $wpdb->prefix . 'aipt_job_products'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query; no WP API for aipt_job_products $processing_rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safely constructed from $wpdb->prefix "SELECT product_id FROM {$job_products_table} WHERE job_id = %d AND status = 'processing' ORDER BY processing_started_at DESC, id DESC LIMIT 3", $job_id ) ); $current_items = []; if (!empty($processing_rows)) { foreach ($processing_rows as $row) { $current_items[] = ['product_id' => (int) $row->product_id]; } } $data = [ 'id' => (int) $job->id, 'status' => $job->status, 'progress_percent' => (int) ($progress['progress'] ?? $job->progress), 'processed_products' => (int) ($progress['processed_products'] ?? $job->processed_products), 'total_products' => (int) ($progress['total_products'] ?? $job->total_products), 'failed_products' => (int) ($progress['failed_products'] ?? $job->failed_products), 'started_at' => UtcTimestamp::fromStored($job->started_at, false), 'estimated_completion' => UtcTimestamp::fromStored($eta_str, false), 'estimated_completion_capped' => !empty($progress['estimated_completion_capped']), 'elapsed_seconds' => $elapsed_seconds, 'elapsed_human' => $human($elapsed_seconds), 'remaining_seconds' => $remaining_seconds, 'remaining_human' => $human($remaining_seconds), 'current_processing' => [ 'count' => count($current_items), 'items' => $current_items ], 'updated_at' => gmdate('Y-m-d\TH:i:s\Z'), ]; set_transient($cache_key, $data, 5); return new \WP_REST_Response(['success' => true, 'data' => $this->withProcessingTitles($data)]); } catch (\Exception $e) { return $this->failure($e, 'Job monitor could not be loaded', 'monitor_error', __('The job monitor could not be loaded.', 'ai-product-tools'), 500); } } /** * The ids of a list that the current user may edit. * * The job routes are gated by manage_woocommerce alone, which lets every * holder read every job. A product's name goes only to a user who may * open that product, as in get_job_logs() and the Business review routes: a * role without edit_others_products must not learn the names of products * it cannot edit from a job's product list or from its monitor. * * @param array $product_ids Product ids. * @return array The editable ids, as keys. */ private function editableProductIds(array $product_ids): array { $product_ids = array_values(array_unique(array_filter(array_map('intval', $product_ids)))); if (empty($product_ids)) { return []; } if (function_exists('_prime_post_caches')) { _prime_post_caches($product_ids, false, false); } $editable = []; foreach ($product_ids as $product_id) { if (current_user_can('edit_post', $product_id)) { $editable[$product_id] = true; } } return $editable; } /** * Adds the names of the products a monitor payload lists as processing, * for the products the current user may edit. The cached payload holds * ids only, so one user's poll never serves names to another. * * @param array $data Monitor payload. * @return array */ private function withProcessingTitles(array $data): array { $items = $data['current_processing']['items'] ?? []; if (!is_array($items) || empty($items)) { return $data; } $editable = $this->editableProductIds(array_column($items, 'product_id')); foreach ($items as $index => $item) { $product_id = (int) ($item['product_id'] ?? 0); $title = isset($editable[$product_id]) ? get_the_title($product_id) : ''; $items[$index] = [ 'product_id' => $product_id, 'title' => is_string($title) ? $title : '', ]; } $data['current_processing']['items'] = $items; return $data; } /** * Get paginated list of job products with statuses and titles (compact) * * @param WP_REST_Request $request * @return WP_REST_Response|WP_Error */ public function get_job_products(WP_REST_Request $request) { global $wpdb; try { $job_id = (int) $request->get_param('id'); $page = max(1, (int) $request->get_param('page')) ?: 1; $per_page = (int) $request->get_param('per_page'); if ($per_page <= 0) { $per_page = 50; } if ($per_page > 200) { $per_page = 200; } $offset = ($page - 1) * $per_page; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query for ownership verification $owner_id = (int) $wpdb->get_var( $wpdb->prepare("SELECT created_by FROM {$wpdb->prefix}aipt_automation_jobs WHERE id = %d", $job_id) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching if ($owner_id <= 0) { return new \WP_Error('job_not_found', __('Job not found', 'ai-product-tools'), ['status' => 404]); } $status = $request->get_param('status'); $allowed_status = ['pending','processing','completed','failed']; $where = " WHERE jp.job_id = %d"; $params = [$job_id]; if (is_string($status) && in_array($status, $allowed_status, true)) { $where .= " AND jp.status = %s"; $params[] = $status; } $job_products_table = $wpdb->prefix . 'aipt_job_products'; $count_sql = "SELECT COUNT(*) FROM {$job_products_table} jp" . $where; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if (count($params) === 1) { $prepared_count = $wpdb->prepare($count_sql, $params[0]); } else { $prepared_count = $wpdb->prepare($count_sql, $params[0], $params[1]); } $total = (int) $wpdb->get_var($prepared_count); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $results_params = array_merge($params, [$per_page, $offset]); $results_sql = "SELECT jp.product_id, jp.status, jp.result, jp.error_message, COALESCE(p.post_title, '') as title FROM {$job_products_table} jp LEFT JOIN {$wpdb->posts} p ON p.ID = jp.product_id " . $where . " ORDER BY jp.id ASC LIMIT %d OFFSET %d"; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if (count($results_params) === 3) { $prepared_results = $wpdb->prepare($results_sql, $results_params[0], $results_params[1], $results_params[2]); } else { $prepared_results = $wpdb->prepare($results_sql, $results_params[0], $results_params[1], $results_params[2], $results_params[3]); } $rows = $wpdb->get_results($prepared_results, ARRAY_A); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $queue_available = $this->reviewQueueAvailableForDisplay(); $items = []; if (!empty($rows)) { $editable = $this->editableProductIds(array_column($rows, 'product_id')); foreach ($rows as $r) { $decoded_result = json_decode((string) ($r['result'] ?? ''), true); $blueprint_summary = $this->blueprintItemSummary(is_array($decoded_result) ? $decoded_result : []); $items[] = [ 'product_id' => (int) $r['product_id'], 'status' => (string) $r['status'], 'title' => isset($editable[(int) $r['product_id']]) ? (string) $r['title'] : '', 'needsReview' => $blueprint_summary['needsReview'], 'waitingInReview' => $queue_available && is_array($decoded_result) && self::isWaitingInReviewMarker($decoded_result), 'blueprint' => $blueprint_summary['blueprint'], 'heldBackMessage' => $blueprint_summary['heldBackMessage'], 'errorMessage' => isset($r['error_message']) && null !== $r['error_message'] && '' !== $r['error_message'] ? (string) $r['error_message'] : null, ]; } } $pages = $per_page > 0 ? (int) ceil($total / $per_page) : 1; $result_counts = $this->countJobResultSummaries($job_id); return new \WP_REST_Response([ 'success' => true, 'data' => [ 'total' => $total, 'page' => $page, 'per_page' => $per_page, 'pages' => $pages, 'needsReviewCount' => $result_counts['needsReview'], 'waitingInReviewCount' => $queue_available ? $result_counts['waitingInReview'] : 0, 'items' => $items, ] ]); } catch (\Exception $e) { return $this->failure($e, 'Job products could not be loaded', 'job_products_error', __('The job products could not be loaded.', 'ai-product-tools'), 500, ['job_id' => (int) $request->get_param('id')]); } } /** * Derive a lightweight, display-only Blueprint summary from one job * product's decoded `result` payload. Returns inert defaults for a * legacy/advanced result (no `executionPath` key) or an undecodable * payload, so a legacy job's products list is unaffected. * * @param array $decoded Decoded `result` JSON, or [] when absent/invalid. * @return array{needsReview:bool,blueprint:array{id:int|null,name:string,revision:int|null}|null,heldBackMessage:?string} */ private function blueprintItemSummary(array $decoded): array { if ('blueprint' !== (string) ($decoded['executionPath'] ?? '')) { return ['needsReview' => false, 'blueprint' => null, 'heldBackMessage' => null]; } $eligibility = is_array($decoded['eligibility'] ?? null) ? $decoded['eligibility'] : []; $needs_review = ! empty($eligibility['requiresReview']) || (array_key_exists('canApply', $eligibility) && empty($eligibility['canApply'])); $blueprint = is_array($decoded['blueprint'] ?? null) ? $decoded['blueprint'] : []; return [ 'needsReview' => $needs_review, 'blueprint' => [ 'id' => isset($blueprint['id']) ? $blueprint['id'] : null, 'name' => (string) ($blueprint['name'] ?? ''), 'revision' => isset($blueprint['revision']) ? $blueprint['revision'] : null, ], 'heldBackMessage' => $needs_review ? BlueprintIntegration::heldBackMessage($decoded) : null, ]; } /** * Whether a stored result is the marker JobExecutor writes when it skipped * a product before the provider call because every field the job would * generate already waited in To review. * * @param array $decoded Decoded `result` JSON. * @return bool */ private static function isWaitingInReviewMarker(array $decoded): bool { return true === ($decoded['skipped'] ?? null) && 'waiting_in_review' === ($decoded['reason'] ?? null); } /** * Whether the products list may point at To review: the Business build * offers a review stager and the entitlement says so. Read through the * cache-only twin, never the plain gate, which can make a synchronous * Freemius call on a request that only renders a list. * * @return bool */ private function reviewQueueAvailableForDisplay(): bool { return (bool) apply_filters('aipt_content_review_enabled_cache_only', false) && null !== ReviewQueueStaging::stager(); } /** * Count, over one job's stored results, the rows whose Blueprint result * still needs review and the rows skipped because their proposals already * waited in To review. A best-effort display aggregate for the job detail * panel: no column indexes this, so it walks the rows with a non-empty * `result` payload in id-ordered chunks (bounded memory) and decodes each * in PHP, once for both counts. The totals are cached briefly because the * open details panel re-requests the products list on every monitor * progress change. Deliberately not called from the high-frequency job * monitor poll or the job list. * * @param int $job_id Job ID. * @return array{needsReview:int,waitingInReview:int} */ private function countJobResultSummaries(int $job_id): array { global $wpdb; $needs_review_key = 'aipt_job_needs_review_' . $job_id; $waiting_key = 'aipt_job_waiting_in_review_' . $job_id; $cached_needs_review = get_transient($needs_review_key); $cached_waiting = get_transient($waiting_key); if (false !== $cached_needs_review && false !== $cached_waiting) { return ['needsReview' => (int) $cached_needs_review, 'waitingInReview' => (int) $cached_waiting]; } $job_products_table = $wpdb->prefix . 'aipt_job_products'; $chunk_size = 200; $last_id = 0; $needs_review = 0; $waiting = 0; do { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name from $wpdb->prefix; the aggregate is cached through a short transient below $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, result FROM {$job_products_table} WHERE job_id = %d AND id > %d AND result IS NOT NULL AND result <> '' ORDER BY id ASC LIMIT %d", $job_id, $last_id, $chunk_size ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching foreach ($rows as $row) { $last_id = (int) $row['id']; $decoded = json_decode((string) $row['result'], true); if (!is_array($decoded)) { continue; } if ($this->blueprintItemSummary($decoded)['needsReview']) { $needs_review++; } if (self::isWaitingInReviewMarker($decoded)) { $waiting++; } } } while (count($rows) === $chunk_size); set_transient($needs_review_key, $needs_review, 15); set_transient($waiting_key, $waiting, 15); return ['needsReview' => $needs_review, 'waitingInReview' => $waiting]; } }