trim((string) ($pair['custom_prompt'] ?? '')), 'system_prompt' => trim((string) ($pair['system_prompt'] ?? '')), 'user_prompt' => trim((string) ($pair['user_prompt'] ?? '')), ]; } foreach (self::LEGACY_FLAT_PROMPT_KEYS as $flat_key) { $normalized[$flat_key] = trim((string) ($settings[$flat_key] ?? '')); } return $normalized; }; return $normalize($a) === $normalize($b); } /** * Re-assert a stored key that a capability-limited user's request must * not actually change: copies it from $source, or removes it from * $target when $source never had it either. * * @param array $target Settings about to be stored. * @param array $source Settings to preserve the key from (the job's * settings BEFORE this write). * @param string $key Key to preserve. * @return array $target with $key re-asserted from $source. */ private static function withPreservedKey(array $target, array $source, string $key): array { if (array_key_exists($key, $source)) { $target[$key] = $source[$key]; } else { unset($target[$key]); } return $target; } /** * Whether STORED job settings are "stored-advanced": already running * on raw custom prompts rather than content structure, so a user * without manage_aipt_settings must not be allowed to switch this job * onto the Blueprint path either — that switch needs the same * capability as switching a job INTO custom prompts. * * stored-advanced = settings.blueprint.mode is 'advanced', OR there is * no settings.blueprint key at all and the settings carry a raw * prompt override in either shape (nested or * self::LEGACY_FLAT_PROMPT_KEYS). A job that predates content * structure has no blueprint key and keeps running on whatever custom * prompts it has (BlueprintIntegration::executionPath()'s * legacyPrompts fallback); this mirrors that run-time fallback here so * the write gate cannot be bypassed on a job content structure never * touched. * * @param array $stored_settings The job's settings BEFORE this write. * @return bool */ private static function isStoredAdvanced(array $stored_settings): bool { if (self::isAdvancedMode($stored_settings)) { return true; } if (array_key_exists('blueprint', $stored_settings)) { return false; } return self::hasNonEmptyPrompts($stored_settings); } /** * Capability gate for Automation's "Custom prompts (Advanced)" per-job * choice. Every sibling Advanced doorway in the * plugin (BlueprintChip's advancedPromptsUrl, PromptSettingsNavButton) * already requires manage_aipt_settings; this brings the job wizard in * line. A user holding manage_aipt_settings keeps today's behavior * exactly — this returns null immediately for them. * * @param array $settings Candidate settings about to be * stored (create and any * duplicate/clone/import path: the * new job's settings; update: the * request's replacement settings). * @param array|null $stored_settings Null on create and on any * duplicate/clone/import path (no * prior job to compare against); * the job's settings BEFORE this * write on update, so a stored * custom-prompts job resubmitted * unchanged (e.g. this user only * edited its schedule) is left * alone — mirroring * coerceUnsupportedCadence() and * JobEntitlementGuard's write * guards elsewhere in this file. * @return WP_Error|null */ private function customPromptsCapabilityBlock(array $settings, ?array $stored_settings) { if (current_user_can('manage_aipt_settings')) { return null; } $requested_advanced = self::isAdvancedMode($settings); $requested_has_prompts = self::hasNonEmptyPrompts($settings); if (null === $stored_settings) { return ($requested_advanced || $requested_has_prompts) ? self::customPromptsCapabilityError() : null; } $stored_advanced = self::isStoredAdvanced($stored_settings); $blueprint_requested = array_key_exists('blueprint', $settings); $mode_changed = $blueprint_requested && ($requested_advanced !== $stored_advanced); $prompts_changed = $requested_has_prompts && !self::samePrompts($settings, $stored_settings); return ($mode_changed || $prompts_changed) ? self::customPromptsCapabilityError() : null; } /** * @return WP_Error */ private static function customPromptsCapabilityError(): WP_Error { return new WP_Error( 'rest_forbidden', __('Only users who can manage AI Product Tools settings can use custom prompts in a job.', 'ai-product-tools'), ['status' => 403] ); } /** * Redact a job's raw prompt text for a user without manage_aipt_settings * (same gate as customPromptsCapabilityBlock()). Every sibling Advanced * doorway already hides its raw prompt fields from a user who lacks * this capability; Automation's job responses now match. Strips BOTH * prompt shapes — the nested `prompts` key and the four legacy flat * keys (self::LEGACY_FLAT_PROMPT_KEYS) — so neither can read through. * The `hasCustomPrompts` boolean (reflecting either shape, via * hasNonEmptyPrompts()) lets the UI show a locked note without the * text itself. * * @param array $settings Stored job settings. * @return array Settings safe to send to the current user. */ private static function redactPromptsForResponse(array $settings): array { if (current_user_can('manage_aipt_settings')) { return $settings; } $settings['hasCustomPrompts'] = self::hasNonEmptyPrompts($settings); unset($settings['prompts']); foreach (self::LEGACY_FLAT_PROMPT_KEYS as $flat_key) { unset($settings[$flat_key]); } return $settings; } /** * Strip the response-only `hasCustomPrompts` marker from incoming * settings before anything is stored. redactPromptsForResponse() adds * this boolean to a GET response for a user without * manage_aipt_settings so the UI can show a locked note without the * prompt text itself; the job wizard seeds its component state from * that GET response and later sends the whole settings object back on * create/update (and Duplicate, which reuses create_job()), so * without this the marker would round-trip into storage as if it were * real job data. Stripped unconditionally, for every user — it is * never legitimate input. * * @param array $settings Candidate settings from the request. * @return array $settings without the marker. */ private static function withoutHasCustomPromptsMarker(array $settings): array { unset($settings['hasCustomPrompts']); return $settings; } /** * Keep a product filter's status only when it is a paid product status * (draft, pending review, private). Anything else, including the legacy * 'all' the job form used to send, means published products and is left * out, so every stored filter has one shape for the same selection. * JobEntitlementGuard::filterWriteBlock() has already refused a paid * status this plan cannot honor. * * Applied after construction so the model has already resolved * product_filter into a real array (it nullifies empty arrays, which * would break the array response contract). * * @param mixed $product_filter Product filter. * @return mixed The filter with its canonical status. */ private static function withCanonicalProductStatus($product_filter) { if (!is_array($product_filter) || !array_key_exists('status', $product_filter)) { return $product_filter; } $status = JobEntitlementGuard::productStatus($product_filter); unset($product_filter['status']); if (JobEntitlementGuard::DEFAULT_PRODUCT_STATUS !== $status) { $product_filter['status'] = $status; } return $product_filter; } /** * Whether a job is still waiting for its first run: its product pool * is built (or building) and nothing has been processed from it yet. * * @param AutomationJob $job Job. * @return bool */ private static function isWaitingForFirstRun(AutomationJob $job): bool { return in_array($job->status, ['ready', 'preparing'], true) && 0 === (int) $job->processed_products + (int) $job->failed_products; } /** * Normalize + persist the `skipProcessed` automation setting. * * Canonicalizes the flag through rest_sanitize_boolean (the codebase's * boolean-canonicalization convention) and writes it back into the job * settings array so it is stored as a real boolean in the * aipt_automation_jobs.settings JSON. Defaults to false when absent. * * @param array $settings Raw job settings. * @return array Settings with a canonical `skipProcessed` boolean. */ private function withSkipProcessedSetting(array $settings): array { return AutomationJob::withSkipProcessedSetting($settings); } /** * Reason-aware denial when a job cannot run with its paid behavior, used * before resume, trigger and retry make a job runnable again. * * A saved filter only matters when the pool still has to be built. * * @param AutomationJob $job Job about to become runnable. * @return WP_Error|null */ private function runEntitlementError(AutomationJob $job) { if ((int) $job->total_products <= 0 && is_array($job->product_filter)) { $filter_block = JobEntitlementGuard::filterBlock($job->product_filter, JobEntitlementGuard::CONTEXT_RUN); if (null !== $filter_block) { return JobEntitlementGuard::restError($filter_block); } } $settings = is_array($job->settings) ? $job->settings : []; $translated = (new OptionsTranslator())->translate($settings, (string) $job->tool_type); $assessment = JobEntitlementGuard::assessRun($job, $translated); return null === $assessment['block'] ? null : JobEntitlementGuard::restError($assessment['block']); } /** * A REST-boundary error when includeIds, excludeIds, categories or tags * was filled in but sanitizes to zero valid numeric ids (e.g. a pasted * SKU or a category name instead of a numeric id). An include-only restriction with nothing * valid to include must never silently widen to the whole catalog, and * an exclusion with nothing valid to exclude matches no product at all * (it never falls through to the excluded products); either way the * caller deserves a specific, actionable error instead of discovering it * later as "0 products matched". * * @param array $product_filter Request's product_filter. * @return WP_Error|null Null when both lists are absent, blank, or sanitize to at least one id. */ private static function invalidProductIdListError(array $product_filter) { $raw = $product_filter['includeIds'] ?? null; if (ProductIdListFilter::wasRequested($raw) && empty(ProductIdListFilter::parse($raw))) { return new WP_Error( 'invalid_include_ids', __('Include Only These Product IDs must contain at least one numeric product ID.', 'ai-product-tools'), ['status' => 400] ); } $raw = $product_filter['excludeIds'] ?? null; if (ProductIdListFilter::wasRequested($raw) && empty(ProductIdListFilter::parse($raw))) { return new WP_Error( 'invalid_exclude_ids', __('Exclude These Product IDs must contain at least one numeric product ID.', 'ai-product-tools'), ['status' => 400] ); } $raw = $product_filter['categories'] ?? null; if (ProductIdListFilter::wasRequested($raw) && empty(ProductIdListFilter::parse($raw))) { return new WP_Error( 'invalid_category_ids', __('Categories must contain at least one numeric category ID.', 'ai-product-tools'), ['status' => 400] ); } $raw = $product_filter['tags'] ?? null; if (ProductIdListFilter::wasRequested($raw) && empty(ProductIdListFilter::parse($raw))) { return new WP_Error( 'invalid_tag_ids', __('Product Tags must contain at least one numeric tag ID.', 'ai-product-tools'), ['status' => 400] ); } return null; } }