PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 2.10.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v2.10.0
2.10.0 2.9.0 2.8.0 2.7.0 2.6.0 2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 1.26.0 1.25.0 trunk 1.0.0 1.0.1 All 51 releases
← All changes | includes/core/class-settings.php +677 -183 1.0.0 → 2.10.0 View file →
@@ -1,5 +1,6 @@
1 1 <?php
2 +
2 3 /**
3 4 * Settings Class
4 5 *
5 6 * Handles plugin settings and configuration using WordPress options
@@ -16,25 +17,200 @@
16 17 if (!defined('ABSPATH')) {
17 18 exit;
18 19 }
19 20
20 -/**
21 +/**
21 22 * Settings Class
22 23 *
23 24 * Single Responsibility: Manage plugin settings and configuration
24 - * Uses WordPress options for storage
25 + * Uses WordPress options for storage.
25 26 *
27 + * Use Settings::instance() to get the shared instance rather than
28 + * creating new instances — this ensures the internal cache is shared
29 + * across all consumers and avoids redundant get_option() calls.
30 + *
26 31 * @since 1.0.0
27 32 */
28 33 class Settings {
29 -
34 +
30 35 /**
36 + * Canonical default AI model per provider.
37 + *
38 + * Single source of truth. Every call site that needs a provider's default
39 + * model — the $defaults array below, the AI client constructors, the manager
40 + * fallbacks, the content-brief generator and the usage-analytics endpoint —
41 + * MUST reference these constants instead of repeating the literal, so the
42 + * defaults can never silently drift out of sync (see issue #273).
43 + *
44 + * @since 1.28.0
45 + */
46 + const DEFAULT_OPENAI_MODEL = 'gpt-5-nano';
47 + const DEFAULT_CLAUDE_MODEL = 'claude-sonnet-5';
48 + const DEFAULT_GEMINI_MODEL = 'gemini-3.5-flash';
49 + const DEFAULT_OPENROUTER_MODEL = 'openai/gpt-4o-mini';
50 +
51 + /**
52 + * Default request timeout for the OpenAI-compatible provider, in seconds.
53 + *
54 + * Deliberately higher than the 120s the hosted providers get: a local model
55 + * on CPU routinely takes minutes for a content brief, and a timeout there
56 + * is never retried (see OpenAI_Client::request_with_retry()).
57 + *
58 + * @since 2.8.0
59 + */
60 + const DEFAULT_OPENAI_COMPATIBLE_TIMEOUT = 120;
61 +
62 + /**
63 + * Canonical default author-archive templates.
64 + *
65 + * Same single-source-of-truth rule as the model constants above: the
66 + * defaults array, the REST endpoint, the get-settings ability and
67 + * Author_Archives_Manager all read these instead of repeating the literal,
68 + * which had already drifted — the title default hardcoded an en dash while
69 + * the feature resolves %separator% from Site Identity (#318).
70 + *
71 + * @since 1.29.1
72 + */
73 + /**
74 + * AI providers this plugin supports.
75 + *
76 + * Single source of truth for the REST enum, the connection test's dispatch
77 + * and sanitize_setting(), so the three cannot disagree about what is legal.
78 + *
79 + * @since 2.2.0
80 + * @var string[]
81 + */
82 + public const SUPPORTED_AI_PROVIDERS = ['openai', 'claude', 'gemini', 'openrouter', 'openai_compatible'];
83 +
84 + /**
85 + * The stored value meaning "the user has not chosen a provider yet".
86 + *
87 + * A fresh install ships with no provider selected: picking one is the
88 + * user's call, and pre-selecting OpenAI made the settings screen open with
89 + * a warning about a missing key for a provider nobody had asked for (#572).
90 + * Every write path accepts this alongside SUPPORTED_AI_PROVIDERS.
91 + *
92 + * @since 2.1.3
93 + */
94 + public const AI_PROVIDER_NONE = '';
95 +
96 + /**
97 + * One-time marker for {@see Settings::retire_seeded_ai_provider()}.
98 + */
99 + private const PROVIDER_MIGRATION_OPTION = 'thinkrank_ai_provider_migration';
100 + private const PROVIDER_MIGRATION_VERSION = '1';
101 +
102 + /**
103 + * Legal values for the `ai_provider` setting, including "not chosen".
104 + *
105 + * @since 2.1.3
106 + * @return string[]
107 + */
108 + public static function selectable_ai_providers(): array {
109 + return array_merge([self::AI_PROVIDER_NONE], self::SUPPORTED_AI_PROVIDERS);
110 + }
111 +
112 + /**
113 + * Is the selected AI provider configured well enough to run a request?
114 + *
115 + * One answer for the whole plugin. The admin menu notice, the metabox
116 + * "Generate with AI" button and every generator used to ask their own
117 + * version of this as an inline OR over the API key settings, which the
118 + * OpenAI-compatible provider invalidates: a local Ollama or LM Studio
119 + * server has no key and is configured by base URL + model id (#721).
120 + *
121 + * Provider-aware on purpose. A stored key for a provider the site did not
122 + * select never made AI features work, so counting it only produced enabled
123 + * buttons that fail on click.
124 + *
125 + * @since 2.8.0
126 + *
127 + * @return bool
128 + */
129 + public function has_ai_provider_configured(): bool {
130 + $provider = (string) $this->get('ai_provider', self::AI_PROVIDER_NONE);
131 +
132 + if (self::AI_PROVIDER_NONE === $provider) {
133 + return false;
134 + }
135 +
136 + if ('openai_compatible' === $provider) {
137 + return '' !== trim((string) $this->get('openai_compatible_base_url', ''))
138 + && '' !== trim((string) $this->get('openai_compatible_model', ''));
139 + }
140 +
141 + return !empty($this->get($provider . '_api_key'));
142 + }
143 +
144 + const DEFAULT_AUTHOR_ARCHIVES_TITLE = '%author_name% %separator% %site_title% %page%';
145 + const DEFAULT_AUTHOR_ARCHIVES_META_DESC = 'Articles written by %author_name% on %site_title%';
146 +
147 + /**
148 + * String settings where a stored empty string is a real value, not "unset".
149 + *
150 + * get() normally treats '' the same as a missing option and returns the
151 + * default, which is right for most keys — a blank API key or model name is
152 + * never what the user meant. For these template fields it is the opposite:
153 + * clearing the box means "render no template", and the consumers already
154 + * branch on an empty value. Without the opt-out the save appeared to
155 + * succeed and the default reappeared on the next request (#316).
156 + *
157 + * @since 1.29.1
158 + * @var string[]
159 + */
160 + private const EMPTY_IS_A_VALUE = [
161 + 'author_archives_title',
162 + 'author_archives_meta_desc',
163 + // '' is the "no provider chosen" state, not "fall back to the default".
164 + // Without this, deselecting a provider would be undone by any caller
165 + // that passes its own fallback to get() (#572).
166 + 'ai_provider',
167 + ];
168 +
169 + /**
170 + * Shared singleton instance
171 + *
172 + * @var Settings|null
173 + */
174 + private static ?Settings $instance = null;
175 +
176 + /**
177 + * Get the shared Settings instance
178 + *
179 + * Returns the instance registered in the main plugin's component
180 + * container, or creates a standalone instance if the plugin hasn't
181 + * loaded yet (e.g., during activation).
182 + *
183 + * @since 1.10.0
184 + * @return Settings
185 + */
186 + public static function instance(): Settings {
187 + if (self::$instance !== null) {
188 + return self::$instance;
189 + }
190 +
191 + // Try to get from the main plugin container
192 + if (function_exists('thinkrank')) {
193 + $plugin = thinkrank();
194 + $component = $plugin->get_component('settings');
195 + if ($component instanceof self) {
196 + self::$instance = $component;
197 + return self::$instance;
198 + }
199 + }
200 +
201 + // Fallback: create standalone instance (during activation, etc.)
202 + self::$instance = new self();
203 + return self::$instance;
204 + }
205 +
206 + /**
31 207 * Settings cache
32 208 *
33 209 * @var array
34 210 */
35 211 private array $cache = [];
36 -
212 +
37 213 /**
38 214 * Default settings
39 215 *
40 216 * @var array
@@ -40,15 +216,27 @@
40 216 * @var array
41 217 */
42 218 private array $defaults = [
43 219 // AI Settings
44 - 'ai_provider' => 'openai',
220 + 'ai_provider' => self::AI_PROVIDER_NONE,
45 221 'openai_api_key' => '',
46 - 'openai_model' => 'gpt-5-nano', // Default to GPT‑5‑nano
222 + 'openai_model' => self::DEFAULT_OPENAI_MODEL,
47 223 'claude_api_key' => '',
48 - 'claude_model' => 'claude-3-7-sonnet-latest', // Use latest stable Claude
224 + 'claude_model' => self::DEFAULT_CLAUDE_MODEL, // Recommended default (best speed/quality balance)
49 225 'gemini_api_key' => '',
50 - 'gemini_model' => 'gemini-2.5-flash',
226 + 'gemini_model' => self::DEFAULT_GEMINI_MODEL,
227 + 'openrouter_api_key' => '',
228 + 'openrouter_model' => self::DEFAULT_OPENROUTER_MODEL,
229 + // OpenAI-compatible endpoint (Ollama, LM Studio, vLLM, Azure OpenAI,
230 + // Groq, a company gateway…). No default URL or model: this provider
231 + // does nothing until the administrator names a server (#721).
232 + 'openai_compatible_base_url' => '',
233 + 'openai_compatible_api_key' => '',
234 + 'openai_compatible_model' => '',
235 + 'openai_compatible_timeout' => self::DEFAULT_OPENAI_COMPATIBLE_TIMEOUT,
236 + 'openai_compatible_supports_images' => false,
237 + 'openai_compatible_json_mode' => false,
238 + 'openai_compatible_price_per_million' => 0.0,
51 239 'max_tokens' => 1000,
52 240 'temperature' => 0.7,
53 241
54 242 // Google API Keys (encrypted)
@@ -55,13 +243,32 @@
55 243 'google_analytics_api_key' => '',
56 244 'google_search_console_api_key' => '',
57 245 'google_pagespeed_api_key' => '',
58 246
247 + // Google OAuth Tokens (encrypted)
248 + 'google_access_token' => '',
249 + 'google_refresh_token' => '',
250 + 'google_token_expires_in' => 0,
251 + 'google_token_created' => 0,
252 + 'google_account_connected' => false,
253 +
254 + // Google Analytics Pro Settings. Read/written by thinkrank-pro's
255 + // GoogleAnalyticsSettings.js through the settings-management endpoint —
256 + // no consumer exists in THIS repo, so don't dead-key these.
257 + 'ga_analytics_account_id' => '',
258 + 'ga_analytics_data_stream_id' => '',
259 +
59 260 // Performance Settings
60 261 'cache_duration' => 3600,
61 - 'max_requests_per_minute' => 10,
262 + 'max_requests_per_minute' => 0,
62 263 'enable_logging' => true,
63 264
265 + // AI spend controls (#448). Both are neutral by default so an upgrade
266 + // changes nothing: 0 means no daily ceiling, and AI is not paused.
267 + // Enforced by ThinkRank\AI\Spend_Guard at the provider HTTP boundary.
268 + 'ai_daily_request_limit' => 0,
269 + 'ai_paused' => false,
270 +
64 271 // Integration Settings
65 272 'api_timeout' => 30,
66 273 'enable_rate_limiting' => true,
67 274 'auto_test_connections' => true,
@@ -82,40 +289,49 @@
82 289 'auto_optimize' => false,
83 290 'seo_score_threshold' => 70,
84 291 'enable_meta_generation' => true,
85 292 'enable_schema_markup' => true,
86 -
293 +
294 + // Author Archives Settings
295 + 'author_archives_enabled' => true,
296 + 'author_archives_index' => true,
297 + 'author_archives_show_empty' => false,
298 + 'author_archives_title' => self::DEFAULT_AUTHOR_ARCHIVES_TITLE,
299 + 'author_archives_meta_desc' => self::DEFAULT_AUTHOR_ARCHIVES_META_DESC,
300 +
87 301 // UI Settings
88 302 'show_welcome_message' => true,
89 303 'dashboard_widgets' => ['seo_score', 'ai_usage', 'recent_briefs'],
90 304 'editor_panel_position' => 'side',
91 -
305 +
92 306 // Advanced Settings
93 307 'debug_mode' => false,
94 308 'retry_attempts' => 3,
95 -
309 + // Exposes the standalone Migration admin page for re-running SEO data
310 + // imports after setup. Hidden by default; opt-in for advanced/support use.
311 + 'enable_migration_tools' => false,
312 + // Exposes ThinkRank's own export / restore. Off by default, like the
313 + // migration toggle above: both are occasional, admin-only tools, and a
314 + // menu item nobody asked for is a menu item in the way. Your data is
315 + // never locked in — the switch is one click away in
316 + // Settings > Import / Export, and turning it on immediately restores
317 + // the screen and the menu item. Off hides the export card and, unless
318 + // migration tools are on, the Import / Export menu item with it.
319 + 'enable_import_export' => false,
320 +
96 321 // Privacy Settings
97 322 'data_retention_days' => 90,
98 323 'anonymize_logs' => true,
99 324 'share_usage_data' => false,
100 -
325 +
101 326 // Integration Settings
102 327 'google_analytics_id' => '',
103 328 'search_console_property' => '',
104 329
105 - // GA4 Tracking Settings
106 - 'ga4_measurement_id' => '',
107 - 'ga4_auto_inject' => false,
108 - 'ga4_anonymize_ip' => false,
109 - 'ga4_exclude_admin' => false,
110 - 'ga4_tracking_verified' => false,
111 - 'ga4_last_verification' => '',
112 -
113 330 // SEO Analytics Settings
114 331 'seo_analytics_enabled' => false,
115 332 'seo_analytics_setup_completed' => false,
116 333 'seo_analytics_google_analytics_property_id' => '',
117 - 'search_console_property' => '',
118 334 'seo_analytics_enable_ai_insights' => true,
119 335 'seo_analytics_enable_automated_alerts' => false,
120 336 'seo_analytics_enable_predictive_analysis' => false,
121 337 'seo_analytics_monitoring_frequency' => 3600,
@@ -122,13 +338,16 @@
122 338 'seo_analytics_alert_thresholds' => [],
123 339 'seo_analytics_report_schedule' => 'weekly',
124 340 'seo_analytics_data_retention_days' => 90,
125 341 'seo_analytics_cache_analytics_data' => true,
126 -
342 +
127 343 // Uninstall Settings
128 344 'keep_data_on_uninstall' => true,
345 +
346 + // MCP (Model Context Protocol) Settings
347 + 'enable_mcp' => false,
129 348 ];
130 -
349 +
131 350 /**
132 351 * Encrypted settings keys
133 352 *
134 353 * @var array
@@ -137,18 +356,22 @@
137 356 // AI API Keys
138 357 'openai_api_key',
139 358 'claude_api_key',
140 359 'gemini_api_key',
360 + 'openrouter_api_key',
361 + 'openai_compatible_api_key',
141 362 // Google API Keys
142 363 'google_analytics_api_key',
143 364 'google_search_console_api_key',
144 365 'google_pagespeed_api_key',
366 + 'google_access_token',
367 + 'google_refresh_token',
145 368 // Social Platform Verification Codes (sensitive)
146 369 'pinterest_site_verification',
147 370 'instagram_verification',
148 371 'tiktok_verification',
149 372 ];
150 -
373 +
151 374 /**
152 375 * Initialize settings
153 376 *
154 377 * @return void
@@ -154,11 +377,145 @@
154 377 * @return void
155 378 */
156 379 public function init(): void {
157 380 add_action('admin_init', [$this, 'register_settings']);
381 + // Every value below is read from THIS site's options, and the cache is
382 + // keyed by setting name alone. On multisite a switch_to_blog() leaves
383 + // the previous site's values sitting in it, so anything that switches
384 + // reads the wrong site's configuration (#516). Nothing in the plugin
385 + // switched blogs before the OAuth discovery resolver did, which is why
386 + // this had never bitten.
387 + //
388 + // Registered against the CLASS, not $this. init() runs on the object in
389 + // the component container, while every consumer reads through
390 + // Settings::instance() — and those are not always the same object: a
391 + // caller that resolves the singleton while load_components() is still
392 + // building the array gets a standalone instance, which is then memoized
393 + // for the rest of the request. Hooking $this there registers the flush
394 + // on an object nobody reads through, which is exactly the shape of bug
395 + // a source-scanning test cannot see.
396 + add_action('switch_blog', [self::class, 'flush_instance_cache']);
397 + // Admin-only: a front-end pageview can never need this migration, and
398 + // the marker is a non-autoloaded option, so hooking it unconditionally
399 + // bought one dedicated query on every request for the life of the
400 + // install (#588).
401 + if (is_admin()) {
402 + add_action('init', [self::class, 'retire_seeded_ai_provider']);
403 + }
158 404 }
159 -
405 +
160 406 /**
407 + * Drop every memoized setting value.
408 + *
409 + * Called on `switch_blog` so a blog switch cannot serve the previous
410 + * site's configuration, and available to any caller that switches
411 + * explicitly. Cheap: the next read repopulates from the options cache.
412 + *
413 + * @since 2.9.0
414 + * @return void
415 + */
416 + public function flush_cache(): void {
417 + $this->cache = [];
418 + }
419 +
420 + /**
421 + * Drop the memo on the instance consumers actually read through.
422 + *
423 + * Resolved at fire time rather than registration time, so it always acts on
424 + * whatever Settings::instance() currently returns.
425 + *
426 + * @since 2.9.0
427 + * @return void
428 + */
429 + public static function flush_instance_cache(): void {
430 + self::instance()->flush_cache();
431 + }
432 +
433 + /**
434 + * Clear the OpenAI selection that older versions seeded on activation.
435 + *
436 + * Changing the default only helps installs created after the change. Every
437 + * site activated before it still carries `ai_provider = 'openai'` written by
438 + * Activator::set_default_options(), and still opens Settings warning about a
439 + * missing key for a provider nobody picked — the whole complaint in #572.
440 + *
441 + * "OpenAI with no OpenAI key" is provably not a user's choice: the settings
442 + * form refuses to save a provider without a key, so the only way to reach
443 + * that state is the old activation seed. A site that genuinely chose OpenAI
444 + * has a key and is left alone, as is any site on another provider.
445 + *
446 + * Version-gated so it runs once and never fights a user who later clears
447 + * their key but keeps the provider selected.
448 + *
449 + * @since 2.1.3
450 + *
451 + * @return void
452 + */
453 + public static function retire_seeded_ai_provider(): void {
454 + if (get_option(self::PROVIDER_MIGRATION_OPTION) === self::PROVIDER_MIGRATION_VERSION) {
455 + self::promote_migration_marker_to_autoload();
456 + return;
457 + }
458 +
459 + // Record first: a site that somehow fails the checks below must not
460 + // re-test on every request for the rest of its life. Autoloaded on
461 + // purpose — it is a short write-once flag that is read on every admin
462 + // request, which is exactly what autoload is for; storing it
463 + // non-autoloaded bought a dedicated query per request instead (#588).
464 + update_option(self::PROVIDER_MIGRATION_OPTION, self::PROVIDER_MIGRATION_VERSION, true);
465 +
466 + if (get_option('thinkrank_ai_provider', null) !== 'openai') {
467 + return;
468 + }
469 +
470 + // Read the stored option directly rather than through Settings::get().
471 + // Only emptiness matters here, and get() adds two things this decision
472 + // must not depend on: a per-instance cache that may already be primed,
473 + // and decryption that can yield '' for a key that is genuinely present.
474 + // The raw option is non-empty whenever a key exists, encrypted or not.
475 + if ('' !== (string) get_option('thinkrank_openai_api_key', '')) {
476 + // A real choice, backed by a key. Leave it.
477 + return;
478 + }
479 +
480 + // Write through the shared instance, not a throwaway one: set() refreshes
481 + // only the cache of the object it is called on, so a private instance
482 + // would leave the registered component serving the old value for the
483 + // rest of this request — including to the admin page it localizes.
484 + self::instance()->set('ai_provider', self::AI_PROVIDER_NONE);
485 + }
486 +
487 + /**
488 + * Move a legacy migration marker into the autoloaded set.
489 + *
490 + * Sites that ran the migration on 2.1.3 wrote the marker with
491 + * `autoload = false`, and the version gate above returns before the write
492 + * that would correct it — so those installs keep paying a dedicated query
493 + * to read a one-byte flag on every admin request, which is the cost #588
494 + * was about. Promote it once.
495 + *
496 + * Free to test: alloptions is loaded from the object cache once per request
497 + * regardless, and an autoloaded marker is in it, so the steady state after
498 + * the promotion is a cache lookup and nothing else. wp_set_option_autoload()
499 + * arrived in WP 6.4 and the plugin supports 6.0, hence the guard.
500 + *
501 + * @since 2.2.0
502 + *
503 + * @return void
504 + */
505 + private static function promote_migration_marker_to_autoload(): void {
506 + if (!function_exists('wp_set_option_autoload') || !function_exists('wp_load_alloptions')) {
507 + return;
508 + }
509 +
510 + if (array_key_exists(self::PROVIDER_MIGRATION_OPTION, wp_load_alloptions())) {
511 + return;
512 + }
513 +
514 + wp_set_option_autoload(self::PROVIDER_MIGRATION_OPTION, true);
515 + }
516 +
517 + /**
161 518 * Register WordPress settings
162 519 *
163 520 * @return void
164 521 */
@@ -167,25 +524,64 @@
167 524 'sanitize_callback' => [$this, 'sanitize_settings'],
168 525 'default' => $this->defaults,
169 526 ]);
170 527 }
171 -
528 +
172 529 /**
530 + * Warm the option cache for a batch of setting keys in one query.
531 + *
532 + * Every `thinkrank_*` option is autoload=off, so WordPress cannot serve
533 + * them from `alloptions` and each get() below is its own round-trip. A
534 + * caller that reads a known list of keys should prime it first: on a
535 + * ~1ms managed-hosting round-trip, sixteen of those on an anonymous
536 + * pageview is ~16ms spent on values the page may not use (#393).
537 + *
538 + * get() memoizes within the request, so only the first read of each key
539 + * ever reaches the database — this is what collapses those first reads.
540 + * Keys already memoized are left out of the batch.
541 + *
542 + * wp_prime_option_caches() is WP 6.4+; the plugin supports 6.0, so an
543 + * older site simply keeps the previous behaviour.
544 + *
545 + * @since 2.1.0
546 + *
547 + * @param string[] $keys Setting keys, without the `thinkrank_` prefix.
548 + * @return void
549 + */
550 + public function prime(array $keys): void {
551 + if (!function_exists('wp_prime_option_caches')) {
552 + return;
553 + }
554 +
555 + $unread = [];
556 +
557 + foreach ($keys as $key) {
558 + if (!isset($this->cache[$key])) {
559 + $unread[] = 'thinkrank_' . $key;
560 + }
561 + }
562 +
563 + if (!empty($unread)) {
564 + wp_prime_option_caches($unread);
565 + }
566 + }
567 +
568 + /**
173 569 * Get setting value
174 570 *
175 571 * @param string $key Setting key
176 - * @param mixed $default Default value
572 + * @param mixed $fallback Default value
177 573 * @param int $user_id User ID (0 for global, >0 for user-specific)
178 574 * @return mixed Setting value
179 575 */
180 - public function get(string $key, $default = null, int $user_id = 0) {
576 + public function get(string $key, $fallback = null, int $user_id = 0) {
181 577 // Check cache first
182 578 $cache_key = $user_id > 0 ? "user_{$user_id}_{$key}" : $key;
183 -
579 +
184 580 if (isset($this->cache[$cache_key])) {
185 581 return $this->maybe_decrypt($key, $this->cache[$cache_key]);
186 582 }
187 -
583 +
188 584 // Load from WordPress options or user meta
189 585 if ($user_id > 0) {
190 586 $value = get_user_meta($user_id, "thinkrank_{$key}", true);
191 587 } else {
@@ -192,9 +588,9 @@
192 588 $value = get_option("thinkrank_{$key}", null);
193 589 }
194 590
195 591
196 -
592 +
197 593 // Handle boolean settings with special logic for WordPress storage quirks
198 594 if (isset($this->defaults[$key]) && is_bool($this->defaults[$key])) {
199 595 // Convert string representations back to booleans
200 596 if ('1' === $value || 1 === $value || true === $value || 'true' === $value) {
@@ -202,31 +598,40 @@
202 598 } elseif ('0' === $value || 0 === $value || false === $value || 'false' === $value) {
203 599 $value = false;
204 600 } elseif (null === $value || '' === $value) {
205 601 // For boolean settings, empty string could mean false was stored
206 - // Check if this setting was explicitly set by looking for the option
207 - $option_exists = get_option("thinkrank_{$key}", 'OPTION_NOT_FOUND') !== 'OPTION_NOT_FOUND';
208 - if ($option_exists && $value === '') {
602 + // null means option doesn't exist, empty string means it was stored as empty
603 + if (null !== $value && $value === '') {
209 604 // Empty string exists in DB, this likely means false was stored
210 605 $value = false;
211 606 } else {
212 607 // Option doesn't exist, use default
213 - $value = $default ?? $this->defaults[$key];
608 + $value = $fallback ?? $this->defaults[$key];
214 609 }
215 610 }
216 611 } else {
217 - // Non-boolean settings: use default if not found
218 - if (null === $value || '' === $value) {
219 - $value = $default ?? ($this->defaults[$key] ?? null);
612 + // Non-boolean settings: use default if not found.
613 + //
614 + // get_option() above is called with a null default, so null means
615 + // "no row" while '' means a value was deliberately stored. For most
616 + // keys we collapse the two — an empty string is treated as unset so
617 + // the documented default applies. Keys in EMPTY_IS_A_VALUE opt out:
618 + // there, clearing the field is a real choice the consumer honours,
619 + // and folding it back into the default made the save look like it
620 + // silently failed (#316).
621 + $empty_is_unset = !in_array($key, self::EMPTY_IS_A_VALUE, true);
622 +
623 + if (null === $value || ($empty_is_unset && '' === $value)) {
624 + $value = $fallback ?? ($this->defaults[$key] ?? null);
220 625 }
221 626 }
222 -
627 +
223 628 // Cache the value
224 629 $this->cache[$cache_key] = $value;
225 -
630 +
226 631 return $this->maybe_decrypt($key, $value);
227 632 }
228 -
633 +
229 634 /**
230 635 * Set setting value
231 636 *
232 637 * @param string $key Setting key
@@ -239,10 +644,14 @@
239 644 if (!array_key_exists($key, $this->defaults)) {
240 645 return false;
241 646 }
242 647
648 + // Apply the declared per-key sanitizer before anything is stored. This
649 + // is the path essentially every caller takes, so skipping it left the
650 + // whole sanitize_setting() switch unreachable — max_tokens,
651 + // cache_duration and temperature persisted whatever string arrived.
652 + $value = $this->sanitize_setting($key, $value);
243 653
244 -
245 654 // Encrypt if needed
246 655 $encrypted_value = $this->maybe_encrypt($key, $value);
247 656
248 657 // Save to WordPress options or user meta
@@ -268,10 +677,15 @@
268 677 }
269 678
270 679 // Verify value actually saved (update_option returns false when unchanged)
271 680 $saved_value = get_option($option_name, 'NOT_FOUND');
681 + // The loose branch is load-bearing: get_option() returns the stored
682 + // STRING ('1', '0', '30') while $encrypted_value may be the original
683 + // bool/int. On an unchanged re-save update_option() returns false, so
684 + // this comparison is the only thing that marks the save successful —
685 + // strict-only here made every unchanged-boolean re-save report failure.
272 686 $values_match = ($saved_value === $encrypted_value) ||
273 - ($saved_value == $encrypted_value && $encrypted_value !== 'NOT_FOUND');
687 + ($saved_value == $encrypted_value && $encrypted_value !== 'NOT_FOUND'); // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- intentional type-tolerant verify, see above.
274 688
275 689 // Consider it successful if the value was saved correctly
276 690 $result = $result || $values_match;
277 691 }
@@ -287,9 +701,9 @@
287 701 }
288 702
289 703 return $result !== false;
290 704 }
291 -
705 +
292 706 /**
293 707 * Delete setting
294 708 *
295 709 * @param string $key Setting key
@@ -302,19 +716,39 @@
302 716 $result = delete_user_meta($user_id, "thinkrank_{$key}");
303 717 } else {
304 718 $result = delete_option("thinkrank_{$key}");
305 719 }
306 -
720 +
307 721 // Remove from cache
308 722 if ($result) {
309 723 $cache_key = $user_id > 0 ? "user_{$user_id}_{$key}" : $key;
310 724 unset($this->cache[$cache_key]);
725 +
726 + // Also invalidate the bulk cache written by get_all(), or it serves
727 + // stale values for up to 5 minutes after a delete.
728 + $bulk_cache_key = $user_id > 0 ? "bulk_user_{$user_id}" : 'bulk_global';
729 + wp_cache_delete($bulk_cache_key, 'thinkrank_settings');
311 730 }
312 -
731 +
313 732 return $result;
314 733 }
315 -
734 +
316 735 /**
736 + * Setting keys whose values are encrypted at rest.
737 + *
738 + * Exposed so callers that must never emit a credential — the data exporter
739 + * in particular — can filter against the same list this class encrypts
740 + * with, instead of keeping a copy that silently drifts when a key is added.
741 + *
742 + * @since 2.2.0
743 + *
744 + * @return string[] Setting keys.
745 + */
746 + public function get_encrypted_keys(): array {
747 + return $this->encrypted_keys;
748 + }
749 +
750 + /**
317 751 * Get all settings (optimized with bulk caching)
318 752 *
319 753 * @param int $user_id User ID (0 for global)
320 754 * @return array All settings
@@ -338,9 +772,9 @@
338 772 wp_cache_set($bulk_cache_key, $settings, 'thinkrank_settings', 300);
339 773
340 774 return $settings;
341 775 }
342 -
776 +
343 777 /**
344 778 * Reset settings to defaults
345 779 *
346 780 * @param int $user_id User ID (0 for global)
@@ -347,21 +781,25 @@
347 781 * @return bool Success status
348 782 */
349 783 public function reset(int $user_id = 0): bool {
350 784 $success = true;
351 -
785 +
352 786 foreach (array_keys($this->defaults) as $key) {
353 787 if (!$this->delete($key, $user_id)) {
354 788 $success = false;
355 789 }
356 790 }
357 -
358 - // Clear cache
791 +
792 + // Clear cache — both the instance array and the bulk object cache
793 + // written by get_all(), which would otherwise return stale pre-reset
794 + // values for up to 5 minutes.
359 795 $this->cache = [];
360 -
796 + $bulk_cache_key = $user_id > 0 ? "bulk_user_{$user_id}" : 'bulk_global';
797 + wp_cache_delete($bulk_cache_key, 'thinkrank_settings');
798 +
361 799 return $success;
362 800 }
363 -
801 +
364 802 /**
365 803 * Sanitize settings
366 804 *
367 805 * @param array $settings Settings array
@@ -368,17 +806,53 @@
368 806 * @return array Sanitized settings
369 807 */
370 808 public function sanitize_settings(array $settings): array {
371 809 $sanitized = [];
372 -
810 +
373 811 foreach ($settings as $key => $value) {
374 812 $sanitized[$key] = $this->sanitize_setting($key, $value);
375 813 }
376 -
814 +
377 815 return $sanitized;
378 816 }
379 -
817 +
380 818 /**
819 + * Sanitize a nested array, preserving its shape.
820 + *
821 + * Scalars keep their type (an int threshold stays an int); strings are
822 + * text-sanitized; objects are dropped, since no setting stores one.
823 + *
824 + * @since 2.2.0
825 + * @param array $value Array to sanitize.
826 + * @param int $depth Current recursion depth.
827 + * @return array
828 + */
829 + private function sanitize_array_recursive(array $value, int $depth = 0): array {
830 + // Settings are configuration, not arbitrary payloads; a cap keeps a
831 + // malformed deep structure from recursing without bound.
832 + if ($depth > 10) {
833 + return [];
834 + }
835 +
836 + $sanitized = [];
837 + foreach ($value as $item_key => $item) {
838 + $key = is_string($item_key) ? sanitize_key($item_key) : $item_key;
839 +
840 + if (is_array($item)) {
841 + $sanitized[$key] = $this->sanitize_array_recursive($item, $depth + 1);
842 + } elseif (is_object($item)) {
843 + continue;
844 + } elseif (is_bool($item) || is_int($item) || is_float($item)) {
845 + $sanitized[$key] = $item;
846 + } else {
847 + $sanitized[$key] = sanitize_text_field((string) $item);
848 + }
849 + }
850 +
851 + return $sanitized;
852 + }
853 +
854 + /**
381 855 * Sanitize individual setting
382 856 *
383 857 * @param string $key Setting key
384 858 * @param mixed $value Setting value
@@ -384,23 +858,86 @@
384 858 * @param mixed $value Setting value
385 859 * @return mixed Sanitized value
386 860 */
387 861 private function sanitize_setting(string $key, $value) {
862 + // Only keys that are declared array-typed may receive an array. For a
863 + // scalar key an array/object value is malformed input, and the scalar
864 + // sanitizers below would fatal on it, so fall back to the declared
865 + // default instead of letting the bad value through.
866 + if (is_array($value) || is_object($value)) {
867 + if (!is_array($this->defaults[$key] ?? null)) {
868 + return $this->defaults[$key] ?? '';
869 + }
870 + $value = (array) $value;
871 + }
872 +
388 873 switch ($key) {
389 874 case 'openai_api_key':
390 875 case 'claude_api_key':
391 876 case 'gemini_api_key':
877 + case 'openrouter_api_key':
878 + case 'openai_compatible_api_key':
392 879 return sanitize_text_field($value);
393 880
881 + case 'openai_compatible_base_url':
882 + // Validation (scheme, SSRF guard) belongs to the write path that
883 + // can report a reason to the user; a value that never went
884 + // through it must not become a URL we fetch, so an invalid one
885 + // is stored as empty — which disables the provider — rather
886 + // than silently kept.
887 + $url = esc_url_raw(trim((string) $value));
888 + if ('' === $url) {
889 + return '';
890 + }
891 + $validated = \ThinkRank\AI\Endpoint_URL_Validator::validate($url);
892 +
893 + return is_wp_error($validated) ? '' : $validated;
894 +
895 + case 'openai_compatible_timeout':
896 + // Below 10s nothing local ever finishes; above 600s PHP-FPM
897 + // kills the request first.
898 + return max(10, min(600, absint($value)));
899 +
900 + case 'openai_compatible_price_per_million':
901 + return max(0.0, (float) $value);
902 +
903 + case 'openai_compatible_supports_images':
904 + case 'openai_compatible_json_mode':
905 + // Each toggle decides whether we send a field (a vision
906 + // payload, response_format) a server may reject, so coerce the '0'/'false' a form
907 + // post can send rather than storing a truthy string (the
908 + // default: arm keeps strings as strings, and '0' is truthy to
909 + // nobody but PHP's loose rules).
910 + if (is_string($value)) {
911 + return !in_array(strtolower(trim($value)), ['', '0', 'false', 'no', 'off'], true);
912 + }
913 +
914 + return (bool) $value;
915 +
394 916 case 'ai_provider':
917 + // sanitize_key() maps '' to '', which is AI_PROVIDER_NONE — the
918 + // deliberate "no provider chosen" state, so it must survive here
919 + // rather than being folded back into the default (#572).
920 + $provider = sanitize_key($value);
921 +
922 + return in_array($provider, self::selectable_ai_providers(), true)
923 + ? $provider
924 + : $this->defaults['ai_provider'];
925 +
395 926 case 'openai_model':
396 927 case 'claude_model':
397 928 case 'gemini_model':
398 - return sanitize_key($value);
399 -
929 + case 'openrouter_model':
930 + case 'openai_compatible_model':
931 + // Model ids may contain dots and slashes (e.g. "gpt-4.1" or
932 + // "openai/gpt-4o-mini") and users can enter custom models, so
933 + // sanitize_key() would corrupt them — use text-field sanitizing.
934 + return sanitize_text_field($value);
935 +
400 936 case 'max_tokens':
401 937 case 'cache_duration':
402 938 case 'max_requests_per_minute':
939 + case 'ai_daily_request_limit':
403 940 case 'seo_score_threshold':
404 941 case 'api_timeout':
405 942 case 'retry_attempts':
406 943 case 'data_retention_days':
@@ -405,21 +942,63 @@
405 942 case 'retry_attempts':
406 943 case 'data_retention_days':
407 944 case 'monitoring_frequency':
408 945 return absint($value);
409 -
946 +
947 + case 'ai_paused':
948 + // The kill switch arrives from REST as a real boolean, from a
949 + // form post as "1"/"0", and from WP-CLI as "true"/"false". The
950 + // default arm's sanitize_text_field() would turn "false" into a
951 + // truthy string and silently pause a site that asked to resume.
952 + return rest_sanitize_boolean($value);
953 +
410 954 case 'temperature':
411 955 return (float) $value;
412 -
956 +
413 957 case 'dashboard_widgets':
958 + return is_array($value) ? array_map('sanitize_key', $value) : [];
959 +
414 960 case 'seo_analytics_alert_thresholds':
415 - return is_array($value) ? array_map('sanitize_key', $value) : [];
961 + // A threshold_name => value map where the values are numbers
962 + // (e.g. traffic_drop_percentage => 20) as well as strings, so
963 + // sanitize each value by its own type rather than forcing every
964 + // one through sanitize_key() — that turned ints into strings.
965 + if (!is_array($value)) {
966 + return [];
967 + }
968 + $thresholds = [];
969 + foreach ($value as $threshold_key => $threshold_value) {
970 + if (is_array($threshold_value)) {
971 + continue;
972 + }
973 + if (is_bool($threshold_value)) {
974 + // Keep booleans as booleans. is_numeric() is false for
975 + // one, so it used to fall to the string arm and a true
976 + // came back as "1" — invisible while this ran only on
977 + // the register_setting() path, now that set() routes
978 + // every write through here it is a type change on save.
979 + $thresholds[sanitize_key($threshold_key)] = $threshold_value;
980 + continue;
981 + }
982 + $thresholds[sanitize_key($threshold_key)] = is_numeric($threshold_value)
983 + ? $threshold_value + 0
984 + : sanitize_text_field((string) $threshold_value);
985 + }
986 + return $thresholds;
416 987
417 988 case 'google_analytics_property_id':
418 989 case 'seo_analytics_google_analytics_property_id':
419 990 case 'seo_analytics_report_schedule':
420 991 return sanitize_text_field($value);
421 -
992 +
993 + case 'robots_txt_content':
994 + // Multi-line content — sanitize_text_field() collapses newlines
995 + // and would flatten the whole file onto a single line. set()
996 + // routes every write through here, so a caller that chose
997 + // sanitize_textarea_field() itself is otherwise silently
998 + // overridden by the default: arm below (#587).
999 + return sanitize_textarea_field($value);
1000 +
422 1001 default:
423 1002 if (is_bool($value)) {
424 1003 return (bool) $value;
425 1004 } elseif (is_string($value)) {
@@ -424,9 +1003,14 @@
424 1003 return (bool) $value;
425 1004 } elseif (is_string($value)) {
426 1005 return sanitize_text_field($value);
427 1006 } elseif (is_array($value)) {
428 - return array_map('sanitize_text_field', $value);
1007 + // Recurse rather than drop. Skipping nested members was
1008 + // harmless while this ran only on the register_setting()
1009 + // path, but set() now routes every write through here, and
1010 + // structured settings (lists of maps) were being silently
1011 + // emptied on save.
1012 + return $this->sanitize_array_recursive($value);
429 1013 }
430 1014 return $value;
431 1015 }
432 1016 }
@@ -431,26 +1015,34 @@
431 1015 }
432 1016 }
433 1017
434 1018 /**
435 - * Encryption version for tracking
1019 + * Marker prefix for values encrypted with the libsodium scheme below.
436 1020 */
437 - private const ENCRYPTION_VERSION = 2;
1021 + private const ENC_PREFIX = 'trenc:v1:';
438 1022
439 1023 /**
440 - * Maybe encrypt value using WordPress native encryption
1024 + * Encrypt secret settings (API keys, OAuth tokens) at rest using libsodium
1025 + * authenticated encryption. Non-secret keys and environments without sodium
1026 + * fall back to plaintext so behaviour stays stable.
441 1027 *
442 1028 * @param string $key Setting key
443 1029 * @param mixed $value Setting value
444 - * @return mixed Encrypted or original value
1030 + * @return mixed Encrypted payload (string) or original value
445 1031 */
446 1032 private function maybe_encrypt(string $key, $value) {
447 - // Critical fix: disable custom encryption; store raw value without transformation
448 - return $value;
1033 + if (!in_array($key, $this->encrypted_keys, true) || !is_string($value) || '' === $value) {
1034 + return $value;
1035 + }
1036 +
1037 + // Same scheme, same key, same prefix — it just lives in Secret_At_Rest
1038 + // now so the MCP pairing token can use it too (#396).
1039 + return Secret_At_Rest::encrypt($value);
449 1040 }
450 1041
451 1042 /**
452 - * Maybe decrypt value using WordPress native encryption
1043 + * Decrypt a value previously encrypted by maybe_encrypt. Values without the
1044 + * marker prefix are legacy plaintext and returned untouched (backward compat).
453 1045 *
454 1046 * @param string $key Setting key
455 1047 * @param mixed $value Setting value
456 1048 * @return mixed Decrypted or original value
@@ -455,124 +1047,26 @@
455 1047 * @param mixed $value Setting value
456 1048 * @return mixed Decrypted or original value
457 1049 */
458 1050 private function maybe_decrypt(string $key, $value) {
459 - if (!in_array($key, $this->encrypted_keys, true) || empty($value)) {
460 - return $value;
1051 + if (!is_string($value) || strncmp($value, self::ENC_PREFIX, strlen(self::ENC_PREFIX)) !== 0) {
1052 + return $value; // legacy plaintext or non-string
461 1053 }
462 1054
463 - // Backward compatibility: if value looks like our old encrypted payload, try to decrypt
464 - $data = base64_decode((string) $value, true);
465 - if ($data !== false && strlen($data) >= 33) {
466 - $version = unpack('C', substr($data, 0, 1))[1] ?? null;
467 - if ($version === self::ENCRYPTION_VERSION) {
468 - $decrypted = $this->decrypt_value((string) $value);
469 - // If decryption worked, return it; otherwise fall through and return original
470 - if ($decrypted !== '') {
471 - return $decrypted;
472 - }
473 - }
474 - }
1055 + $plain = Secret_At_Rest::decrypt($value);
475 1056
476 - // Treat as already plain
477 - return $value;
478 - }
479 -
480 - /**
481 - * Encrypt value using WordPress native methods
482 - *
483 - * @param string $value Value to encrypt
484 - * @return string Encrypted value (base64 encoded) or empty string on failure
485 - * @throws \Exception When encryption process fails
486 - */
487 - private function encrypt_value(string $value): string {
488 - try {
489 - // Generate unique salt for this encryption
490 - $salt = wp_generate_password(32, false);
491 -
492 - // Create encryption key using WordPress salts
493 - $auth_salt = wp_salt('auth');
494 - $secure_salt = wp_salt('secure_auth');
495 - $key = wp_hash($salt . $auth_salt . $secure_salt);
496 -
497 - // XOR encryption
498 - $encrypted = $this->xor_encrypt($value, $key);
499 -
500 - // Version prefix + salt + encrypted data
501 - $version = pack('C', self::ENCRYPTION_VERSION);
502 - return base64_encode($version . $salt . $encrypted);
503 -
504 - } catch (\Exception $e) {
505 - // Silent failure on encryption error
506 - return ''; // Return empty on encryption failure
507 - }
508 - }
509 -
510 - /**
511 - * Decrypt value using WordPress native methods
512 - *
513 - * @param string $encrypted_value Encrypted value to decrypt
514 - * @return string Decrypted value or empty string on failure
515 - * @throws \Exception When decryption process fails
516 - */
517 - private function decrypt_value(string $encrypted_value): string {
518 - try {
519 - $data = base64_decode($encrypted_value, true);
520 - if (false === $data || strlen($data) < 33) {
521 - return '';
522 - }
523 -
524 - // Extract version, salt, and encrypted data
525 - $version = unpack('C', substr($data, 0, 1))[1];
526 - $salt = substr($data, 1, 32);
527 - $encrypted = substr($data, 33);
528 -
529 - // Verify version
530 - if ($version !== self::ENCRYPTION_VERSION) {
531 - return '';
532 - }
533 -
534 - // Recreate encryption key
535 - $auth_salt = wp_salt('auth');
536 - $secure_salt = wp_salt('secure_auth');
537 - $key = wp_hash($salt . $auth_salt . $secure_salt);
538 -
539 - // Decrypt using XOR
540 - return $this->xor_decrypt($encrypted, $key);
541 -
542 - } catch (\Exception $e) {
543 - // Silent failure on decryption error
1057 + if ('' === $plain) {
1058 + // We reach here only when sodium is available and a key was
1059 + // derivable, so this is a genuine failure: the auth salt changed
1060 + // (config rotated, or the site was migrated without wp-config) or
1061 + // the row is corrupt. The value is unrecoverable either way.
1062 + //
1063 + // Returning the ciphertext would send it upstream as a bearer
1064 + // token or API key, producing an opaque 401 far from the cause.
1065 + // Return empty so callers see "no credential" and can prompt for
1066 + // a reconnect instead.
544 1067 return '';
545 1068 }
546 - }
547 1069
548 - /**
549 - * XOR encryption helper
550 - *
551 - * @param string $data Data to encrypt
552 - * @param string $key Encryption key
553 - * @return string Encrypted data
554 - */
555 - private function xor_encrypt(string $data, string $key): string {
556 - $result = '';
557 - $key_length = strlen($key);
558 - $data_length = strlen($data);
559 -
560 - for ($i = 0; $i < $data_length; $i++) {
561 - $result .= chr(ord($data[$i]) ^ ord($key[$i % $key_length]));
562 - }
563 -
564 - return $result;
565 - }
566 -
567 - /**
568 - * XOR decryption helper (XOR is symmetric)
569 - *
570 - * @param string $encrypted Encrypted data
571 - * @param string $key Encryption key
572 - * @return string Decrypted data
573 - */
574 - private function xor_decrypt(string $encrypted, string $key): string {
575 - // XOR is symmetric, so decryption is the same as encryption
576 - return $this->xor_encrypt($encrypted, $key);
1070 + return $plain;
577 1071 }
578 1072 }