'array', 'sanitize_callback' => [self::class, 'sanitizePrompts'], 'default' => [], ]); } public static function sanitizePrompts($input): array { if (!is_array($input)) { return Prompts::overrides(); } // Must not write the option here: update_option() re-runs this callback. return Prompts::normalize($input); } public static function handlePromptTest(): void { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to do this.', 'aipcf-ai-provider-for-cloudflare'), 403); } check_admin_referer('aipcf_prompt_test'); $key = isset($_GET['key']) ? sanitize_key(wp_unslash((string) $_GET['key'])) : ''; if (!isset(Prompts::definitions()[$key])) { wp_safe_redirect(SettingsPage::tabUrl('prompts')); exit; } if (!empty($_GET['reset'])) { $o = Prompts::overrides(); unset($o[$key]); $o === [] ? delete_option(Prompts::OPTION) : update_option(Prompts::OPTION, $o, false); set_transient('aipcf_notice_' . get_current_user_id(), ['type' => 'success', 'message' => __('Prompt reset to default.', 'aipcf-ai-provider-for-cloudflare')], 60); wp_safe_redirect(SettingsPage::tabUrl('prompts') . '#' . self::fieldId('prompt_' . $key)); exit; } $before = UsageTracker::todayNeurons(); $out = ''; // Same task context as the backfill so the test uses the same (light) model and cost. TaskContext::pin($key === 'alt_text' ? 'backfill-alt-text' : 'backfill-meta-description'); try { if ($key === 'meta_description') { $ids = get_posts(['numberposts' => 1, 'post_status' => 'publish', 'fields' => 'ids']); if ($ids === []) { throw new \RuntimeException(__('No published post to test on.', 'aipcf-ai-provider-for-cloudflare')); } $post = get_post((int) $ids[0]); $content = mb_substr(trim((string) preg_replace('/\s+/', ' ', wp_strip_all_tags(strip_shortcodes((string) $post->post_content)))), 0, 6000); $r = \WordPress\AiClient\AiClient::prompt("Title: " . get_the_title($post) . "\n\nContent:\n" . $content) ->usingProvider('cloudflare-workers-ai')->usingSystemInstruction(Prompts::render('meta_description'))->usingMaxTokens(120)->generateTextResult(); $out = sprintf( /* translators: 1: generated text, 2: number of characters, 3: post title */ __('"%1$s" (%2$d characters, from the post "%3$s")', 'aipcf-ai-provider-for-cloudflare'), trim($r->toText()), mb_strlen(trim($r->toText())), get_the_title($post) ); } else { $ids = get_posts(['numberposts' => 1, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_status' => 'inherit', 'fields' => 'ids']); if ($ids === []) { throw new \RuntimeException(__('No image in the media library to test on.', 'aipcf-ai-provider-for-cloudflare')); } $aid = (int) $ids[0]; $path = (string) (get_attached_file($aid) ?: ''); $src = $path !== '' && file_exists($path) ? $path : (string) wp_get_attachment_url($aid); $vm = \WordPress\AiClient\AiClient::defaultRegistry()->getProviderModel('cloudflare-workers-ai', vision_model_id()); $msg = new \WordPress\AiClient\Messages\DTO\Message(\WordPress\AiClient\Messages\Enums\MessageRoleEnum::user(), [ new \WordPress\AiClient\Messages\DTO\MessagePart(Prompts::render('alt_text')), new \WordPress\AiClient\Messages\DTO\MessagePart(new \WordPress\AiClient\Files\DTO\File($src)), ]); $r = \WordPress\AiClient\AiClient::prompt([$msg])->usingModel($vm)->usingMaxTokens(80)->generateTextResult(); /* translators: 1: generated alt text, 2: image file name */ $out = sprintf(__('"%1$s" (for %2$s)', 'aipcf-ai-provider-for-cloudflare'), trim($r->toText()), basename($src)); } $cost = UsageTracker::todayNeurons() - $before; set_transient('aipcf_notice_' . get_current_user_id(), ['type' => 'success', 'message' => sprintf( /* translators: 1: result, 2: neurons */ __('Result: %1$s. Cost: %2$s neurons.', 'aipcf-ai-provider-for-cloudflare'), $out, number_format($cost, 2) )], 60); } catch (\Throwable $e) { set_transient('aipcf_notice_' . get_current_user_id(), ['type' => 'error', 'message' => $e->getMessage()], 60); } TaskContext::clear(); wp_safe_redirect(SettingsPage::tabUrl('prompts') . '#' . self::fieldId('prompt_' . $key)); exit; } // ================================================================ overview public static function tryItHint(): array { $on = static function (string $feature): bool { return (bool) get_option('wpai_features_enabled') && (bool) get_option('wpai_feature_' . $feature . '_enabled', false); }; if ($on('meta-description')) { return [ 'text' => __('Open a post, expand "Meta description" in the sidebar and click "Generate meta description". About 2 neurons.', 'aipcf-ai-provider-for-cloudflare'), 'url' => admin_url('edit.php'), 'label' => __('Posts', 'aipcf-ai-provider-for-cloudflare'), ]; } if ($on('excerpt')) { return [ 'text' => __('Open a post and click "Generate excerpt" in the excerpt panel. About 2 neurons.', 'aipcf-ai-provider-for-cloudflare'), 'url' => admin_url('edit.php'), 'label' => __('Posts', 'aipcf-ai-provider-for-cloudflare'), ]; } if ($on('alt-text-generation')) { return [ 'text' => __('Open an image in the Media Library and click "Generate alt text". About 17 neurons.', 'aipcf-ai-provider-for-cloudflare'), 'url' => admin_url('upload.php'), 'label' => __('Media Library', 'aipcf-ai-provider-for-cloudflare'), ]; } return [ 'text' => __('Turn on a feature in the AI plugin (meta descriptions, excerpts, alt text) and it will use this provider.', 'aipcf-ai-provider-for-cloudflare'), 'url' => admin_url('options-general.php?page=ai-wp-admin'), 'label' => __('AI settings', 'aipcf-ai-provider-for-cloudflare'), ]; } // ================================================================ notices public static function gatewayNotice(): void { if (!current_user_can('manage_options') || Gateway::id() === '' || !get_transient(Gateway::DOWN_TRANSIENT)) { return; } $last = get_option(Gateway::LAST_ERROR_OPTION); printf( '

%s %s %s %s

', esc_html__('Cloudflare AI Gateway bypassed.', 'aipcf-ai-provider-for-cloudflare'), esc_html(is_array($last) && !empty($last['reason']) ? (string) $last['reason'] : ''), esc_html__('Requests go directly to Workers AI for up to an hour.', 'aipcf-ai-provider-for-cloudflare'), esc_url(SettingsPage::tabUrl('gateway')), esc_html__('Check the gateway settings', 'aipcf-ai-provider-for-cloudflare') ); } public static function licenceNotice(): void { if (!current_user_can('manage_options')) { return; } $gates = get_option(Gateway::LICENCE_OPTION, []); if (!is_array($gates) || $gates === []) { return; } foreach (array_keys($gates) as $modelId) { $model = (string) $modelId; $owner = Gateway::licenceOwner($model); echo '

' . esc_html(sprintf( /* translators: 1: license owner, e.g. Meta, 2: model name */ __('%1$s\'s license for %2$s needs to be accepted once.', 'aipcf-ai-provider-for-cloudflare'), $owner, pretty_model_name($model) )) . ' '; echo esc_html(sprintf( /* translators: 1: license owner, e.g. Meta */ __('This is %1$s\'s license, not AIPCF\'s. Cloudflare will not run this model on your account until you accept it, and Cloudflare keeps the record of your acceptance. AIPCF has no license of its own: the button below only sends your acceptance ("agree") to Cloudflare with your API token, exactly as the manual command does. Alt text and image reading use this model.', 'aipcf-ai-provider-for-cloudflare'), $owner )) . '

