'overview', 'models' => 'models', 'budget' => 'budget', 'gateway' => 'gateway', 'backfill' => 'backfill', 'prompts' => 'prompts', 'embeddings' => 'embeddings', 'content' => 'content', ]; /** Settings (2.0): its sections, each saved as one settings "tab". */ public const SETTINGS_SLUG = 'aipcf-settings'; /** Section => [the tab it saves as, its screen]. */ public const SECTIONS = [ 'connection' => ['connection', Screens\ConnectionScreen::class], 'models' => ['models', Screens\ModelsScreen::class], 'budget' => ['budget', Screens\BudgetScreen::class], 'content-index' => ['embeddings', Screens\ContentIndexScreen::class], 'prompts' => ['prompts', Screens\PromptsScreen::class], ]; /** * The plugin's admin pages by slug, for the shared styles, the page background and the * settings messages. * * @return list */ public static function pageSlugs(): array { return [self::PAGE_SLUG, self::SETTINGS_SLUG, FeaturesPage::SLUG, HelpPage::SLUG, InsightsTab::SLUG, ActivityPage::SLUG, AssistantPage::SLUG, LinkAssistant::SLUG, Wizard::SLUG]; } public static function isPluginScreen(): bool { $page = isset($_GET['page']) ? sanitize_key(wp_unslash((string) $_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended return in_array($page, self::pageSlugs(), true); } public static function panel(): array { return ['before_section' => '
', 'after_section' => '
']; } public const TAB_KEYS = [ 'overview' => ['account_id', 'api_key'], 'models' => ['preferred_model', 'light_model', 'light_tasks', 'image_model', 'vision_model'], 'budget' => ['budget_enabled', 'budget_neurons', 'budget_action', 'budget_email', 'budget_account', 'cloudflare_only', 'gateway_cache_ttl', 'local_cache_ttl'], 'gateway' => ['gateway_id', 'gateway_token', 'gateway_log_payload', 'dynamic_route'], 'backfill' => ['backfill_enabled', 'backfill_tasks', 'backfill_daily_neurons', 'backfill_batch'], 'embeddings' => EmbeddingSettings::KEYS, 'content' => \WordPress\CloudflareWorkersAiProvider\Features\Settings::KEYS, ]; /** The content tools' settings, one feature page each (2.0), by key prefix. */ public const FEATURE_TABS = ['related', 'search', 'links', 'insights', 'agents']; /** * The settings a screen ("tab") owns. Saving a screen keeps every other setting as it is; * an owned checkbox that is not sent means off. * * @return list */ public static function tabKeys(string $tab): array { if ($tab === 'connection') { return array_merge(self::TAB_KEYS['overview'], self::TAB_KEYS['gateway']); } if (in_array($tab, self::FEATURE_TABS, true)) { return array_values(array_filter( \WordPress\CloudflareWorkersAiProvider\Features\Settings::KEYS, static fn(string $k): bool => strpos($k, $tab . '_') === 0 )); } return self::TAB_KEYS[$tab] ?? []; } /** * Where an old settings tab lives now (2.0): Home, a Settings section or a Features page. * Every link to a tab goes through here, so older links land in the right place. */ public static function tabUrl(string $tab): string { $map = [ 'models' => self::settingsUrl('models'), 'budget' => self::settingsUrl('budget'), 'gateway' => self::settingsUrl('connection'), 'prompts' => self::settingsUrl('prompts'), 'embeddings' => self::settingsUrl('content-index'), 'backfill' => FeaturesPage::url('backfill'), 'content' => FeaturesPage::url(), ]; return $map[$tab] ?? admin_url('admin.php?page=' . self::PAGE_SLUG); } public static function settingsUrl(string $section = 'connection'): string { return add_query_arg(['page' => self::SETTINGS_SLUG, 'section' => $section], admin_url('admin.php')); } public static function currentSection(): string { $section = isset($_GET['section']) ? sanitize_key(wp_unslash((string) $_GET['section'])) : 'connection'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended return isset(self::SECTIONS[$section]) ? $section : 'connection'; } public static function pageUrl(string $fragment = ''): string { return admin_url('admin.php?page=' . self::PAGE_SLUG) . ($fragment !== '' ? '#' . $fragment : ''); } public static function boot(): void { static $booted = false; if ($booted) { return; } $booted = true; add_action('admin_menu', [self::class, 'registerMenu']); add_action('admin_menu', [self::class, 'registerMenuEnd'], 30); add_filter('submenu_file', [self::class, 'highlightMenu']); add_filter('parent_file', [self::class, 'highlightParent']); add_action('current_screen', [self::class, 'titleHiddenPage']); add_action('admin_init', [self::class, 'redirectLegacyUrl']); add_action('admin_post_aipcf_reset', [self::class, 'handleReset']); add_action('admin_init', [self::class, 'registerSettings']); add_action('admin_init', [self::class, 'maybeHandleAdminPost']); add_action('admin_notices', [self::class, 'maybeRenderNotice']); add_filter('admin_body_class', [self::class, 'bodyClass']); add_action('admin_enqueue_scripts', [self::class, 'enqueueAdminScripts']); add_action('admin_init', [self::class, 'privacyPolicyContent']); } /** * Suggested text for Settings > Privacy > Policy Guide. */ public static function privacyPolicyContent(): void { if (!function_exists('wp_add_privacy_policy_content')) { return; } $text = '

' . esc_html__('AIPCF sends content to Cloudflare to run AI features. Adapt the suggested text below to the features you use.', 'aipcf-ai-provider-for-cloudflare') . '

' . '' . esc_html__('Suggested text:', 'aipcf-ai-provider-for-cloudflare') . ' ' . '

' . esc_html__('This site uses Cloudflare Workers AI (Cloudflare, Inc.) to generate text such as summaries, image descriptions and translations. When these features run, the content they work on (for example a post, its title or an image) is sent to Cloudflare for processing. Cloudflare\'s privacy policy: https://www.cloudflare.com/privacypolicy/', 'aipcf-ai-provider-for-cloudflare') . '

' . '

' . esc_html__('If the content index is switched on, the content chosen in the plugin\'s settings, such as published posts and pages, is sent to Cloudflare Workers AI. There it becomes embeddings, which are kept with that text in the vector store the site owner chose: Cloudflare Vectorize, a Qdrant server, or a PostgreSQL database. Comments and visitors\' personal data are not included unless they are part of the selected content; author names are included only if the site owner selects them. Embedding requests are not stored in Cloudflare AI Gateway logs.', 'aipcf-ai-provider-for-cloudflare') . '

' . '

' . esc_html__('If search by meaning is switched on, what a logged-in member types into it is sent to Cloudflare Workers AI to find matching posts. It is not stored by this plugin unless Search insights is on.', 'aipcf-ai-provider-for-cloudflare') . '

' . '

' . esc_html__('If the Site assistant is switched on, the questions a logged-in member asks it are sent to Cloudflare Workers AI. They go with the earlier messages of the same conversation and with passages from this site\'s posts, to write an answer. Before the first question the member is asked for a name (no email or phone) and whether to save the chat. Only if they agree are the name they gave, their questions and the answers stored with their user account, for the site owner to read, for 90 days by default. Otherwise nothing is stored and the conversation stays in the browser tab. Saved chats are included in personal data exports and erasures, and deleted with the account.', 'aipcf-ai-provider-for-cloudflare') . '

' . '

' . esc_html__('If the Site assistant is open to visitors who are not logged in, their questions are sent to Cloudflare Workers AI in the same way. To limit how many questions each visitor may ask, a one-way key made from the visitor\'s IP address is kept in the site\'s cache for up to a day. The address itself is not stored. If the site uses Cloudflare Turnstile for the assistant, Cloudflare checks the visitor\'s browser once a day. A visitor\'s chat is saved only if they agree, without an account or IP address, so a personal data request cannot find it. It is deleted after the retention period.', 'aipcf-ai-provider-for-cloudflare') . '

' . '

' . esc_html__('If Search insights is switched on, searches made on this site are recorded to understand what visitors look for. Each record holds the search text, the number of results, when it was made and whether the searcher was logged in. No name, user account, IP address or browser details are stored with it. To count a repeated search once, a one-way key made from the visitor\'s IP address may be kept in the site\'s memory cache for up to an hour. Searches are kept for 90 days by default and then deleted, also if Search insights is later switched off. To compare them with the site\'s content, search texts are sent to Cloudflare Workers AI.', 'aipcf-ai-provider-for-cloudflare') . '

