PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 1.26.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v1.26.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 1.0.2 1.1.0 1.10.0 All 48 releases
thinkrank / includes / admin / class-metabox-manager.php

class-metabox-manager.php in ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO 1.26.0, at includes/admin/class-metabox-manager.php

1,202 lines 46.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Meta Box Manager
5 *
6 * Handles ThinkRank meta boxes in post/page edit screens
7 *
8 * @package ThinkRank\Admin
9 * @since 1.0.0
10 */
11
12 declare(strict_types=1);
13
14 namespace ThinkRank\Admin;
15
16 use ThinkRank\AI\Metadata_Generator;
17 use ThinkRank\AI\SEOScoreCalculator;
18 use ThinkRank\Core\Settings;
19 use ThinkRank\Core\Database;
20 use ThinkRank\Core\Plan_Config;
21 use ThinkRank\SEO\Focus_Keywords;
22 use ThinkRank\SEO\Pattern_Resolver;
23
24 // Prevent direct access
25 if (!defined('ABSPATH')) {
26 exit;
27 }
28
29 /**
30 * Meta Box Manager Class
31 *
32 * Single Responsibility: Manage post/page meta boxes
33 *
34 * @since 1.0.0
35 */
36 class Metabox_Manager {
37
38 /**
39 * Settings instance
40 *
41 * @var Settings
42 */
43 private Settings $settings;
44
45 /**
46 * Metadata generator instance
47 *
48 * @var Metadata_Generator
49 */
50 private Metadata_Generator $metadata_generator;
51
52 /**
53 * SEO Score Calculator instance
54 *
55 * @var SEOScoreCalculator
56 */
57 private SEOScoreCalculator $seo_calculator;
58
59 /**
60 * Constructor
61 *
62 * @param Settings|null $settings Settings instance
63 * @param Metadata_Generator|null $metadata_generator Metadata generator instance
64 * @param SEOScoreCalculator|null $seo_calculator SEO Score Calculator instance
65 */
66 public function __construct(?Settings $settings = null, ?Metadata_Generator $metadata_generator = null, ?SEOScoreCalculator $seo_calculator = null) {
67 $this->settings = $settings ?? Settings::instance();
68 $this->metadata_generator = $metadata_generator ?? new Metadata_Generator();
69 $this->seo_calculator = $seo_calculator ?? new SEOScoreCalculator(new Database());
70 }
71
72 /**
73 * Initialize meta box manager
74 *
75 * @return void
76 */
77 public function init(): void {
78 add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
79 add_action('save_post', [$this, 'save_meta_boxes'], 10, 2);
80 add_action('admin_enqueue_scripts', [$this, 'enqueue_metabox_scripts']);
81 add_action('init', [$this, 'register_meta_fields']);
82
83 // AJAX handlers for meta box functionality
84 add_action('wp_ajax_thinkrank_generate_post_metadata', [$this, 'ajax_generate_post_metadata']);
85
86 // Full metabox save used by editors that don't submit the #post form
87 // (e.g. the Elementor editor). Persists every metabox field at once.
88 add_action('wp_ajax_thinkrank_save_metabox', [$this, 'ajax_save_metabox']);
89
90 // Removed debug hooks
91 }
92
93 /**
94 * Register meta fields for REST API access
95 *
96 * @return void
97 */
98 public function register_meta_fields(): void {
99 // Register schema form data meta fields
100 register_post_meta('', '_thinkrank_schema_form_data', [
101 'show_in_rest' => true,
102 'single' => true,
103 'type' => 'string',
104 'sanitize_callback' => [$this, 'sanitize_json_meta_field'],
105 'auth_callback' => function () {
106 return current_user_can('edit_posts') || current_user_can('edit_pages');
107 }
108 ]);
109
110 register_post_meta('', '_thinkrank_selected_schema_type', [
111 'show_in_rest' => true,
112 'single' => true,
113 'type' => 'string',
114 'auth_callback' => function () {
115 return current_user_can('edit_posts') || current_user_can('edit_pages');
116 }
117 ]);
118
119 register_post_meta('', '_thinkrank_additional_schemas', [
120 'show_in_rest' => true,
121 'single' => true,
122 'type' => 'string',
123 'sanitize_callback' => [$this, 'sanitize_json_ld_field'],
124 'auth_callback' => function() {
125 return current_user_can('edit_posts') || current_user_can('edit_pages');
126 }
127 ]);
128
129 // SEO meta fields for import support
130 $string_meta_fields = [
131 '_thinkrank_canonical_url',
132 '_thinkrank_og_title',
133 '_thinkrank_og_description',
134 '_thinkrank_og_image',
135 '_thinkrank_twitter_title',
136 '_thinkrank_twitter_description',
137 '_thinkrank_twitter_image',
138 '_thinkrank_imported_from',
139 ];
140
141 foreach ($string_meta_fields as $meta_key) {
142 register_post_meta('', $meta_key, [
143 'show_in_rest' => true,
144 'single' => true,
145 'type' => 'string',
146 'auth_callback' => function () {
147 return current_user_can('edit_posts') || current_user_can('edit_pages');
148 }
149 ]);
150 }
151
152 // Multiple focus keywords (array). The legacy single-value
153 // `_thinkrank_focus_keyword` is kept in sync by Focus_Keywords for
154 // backward compatibility and registered for REST as a string elsewhere.
155 register_post_meta('', Focus_Keywords::META_KEY, [
156 'show_in_rest' => [
157 'schema' => [
158 'type' => 'array',
159 'items' => ['type' => 'string'],
160 ],
161 ],
162 'single' => true,
163 'type' => 'array',
164 'sanitize_callback' => function ($value) {
165 return Focus_Keywords::normalize($value);
166 },
167 'auth_callback' => function () {
168 return current_user_can('edit_posts') || current_user_can('edit_pages');
169 }
170 ]);
171
172 register_post_meta('', Focus_Keywords::LEGACY_META_KEY, [
173 'show_in_rest' => true,
174 'single' => true,
175 'type' => 'string',
176 'auth_callback' => function () {
177 return current_user_can('edit_posts') || current_user_can('edit_pages');
178 }
179 ]);
180
181 register_post_meta('', '_thinkrank_robots_meta_enabled', [
182 'show_in_rest' => true,
183 'single' => true,
184 'type' => 'integer',
185 'auth_callback' => function () {
186 return current_user_can('edit_posts') || current_user_can('edit_pages');
187 }
188 ]);
189
190 register_post_meta('', '_thinkrank_robots_meta', [
191 'show_in_rest' => true,
192 'single' => true,
193 'type' => 'string',
194 'sanitize_callback' => [$this, 'sanitize_json_meta_field'],
195 'auth_callback' => function () {
196 return current_user_can('edit_posts') || current_user_can('edit_pages');
197 }
198 ]);
199
200 register_post_meta('', '_thinkrank_advanced_robots_meta', [
201 'show_in_rest' => true,
202 'single' => true,
203 'type' => 'string',
204 'sanitize_callback' => [$this, 'sanitize_json_meta_field'],
205 'auth_callback' => function () {
206 return current_user_can('edit_posts') || current_user_can('edit_pages');
207 }
208 ]);
209
210 register_post_meta('', '_thinkrank_primary_category', [
211 'show_in_rest' => true,
212 'single' => true,
213 'type' => 'integer',
214 'auth_callback' => function () {
215 return current_user_can('edit_posts') || current_user_can('edit_pages');
216 }
217 ]);
218 }
219
220 /**
221 * Sanitize JSON meta field data
222 *
223 * Validates JSON structure and recursively sanitizes all string values
224 * to prevent XSS and injection attacks.
225 *
226 * @param string $value Raw JSON string value
227 * @return string Sanitized JSON string or empty string if invalid
228 */
229 public function sanitize_json_meta_field(string $value): string {
230 // Return empty string for non-string values
231 if (!is_string($value) || empty($value)) {
232 return '';
233 }
234
235 // Validate JSON structure
236 $decoded = json_decode($value, true);
237 if (json_last_error() !== JSON_ERROR_NONE) {
238 // Invalid JSON - return empty string
239 return '';
240 }
241
242 // Check for reasonable data size (prevent JSON bombs)
243 if (strlen($value) > 50000) { // 50KB limit
244 return '';
245 }
246
247 // Recursively sanitize all values
248 $sanitized = $this->sanitize_json_recursively($decoded);
249
250 // Re-encode as JSON
251 $result = wp_json_encode($sanitized);
252 return $result !== false ? $result : '';
253 }
254
255 /**
256 * Recursively sanitize JSON data
257 *
258 * @param mixed $data Data to sanitize
259 * @param int $depth Current recursion depth
260 * @return mixed Sanitized data
261 */
262 private function sanitize_json_recursively($data, int $depth = 0): mixed {
263 // Prevent deep recursion attacks
264 if ($depth > 10) {
265 return null;
266 }
267
268 if (is_array($data)) {
269 $sanitized = [];
270 foreach ($data as $key => $value) {
271 $clean_key = sanitize_key($key);
272 $sanitized[$clean_key] = $this->sanitize_json_recursively($value, $depth + 1);
273 }
274 return $sanitized;
275 }
276
277 if (is_string($data)) {
278 // Sanitize string data to prevent XSS
279 return sanitize_textarea_field($data);
280 }
281
282 if (is_numeric($data)) {
283 return $data;
284 }
285
286 if (is_bool($data)) {
287 return $data;
288 }
289
290 // For any other data type, return null
291 return null;
292 }
293
294 /**
295 * Sanitize JSON-LD meta field data
296 *
297 * Validates JSON structure, recursively sanitizes all string values,
298 * and preserves @ characters in keys (crucial for JSON-LD).
299 *
300 * @param string $value Raw JSON string value
301 *
302 * @return string Sanitized JSON string or empty string if invalid
303 */
304 public function sanitize_json_ld_field( string $value ): string {
305 // Return empty string for non-string values
306 if ( ! is_string( $value ) || empty( $value ) ) {
307 return '';
308 }
309
310 // Validate JSON structure
311 $decoded = json_decode( $value, true );
312 if ( json_last_error() !== JSON_ERROR_NONE ) {
313 // Invalid JSON - return empty string
314 return '';
315 }
316
317 // Check for reasonable data size (prevent JSON bombs)
318 if ( strlen( $value ) > 200000 ) { // Limit to 200KB for larger schemas
319 return '';
320 }
321
322 // Recursively sanitize all values
323 $sanitized = $this->sanitize_json_ld_recursively( $decoded );
324
325 // Re-encode as JSON
326 $result = wp_json_encode( $sanitized );
327
328 return $result !== false ? $result : '';
329 }
330
331 /**
332 * Recursively sanitize JSON-LD data
333 *
334 * Similar to sanitize_json_recursively but preserves @ symbol and case in keys.
335 *
336 * @param mixed $data Data to sanitize
337 * @param int $depth Current recursion depth
338 *
339 * @return mixed Sanitized data
340 */
341 private function sanitize_json_ld_recursively( $data, int $depth = 0 ): mixed {
342 // Prevent deep recursion attacks
343 if ( $depth > 10 ) {
344 return null;
345 }
346
347 if ( is_array( $data ) ) {
348 $sanitized = [];
349 foreach ( $data as $key => $value ) {
350 // Allow alphanumeric, underscore, dash, and @ (crucial for JSON-LD)
351 // Also preserve case as JSON-LD keys are case-sensitive
352 $clean_key = preg_replace( '/[^a-zA-Z0-9_\-@]/', '', (string) $key );
353 $sanitized[ $clean_key ] = $this->sanitize_json_ld_recursively( $value, $depth + 1 );
354 }
355
356 return $sanitized;
357 }
358
359 if ( is_string( $data ) ) {
360 // Sanitize string data to prevent XSS
361 return sanitize_textarea_field( $data );
362 }
363
364 if ( is_numeric( $data ) ) {
365 return $data;
366 }
367
368 if ( is_bool( $data ) ) {
369 return $data;
370 }
371
372 // For any other data type, return null
373 return null;
374 }
375
376 // Removed debug methods
377
378 /**
379 * Add ThinkRank meta boxes
380 *
381 * @return void
382 */
383 public function add_meta_boxes(): void {
384 $post_types = $this->get_supported_post_types();
385
386 $is_block_editor = $this->is_block_editor_screen();
387
388 foreach ($post_types as $post_type) {
389 add_meta_box(
390 'thinkrank-seo-metabox',
391 __('ThinkRank SEO', 'thinkrank'),
392 [$this, 'render_seo_metabox'],
393 $post_type,
394 'normal',
395 'high'
396 );
397
398 // Classic Editor sidebar quick-access widget (mirrors SureRank's
399 // "Manage your SEO" sidebar box). Skipped in the Block Editor, which
400 // surfaces the full panel below the content instead.
401 if (!$is_block_editor) {
402 add_meta_box(
403 'thinkrank-seo-sidebar',
404 __('ThinkRank', 'thinkrank'),
405 [$this, 'render_sidebar_meta_box'],
406 $post_type,
407 'side',
408 'high'
409 );
410 }
411 }
412 }
413
414 /**
415 * Whether the current edit screen is using the Block Editor.
416 *
417 * @return bool True when the Block Editor is active, false for Classic Editor.
418 */
419 private function is_block_editor_screen(): bool {
420 if (!function_exists('get_current_screen')) {
421 return false;
422 }
423
424 $screen = get_current_screen();
425
426 return $screen instanceof \WP_Screen
427 && method_exists($screen, 'is_block_editor')
428 && $screen->is_block_editor();
429 }
430
431 /**
432 * Render the Classic Editor sidebar quick-access widget.
433 *
434 * Shows a short label plus a button that scrolls to (and expands) the full
435 * "ThinkRank SEO" panel in the main column.
436 *
437 * @param \WP_Post $post Post object.
438 * @return void
439 */
440 public function render_sidebar_meta_box(\WP_Post $post): void {
441 $box_title = apply_filters('thinkrank_seo_sidebar_box_title', __('Optimize this content for search & AI with ThinkRank.', 'thinkrank'), $post);
442 $cta_label = apply_filters('thinkrank_seo_sidebar_cta_label', __('Open ThinkRank SEO', 'thinkrank'), $post);
443 ?>
444 <div class="thinkrank-classic-sidebar-box">
445 <p class="thinkrank-classic-sidebar-box-title"><?php echo esc_html($box_title); ?></p>
446 <button
447 type="button"
448 class="button button-primary thinkrank-classic-sidebar-box-cta"
449 >
450 <?php echo esc_html($cta_label); ?>
451 </button>
452 </div>
453 <?php
454 }
455
456 /**
457 * Render SEO meta box
458 *
459 * @param \WP_Post $post Post object
460 * @return void
461 */
462 public function render_seo_metabox(\WP_Post $post): void {
463 // Add nonce for security
464 wp_nonce_field('thinkrank_metabox_nonce', 'thinkrank_metabox_nonce');
465
466 // Get existing metadata
467 $existing_metadata = $this->get_post_metadata($post->ID);
468
469 // Get post content for AI analysis
470 $content_preview = $this->get_content_preview($post);
471
472 // Render React metabox container with hidden form fields for data
473 ?>
474 <div id="thinkrank-metabox-container" class="thinkrank-metabox">
475
476 <!-- Hidden form fields for React to read initial data -->
477 <input type="hidden" id="thinkrank_seo_title" name="thinkrank_seo_title" value="<?php echo esc_attr($existing_metadata['title'] ?? ''); ?>" />
478 <input type="hidden" id="thinkrank_meta_description" name="thinkrank_meta_description" value="<?php echo esc_attr($existing_metadata['description'] ?? ''); ?>" />
479 <input type="hidden" id="thinkrank_focus_keyword" name="thinkrank_focus_keyword" value="<?php echo esc_attr($existing_metadata['focus_keyword'] ?? ''); ?>" />
480 <input type="hidden" id="thinkrank_focus_keywords" name="thinkrank_focus_keywords" value="<?php echo esc_attr(wp_json_encode($existing_metadata['focus_keywords'] ?? [])); ?>" />
481 <input type="hidden" id="thinkrank_seo_score" name="thinkrank_seo_score" value="<?php echo esc_attr($existing_metadata['seo_score'] ?? '0'); ?>" />
482 <input type="hidden" id="thinkrank_generated_at" name="thinkrank_generated_at" value="<?php echo esc_attr($existing_metadata['generated_at'] ?? ''); ?>" />
483 <input type="hidden" id="thinkrank_pillar_content" name="thinkrank_pillar_content" value="<?php echo esc_attr($existing_metadata['pillar_content'] ?? ''); ?>" />
484 <input type="hidden" id="thinkrank_canonical_url" name="thinkrank_canonical_url" value="<?php echo esc_url($existing_metadata['canonical_url'] ?? ''); ?>" />
485 <input type="hidden" id="thinkrank_robots_meta_enabled" name="thinkrank_robots_meta_enabled" value="<?php echo esc_attr((string) ($existing_metadata['robots_meta_enabled'] ?? '0')); ?>" />
486 <input type="hidden" id="thinkrank_robots_meta" name="thinkrank_robots_meta" value="<?php echo esc_attr((string) ($existing_metadata['robots_meta'] ?? '')); ?>" />
487 <input type="hidden" id="thinkrank_advanced_robots_meta" name="thinkrank_advanced_robots_meta" value="<?php echo esc_attr((string) ($existing_metadata['advanced_robots_meta'] ?? '')); ?>" />
488 <input type="hidden" id="thinkrank_og_title" name="thinkrank_og_title" value="<?php echo esc_attr((string) ($existing_metadata['og_title'] ?? '')); ?>" />
489 <input type="hidden" id="thinkrank_og_description" name="thinkrank_og_description" value="<?php echo esc_attr((string) ($existing_metadata['og_description'] ?? '')); ?>" />
490 <input type="hidden" id="thinkrank_og_image" name="thinkrank_og_image" value="<?php echo esc_url((string) ($existing_metadata['og_image'] ?? '')); ?>" />
491 <input type="hidden" id="thinkrank_twitter_title" name="thinkrank_twitter_title" value="<?php echo esc_attr((string) ($existing_metadata['twitter_title'] ?? '')); ?>" />
492 <input type="hidden" id="thinkrank_twitter_description" name="thinkrank_twitter_description" value="<?php echo esc_attr((string) ($existing_metadata['twitter_description'] ?? '')); ?>" />
493 <input type="hidden" id="thinkrank_twitter_image" name="thinkrank_twitter_image" value="<?php echo esc_url((string) ($existing_metadata['twitter_image'] ?? '')); ?>" />
494 <textarea id="thinkrank_content_preview" style="display: none;"><?php echo esc_textarea($content_preview); ?></textarea>
495 </div>
496 <?php
497
498 }
499
500 /**
501 * Save meta box data
502 *
503 * @param int $post_id Post ID
504 * @param \WP_Post $post Post object
505 * @return void
506 */
507 public function save_meta_boxes(int $post_id, \WP_Post $post): void {
508 // Verify nonce
509 if (!isset($_POST['thinkrank_metabox_nonce'])) {
510 return;
511 }
512
513 $nonce = sanitize_text_field(wp_unslash($_POST['thinkrank_metabox_nonce']));
514 if (!wp_verify_nonce($nonce, 'thinkrank_metabox_nonce')) {
515 return;
516 }
517
518 // Check permissions
519 if (!current_user_can('edit_post', $post_id)) {
520 return;
521 }
522
523 // Skip autosave
524 if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
525 return;
526 }
527
528 // The classic/block editor submits the metabox fields as part of the
529 // #post form, so they arrive (slashed) in $_POST. Hand them straight to
530 // the shared persistence routine.
531 // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified above
532 $this->persist_metadata($post_id, wp_unslash($_POST));
533 }
534
535 /**
536 * Persist metabox fields for a post from a form-field-name => value map,
537 * reusing the shared metabox persistence (sanitization, JSON encoding,
538 * focus-keyword normalization, empty-value deletion).
539 *
540 * Intended for non-form callers such as the MCP abilities layer. The
541 * caller is responsible for authorization; keys use the same
542 * `thinkrank_*` field names accepted by the metabox form (e.g.
543 * `thinkrank_seo_title`, `thinkrank_meta_description`, `thinkrank_robots_meta`).
544 *
545 * @param int $post_id Post to update.
546 * @param array $fields Field name => value map.
547 * @return void
548 */
549 public function save_seo_fields(int $post_id, array $fields): void {
550 $this->persist_metadata($post_id, $fields);
551 }
552
553 /**
554 * Persist all metabox fields for a post from a $_POST-shaped (already
555 * unslashed) source array.
556 *
557 * Shared by `save_meta_boxes()` (classic/block editor form submit) and
558 * `ajax_save_metabox()` (editors like Elementor that don't submit the #post
559 * form). Nonce/permission checks are the caller's responsibility. Each field
560 * is independently sanitized; missing keys are left untouched.
561 *
562 * @param int $post_id Post to update.
563 * @param array $src Field name => raw value map (unslashed).
564 * @return void
565 */
566 private function persist_metadata(int $post_id, array $src): void {
567 // Save metadata. Focus keywords are handled separately (array meta) via
568 // Focus_Keywords below, so they are intentionally absent from this list.
569 $fields = [
570 'thinkrank_seo_title' => 'sanitize_text_field',
571 'thinkrank_meta_description' => 'sanitize_textarea_field',
572 'thinkrank_seo_score' => 'absint',
573 'thinkrank_generated_at' => 'sanitize_text_field',
574 'thinkrank_pillar_content' => 'sanitize_text_field',
575 ];
576
577 // Focus keywords: prefer the JSON array field; fall back to the legacy
578 // single string. Focus_Keywords::save() normalizes (dedupe, drop empty,
579 // cap at MAX) and keeps the legacy single-value meta in sync.
580 if (isset($src['thinkrank_focus_keywords'])) {
581 $raw_keywords = $src['thinkrank_focus_keywords'];
582 $decoded = is_string($raw_keywords) ? json_decode($raw_keywords, true) : $raw_keywords;
583 Focus_Keywords::save($post_id, is_array($decoded) ? $decoded : []);
584 } elseif (isset($src['thinkrank_focus_keyword'])) {
585 Focus_Keywords::save($post_id, $src['thinkrank_focus_keyword']);
586 }
587
588 // Update the post slug (post_name) when the metabox permalink field
589 // was edited. This touches the WP post itself, not post meta.
590 if (isset($src['thinkrank_post_slug'])) {
591 $this->maybe_update_slug($post_id, (string) $src['thinkrank_post_slug']);
592 }
593
594 // Save canonical URL separately with URL sanitization
595 if (isset($src['thinkrank_canonical_url'])) {
596 $canonical_url = esc_url_raw((string) $src['thinkrank_canonical_url']);
597 if (empty($canonical_url)) {
598 delete_post_meta($post_id, '_thinkrank_canonical_url');
599 } else {
600 update_post_meta($post_id, '_thinkrank_canonical_url', $canonical_url);
601 }
602 }
603
604 foreach ($fields as $field => $sanitize_callback) {
605 if (isset($src[$field])) {
606 $value = call_user_func($sanitize_callback, $src[$field]);
607 update_post_meta($post_id, "_{$field}", $value);
608 }
609 }
610
611 $this->save_robots_meta($post_id, $src);
612 $this->save_social_meta($post_id, $src);
613
614 // Update last modified timestamp
615 update_post_meta($post_id, '_thinkrank_last_updated', current_time('mysql'));
616 }
617
618 /**
619 * Update the post slug (post_name) from the metabox permalink field.
620 *
621 * Runs inside the save_post cycle, so wp_update_post() would recurse — a
622 * static guard prevents re-entry. WordPress applies wp_unique_post_slug(),
623 * so a colliding slug is de-duplicated automatically. Empty input is left
624 * alone (WP keeps/auto-generates the slug); auto-drafts and revisions are
625 * skipped so we don't fight the editor's own slug generation.
626 *
627 * @param int $post_id Post to update.
628 * @param string $raw_slug Desired slug from the metabox.
629 * @return void
630 */
631 private function maybe_update_slug(int $post_id, string $raw_slug): void {
632 static $updating = false;
633 if ($updating) {
634 return;
635 }
636
637 $post = get_post($post_id);
638 if (!$post || wp_is_post_revision($post_id)) {
639 return;
640 }
641
642 if (in_array($post->post_status, ['auto-draft', 'trash'], true)) {
643 return;
644 }
645
646 $desired = sanitize_title($raw_slug);
647 if ($desired === '' || $desired === $post->post_name) {
648 return;
649 }
650
651 $updating = true;
652 wp_update_post([
653 'ID' => $post_id,
654 'post_name' => $desired,
655 ]);
656 $updating = false;
657 }
658
659 /**
660 * Persist per-post Open Graph and Twitter Card overrides.
661 *
662 * Empty values delete the meta entry so the frontend falls back to the
663 * SEO title / meta description / featured image chain.
664 */
665 private function save_social_meta(int $post_id, array $src): void {
666 $text_fields = [
667 'thinkrank_og_title' => '_thinkrank_og_title',
668 'thinkrank_og_description' => '_thinkrank_og_description',
669 'thinkrank_twitter_title' => '_thinkrank_twitter_title',
670 'thinkrank_twitter_description' => '_thinkrank_twitter_description',
671 ];
672 foreach ($text_fields as $field => $meta_key) {
673 if (!isset($src[$field])) {
674 continue;
675 }
676 $value = sanitize_textarea_field((string) $src[$field]);
677 if ($value === '') {
678 delete_post_meta($post_id, $meta_key);
679 } else {
680 update_post_meta($post_id, $meta_key, $value);
681 }
682 }
683
684 $url_fields = [
685 'thinkrank_og_image' => '_thinkrank_og_image',
686 'thinkrank_twitter_image' => '_thinkrank_twitter_image',
687 ];
688 foreach ($url_fields as $field => $meta_key) {
689 if (!isset($src[$field])) {
690 continue;
691 }
692 $value = esc_url_raw((string) $src[$field]);
693 if ($value === '') {
694 delete_post_meta($post_id, $meta_key);
695 } else {
696 update_post_meta($post_id, $meta_key, $value);
697 }
698 }
699 }
700
701 /**
702 * Save per-post robots meta and advanced robots meta from the metabox.
703 *
704 * Stores the robots payloads as JSON-encoded strings, sanitized via
705 * sanitize_json_meta_field. The toggle plus the two JSON blobs are the
706 * single source of truth for per-post robots overrides.
707 */
708 private function save_robots_meta(int $post_id, array $src): void {
709 if (!isset($src['thinkrank_robots_meta_enabled'])) {
710 return;
711 }
712
713 $enabled = (int) (bool) $src['thinkrank_robots_meta_enabled'];
714 update_post_meta($post_id, '_thinkrank_robots_meta_enabled', $enabled);
715
716 if (isset($src['thinkrank_robots_meta'])) {
717 update_post_meta($post_id, '_thinkrank_robots_meta', $this->sanitize_json_meta_field((string) $src['thinkrank_robots_meta']));
718 }
719
720 if (isset($src['thinkrank_advanced_robots_meta'])) {
721 update_post_meta($post_id, '_thinkrank_advanced_robots_meta', $this->sanitize_json_meta_field((string) $src['thinkrank_advanced_robots_meta']));
722 }
723 }
724
725
726 /**
727 * Enqueue meta box scripts
728 *
729 * @param string $hook Current admin page hook
730 * @return void
731 */
732 public function enqueue_metabox_scripts(string $hook): void {
733 // Only load on post edit screens (including block editor)
734 if (!in_array($hook, ['post.php', 'post-new.php'])) {
735 return;
736 }
737
738 // Get current post type - handle both classic and block editor contexts
739 $current_post_type = $this->get_current_post_type();
740 if (!$current_post_type || !in_array($current_post_type, $this->get_supported_post_types())) {
741 return;
742 }
743
744 // Get post object for additional data
745 global $post;
746
747 // Ensure wp.media is available for the social-image media picker.
748 wp_enqueue_media();
749
750 // No chunk dependencies needed - all bundled into main metabox.js
751 // Enqueue React metabox script with direct dependencies
752 $asset_file = THINKRANK_PLUGIN_DIR . 'assets/metabox.asset.php';
753 $asset = file_exists($asset_file) ? include $asset_file : [
754 'dependencies' => ['react', 'wp-element', 'wp-i18n', 'wp-api-fetch', 'wp-components'],
755 'version' => THINKRANK_VERSION
756 ];
757
758 // Use dependencies directly from the asset file. The pinned "Configure
759 // SEO" launcher needs wp-plugins (already listed by the build) and
760 // resolves PinnedItems from wp.editor / wp.interface at runtime, so we do
761 // NOT add wp-interface here: it is not a registered script handle on
762 // WP 7.x, and an unmet dependency would drop the whole metabox script.
763 $dependencies = $asset['dependencies'];
764
765 wp_enqueue_script(
766 'thinkrank-metabox',
767 THINKRANK_PLUGIN_URL . 'assets/metabox.js',
768 $dependencies,
769 $asset['version'],
770 true
771 );
772
773 // Localize script data (shared builder; reused by the Elementor editor
774 // integration, which has no #post form / hidden inputs of its own).
775 wp_localize_script('thinkrank-metabox', 'thinkrankMetabox', $this->get_localized_data($post->ID));
776
777 // Add defer attribute for non-blocking script loading
778 wp_script_add_data('thinkrank-metabox', 'defer', true);
779
780 // Enqueue metabox styles
781 wp_enqueue_style(
782 'thinkrank-metabox',
783 THINKRANK_PLUGIN_URL . 'assets/metabox.css',
784 ['wp-components'],
785 THINKRANK_VERSION
786 );
787
788 // Classic Editor sidebar widget: lightweight styles + a vanilla-JS
789 // handler so the "Optimize Here" button works without depending on the
790 // React bundle. The box itself is only registered in the Classic Editor.
791 $sidebar_css = <<<'CSS'
792 .thinkrank-classic-sidebar-box-title{margin:0 0 12px;font-size:13px;line-height:1.5;color:#1e1e1e;}
793 .thinkrank-classic-sidebar-box-cta{width:100%;text-align:center;justify-content:center;}
794 CSS;
795 wp_add_inline_style('thinkrank-metabox', $sidebar_css);
796
797 $sidebar_js = <<<'JS'
798 (function(){
799 document.addEventListener('click', function(e){
800 var btn = e.target.closest && e.target.closest('.thinkrank-classic-sidebar-box-cta');
801 if(!btn){return;}
802 e.preventDefault();
803 // Open the ThinkRank SEO drawer mounted by the React metabox app.
804 window.dispatchEvent(new CustomEvent('thinkrank:toggle-seo-drawer'));
805 });
806 })();
807 JS;
808 wp_add_inline_script('thinkrank-metabox', $sidebar_js);
809 }
810
811 /**
812 * Build the data object localized into the metabox script (`thinkrankMetabox`).
813 *
814 * Extracted so the Elementor editor integration can reuse the exact same
815 * configuration. Callers that run outside the #post form (Elementor) also
816 * read `existingMetadata`/`contentPreview`, which they add on top of this.
817 *
818 * @param int $post_id Post being edited.
819 * @return array Localized config consumed by the React metabox.
820 */
821 public function get_localized_data(int $post_id): array {
822 $post = get_post($post_id);
823 $post_type = $post ? $post->post_type : 'post';
824
825 // Resolve the correct REST API base for the current post type.
826 // Falls back to the post type slug for any type without a rest_base.
827 $post_type_obj = get_post_type_object($post_type);
828 $post_rest_base = ($post_type_obj && !empty($post_type_obj->rest_base))
829 ? $post_type_obj->rest_base
830 : $post_type;
831
832 return [
833 'ajaxUrl' => admin_url('admin-ajax.php'),
834 'nonce' => wp_create_nonce('thinkrank_metabox_ajax'),
835 'postId' => $post_id,
836 'postType' => $post_type,
837 'postRestBase' => $post_rest_base,
838 'postPermalink' => get_permalink($post_id),
839 'postSlug' => $post ? $post->post_name : '',
840 'restUrl' => rest_url('thinkrank/v1/'),
841 'restNonce' => wp_create_nonce('wp_rest'),
842 'homeUrl' => home_url(),
843 'siteName' => get_bloginfo('name'),
844 'faviconUrl' => $this->get_site_favicon_url(),
845 'featuredImageUrl' => $this->get_post_featured_image_url($post_id),
846 'strings' => [
847 'generating' => __('Generating...', 'thinkrank'),
848 'analyzing' => __('Analyzing...', 'thinkrank'),
849 'error' => __('Error occurred', 'thinkrank'),
850 'success' => __('Success!', 'thinkrank'),
851 'generated' => __('Metadata generated successfully', 'thinkrank'),
852 'contentTooShort' => __('Please add some content before generating SEO metadata.', 'thinkrank'),
853 'apiError' => __('Failed to connect to AI service. Please check your API settings.', 'thinkrank'),
854 ],
855 'seoScore' => $this->get_persisted_seo_score($post_id),
856 'postModified' => $post ? get_the_modified_date('c', $post) : '',
857 'linkSuggestionsEnabled' => $this->is_link_suggestions_enabled($post_type),
858 'postStatus' => get_post_status($post_id),
859 'isPro' => Plan_Config::is_pro(),
860 // Whether any AI provider API key is configured — gates the
861 // "Generate with AI" button in the metabox
862 'aiConfigured' => !empty($this->settings->get('openai_api_key', ''))
863 || !empty($this->settings->get('claude_api_key', ''))
864 || !empty($this->settings->get('gemini_api_key', ''))
865 || !empty($this->settings->get('openrouter_api_key', '')),
866 // Focus keywords plan limits (max_keywords; 0 = unlimited).
867 'focusKeywords' => Plan_Config::focus_keywords(),
868 // Resolved Global/Bulk SEO variable-tag patterns for this post, shown
869 // as placeholder previews when a field is empty (the frontend applies
870 // these same patterns on output). Typing a value overrides them.
871 'patternPreviews' => Pattern_Resolver::previews($post_id),
872 // Token => value map (keys without %), for live client-side preview of
873 // a custom pattern typed into a metabox field.
874 'patternVariables' => Pattern_Resolver::variables($post_id),
875 ];
876 }
877
878 /**
879 * Latest persisted SEO score for a post.
880 *
881 * Read from the scores table — the same source the posts list column and the
882 * Analysis panel use — so the editor badge agrees with them on load rather
883 * than showing 0 until the Analysis panel mounts and fetches the score.
884 *
885 * The `thinkrank_seo_score` form field is unusable for this: it is only
886 * written by the AI "Analyze Content" flow and is reset to 0 on every save.
887 *
888 * @param int $post_id Post ID
889 * @return int|null Score, or null when the post has never been analyzed.
890 */
891 private function get_persisted_seo_score(int $post_id): ?int {
892 $existing = $this->seo_calculator->get_existing_score_data($post_id);
893 $score = $existing['overall_score'] ?? null;
894
895 return $score !== null ? (int) $score : null;
896 }
897
898 /**
899 * Check if link suggestions are enabled for a post type
900 *
901 * @param string $post_type Post type to check
902 * @return bool True if enabled, false otherwise
903 */
904 private function is_link_suggestions_enabled(string $post_type): bool {
905 $settings = get_option('thinkrank_global_seo_settings', []);
906
907 if (isset($settings[$post_type]['link_suggestions'])) {
908 return (bool) $settings[$post_type]['link_suggestions'];
909 }
910
911 return true;
912 }
913
914 /**
915 * Get current post type in admin context
916 *
917 * Handles both classic editor and block editor contexts
918 *
919 * @return string|null Current post type or null if not found
920 */
921 private function get_current_post_type(): ?string {
922 global $post, $typenow, $current_screen;
923
924 // Try to get post type from various sources
925 if ($post && !empty($post->post_type)) {
926 return $post->post_type;
927 }
928
929 if (!empty($typenow)) {
930 return $typenow;
931 }
932
933 if ($current_screen && !empty($current_screen->post_type)) {
934 return $current_screen->post_type;
935 }
936
937 // Fallback: check URL parameters for block editor
938 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameters for context determination, not processing form data
939 if (isset($_GET['post_type'])) {
940 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameters for context determination, not processing form data
941 return sanitize_text_field(wp_unslash($_GET['post_type']));
942 }
943
944 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameters for context determination, not processing form data
945 if (isset($_GET['post'])) {
946 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameters for context determination, not processing form data
947 $post_id = absint($_GET['post']);
948 $post_type = get_post_type($post_id);
949 if ($post_type) {
950 return $post_type;
951 }
952 }
953
954 return null;
955 }
956
957 /**
958 * Get supported post types
959 *
960 * @return array Supported post types
961 */
962 public function get_supported_post_types(): array {
963 $default_types = ['post', 'page'];
964
965 // Add WooCommerce product if available
966 if (class_exists('WooCommerce')) {
967 $default_types[] = 'product';
968 }
969
970 // Add other common e-commerce post types
971 $ecommerce_types = ['product', 'shop_order', 'shop_coupon'];
972 foreach ($ecommerce_types as $type) {
973 if (post_type_exists($type) && !in_array($type, $default_types)) {
974 $default_types[] = $type;
975 }
976 }
977
978 // Add custom post types that are public and have UI
979 $custom_post_types = get_post_types([
980 'public' => true,
981 'show_ui' => true,
982 '_builtin' => false,
983 ]);
984
985 foreach ($custom_post_types as $post_type) {
986 // Skip certain post types that shouldn't have SEO metabox
987 $excluded_types = [
988 'attachment',
989 'revision',
990 'nav_menu_item',
991 'custom_css',
992 'customize_changeset',
993 'oembed_cache',
994 'user_request',
995 'wp_block',
996 'wp_template',
997 'wp_template_part',
998 'wp_global_styles',
999 'wp_navigation',
1000 'acf-field',
1001 'acf-field-group',
1002 ];
1003
1004 if (!in_array($post_type, $excluded_types) && !in_array($post_type, $default_types)) {
1005 $default_types[] = $post_type;
1006 }
1007 }
1008
1009 return apply_filters('thinkrank_supported_post_types', $default_types);
1010 }
1011
1012 /**
1013 * Get existing post metadata
1014 *
1015 * @param int $post_id Post ID
1016 * @return array Existing metadata
1017 */
1018 public function get_post_metadata(int $post_id): array {
1019 return [
1020 'title' => get_post_meta($post_id, '_thinkrank_seo_title', true),
1021 'description' => get_post_meta($post_id, '_thinkrank_meta_description', true),
1022 'focus_keyword' => Focus_Keywords::get_primary($post_id),
1023 'focus_keywords' => Focus_Keywords::get($post_id),
1024 'seo_score' => get_post_meta($post_id, '_thinkrank_seo_score', true),
1025 'generated_at' => get_post_meta($post_id, '_thinkrank_generated_at', true),
1026 'pillar_content' => get_post_meta($post_id, '_thinkrank_pillar_content', true),
1027 'canonical_url' => get_post_meta($post_id, '_thinkrank_canonical_url', true),
1028 'robots_meta_enabled' => get_post_meta($post_id, '_thinkrank_robots_meta_enabled', true),
1029 'robots_meta' => get_post_meta($post_id, '_thinkrank_robots_meta', true),
1030 'advanced_robots_meta' => get_post_meta($post_id, '_thinkrank_advanced_robots_meta', true),
1031 'og_title' => get_post_meta($post_id, '_thinkrank_og_title', true),
1032 'og_description' => get_post_meta($post_id, '_thinkrank_og_description', true),
1033 'og_image' => get_post_meta($post_id, '_thinkrank_og_image', true),
1034 'twitter_title' => get_post_meta($post_id, '_thinkrank_twitter_title', true),
1035 'twitter_description' => get_post_meta($post_id, '_thinkrank_twitter_description', true),
1036 'twitter_image' => get_post_meta($post_id, '_thinkrank_twitter_image', true),
1037 ];
1038 }
1039
1040 /**
1041 * Get site favicon URL
1042 *
1043 * Prefers WordPress' native Site Icon (zero HTTP). Only when no Site Icon is
1044 * configured does it probe common favicon locations — and that probe is
1045 * cached (including a "no favicon" sentinel) so the editor never fires
1046 * blocking loopback HEAD requests on every load.
1047 *
1048 * @since 1.16.2 Prefer get_site_icon_url() and cache the fallback probe.
1049 * @return string Favicon URL, or '' when none can be resolved.
1050 */
1051 private function get_site_favicon_url(): string {
1052 // Try the native Site Icon first (WordPress 4.3+) — no HTTP required.
1053 $site_icon_url = get_site_icon_url();
1054 if ($site_icon_url) {
1055 return $site_icon_url;
1056 }
1057
1058 // No Site Icon configured: fall back to probing common favicon paths.
1059 // Cache the resolved value (empty string included) so the blocking
1060 // loopback probe runs at most once per ~12h per site host instead of on
1061 // every editor load.
1062 $cache_key = 'thinkrank_favicon_url_' . md5((string) wp_parse_url(home_url(), PHP_URL_HOST));
1063 $cached = get_transient($cache_key);
1064 if (false !== $cached) {
1065 return (string) $cached;
1066 }
1067
1068 $favicon_url = '';
1069
1070 $favicon_paths = [
1071 '/favicon.ico',
1072 '/favicon.png',
1073 '/apple-touch-icon.png',
1074 ];
1075
1076 foreach ($favicon_paths as $path) {
1077 $candidate = home_url($path);
1078 $response = wp_remote_head($candidate, ['timeout' => 3]);
1079 if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
1080 $favicon_url = $candidate;
1081 break;
1082 }
1083 }
1084
1085 set_transient($cache_key, $favicon_url, 12 * HOUR_IN_SECONDS);
1086
1087 return $favicon_url;
1088 }
1089
1090 /**
1091 * Get post featured image URL
1092 *
1093 * @param int $post_id Post ID
1094 * @return string|null Featured image URL or null if not available
1095 */
1096 private function get_post_featured_image_url(int $post_id): ?string {
1097 $thumbnail_id = get_post_thumbnail_id($post_id);
1098 if ($thumbnail_id) {
1099 // Use the full-size image — social share images need a large source
1100 // (the preview scales it down), not a small thumbnail.
1101 $image_url = wp_get_attachment_image_url($thumbnail_id, 'full');
1102 return $image_url ?: null;
1103 }
1104 return null;
1105 }
1106
1107 /**
1108 * Get content preview for AI analysis
1109 *
1110 * @param \WP_Post $post Post object
1111 * @return string Content preview
1112 */
1113 public function get_content_preview(\WP_Post $post): string {
1114 $content = $post->post_title . "\n\n";
1115
1116 if (!empty($post->post_excerpt)) {
1117 $content .= $post->post_excerpt . "\n\n";
1118 }
1119
1120 // Resolve through Builder_Content: a page builder keeps its words
1121 // outside post_content (Oxygen empties it entirely), and the editor
1122 // cannot reach postmeta, so without this the preview handed to the
1123 // browser is just the title and the live panel reports "No content".
1124 if (!class_exists('\\ThinkRank\\SEO\\Builder_Content')) {
1125 require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-builder-content.php';
1126 }
1127 $content .= \ThinkRank\SEO\Builder_Content::resolve($post);
1128
1129 // Clean and limit content
1130 $content = wp_strip_all_tags($content);
1131 $content = preg_replace('/\s+/', ' ', $content);
1132
1133 return trim(substr($content, 0, 4000));
1134 }
1135
1136 /**
1137 * AJAX handler for generating post metadata
1138 *
1139 * @return void
1140 */
1141 public function ajax_generate_post_metadata(): void {
1142 // Verify nonce
1143 $nonce = sanitize_text_field(wp_unslash($_POST['nonce'] ?? ''));
1144 if (!wp_verify_nonce($nonce, 'thinkrank_metabox_ajax')) {
1145 wp_die('Security check failed');
1146 }
1147
1148 // Check permissions
1149 $post_id = absint($_POST['post_id'] ?? 0);
1150 if (!current_user_can('edit_post', $post_id)) {
1151 wp_die('Insufficient permissions');
1152 }
1153
1154 try {
1155 $options = [
1156 'target_keyword' => sanitize_text_field(wp_unslash($_POST['target_keyword'] ?? '')),
1157 'content_type' => sanitize_text_field(wp_unslash($_POST['content_type'] ?? 'blog_post')),
1158 'tone' => sanitize_text_field(wp_unslash($_POST['tone'] ?? 'professional')),
1159 ];
1160
1161 $metadata = $this->metadata_generator->generate_for_post($post_id, $options);
1162
1163 wp_send_json_success([
1164 'metadata' => $metadata,
1165 'message' => __('SEO metadata generated successfully!', 'thinkrank'),
1166 ]);
1167 } catch (\Exception $e) {
1168 wp_send_json_error([
1169 'message' => $e->getMessage(),
1170 ]);
1171 }
1172 }
1173
1174 /**
1175 * AJAX: persist the full set of metabox fields for a post.
1176 *
1177 * Used by editors that don't submit the #post form (Elementor). Expects the
1178 * same field names the classic/block metabox submits, sent as POST params.
1179 * $_POST is slashed by WordPress, matching what `persist_metadata()` expects.
1180 *
1181 * @return void
1182 */
1183 public function ajax_save_metabox(): void {
1184 $nonce = sanitize_text_field(wp_unslash($_POST['nonce'] ?? ''));
1185 if (!wp_verify_nonce($nonce, 'thinkrank_metabox_ajax')) {
1186 wp_send_json_error(['message' => __('Security check failed', 'thinkrank')], 403);
1187 }
1188
1189 $post_id = absint($_POST['post_id'] ?? 0);
1190 if (!$post_id || !current_user_can('edit_post', $post_id)) {
1191 wp_send_json_error(['message' => __('Insufficient permissions', 'thinkrank')], 403);
1192 }
1193
1194 // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- nonce verified above; each field sanitized inside persist_metadata()
1195 $this->persist_metadata($post_id, wp_unslash($_POST));
1196
1197 wp_send_json_success([
1198 'message' => __('SEO settings saved successfully!', 'thinkrank'),
1199 ]);
1200 }
1201 }
1202