'; $terms = sprintf( /* translators: 1: license owner, 2: link to the model page */ __('By accepting, you agree to %1$s\'s license terms and acceptable use policy, linked on %2$s.', 'aipcf-ai-provider-for-cloudflare'), esc_html($owner), '' . esc_html__('Cloudflare\'s page for this model', 'aipcf-ai-provider-for-cloudflare') . '' ); if (Gateway::licenceExcludesEu($model)) { /* translators: %s: license owner */ $terms .= ' ' . esc_html(sprintf(__('You also confirm you are not based in the EU: %s\'s license excludes EU residents for this model.', 'aipcf-ai-provider-for-cloudflare'), $owner)); } $terms .= ' ' . esc_html__('It is done once per Cloudflare account.', 'aipcf-ai-provider-for-cloudflare'); echo '

' . wp_kses_post($terms) . '

'; // This notice shows on every admin screen, where the plugin's stylesheet is not loaded, // so it uses only WordPress notice markup: the

elements give the spacing. The //

sits between two paragraphs so their margins space it, open or closed. echo '
' . esc_html__('Prefer to send it yourself?', 'aipcf-ai-provider-for-cloudflare') . '

' . esc_html__('Run this once from any machine, with your Workers AI token in place of TOKEN:', 'aipcf-ai-provider-for-cloudflare') . '
curl -X POST https://api.cloudflare.com/client/v4/accounts/' . esc_html(get_account_id()) . '/ai/run/' . esc_html($model) . ' -H "Authorization: Bearer TOKEN" -H "Content-Type: application/json" -d \'{"prompt":"agree"}\'