' . '

' . esc_html__('The plugin keeps an activity log that only administrators can see: which administrator used which of its tools and when, and the settings they changed. It also keeps the text Backfill wrote into meta descriptions and image alt text, with the text it replaced. Visitors and members are not recorded in it. Entries are kept for 90 days by default and then deleted; when a user account is deleted, its entries stay without the user.', 'aipcf-ai-provider-for-cloudflare') . '

'; wp_add_privacy_policy_content(__('AIPCF - AI Provider for Cloudflare', 'aipcf-ai-provider-for-cloudflare'), wp_kses_post($text)); } public static function handleReset(): 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_reset'); \WordPress\CloudflareWorkersAiProvider\Reset::run(); set_transient('aipcf_notice_' . get_current_user_id(), [ 'type' => 'success', 'message' => __('Plugin reset. Settings, usage history and caches were cleared; everything it generated was kept.', 'aipcf-ai-provider-for-cloudflare'), ], 60); wp_safe_redirect(self::tabUrl('overview')); exit; } public static function redirectLegacyUrl(): void { global $pagenow; // Search insights moved from a settings tab to its own page (1.9.0). $page = sanitize_key(wp_unslash((string) ($_GET['page'] ?? ''))); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $tab = sanitize_key(wp_unslash((string) ($_GET['tab'] ?? ''))); // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ($pagenow === 'admin.php' && $page === self::PAGE_SLUG && $tab === 'insights') { wp_safe_redirect(admin_url('admin.php?page=aipcf-search-insights'), 302); exit; } // 2.0: the settings tabs moved to Settings and Features; old addresses follow them. if ($pagenow === 'admin.php' && $page === self::PAGE_SLUG && $tab !== '' && $tab !== 'overview' && isset(self::TABS[$tab])) { wp_safe_redirect(self::tabUrl($tab), 302); exit; } if ($pagenow !== 'options-general.php' || !isset($_GET['page']) || $_GET['page'] !== self::PAGE_SLUG) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return; } $tab = isset($_GET['tab']) ? sanitize_key(wp_unslash((string) $_GET['tab'])) : 'overview'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended wp_safe_redirect(self::tabUrl(isset(self::TABS[$tab]) ? $tab : 'overview'), 302); exit; } /** * The menu (2.0): AIPCF > Home, Features, Insights, Settings, Help. Each is a job. The tool * pages (Site assistant, Link assistant, Activity) open from their cards and keep their * parent highlighted; editors, who cannot manage options, see the Link assistant itself. */ public static function registerMenu(): void { add_menu_page( Brand::FULL, Brand::NAME, 'manage_options', self::PAGE_SLUG, [self::class, 'renderPage'], Brand::menuIcon(), 81 ); add_submenu_page(self::PAGE_SLUG, __('Home', 'aipcf-ai-provider-for-cloudflare') . ' ‹ ' . Brand::NAME, __('Home', 'aipcf-ai-provider-for-cloudflare'), 'manage_options', self::PAGE_SLUG, [self::class, 'renderPage']); add_submenu_page(self::PAGE_SLUG, __('Features', 'aipcf-ai-provider-for-cloudflare') . ' ‹ ' . Brand::NAME, __('Features', 'aipcf-ai-provider-for-cloudflare'), 'manage_options', FeaturesPage::SLUG, [FeaturesPage::class, 'render']); } /** * Settings and Help, after Insights (registered at 21). */ public static function registerMenuEnd(): void { add_submenu_page(self::PAGE_SLUG, __('Settings', 'aipcf-ai-provider-for-cloudflare') . ' ‹ ' . Brand::NAME, __('Settings', 'aipcf-ai-provider-for-cloudflare'), 'manage_options', self::SETTINGS_SLUG, [self::class, 'renderSettingsPage']); add_submenu_page(self::PAGE_SLUG, __('Activity', 'aipcf-ai-provider-for-cloudflare') . ' ‹ ' . Brand::NAME, __('Activity', 'aipcf-ai-provider-for-cloudflare'), 'manage_options', ActivityPage::SLUG, [ActivityPage::class, 'render']); add_submenu_page(self::PAGE_SLUG, __('Help', 'aipcf-ai-provider-for-cloudflare') . ' ‹ ' . Brand::NAME, __('Help', 'aipcf-ai-provider-for-cloudflare'), 'manage_options', HelpPage::SLUG, [HelpPage::class, 'render']); } /** * On a tool page that is not in the menu, highlight the menu item it belongs to. * * @param string|null $submenu * @return string|null */ public static function highlightMenu($submenu) { $page = isset($_GET['page']) ? sanitize_key(wp_unslash((string) $_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if (!current_user_can('manage_options')) { return $submenu; } $parent = [ AssistantPage::SLUG => FeaturesPage::SLUG, LinkAssistant::SLUG => FeaturesPage::SLUG, ]; return $parent[$page] ?? $submenu; } /** * @param string $file */ public static function highlightParent($file): string { $page = isset($_GET['page']) ? sanitize_key(wp_unslash((string) $_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended return in_array($page, [AssistantPage::SLUG, LinkAssistant::SLUG], true) && current_user_can('manage_options') ? self::PAGE_SLUG : (string) $file; } /** * Pages outside the menu (Setup, Site assistant, Link assistant for administrators) get no * title from WordPress: the browser tab would read "‹ Site" and admin-header.php warns. */ public static function titleHiddenPage(): void { global $title; $page = isset($_GET['page']) ? sanitize_key(wp_unslash((string) $_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $titles = [ Wizard::SLUG => __('Setup', 'aipcf-ai-provider-for-cloudflare'), AssistantPage::SLUG => __('Site assistant', 'aipcf-ai-provider-for-cloudflare'), LinkAssistant::SLUG => __('Link assistant', 'aipcf-ai-provider-for-cloudflare'), ]; if (isset($titles[$page]) && empty($title)) { $title = $titles[$page] . ' ‹ ' . Brand::NAME; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- WordPress leaves it empty for these pages } } public static function enqueueAdminScripts(string $hookSuffix): void { // Every plugin screen shares the styles and the confirm/busy behaviour. if (!self::isPluginScreen()) { return; } $base = plugin_dir_url(AIPCF_FILE) . 'assets/admin/'; wp_enqueue_style('dashicons'); wp_enqueue_style('aipcf-admin', $base . 'settings.css', ['dashicons'], AIPCF_VERSION); wp_enqueue_script('aipcf-admin', $base . 'settings.js', [], AIPCF_VERSION, true); // The 2.0 components (scoped to .aipcf-ui, so the screens not moved yet are unchanged). wp_enqueue_style('aipcf-ui', $base . 'ui.css', ['aipcf-admin'], AIPCF_VERSION); wp_enqueue_script('aipcf-ui', $base . 'ui.js', [], AIPCF_VERSION, true); wp_localize_script( 'aipcf-admin', 'aipcfAdmin', [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'i18n' => [ 'working' => __('Working...', 'aipcf-ai-provider-for-cloudflare'), /* translators: 1: posts embedded, 2: waiting, 3: failed */ 'progress' => __('%1$s embedded, %2$s waiting, %3$s failed.', 'aipcf-ai-provider-for-cloudflare'), 'showKey' => __('Show API token', 'aipcf-ai-provider-for-cloudflare'), 'hideKey' => __('Hide API token', 'aipcf-ai-provider-for-cloudflare'), 'networkError' => __('Network error. Try again.', 'aipcf-ai-provider-for-cloudflare'), ], ] ); } public static function registerSettings(): void { register_setting( self::SETTINGS_GROUP, AIPCF_SETTINGS_OPTION, [ 'type' => 'array', 'sanitize_callback' => [self::class, 'sanitizeSettings'], 'default' => \WordPress\CloudflareWorkersAiProvider\default_settings(), ] ); } public static function sanitizeSettings($input): array { $current = get_plugin_settings(); if (!is_array($input)) { $input = []; } // Each tab submits only its own fields; fill the rest from the saved values // so an unrelated tab's Save never blanks a checkbox it did not show. $tab = isset($input['_tab']) ? sanitize_key((string) $input['_tab']) : ''; if ($tab !== '') { // A screen name the settings do not know owns nothing: everything is kept. $owned = self::tabKeys($tab); foreach ($current as $key => $value) { if (!in_array($key, $owned, true) && !array_key_exists($key, $input)) { $input[$key] = $value; } } } $apiKey = array_key_exists('api_key', $input) ? sanitize_text_field(trim((string) $input['api_key'])) : ''; if (!empty($input['api_key_clear'])) { $apiKey = ''; } elseif ($apiKey === '') { // Blank keeps the saved token (the field is rendered empty). $apiKey = (string) $current['api_key']; } $accountId = sanitize_text_field(trim((string) ($input['account_id'] ?? ''))); $preferredModel = sanitize_text_field(trim((string) ($input['preferred_model'] ?? ''))); $credentialsChanged = ($accountId !== $current['account_id'] || $apiKey !== $current['api_key']); $credentialsPresent = ($accountId !== '' && $apiKey !== ''); if ($credentialsChanged) { flush_model_caches(); if ($credentialsPresent) { $test = self::testCredentials($accountId, $apiKey); if ($test === true) { add_settings_error( AIPCF_SETTINGS_OPTION, 'cfai_conn_ok', __('Connected: the credentials work.', 'aipcf-ai-provider-for-cloudflare'), 'success' ); } elseif ($test === 'pending_approval') { add_settings_error( AIPCF_SETTINGS_OPTION, 'cfai_pending', __('Credentials saved. To finish, allow this plugin on Tools > Connector Approvals.', 'aipcf-ai-provider-for-cloudflare'), // phpcs:ignore Generic.Files.LineLength.TooLong 'warning' ); } else { add_settings_error( AIPCF_SETTINGS_OPTION, 'cfai_conn_fail', sprintf( /* translators: %s: error detail from the Cloudflare API */ __('Credentials saved, but the connection test failed: %s', 'aipcf-ai-provider-for-cloudflare'), // settings_errors() prints messages as HTML; this part comes from the API. esc_html((string) $test) ), 'error' ); } } } $clean = [ 'api_key' => $apiKey, 'account_id' => $accountId, 'preferred_model' => $preferredModel, ]; if ($preferredModel !== (string) $current['preferred_model']) { flush_model_caches(); } return (array) apply_filters('aipcf_sanitize_settings', $clean, $input); } public static function testCredentials(string $accountId, string $apiKey) { if (!is_connector_approved()) { return 'pending_approval'; } $url = sprintf( 'https://api.cloudflare.com/client/v4/accounts/%s/ai/models/search?per_page=1', rawurlencode($accountId) ); $response = wp_remote_get( $url, [ 'timeout' => 8, 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/json', ], ] ); if (is_wp_error($response)) { return $response->get_error_message(); } $status = (int) wp_remote_retrieve_response_code($response); if ($status < 200 || $status >= 300) { $body = (string) wp_remote_retrieve_body($response); $decoded = json_decode($body, true); return is_array($decoded) && !empty($decoded['errors'][0]['message']) ? (string) $decoded['errors'][0]['message'] : sprintf('HTTP %d', $status); } return true; } public static function modelGroupLabel(string $id): string { static $map = [ 'meta' => 'Meta Llama', 'mistral' => 'Mistral', 'google' => 'Google', 'deepseek-ai' => 'DeepSeek', 'qwen' => 'Qwen', 'mistralai' => 'Mistral', 'openai' => 'OpenAI (open-weight)', 'ibm-granite' => 'IBM Granite', 'zai-org' => 'Z.ai GLM', 'moonshotai' => 'Moonshot Kimi', 'nvidia' => 'NVIDIA', 'aisingapore' => 'AI Singapore', 'microsoft' => 'Microsoft', 'stabilityai' => 'Stability AI', 'openchat' => 'OpenChat', ]; if (preg_match('#^@cf/([^/]+)/#', $id, $matches)) { $vendor = $matches[1]; return $map[$vendor] ?? (string) ucwords(str_replace(['-', '_'], ' ', $vendor)); } return __('Other', 'aipcf-ai-provider-for-cloudflare'); } /** * Home: is it working, what is on, today's use, anything that needs you. Nothing to save. */ public static function renderPage(): void { if (!current_user_can('manage_options')) { return; } echo '
'; echo Ui::header(__('Home', 'aipcf-ai-provider-for-cloudflare'), __('Is it working, what is on, and anything that needs you.', 'aipcf-ai-provider-for-cloudflare'), self::connectionPillUi()); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Ui escapes echo '
'; echo '
'; echo Screens\HomeScreen::render(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Ui escapes echo '
'; } /** * Settings: Connection, Models, Budget, Content index, Prompts. */ public static function renderSettingsPage(): void { if (!current_user_can('manage_options')) { return; } $section = self::currentSection(); $labels = [ 'connection' => __('Connection', 'aipcf-ai-provider-for-cloudflare'), 'models' => __('Models', 'aipcf-ai-provider-for-cloudflare'), 'budget' => __('Budget', 'aipcf-ai-provider-for-cloudflare'), 'content-index' => __('Content index', 'aipcf-ai-provider-for-cloudflare'), 'prompts' => __('Prompts', 'aipcf-ai-provider-for-cloudflare'), ]; $links = []; foreach ($labels as $slug => $label) { $links[$slug] = [$label, self::settingsUrl($slug)]; } [$tab, $screen] = self::SECTIONS[$section]; echo '
'; echo Ui::header(__('Settings', 'aipcf-ai-provider-for-cloudflare'), __('How AIPCF connects to Cloudflare, which models it uses, and what it may spend.', 'aipcf-ai-provider-for-cloudflare'), self::connectionPillUi()); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Ui escapes echo '
'; echo Ui::tabs($links, $section, __('Settings sections', 'aipcf-ai-provider-for-cloudflare')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Ui escapes self::form($tab, $screen::render()); echo '
'; } /** * A settings form for one screen: saved through options.php as that screen's tab, so it * only changes the settings that screen owns. * * @param string $html The screen, escaped. */ public static function form(string $tab, string $html): void { // A screen with no setting fields (Models before connecting, say) gets no form and no // Save: saving it as its tab would blank every setting that tab owns. if (!str_contains($html, 'name="' . AIPCF_SETTINGS_OPTION . '[') && !str_contains($html, 'name="' . \WordPress\CloudflareWorkersAiProvider\Prompts::OPTION . '[')) { echo '
'; echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- screens and Settings API sections escape their parts echo '
'; return; } echo '
'; // Pressing Enter in a field saves: this hidden button is the form's first submit button, // ahead of any action button inside a card. printf('', esc_html__('Save changes', 'aipcf-ai-provider-for-cloudflare')); settings_fields(self::SETTINGS_GROUP); printf('', esc_attr(AIPCF_SETTINGS_OPTION), esc_attr($tab)); echo '
'; echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- screens and Settings API sections escape their parts echo Ui::saveBar(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Ui escapes echo '
'; } /** * Older Settings API sections as 2.0 cards: the section's own intro, then each field's * existing control in a 2.0 row (so its scripts and tests keep working), "advanced" rows * under More settings. For screens whose controls are too involved to rebuild at once. * * @param array, id?: string}> $cards section id => card */ public static function legacyCards(string $page, array $cards): string { global $wp_settings_sections, $wp_settings_fields; $out = ''; foreach ($cards as $sectionId => $card) { $section = $wp_settings_sections[$page][$sectionId] ?? null; if (!is_array($section)) { continue; } $body = ''; if (($card['intro'] ?? true) && is_callable($section['callback'] ?? null)) { ob_start(); call_user_func($section['callback'], $section); $intro = (string) ob_get_clean(); $body .= $intro !== '' ? '
' . $intro . '
' : ''; } $rows = ''; $more = ''; foreach ((array) ($wp_settings_fields[$page][$sectionId] ?? []) as $id => $field) { $args = (array) ($field['args'] ?? []); ob_start(); call_user_func($field['callback'], $args); $control = (string) ob_get_clean(); $class = (string) ($args['class'] ?? ''); $advanced = strpos(' ' . $class . ' ', ' aipcf-advanced ') !== false; $row = Ui::row( (string) ($card['labels'][$id] ?? $field['title']), $control, array_filter([ 'for' => (string) ($args['label_for'] ?? ''), 'class' => trim(str_replace('aipcf-advanced', '', $class)), ]) ); if ($advanced) { $more .= $row; } else { $rows .= $row; } } $body .= $rows . ($more !== '' ? Ui::moreSettings($more) : ''); $out .= Ui::card($card['title'], $body, array_filter(['text' => $card['text'] ?? '', 'id' => $card['id'] ?? ''])); } return $out; } /** * The connection pill for a 2.0 header: [state, label]. * * @return array{0: string, 1: string} */ public static function connectionPillUi(): array { [$class, $label] = self::connectionPill(); return [str_replace('is-', '', $class), $label]; } /** * The connection pill: [class, label]. * * @return array{0: string, 1: string} */ public static function connectionPill(): array { $configured = get_account_id() !== '' && get_api_key() !== ''; $gate = class_exists('\\WordPress\\AI\\Connector_Approval\\Approvals_Store'); if (!$configured) { return ['', __('Not connected', 'aipcf-ai-provider-for-cloudflare')]; } if ($gate && !is_connector_approved()) { return ['is-warn', __('Needs approval', 'aipcf-ai-provider-for-cloudflare')]; } if (get_transient(Gateway::DOWN_TRANSIENT)) { return ['is-warn', __('Connected, AI Gateway bypassed', 'aipcf-ai-provider-for-cloudflare')]; } return ['is-ok', Gateway::mode() === 'direct' ? __('Connected', 'aipcf-ai-provider-for-cloudflare') : __('Connected via AI Gateway', 'aipcf-ai-provider-for-cloudflare')]; } /** * The header every plugin screen shares: "Cloudflare AI" above the screen's name, a line on * what it is for, and on the right a status pill and optional links. * * @param array{0: string, 1: string}|null $pill [class, label]; null for the connection pill. * @param string $side Extra escaped HTML for the right-hand side. */ public static function header(string $icon, string $title, string $sub, ?array $pill = null, string $side = ''): void { unset($icon); // 2.0: every page carries the AIPCF mark. $pill = $pill ?? self::connectionPill(); echo Ui::header($title, $sub, [str_replace('is-', '', $pill[0]), $pill[1]], $side); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Ui escapes; callers pass escaped HTML in $side // Tool pages opened from a card lead back to it. $page = isset($_GET['page']) ? sanitize_key(wp_unslash((string) $_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $back = [ AssistantPage::SLUG => [__('Features', 'aipcf-ai-provider-for-cloudflare'), FeaturesPage::url()], LinkAssistant::SLUG => [__('Features', 'aipcf-ai-provider-for-cloudflare'), FeaturesPage::url()], ]; if (isset($back[$page]) && current_user_can('manage_options')) { echo Ui::back($back[$page][0], $back[$page][1]); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Ui escapes } } /** * The Tools > Connector Approvals screen, or '' when the AI plugin that adds it is not active. */ public static function connectorApprovalUrl(): string { if (!class_exists('\WordPress\AI\Connector_Approval\Approvals_Store')) { return ''; } return admin_url('tools.php?page=ai-connector-approval'); } public static function maybeHandleAdminPost(): void { add_action( 'admin_post_aipcf_test_connection', [self::class, 'handleTestConnection'] ); } public static function handleTestConnection(): void { self::ensureAdminPostCapability(); $accountId = get_account_id(); $apiKey = get_api_key(); if ($accountId === '') { self::queueNotice( 'error', __('Save your Account ID first, then test again.', 'aipcf-ai-provider-for-cloudflare') ); self::redirectBack(); } if ($apiKey === '') { self::queueNotice( 'error', __('Save your API token first, then test again.', 'aipcf-ai-provider-for-cloudflare') ); self::redirectBack(); } $result = self::testCredentials($accountId, $apiKey); if ($result === true) { flush_model_caches(); self::queueNotice( 'success', __('Connected: the credentials work.', 'aipcf-ai-provider-for-cloudflare') ); self::redirectBack(); } if ($result === 'pending_approval') { self::queueNotice( 'warning', __('The connector is not approved yet. Allow this plugin on Tools > Connector Approvals, then test again.', 'aipcf-ai-provider-for-cloudflare') // phpcs:ignore Generic.Files.LineLength.TooLong ); self::redirectBack(); } self::queueNotice( 'error', sprintf( /* translators: %s: error detail from the Cloudflare API */ __('Connection failed: %s', 'aipcf-ai-provider-for-cloudflare'), (string) $result ) ); self::redirectBack(); } /** * Marks the plugin's screens, for the shared page background. */ public static function bodyClass($classes): string { $page = isset($_GET['page']) ? sanitize_key(wp_unslash((string) $_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended return (string) $classes . (self::isPluginScreen() ? ' aipcf-screen' : '') . ($page === Wizard::SLUG ? ' aipcf-wizard-screen' : ''); } public static function maybeRenderNotice(): void { $userId = get_current_user_id(); if ($userId === 0) { return; } // WordPress shows the messages of a settings save ("Settings saved.", the credentials // test, budget warnings) only on pages under Settings; this is a top-level page. if (self::isPluginScreen()) { settings_errors(); } $notice = get_transient(self::noticeTransientKey($userId)); if (!is_array($notice) || empty($notice['message'])) { return; } delete_transient(self::noticeTransientKey($userId)); $type = (string) ($notice['type'] ?? 'info'); $class = in_array($type, ['error', 'warning', 'success', 'info'], true) ? 'notice-' . $type : 'notice-info'; printf( '

%2$s

', esc_attr($class), esc_html((string) $notice['message']) ); } private static function queueNotice(string $type, string $message): void { $userId = get_current_user_id(); if ($userId === 0) { return; } set_transient( self::noticeTransientKey($userId), ['type' => $type, 'message' => $message], 60 ); } private static function noticeTransientKey(int $userId): string { return 'aipcf_notice_' . $userId; } private static function ensureAdminPostCapability(): 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(self::NONCE_ACTION); } private static function redirectBack(): void { wp_safe_redirect(self::settingsUrl('connection')); exit; } }