'; echo '

'; echo ''; wp_nonce_field('aipcf_licence_accept'); printf( ' ', esc_attr__('Sending...', 'aipcf-ai-provider-for-cloudflare'), /* translators: %s: license owner, e.g. Meta */ esc_html(sprintf(__('Accept %s\'s license and send it to Cloudflare', 'aipcf-ai-provider-for-cloudflare'), $owner)) ); printf( '%s', esc_url(wp_nonce_url(admin_url('admin-post.php?action=aipcf_licence_recheck&model=' . rawurlencode($model)), 'aipcf_licence_recheck')), esc_attr__('Checking...', 'aipcf-ai-provider-for-cloudflare'), esc_html__('Already accepted? Check again', 'aipcf-ai-provider-for-cloudflare') ); echo '

'; } } // ================================================================ handlers public static function handleRefreshModels(): void { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to do this.', 'aipcf-ai-provider-for-cloudflare'), 403); } check_admin_referer('aipcf_refresh_models'); flush_model_caches(); $n = count(fetch_catalog()); $t = count(fetch_available_models()); set_transient('aipcf_notice_' . get_current_user_id(), [ 'type' => $n > 0 ? 'success' : 'error', 'message' => $n > 0 /* translators: 1: number of text models, 2: number of models in total */ ? sprintf(_n('Model list refreshed: %1$d text model (%2$d models in total) on your account.', 'Model list refreshed: %1$d text models (%2$d models in total) on your account.', $t, 'aipcf-ai-provider-for-cloudflare'), $t, $n) : (core_connector_is_available() && (string) (get_plugin_settings()['api_key'] ?? '') === '' ? __('Could not read the model list from Cloudflare. Check the API token on Settings > Connectors and the Account ID on Settings > Connection.', 'aipcf-ai-provider-for-cloudflare') : __('Could not read the model list from Cloudflare. Check the credentials on Settings > Connection.', 'aipcf-ai-provider-for-cloudflare')), ], 60); wp_safe_redirect(SettingsPage::tabUrl('models') . '#aipcf_preferred_model'); exit; } public static function handleLicenceAccept(): void { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to do this.', 'aipcf-ai-provider-for-cloudflare'), 403); } check_admin_referer('aipcf_licence_accept'); $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash((string) $_POST['model'])) : ''; $result = Gateway::acceptLicence($model); set_transient('aipcf_notice_' . get_current_user_id(), [ 'type' => $result === true ? 'success' : 'error', 'message' => $result === true /* translators: 1: license owner, 2: model id */ ? sprintf(__('Cloudflare has recorded your acceptance of %1$s\'s license for %2$s. Alt text and image reading work now.', 'aipcf-ai-provider-for-cloudflare'), Gateway::licenceOwner($model), $model) /* translators: %s: error */ : sprintf(__('Cloudflare did not record the acceptance: %s', 'aipcf-ai-provider-for-cloudflare'), $result), ], 60); wp_safe_redirect(SettingsPage::tabUrl('overview')); exit; } public static function handleLicenceRecheck(): void { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to do this.', 'aipcf-ai-provider-for-cloudflare'), 403); } check_admin_referer('aipcf_licence_recheck'); $model = isset($_GET['model']) ? sanitize_text_field(wp_unslash((string) $_GET['model'])) : ''; $ok = false; $msg = ''; if ($model !== '' && class_exists('\\WordPress\\AiClient\\AiClient')) { try { TaskContext::set('licence-recheck'); $m = \WordPress\AiClient\AiClient::defaultRegistry()->getProviderModel('cloudflare-workers-ai', $model); \WordPress\AiClient\AiClient::prompt('Reply with OK')->usingModel($m)->usingMaxTokens(5)->generateTextResult(); $ok = true; Gateway::clearLicenceGate($model); } catch (\Throwable $e) { $msg = $e->getMessage(); } TaskContext::clear(); } set_transient('aipcf_notice_' . get_current_user_id(), [ 'type' => $ok ? 'success' : 'error', 'message' => $ok ? sprintf( /* translators: 1: model id, 2: license owner */ __('%1$s answered: Cloudflare has your acceptance of %2$s\'s license on record.', 'aipcf-ai-provider-for-cloudflare'), $model, Gateway::licenceOwner($model) ) : sprintf( /* translators: %s: error */ __('Still blocked: %s', 'aipcf-ai-provider-for-cloudflare'), $msg ), ], 60); wp_safe_redirect(SettingsPage::tabUrl('overview')); exit; } public static function handleGatewayTest(): void { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to do this.', 'aipcf-ai-provider-for-cloudflare'), 403); } check_admin_referer('aipcf_gateway_test'); Gateway::markUp(); // The site's own default model, so the test shows up in the gateway logs as // the model the site actually uses. $model = get_default_model_id(); $url = Gateway::chatUrl(); $body = [ 'model' => Gateway::modelParam($model), 'messages' => [['role' => 'user', 'content' => 'Reply with OK']], 'max_tokens' => 5, ]; $headers = ['Authorization' => 'Bearer ' . get_api_key(), 'Content-Type' => 'application/json'] + Gateway::headers('gateway-test', false, $model); $resp = wp_remote_post($url, ['timeout' => 30, 'headers' => $headers, 'body' => wp_json_encode($body)]); if (is_wp_error($resp)) { $msg = $resp->get_error_message(); $ok = false; } else { $code = (int) wp_remote_retrieve_response_code($resp); $ok = $code >= 200 && $code < 300; $data = json_decode((string) wp_remote_retrieve_body($resp), true); if ($ok) { $msg = Gateway::isGatewayUrl($url) /* translators: %d: HTTP status code */ ? sprintf(__('HTTP %d, through the gateway', 'aipcf-ai-provider-for-cloudflare'), $code) /* translators: %d: HTTP status code */ : sprintf(__('HTTP %d, directly (the gateway is bypassed)', 'aipcf-ai-provider-for-cloudflare'), $code); } else { $msg = sprintf('HTTP %d: %s', $code, self::errorText($data, (string) wp_remote_retrieve_body($resp))); } if ($ok && is_array($data)) { UsageTracker::recordFromResponse($model, $data, 'gateway-test'); } } set_transient('aipcf_notice_' . get_current_user_id(), [ 'type' => $ok ? 'success' : 'error', 'message' => $ok /* translators: %s: detail, e.g. "HTTP 200, through the gateway" */ ? sprintf(__('Gateway test passed: %s', 'aipcf-ai-provider-for-cloudflare'), $msg) /* translators: %s: error detail */ : sprintf(__('Gateway test failed: %s', 'aipcf-ai-provider-for-cloudflare'), $msg), ], 60); wp_safe_redirect(SettingsPage::tabUrl('gateway')); exit; } private static function errorText($data, string $fallback): string { $m = is_array($data) ? ($data['errors'][0]['message'] ?? $data['error'][0]['message'] ?? $data['error']['message'] ?? $data['error'] ?? null) : null; return is_scalar($m) && (string) $m !== '' ? (string) $m : $fallback; } // ================================================================ sanitize public static function sanitize(array $clean, array $input): array { $prev = get_plugin_settings(); $tab = isset($input['_tab']) ? sanitize_key((string) $input['_tab']) : ''; $own = static function (string $key) use ($tab): bool { return $tab === '' || in_array($key, SettingsPage::tabKeys($tab), true); }; $keep = static function (string $key) use ($prev, $input) { return array_key_exists($key, $input) ? $input[$key] : ($prev[$key] ?? null); }; $flag = static function (string $key, int $default) use ($own, $input, $prev): int { return $own($key) ? (empty($input[$key]) ? 0 : 1) : (int) ($prev[$key] ?? $default); }; $clean['gateway_id'] = sanitize_text_field((string) $keep('gateway_id')); $token = sanitize_text_field(trim((string) ($input['gateway_token'] ?? ''))); if (!empty($input['gateway_token_clear'])) { $token = ''; } elseif ($token === '') { $token = (string) ($prev['gateway_token'] ?? ''); } $clean['gateway_token'] = $token; $clean['dynamic_route'] = sanitize_text_field((string) $keep('dynamic_route')); $clean['gateway_log_payload'] = $flag('gateway_log_payload', 1); $clean['gateway_cache_ttl'] = self::int($keep('gateway_cache_ttl') ?? 0, 0, 2592000); $clean['local_cache_ttl'] = self::int($keep('local_cache_ttl') ?? 0, 0, 2592000); $clean['budget_enabled'] = $flag('budget_enabled', 0); $clean['budget_neurons'] = self::int($keep('budget_neurons') ?? UsageTracker::FREE_TIER, 100, 10000000); $clean['budget_action'] = ($keep('budget_action') ?? 'stop') === 'cheapest' ? 'cheapest' : 'stop'; $clean['budget_email'] = $flag('budget_email', 1); $clean['budget_account'] = $flag('budget_account', 1); $clean['cloudflare_only'] = $flag('cloudflare_only', 0); $clean['light_model'] = sanitize_text_field((string) $keep('light_model')); if ($own('light_tasks')) { $tasks = isset($input['light_tasks']) && is_array($input['light_tasks']) ? array_map('sanitize_key', $input['light_tasks']) : []; $clean['light_tasks'] = array_values(array_filter($tasks)); } else { $clean['light_tasks'] = is_array($prev['light_tasks'] ?? null) ? $prev['light_tasks'] : TaskContext::DEFAULT_LIGHT_TASKS; } $clean['image_model'] = sanitize_text_field((string) ($keep('image_model') ?: '@cf/black-forest-labs/flux-1-schnell')); $clean['vision_model'] = sanitize_text_field((string) $keep('vision_model')); $clean['backfill_enabled'] = $flag('backfill_enabled', 0); if ($own('backfill_tasks')) { $bt = isset($input['backfill_tasks']) && is_array($input['backfill_tasks']) ? array_map('sanitize_key', $input['backfill_tasks']) : []; $clean['backfill_tasks'] = array_values(array_intersect(['meta_description', 'alt_text'], $bt)); } else { $clean['backfill_tasks'] = is_array($prev['backfill_tasks'] ?? null) ? $prev['backfill_tasks'] : ['meta_description']; } $clean['backfill_daily_neurons'] = self::int($keep('backfill_daily_neurons') ?? 3000, 0, 10000000); $clean['backfill_batch'] = self::int($keep('backfill_batch') ?? 10, 1, 200); if (($clean['gateway_id'] !== ($prev['gateway_id'] ?? '')) || ($clean['gateway_token'] !== ($prev['gateway_token'] ?? ''))) { Gateway::markUp(); } return $clean; } // ================================================================ helpers private static function int($v, int $min, int $max): int { return max($min, min($max, (int) $v)); } /** A field's HTML id: "aipcf-" and the setting key with dashes. */ private static function fieldId(string $key): string { return 'aipcf-' . str_replace('_', '-', $key); } /** * After a save on any tab: warn when the tools' limits no longer fit the budget, so the * owner sees it where the limit was changed (Backfill, Embeddings, Content tools). * * @param array $clean * @return array */ public static function warnOverAllocation(array $clean): array { $warning = Budget::overAllocation($clean); if ($warning !== '' && function_exists('add_settings_error')) { add_settings_error(\WordPress\CloudflareWorkersAiProvider\AIPCF_SETTINGS_OPTION, 'aipcf_overallocated', $warning . ' ' . __('Settings > Budget shows how the daily budget is shared.', 'aipcf-ai-provider-for-cloudflare'), 'warning'); } return $clean; } public static function fieldArgs(bool $advanced): array { return $advanced ? ['class' => 'aipcf-advanced'] : []; } /** * Help text below a field. A
, not a

, because it can hold a

block. */ public static function help(string $line, string $moreLabel = '', string $more = ''): string { $html = '
' . esc_html($line); if ($moreLabel !== '' && $more !== '') { $html .= '
' . esc_html($moreLabel) . '
' . wp_kses_post($more) . '
'; } return $html . '
'; } public static function textModels(): array { $m = (get_account_id() !== '' && get_api_key() !== '') ? fetch_available_models() : []; return $m !== [] ? $m : static_model_catalog(); } public static function imageModels(): array { $out = []; $live = fetch_catalog(); foreach ($live !== [] ? $live : \WordPress\CloudflareWorkersAiProvider\static_task_catalog() as $m) { if (($m['task'] ?? '') === 'Text-to-Image') { $out[] = $m; } } return $out; } }