PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 1.29.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v1.29.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 / seo / class-social-meta-manager.php

class-social-meta-manager.php in ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO 1.29.0, at includes/seo/class-social-meta-manager.php

2,651 lines 103.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Social Meta Manager Class
4 *
5 * Universal social media meta tag generation and optimization for all platforms.
6 * Implements 2025 social media SEO best practices with real Open Graph and Twitter Card
7 * specifications, social image optimization, and platform-specific handling.
8 *
9 * @package ThinkRank
10 * @subpackage SEO
11 * @since 1.0.0
12 */
13
14 declare(strict_types=1);
15
16 namespace ThinkRank\SEO;
17
18 // Prevent direct access
19 if (!defined('ABSPATH')) {
20 exit;
21 }
22
23 /**
24 * Social Meta Manager Class
25 *
26 * Generates and validates social media meta tags for all supported platforms.
27 * Provides context-aware social meta generation with image optimization and
28 * platform-specific meta tag handling.
29 *
30 * @since 1.0.0
31 */
32 class Social_Meta_Manager extends Abstract_SEO_Manager {
33
34 /**
35 * Supported social media platforms with their specifications
36 *
37 * @since 1.0.0
38 * @var array
39 */
40 private array $supported_platforms = [
41 'facebook' => [
42 'og_required' => ['og:title', 'og:type', 'og:image', 'og:url'],
43 'og_recommended' => ['og:description', 'og:site_name', 'og:locale'],
44 'og_optional' => ['og:updated_time', 'og:see_also', 'og:video', 'og:audio'],
45 'image_min_width' => 600,
46 'image_min_height' => 315,
47 'image_recommended_ratio' => 1.91,
48 'title_max_length' => 60,
49 'description_max_length' => 160
50 ],
51 'twitter' => [
52 'card_types' => ['summary', 'summary_large_image', 'app', 'player'],
53 'required' => ['twitter:card', 'twitter:title'],
54 'recommended' => ['twitter:description', 'twitter:image', 'twitter:site'],
55 'optional' => ['twitter:creator', 'twitter:player', 'twitter:app:name'],
56 'image_min_width' => 300,
57 'image_min_height' => 157,
58 'image_max_size' => 5242880, // 5MB
59 'title_max_length' => 70,
60 'description_max_length' => 200
61 ],
62 'linkedin' => [
63 'og_required' => ['og:title', 'og:type', 'og:image', 'og:url'],
64 'og_recommended' => ['og:description'],
65 'image_min_width' => 1200,
66 'image_min_height' => 627,
67 'image_recommended_ratio' => 1.91,
68 'title_max_length' => 70,
69 'description_max_length' => 160
70 ],
71 'pinterest' => [
72 'required' => ['og:title', 'og:type', 'og:image', 'og:url'],
73 'recommended' => ['og:description', 'og:site_name'],
74 'image_min_width' => 600,
75 'image_min_height' => 900,
76 'image_recommended_ratio' => 0.67, // 2:3 ratio
77 'title_max_length' => 100,
78 'description_max_length' => 500
79 ],
80 'whatsapp' => [
81 'og_required' => ['og:title', 'og:type', 'og:image', 'og:url'],
82 'og_recommended' => ['og:description'],
83 'image_min_width' => 300,
84 'image_min_height' => 200,
85 'title_max_length' => 65,
86 'description_max_length' => 160
87 ]
88 ];
89
90 /**
91 * Open Graph types with their specifications
92 *
93 * @since 1.0.0
94 * @var array
95 */
96 private array $og_types = [
97 'website' => ['og:title', 'og:type', 'og:image', 'og:url'],
98 'article' => ['og:title', 'og:type', 'og:image', 'og:url', 'article:author', 'article:published_time'],
99 'product' => ['og:title', 'og:type', 'og:image', 'og:url', 'product:price:amount', 'product:price:currency'],
100 'video' => ['og:title', 'og:type', 'og:image', 'og:url', 'og:video', 'video:duration'],
101 'music' => ['og:title', 'og:type', 'og:image', 'og:url', 'music:duration', 'music:album'],
102 'book' => ['og:title', 'og:type', 'og:image', 'og:url', 'book:author', 'book:isbn'],
103 'profile' => ['og:title', 'og:type', 'og:image', 'og:url', 'profile:first_name', 'profile:last_name']
104 ];
105
106 /**
107 * Constructor
108 *
109 * @since 1.0.0
110 */
111 public function __construct() {
112 parent::__construct('social_meta');
113 }
114
115 /**
116 * Generate Open Graph tags for content
117 *
118 * @since 1.0.0
119 *
120 * @param array $data Content data for OG generation
121 * @param string $context Context type ('site', 'post', 'page', etc.)
122 * @param string $platform Target platform ('facebook', 'linkedin', etc.)
123 * @return array Generated Open Graph tags
124 */
125 public function generate_og_tags(array $data, string $context = 'site', string $platform = 'facebook'): array {
126 $platform = strtolower($platform);
127 if (!isset($this->supported_platforms[$platform])) {
128 $platform = 'facebook'; // Default fallback
129 }
130
131 $platform_spec = $this->supported_platforms[$platform];
132 $og_tags = [];
133
134 // Determine OG type based on context
135 $og_type = $this->determine_og_type($context, $data);
136 $og_tags['og:type'] = $og_type;
137
138 // Required OG tags
139 // og:title must render the full resolved Open Graph title. The 60-char
140 // cap in optimize_title_for_platform() is an SEO-title recommendation for
141 // search results and does not apply to the og:title social tag, so use the
142 // resolved title verbatim (falling back to the site name when empty).
143 $og_tags['og:title'] = ($data['title'] ?? '') !== '' ? $data['title'] : get_bloginfo('name');
144 $og_tags['og:url'] = $data['url'] ?? $this->get_current_url();
145
146 // Image handling with optimization
147 if (!empty($data['image'])) {
148 $optimized_image = $this->optimize_image_for_platform($data['image'], $platform);
149 $og_tags['og:image'] = $optimized_image['url'];
150 // Emit og:image:secure_url for https images (parity with the basic
151 // emitter), so crawlers that prefer the secure URL get it.
152 if (!empty($optimized_image['url']) && strpos((string) $optimized_image['url'], 'https://') === 0) {
153 $og_tags['og:image:secure_url'] = $optimized_image['url'];
154 }
155 if (!empty($optimized_image['width'])) {
156 $og_tags['og:image:width'] = $optimized_image['width'];
157 }
158 if (!empty($optimized_image['height'])) {
159 $og_tags['og:image:height'] = $optimized_image['height'];
160 }
161 if (!empty($optimized_image['type'])) {
162 $og_tags['og:image:type'] = $optimized_image['type'];
163 }
164 if (!empty($optimized_image['alt'])) {
165 $og_tags['og:image:alt'] = $optimized_image['alt'];
166 }
167 } else {
168 // Fallback to site default image
169 $default_image = $this->get_default_social_image();
170 if ($default_image) {
171 $og_tags['og:image'] = $default_image;
172 }
173 }
174
175 // Recommended OG tags
176 if (!empty($data['description'])) {
177 $og_tags['og:description'] = $this->optimize_description_for_platform($data['description'], $platform);
178 }
179
180 $og_tags['og:site_name'] = $data['site_name'] ?? get_bloginfo('name');
181 $og_tags['og:locale'] = $data['locale'] ?? $this->get_og_locale();
182
183 // Context-specific OG tags
184 $og_tags = $this->add_context_specific_og_tags($og_tags, $context, $data, $og_type);
185
186 // Platform-specific optimizations
187 $og_tags = $this->apply_platform_specific_optimizations($og_tags, $platform, $data);
188
189 return $og_tags;
190 }
191
192 /**
193 * Generate Twitter Card tags for content
194 *
195 * @since 1.0.0
196 *
197 * @param array $data Content data for Twitter Card generation
198 * @param string $context Context type ('site', 'post', 'page', etc.)
199 * @return array Generated Twitter Card tags
200 */
201 public function generate_twitter_tags(array $data, string $context = 'site'): array {
202 $twitter_tags = [];
203
204 // Determine card type based on content
205 $card_type = $this->determine_twitter_card_type($data, $context);
206 $twitter_tags['twitter:card'] = $card_type;
207
208 // Required tags. Prefer a per-post Twitter-specific title, falling back
209 // to the resolved og:title/SEO title. Render it in full — the length cap
210 // in optimize_title_for_platform() is an SEO-title recommendation for
211 // search results, not a rule for the twitter:title social tag.
212 $twitter_title = ($data['twitter_title'] ?? '') !== '' ? $data['twitter_title'] : ($data['title'] ?? '');
213 $twitter_tags['twitter:title'] = $twitter_title !== '' ? $twitter_title : get_bloginfo('name');
214
215 // Recommended tags
216 if (!empty($data['description'])) {
217 $twitter_tags['twitter:description'] = $this->optimize_description_for_platform($data['description'], 'twitter');
218 }
219
220 // Image handling - prioritize Twitter-specific image
221 $twitter_image = !empty($data['twitter_image']) ? $data['twitter_image'] : $data['image'];
222 if (!empty($twitter_image)) {
223 $optimized_image = $this->optimize_image_for_platform($twitter_image, 'twitter');
224 $twitter_tags['twitter:image'] = $optimized_image['url'];
225 if (!empty($optimized_image['alt'])) {
226 $twitter_tags['twitter:image:alt'] = $optimized_image['alt'];
227 }
228 }
229
230 // Site and creator information
231 $twitter_site = $this->get_twitter_site_handle();
232 if ($twitter_site) {
233 $twitter_tags['twitter:site'] = $twitter_site;
234 }
235
236 $twitter_creator = $this->get_twitter_creator_handle();
237 if ($twitter_creator) {
238 $twitter_tags['twitter:creator'] = $twitter_creator;
239 } elseif (!empty($data['author']['twitter'])) {
240 // Fallback to author data if available
241 $twitter_tags['twitter:creator'] = $data['author']['twitter'];
242 }
243
244 // Card-specific tags
245 $twitter_tags = $this->add_twitter_card_specific_tags($twitter_tags, $card_type, $data, $context);
246
247 return $twitter_tags;
248 }
249
250 /**
251 * Optimize social image for platform requirements
252 *
253 * @since 1.0.0
254 *
255 * @param string $image_url Image URL to optimize
256 * @param string $platform Target platform
257 * @return array Optimized image data
258 */
259 public function optimize_social_image(string $image_url, string $platform): array {
260 return $this->optimize_image_for_platform($image_url, $platform);
261 }
262
263 /**
264 * Generate social media preview data
265 *
266 * @since 1.0.0
267 *
268 * @param array $data Content data
269 * @param string $platform Target platform
270 * @return array Preview data for the platform
271 */
272 public function preview_social_post(array $data, string $platform): array {
273 $preview = [
274 'platform' => $platform,
275 'valid' => false,
276 'preview_url' => '',
277 'title' => '',
278 'description' => '',
279 'image' => '',
280 'warnings' => [],
281 'suggestions' => []
282 ];
283
284 switch ($platform) {
285 case 'facebook':
286 case 'linkedin':
287 $og_tags = $this->generate_og_tags($data, 'post', $platform);
288 $preview = $this->generate_og_preview($og_tags, $platform, $preview);
289 break;
290 case 'twitter':
291 $twitter_tags = $this->generate_twitter_tags($data, 'post');
292 $preview = $this->generate_twitter_preview($twitter_tags, $preview);
293 break;
294 case 'pinterest':
295 $og_tags = $this->generate_og_tags($data, 'post', $platform);
296 $preview = $this->generate_pinterest_preview($og_tags, $preview);
297 break;
298 default:
299 $preview['warnings'][] = 'Unsupported platform for preview generation';
300 }
301
302 return $preview;
303 }
304
305 /**
306 * Validate SEO settings (implements interface)
307 *
308 * @since 1.0.0
309 *
310 * @param array $settings Settings array to validate
311 * @param string $context Optional context for focused validation
312 * @return array Validation results
313 */
314 public function validate_settings(array $settings, string $context = 'all'): array {
315 $validation = [
316 'valid' => true,
317 'errors' => [],
318 'warnings' => [],
319 'suggestions' => [],
320 'score' => 100
321 ];
322
323 // Add detailed field validation breakdown
324 $field_details = $this->get_detailed_field_validation($settings, $context);
325 $validation['field_details'] = $field_details;
326
327 // Convert field details to validation format
328 foreach ($field_details as $field) {
329 switch ($field['status']) {
330 case 'error':
331 $validation['errors'][] = $field['label'];
332 $validation['valid'] = false;
333 $validation['score'] -= 15;
334 break;
335 case 'warning':
336 $validation['warnings'][] = $field['label'];
337 $validation['score'] -= 8;
338 break;
339 case 'suggestion':
340 $validation['suggestions'][] = $field['label'];
341 $validation['score'] -= 3;
342 break;
343 }
344 }
345
346 // Ensure score doesn't go below 0
347 $validation['score'] = max(0, $validation['score']);
348
349
350 // Validate general enabled setting (Social Media tab format)
351 if (isset($settings['enabled'])) {
352 // Convert string booleans to actual booleans
353 if (is_string($settings['enabled'])) {
354 $settings['enabled'] = filter_var($settings['enabled'], FILTER_VALIDATE_BOOLEAN);
355 }
356 if (!is_bool($settings['enabled'])) {
357 $validation['errors'][] = 'enabled must be a boolean value';
358 $validation['valid'] = false;
359 }
360 }
361
362 // Validate Open Graph settings (Social Media tab format)
363 if (isset($settings['enable_open_graph'])) {
364 // Convert string booleans to actual booleans
365 if (is_string($settings['enable_open_graph'])) {
366 $settings['enable_open_graph'] = filter_var($settings['enable_open_graph'], FILTER_VALIDATE_BOOLEAN);
367 }
368 if (!is_bool($settings['enable_open_graph'])) {
369 $validation['errors'][] = 'enable_open_graph must be a boolean value';
370 $validation['valid'] = false;
371 }
372 }
373
374 // Validate Twitter Cards settings (Social Media tab format)
375 if (isset($settings['enable_twitter_cards'])) {
376 // Convert string booleans to actual booleans
377 if (is_string($settings['enable_twitter_cards'])) {
378 $settings['enable_twitter_cards'] = filter_var($settings['enable_twitter_cards'], FILTER_VALIDATE_BOOLEAN);
379 }
380 if (!is_bool($settings['enable_twitter_cards'])) {
381 $validation['errors'][] = 'enable_twitter_cards must be a boolean value';
382 $validation['valid'] = false;
383 }
384 }
385
386 // Validate Twitter settings (only when relevant)
387 if ($context === 'all' || $context === 'twitter' || $context === 'twitter-cards') {
388 // Validate Twitter username format
389 if (isset($settings['twitter_username']) && !empty($settings['twitter_username'])) {
390 $username = trim($settings['twitter_username']);
391
392 // Remove @ if present (we store without @, add @ in output)
393 $clean_username = ltrim($username, '@');
394
395 if (empty($clean_username)) {
396 $validation['errors'][] = 'twitter_username cannot be empty';
397 $validation['valid'] = false;
398 } elseif (strlen($clean_username) > 15) {
399 $validation['errors'][] = 'twitter_username must be 15 characters or less';
400 $validation['valid'] = false;
401 } elseif (!preg_match('/^[A-Za-z0-9_]+$/', $clean_username)) {
402 $validation['errors'][] = 'twitter_username can only contain letters, numbers, and underscores';
403 $validation['valid'] = false;
404 }
405
406 // Update the setting to store without @ for consistency
407 $settings['twitter_username'] = $clean_username;
408 }
409
410 // Validate Twitter creator format
411 if (isset($settings['twitter_creator']) && !empty($settings['twitter_creator'])) {
412 $creator = trim($settings['twitter_creator']);
413
414 // Remove @ if present (we store without @, add @ in output)
415 $clean_creator = ltrim($creator, '@');
416
417 if (empty($clean_creator)) {
418 $validation['errors'][] = 'twitter_creator cannot be empty';
419 $validation['valid'] = false;
420 } elseif (strlen($clean_creator) > 15) {
421 $validation['errors'][] = 'twitter_creator must be 15 characters or less';
422 $validation['valid'] = false;
423 } elseif (!preg_match('/^[A-Za-z0-9_]+$/', $clean_creator)) {
424 $validation['errors'][] = 'twitter_creator can only contain letters, numbers, and underscores';
425 $validation['valid'] = false;
426 }
427
428 // Update the setting to store without @ for consistency
429 $settings['twitter_creator'] = $clean_creator;
430 }
431
432 // Validate Twitter card type
433 if (isset($settings['twitter_card_type'])) {
434 $valid_types = ['summary', 'summary_large_image', 'app', 'player'];
435 if (!in_array($settings['twitter_card_type'], $valid_types, true)) {
436 $validation['errors'][] = 'twitter_card_type must be one of: ' . implode(', ', $valid_types);
437 $validation['valid'] = false;
438 }
439 }
440 }
441
442 // Validate OG type
443 if (isset($settings['og_type'])) {
444 $valid_types = ['website', 'article', 'book', 'profile', 'music.song', 'music.album', 'video.movie', 'video.episode'];
445 if (!in_array($settings['og_type'], $valid_types, true)) {
446 $validation['warnings'][] = 'og_type should be one of the standard Open Graph types for best compatibility';
447 }
448 }
449
450 // Validate image dimensions
451 if (isset($settings['og_image_width']) && (!is_numeric($settings['og_image_width']) || $settings['og_image_width'] < 200)) {
452 $validation['warnings'][] = 'og_image_width should be at least 200 pixels for optimal social sharing';
453 }
454
455 if (isset($settings['og_image_height']) && (!is_numeric($settings['og_image_height']) || $settings['og_image_height'] < 200)) {
456 $validation['warnings'][] = 'og_image_height should be at least 200 pixels for optimal social sharing';
457 }
458
459 // Validate description length
460 if (isset($settings['max_description_length']) && (!is_numeric($settings['max_description_length']) || $settings['max_description_length'] < 50 || $settings['max_description_length'] > 300)) {
461 $validation['warnings'][] = 'max_description_length should be between 50 and 300 characters';
462 }
463
464 // Legacy validation for backward compatibility (only when legacy fields are actually present)
465 if (isset($settings['og_enabled'])) {
466 // Convert string booleans to actual booleans
467 if (is_string($settings['og_enabled'])) {
468 $settings['og_enabled'] = filter_var($settings['og_enabled'], FILTER_VALIDATE_BOOLEAN);
469 }
470 if (!is_bool($settings['og_enabled'])) {
471 $validation['errors'][] = 'og_enabled must be a boolean value';
472 $validation['valid'] = false;
473 }
474 }
475
476 if (isset($settings['twitter_enabled'])) {
477 // Convert string booleans to actual booleans
478 if (is_string($settings['twitter_enabled'])) {
479 $settings['twitter_enabled'] = filter_var($settings['twitter_enabled'], FILTER_VALIDATE_BOOLEAN);
480 }
481 if (!is_bool($settings['twitter_enabled'])) {
482 $validation['errors'][] = 'twitter_enabled must be a boolean value';
483 $validation['valid'] = false;
484 }
485 }
486
487 // Validate Twitter card type
488 if (isset($settings['twitter_card_type'])) {
489 $valid_card_types = $this->supported_platforms['twitter']['card_types'];
490 if (!in_array($settings['twitter_card_type'], $valid_card_types, true)) {
491 $validation['errors'][] = 'Invalid Twitter card type. Must be one of: ' . implode(', ', $valid_card_types);
492 $validation['valid'] = false;
493 }
494 }
495
496 // Validate default image
497 if (isset($settings['default_image']) && !empty($settings['default_image'])) {
498 if (!filter_var($settings['default_image'], FILTER_VALIDATE_URL)) {
499 $validation['errors'][] = 'default_image must be a valid URL';
500 $validation['valid'] = false;
501 } else {
502 // Check image dimensions and format
503 $image_validation = $this->validate_social_image($settings['default_image']);
504 if (!$image_validation['valid']) {
505 $validation['warnings'] = array_merge($validation['warnings'], $image_validation['warnings']);
506 }
507 }
508 }
509
510 // Validate Twitter site handle
511 if (isset($settings['twitter_site']) && !empty($settings['twitter_site'])) {
512 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}$/', $settings['twitter_site'])) {
513 $validation['errors'][] = 'twitter_site must be a valid Twitter handle (e.g., @username)';
514 $validation['valid'] = false;
515 }
516 }
517
518 // Validate custom OG tags
519 if (isset($settings['custom_og_tags']) && !empty($settings['custom_og_tags'])) {
520 if (!is_array($settings['custom_og_tags'])) {
521 $validation['errors'][] = 'custom_og_tags must be an array';
522 $validation['valid'] = false;
523 } else {
524 foreach ($settings['custom_og_tags'] as $property => $content) {
525 if (!is_string($property) || !is_string($content)) {
526 $validation['errors'][] = 'Custom OG tags must have string property names and content';
527 $validation['valid'] = false;
528 break;
529 }
530 }
531 }
532 }
533
534 // Validate platform verification codes / IDs (Instagram, TikTok, YouTube,
535 // WhatsApp, Facebook App ID, Pinterest) against the shared format rules.
536 // Single source of truth — also enforced on the Social Platforms REST save
537 // path via self::validate_platform_field(). See get_platform_field_validation_rules().
538 foreach (self::get_platform_field_validation_rules() as $field_key => $rule) {
539 if (isset($settings[$field_key]) && $settings[$field_key] !== '') {
540 $error = self::validate_platform_field($field_key, $settings[$field_key]);
541 if ($error !== null) {
542 $validation['errors'][] = $error;
543 $validation['valid'] = false;
544 }
545 }
546 }
547
548 return $validation;
549 }
550
551 /**
552 * Format-validation rules for social platform verification codes / IDs.
553 *
554 * Single source of truth for the per-field format constraints, shared by
555 * validate_settings() and the Social Platforms REST endpoint
556 * (ThinkRank\API\Social_Platforms_Endpoint) so a value that is accepted on
557 * one path is accepted on the other. These mirror the `pattern` entries in
558 * get_settings_schema(); sanitization strips unsafe characters but does not
559 * enforce shape, so these rules back it with real validation.
560 *
561 * @since 1.14.0
562 *
563 * @return array<string, array{pattern: string, message: string}> Map of field key => rule.
564 */
565 public static function get_platform_field_validation_rules(): array {
566 return [
567 'facebook_app_id' => [
568 'pattern' => '/^[0-9]+$/',
569 'message' => 'Facebook App ID must contain digits only.',
570 ],
571 'pinterest_site_verification' => [
572 'pattern' => '/^[a-f0-9]{32}$/',
573 'message' => 'Pinterest site verification must be a 32-character hexadecimal string.',
574 ],
575 'instagram_verification' => [
576 'pattern' => '/^[a-zA-Z0-9_-]{20,}$/',
577 'message' => 'Instagram verification must be at least 20 characters (letters, numbers, underscore, dash).',
578 ],
579 'tiktok_verification' => [
580 'pattern' => '/^[a-zA-Z0-9_-]{20,}$/',
581 'message' => 'TikTok verification must be at least 20 characters (letters, numbers, underscore, dash).',
582 ],
583 'youtube_channel_id' => [
584 'pattern' => '/^UC[a-zA-Z0-9_-]{22}$/',
585 'message' => 'YouTube channel ID must start with "UC" followed by 22 characters (letters, numbers, underscore, dash).',
586 ],
587 'whatsapp_business_id' => [
588 'pattern' => '/^[0-9]{10,15}$/',
589 'message' => 'WhatsApp Business ID must be 10-15 digits.',
590 ],
591 ];
592 }
593
594 /**
595 * Validate a single social platform field value against its shared format rule.
596 *
597 * Returns null for fields with no format rule (e.g. facebook_admins) and for
598 * empty values, so callers can validate an arbitrary settings map and only
599 * act on genuine format violations.
600 *
601 * @since 1.14.0
602 *
603 * @param string $key Field key.
604 * @param mixed $value Field value.
605 * @return string|null Error message when the value violates the format, null otherwise.
606 */
607 public static function validate_platform_field(string $key, $value): ?string {
608 $rules = self::get_platform_field_validation_rules();
609
610 if (!isset($rules[$key]) || $value === '' || $value === null) {
611 return null;
612 }
613
614 if (!preg_match($rules[$key]['pattern'], (string) $value)) {
615 return $rules[$key]['message'];
616 }
617
618 return null;
619 }
620
621 /**
622 * Get detailed field validation breakdown
623 *
624 * @since 1.0.0
625 *
626 * @param array $settings Settings array to validate
627 * @param string $context Context for specific validation
628 * @return array Detailed field validation results
629 */
630 private function get_detailed_field_validation(array $settings, string $context = 'all'): array {
631 $field_details = [];
632
633 // Return tab-specific validation based on context
634 switch ($context) {
635 case 'open-graph':
636 return $this->validate_open_graph_fields($settings);
637 case 'twitter-cards':
638 return $this->validate_twitter_fields($settings);
639 default:
640 // For 'all' or unknown context, return only Social Media fields (Open Graph + Twitter)
641 $field_details = array_merge($field_details, $this->validate_open_graph_fields($settings));
642 $field_details = array_merge($field_details, $this->validate_twitter_fields($settings));
643 return $field_details;
644 }
645 }
646
647 /**
648 * Validate Open Graph fields
649 *
650 * @since 1.0.0
651 *
652 * @param array $settings Settings array to validate
653 * @return array Open Graph field validation results
654 */
655 private function validate_open_graph_fields(array $settings): array {
656 $field_details = [];
657
658 // Open Graph Enabled
659 if (!empty($settings['enable_open_graph'])) {
660 $field_details[] = [
661 'field' => 'enable_open_graph',
662 'label' => 'Open Graph is enabled for social media sharing.',
663 'status' => 'valid',
664 'icon' => ''
665 ];
666
667 // Site Name validation
668 if (!empty($settings['og_site_name'])) {
669 if (strlen($settings['og_site_name']) <= 60) {
670 $field_details[] = [
671 'field' => 'og_site_name',
672 'label' => 'Site name is properly configured for Open Graph.',
673 'status' => 'valid',
674 'icon' => ''
675 ];
676 } else {
677 $field_details[] = [
678 'field' => 'og_site_name',
679 'label' => 'Site name is longer than 60 characters, may be truncated.',
680 'status' => 'warning',
681 'icon' => ''
682 ];
683 }
684 } else {
685 $field_details[] = [
686 'field' => 'og_site_name',
687 'label' => 'Site name is required for Open Graph.',
688 'status' => 'error',
689 'icon' => ''
690 ];
691 }
692
693 // Description validation
694 if (!empty($settings['og_description'])) {
695 $length = strlen($settings['og_description']);
696 if ($length >= 120 && $length <= 160) {
697 $field_details[] = [
698 'field' => 'og_description',
699 'label' => 'Description is properly configured for social sharing.',
700 'status' => 'valid',
701 'icon' => ''
702 ];
703 } else {
704 $field_details[] = [
705 'field' => 'og_description',
706 'label' => 'Description length could be optimized (120-160 characters recommended).',
707 'status' => 'warning',
708 'icon' => ''
709 ];
710 }
711 } else {
712 $field_details[] = [
713 'field' => 'og_description',
714 'label' => 'Description is recommended for better social sharing.',
715 'status' => 'warning',
716 'icon' => ''
717 ];
718 }
719
720 // Content Type validation
721 if (!empty($settings['og_type'])) {
722 $field_details[] = [
723 'field' => 'og_type',
724 'label' => 'Content type is configured for Open Graph.',
725 'status' => 'valid',
726 'icon' => ''
727 ];
728 } else {
729 $field_details[] = [
730 'field' => 'og_type',
731 'label' => 'Content type should be specified.',
732 'status' => 'suggestion',
733 'icon' => ''
734 ];
735 }
736
737 // Default Image validation
738 if (!empty($settings['default_og_image'])) {
739 if (filter_var($settings['default_og_image'], FILTER_VALIDATE_URL)) {
740 $field_details[] = [
741 'field' => 'default_og_image',
742 'label' => 'Default Open Graph image is configured.',
743 'status' => 'valid',
744 'icon' => ''
745 ];
746 } else {
747 $field_details[] = [
748 'field' => 'default_og_image',
749 'label' => 'Default Open Graph image URL appears invalid.',
750 'status' => 'warning',
751 'icon' => ''
752 ];
753 }
754 } else {
755 $field_details[] = [
756 'field' => 'default_og_image',
757 'label' => 'Default image is recommended for social sharing.',
758 'status' => 'suggestion',
759 'icon' => ''
760 ];
761 }
762
763 } else {
764 $field_details[] = [
765 'field' => 'enable_open_graph',
766 'label' => 'Open Graph is disabled. Enable for better social media sharing.',
767 'status' => 'suggestion',
768 'icon' => ''
769 ];
770 }
771
772 return $field_details;
773 }
774
775 /**
776 * Validate Twitter fields
777 *
778 * @since 1.0.0
779 *
780 * @param array $settings Settings array to validate
781 * @return array Twitter field validation results
782 */
783 private function validate_twitter_fields(array $settings): array {
784 $field_details = [];
785
786 // Twitter Cards Enabled
787 if (!empty($settings['enable_twitter_cards'])) {
788 $field_details[] = [
789 'field' => 'enable_twitter_cards',
790 'label' => 'Twitter Cards are enabled for Twitter sharing.',
791 'status' => 'valid',
792 'icon' => ''
793 ];
794
795 // Twitter Username validation
796 if (!empty($settings['twitter_username'])) {
797 $username = trim($settings['twitter_username']);
798 $clean_username = ltrim($username, '@');
799
800 if (strlen($clean_username) <= 15 && preg_match('/^[A-Za-z0-9_]+$/', $clean_username)) {
801 $field_details[] = [
802 'field' => 'twitter_username',
803 'label' => 'Twitter username is properly formatted.',
804 'status' => 'valid',
805 'icon' => ''
806 ];
807 } else {
808 $field_details[] = [
809 'field' => 'twitter_username',
810 'label' => 'Twitter username format is invalid (max 15 chars, letters/numbers/underscore only).',
811 'status' => 'error',
812 'icon' => ''
813 ];
814 }
815 } else {
816 $field_details[] = [
817 'field' => 'twitter_username',
818 'label' => 'Twitter username recommended for better attribution.',
819 'status' => 'suggestion',
820 'icon' => ''
821 ];
822 }
823
824 // Twitter Creator validation
825 if (!empty($settings['twitter_creator'])) {
826 $creator = trim($settings['twitter_creator']);
827 $clean_creator = ltrim($creator, '@');
828
829 if (strlen($clean_creator) <= 15 && preg_match('/^[A-Za-z0-9_]+$/', $clean_creator)) {
830 $field_details[] = [
831 'field' => 'twitter_creator',
832 'label' => 'Twitter creator is properly formatted.',
833 'status' => 'valid',
834 'icon' => ''
835 ];
836 } else {
837 $field_details[] = [
838 'field' => 'twitter_creator',
839 'label' => 'Twitter creator format is invalid (max 15 chars, letters/numbers/underscore only).',
840 'status' => 'error',
841 'icon' => ''
842 ];
843 }
844 } else {
845 $field_details[] = [
846 'field' => 'twitter_creator',
847 'label' => 'Twitter creator recommended for content attribution.',
848 'status' => 'suggestion',
849 'icon' => ''
850 ];
851 }
852
853 // Card Type validation
854 $valid_card_types = ['summary', 'summary_large_image', 'app', 'player'];
855 if (!empty($settings['twitter_card_type']) && in_array($settings['twitter_card_type'], $valid_card_types, true)) {
856 $field_details[] = [
857 'field' => 'twitter_card_type',
858 'label' => 'Twitter Card type is properly configured.',
859 'status' => 'valid',
860 'icon' => ''
861 ];
862 } else {
863 $field_details[] = [
864 'field' => 'twitter_card_type',
865 'label' => 'Valid Twitter Card type is required.',
866 'status' => 'error',
867 'icon' => ''
868 ];
869 }
870
871 // Default Twitter Image validation
872 if (!empty($settings['default_twitter_image'])) {
873 if (filter_var($settings['default_twitter_image'], FILTER_VALIDATE_URL)) {
874 $field_details[] = [
875 'field' => 'default_twitter_image',
876 'label' => 'Default Twitter Card image is configured.',
877 'status' => 'valid',
878 'icon' => ''
879 ];
880 } else {
881 $field_details[] = [
882 'field' => 'default_twitter_image',
883 'label' => 'Default Twitter Card image URL appears invalid.',
884 'status' => 'warning',
885 'icon' => ''
886 ];
887 }
888 } else {
889 $field_details[] = [
890 'field' => 'default_twitter_image',
891 'label' => 'Default image recommended for Twitter sharing.',
892 'status' => 'suggestion',
893 'icon' => ''
894 ];
895 }
896
897 } else {
898 $field_details[] = [
899 'field' => 'enable_twitter_cards',
900 'label' => 'Twitter Cards are disabled. Enable for better Twitter sharing.',
901 'status' => 'suggestion',
902 'icon' => ''
903 ];
904 }
905
906 return $field_details;
907 }
908
909
910 /**
911 * Get output data for frontend rendering (implements interface)
912 *
913 * @since 1.0.0
914 *
915 * @param string $context_type The context type
916 * @param int|null $context_id Optional. Context ID
917 * @param string|null $fallback_title Optional. Effective SEO title to
918 * use when no per-post Open Graph
919 * title override is set, so
920 * rendered output mirrors the
921 * document title and the Social
922 * metabox preview.
923 * @param string|null $fallback_description Optional. Effective meta
924 * description, used as the
925 * Open Graph description fallback
926 * for the same parity reason.
927 * @return array Output data ready for frontend rendering
928 */
929 public function get_output_data(string $context_type, ?int $context_id, ?string $fallback_title = null, ?string $fallback_description = null): array {
930 // Memoize per request: the OG, Twitter and platform wp_head callbacks
931 // each call this with the same arguments, so the extraction work +
932 // Site_Identity_Manager instantiation would otherwise run three times.
933 $cache_key = $context_type . ':' . ($context_id ?? 0) . ':' . md5((string) $fallback_title . '|' . (string) $fallback_description);
934 if (isset($this->output_data_cache[$cache_key])) {
935 return $this->output_data_cache[$cache_key];
936 }
937
938 $settings = $this->get_settings($context_type, $context_id);
939 $output = [
940 'og_tags' => [],
941 'twitter_tags' => [],
942 'meta_tags' => [],
943 'platform_tags' => [],
944 // Per-feature flags so each emitter can honor its own toggle. The
945 // aggregate `enabled` (true if either is on) is kept for callers
946 // that only care whether social output ran at all.
947 'og_enabled' => false,
948 'twitter_enabled' => false,
949 'enabled' => false,
950 ];
951
952 // Check if individual social features are enabled
953 $og_enabled = !empty($settings['enable_open_graph'] ?? $settings['og_enabled'] ?? false);
954 $twitter_enabled = !empty($settings['enable_twitter_cards'] ?? $settings['twitter_enabled'] ?? false);
955 $output['og_enabled'] = $og_enabled;
956 $output['twitter_enabled'] = $twitter_enabled;
957
958 if (!$og_enabled && !$twitter_enabled) {
959 $this->output_data_cache[$cache_key] = $output;
960 return $output;
961 }
962
963 $output['enabled'] = true;
964
965 // Extract content data
966 $content_data = $this->extract_social_content_data($context_type, $context_id, $settings, $fallback_title, $fallback_description);
967
968 // Generate Open Graph tags if enabled
969 if ($og_enabled) {
970 $output['og_tags'] = $this->generate_og_tags($content_data, $context_type);
971
972 // Add custom OG tags
973 if (!empty($settings['custom_og_tags'])) {
974 $output['og_tags'] = array_merge($output['og_tags'], $settings['custom_og_tags']);
975 }
976 }
977
978 // Generate Twitter Card tags if enabled
979 if ($twitter_enabled) {
980 $output['twitter_tags'] = $this->generate_twitter_tags($content_data, $context_type);
981 }
982
983 // Generate platform-specific meta tags
984 $output['platform_tags'] = $this->generate_platform_meta_tags($settings);
985
986 // Convert to meta tag format for HTML output
987 $output['meta_tags'] = $this->convert_to_meta_tags($output['og_tags'], $output['twitter_tags'], $output['platform_tags']);
988
989 $this->output_data_cache[$cache_key] = $output;
990 return $output;
991 }
992
993 /**
994 * Request-scoped memoization of get_output_data() keyed by context + title/desc.
995 *
996 * @var array<string, array>
997 */
998 private array $output_data_cache = [];
999
1000 /**
1001 * Site-wide default image keys inherited by every other context.
1002 *
1003 * @since 1.24.1
1004 * @var string[]
1005 */
1006 private const INHERITED_SITE_KEYS = [
1007 'default_og_image',
1008 'default_twitter_image',
1009 'default_image',
1010 ];
1011
1012 /**
1013 * Get settings for a context, inheriting the site-wide default images
1014 *
1015 * Two corrections over the generic lookup:
1016 *
1017 * 1. Site-wide settings are always stored with context_id 0, but the
1018 * frontend maps a homepage request to the `site` context while still
1019 * passing the queried object ID (non-zero on a static front page). That
1020 * looked up `site`/<page ID>, matched no row and silently fell back to
1021 * the schema defaults, so a configured default OG image never rendered
1022 * on a static front page. Normalize the ID away for `site`.
1023 * 2. `default_og_image` / `default_twitter_image` only exist in the site
1024 * context, so post/page and archive contexts had nothing to fall back to
1025 * when a post had no featured image — og:image dropped to the site logo
1026 * or vanished entirely. Inherit those keys when the context has no value
1027 * of its own.
1028 *
1029 * @since 1.24.1
1030 *
1031 * @param string $context_type The context type
1032 * @param int|null $context_id Optional. Context ID
1033 * @return array Settings with site-wide image defaults applied
1034 */
1035 public function get_settings(string $context_type, ?int $context_id = null): array {
1036 if ($context_type === 'site') {
1037 $context_id = null;
1038 }
1039
1040 $settings = parent::get_settings($context_type, $context_id);
1041
1042 if ($context_type === 'site') {
1043 return $settings;
1044 }
1045
1046 $site_settings = parent::get_settings('site', null);
1047 foreach (self::INHERITED_SITE_KEYS as $key) {
1048 if (empty($settings[$key]) && !empty($site_settings[$key])) {
1049 $settings[$key] = $site_settings[$key];
1050 }
1051 }
1052
1053 return $settings;
1054 }
1055
1056 /**
1057 * Get default settings for a context type (implements interface)
1058 *
1059 * @since 1.0.0
1060 *
1061 * @param string $context_type The context type to get defaults for
1062 * @return array Default settings array
1063 */
1064 public function get_default_settings(string $context_type): array {
1065 // Get WordPress site defaults
1066 $site_name = get_bloginfo('name');
1067 $site_description = get_bloginfo('description');
1068
1069 $defaults = [
1070 // Open Graph settings
1071 'enable_open_graph' => true,
1072 'og_site_name' => $site_name,
1073 'og_description' => $site_description,
1074 'og_type' => 'website',
1075 'og_locale' => 'en_US',
1076 'default_og_image' => '',
1077 'og_image_width' => 1200,
1078 'og_image_height' => 630,
1079
1080 // Twitter Cards settings
1081 'enable_twitter_cards' => true,
1082 'twitter_username' => '',
1083 'twitter_creator' => '',
1084 'twitter_card_type' => 'summary_large_image',
1085 'default_twitter_image' => '',
1086
1087 // Facebook settings
1088 'facebook_app_id' => '',
1089 'facebook_admins' => '',
1090
1091 // LinkedIn settings
1092 'enable_linkedin' => false,
1093
1094 // Pinterest settings
1095 'enable_pinterest' => false,
1096 'pinterest_site_verification' => '',
1097
1098 // Instagram settings
1099 'enable_instagram' => false,
1100 'instagram_verification' => '',
1101
1102 // TikTok settings
1103 'enable_tiktok' => false,
1104 'tiktok_verification' => '',
1105
1106 // YouTube settings
1107 'enable_youtube' => false,
1108 'youtube_channel_id' => '',
1109
1110 // WhatsApp Business settings
1111 'enable_whatsapp' => false,
1112 'whatsapp_business_id' => '',
1113
1114 // Advanced settings
1115 'auto_generate_descriptions' => true,
1116 'fallback_to_excerpt' => true,
1117 'strip_html_tags' => true,
1118 'max_description_length' => 160,
1119
1120 // Legacy format for backward compatibility (only when needed)
1121 'custom_og_tags' => [],
1122 'image_optimization' => true,
1123 'auto_generate' => true
1124 ];
1125
1126 // Context-specific defaults
1127 switch ($context_type) {
1128 case 'site':
1129 $defaults['og_type'] = 'website';
1130 break;
1131 case 'post':
1132 $defaults['og_type'] = 'article';
1133 break;
1134 case 'page':
1135 $defaults['og_type'] = 'website';
1136 break;
1137 case 'product':
1138 $defaults['og_type'] = 'product';
1139 break;
1140 }
1141
1142 return $defaults;
1143 }
1144
1145 /**
1146 * Get settings schema definition (implements interface)
1147 *
1148 * @since 1.0.0
1149 *
1150 * @param string $context_type The context type to get schema for
1151 * @return array Settings schema definition
1152 */
1153 public function get_settings_schema(string $context_type): array {
1154 return [
1155 'enable_open_graph' => [
1156 'type' => 'boolean',
1157 'title' => 'Enable Open Graph',
1158 'description' => 'Generate Open Graph meta tags for social media sharing',
1159 'default' => true
1160 ],
1161 'og_site_name' => [
1162 'type' => 'string',
1163 'title' => 'Site Name',
1164 'description' => 'The name of your website for Open Graph',
1165 'maxLength' => 60,
1166 'default' => get_bloginfo('name')
1167 ],
1168 'og_description' => [
1169 'type' => 'string',
1170 'title' => 'Site Description',
1171 'description' => 'Default description for Open Graph tags',
1172 'maxLength' => 160,
1173 'default' => get_bloginfo('description')
1174 ],
1175 'og_locale' => [
1176 'type' => 'string',
1177 'title' => 'Locale',
1178 'description' => 'The locale for Open Graph tags',
1179 'default' => 'en_US'
1180 ],
1181 'default_og_image' => [
1182 'type' => 'string',
1183 'title' => 'Default Open Graph Image',
1184 'description' => 'Default image URL for Open Graph tags',
1185 'format' => 'uri',
1186 'default' => ''
1187 ],
1188 'og_image_width' => [
1189 'type' => 'integer',
1190 'title' => 'Image Width',
1191 'description' => 'Default width for Open Graph images',
1192 'minimum' => 200,
1193 'default' => 1200
1194 ],
1195 'og_image_height' => [
1196 'type' => 'integer',
1197 'title' => 'Image Height',
1198 'description' => 'Default height for Open Graph images',
1199 'minimum' => 200,
1200 'default' => 630
1201 ],
1202 'enable_twitter_cards' => [
1203 'type' => 'boolean',
1204 'title' => 'Enable Twitter Cards',
1205 'description' => 'Generate Twitter Card meta tags for Twitter sharing',
1206 'default' => true
1207 ],
1208 'twitter_username' => [
1209 'type' => 'string',
1210 'title' => 'Twitter Username',
1211 'description' => 'Twitter username for the site (without @, e.g., username)',
1212 'pattern' => '^[a-zA-Z0-9_]{1,15}$',
1213 'default' => ''
1214 ],
1215 'twitter_creator' => [
1216 'type' => 'string',
1217 'title' => 'Twitter Creator',
1218 'description' => 'Content creator Twitter username (without @, e.g., creator_username)',
1219 'pattern' => '^[a-zA-Z0-9_]{1,15}$',
1220 'default' => ''
1221 ],
1222 'twitter_card_type' => [
1223 'type' => 'string',
1224 'title' => 'Twitter Card Type',
1225 'description' => 'The type of Twitter Card to generate',
1226 'enum' => $this->supported_platforms['twitter']['card_types'],
1227 'default' => 'summary_large_image'
1228 ],
1229 'og_type' => [
1230 'type' => 'string',
1231 'title' => 'Open Graph Type',
1232 'description' => 'The Open Graph type for this content',
1233 'enum' => array_keys($this->og_types),
1234 'default' => $this->get_default_settings($context_type)['og_type']
1235 ],
1236 'default_image' => [
1237 'type' => 'string',
1238 'title' => 'Default Social Image',
1239 'description' => 'Default image URL for social media sharing',
1240 'format' => 'uri',
1241 'default' => ''
1242 ],
1243 'twitter_site' => [
1244 'type' => 'string',
1245 'title' => 'Twitter Site Handle',
1246 'description' => 'Twitter handle for the site (e.g., @username)',
1247 'pattern' => '^@[a-zA-Z0-9_]{1,15}$',
1248 'default' => ''
1249 ],
1250 'default_twitter_image' => [
1251 'type' => 'string',
1252 'title' => 'Default Twitter Image',
1253 'description' => 'Default image URL for Twitter Cards',
1254 'format' => 'uri',
1255 'default' => ''
1256 ],
1257 'facebook_app_id' => [
1258 'type' => 'string',
1259 'title' => 'Facebook App ID',
1260 'description' => 'Facebook App ID for analytics and insights',
1261 'pattern' => '^[0-9]+$',
1262 'default' => ''
1263 ],
1264 'facebook_admins' => [
1265 'type' => 'string',
1266 'title' => 'Facebook Admins',
1267 'description' => 'Comma-separated list of Facebook admin user IDs',
1268 'default' => ''
1269 ],
1270 'enable_linkedin' => [
1271 'type' => 'boolean',
1272 'title' => 'Enable LinkedIn',
1273 'description' => 'Enable LinkedIn-specific optimizations',
1274 'default' => false
1275 ],
1276 'enable_pinterest' => [
1277 'type' => 'boolean',
1278 'title' => 'Enable Pinterest',
1279 'description' => 'Enable Pinterest-specific optimizations',
1280 'default' => false
1281 ],
1282 'pinterest_site_verification' => [
1283 'type' => 'string',
1284 'title' => 'Pinterest Site Verification',
1285 'description' => 'Pinterest site verification meta tag content',
1286 'pattern' => '^[a-f0-9]{32}$',
1287 'default' => ''
1288 ],
1289 'enable_instagram' => [
1290 'type' => 'boolean',
1291 'title' => 'Enable Instagram',
1292 'description' => 'Enable Instagram-specific optimizations',
1293 'default' => false
1294 ],
1295 'instagram_verification' => [
1296 'type' => 'string',
1297 'title' => 'Instagram Site Verification',
1298 'description' => 'Instagram Business account verification code',
1299 'pattern' => '^[a-zA-Z0-9_-]{20,}$',
1300 'default' => ''
1301 ],
1302 'enable_tiktok' => [
1303 'type' => 'boolean',
1304 'title' => 'Enable TikTok',
1305 'description' => 'Enable TikTok-specific optimizations',
1306 'default' => false
1307 ],
1308 'tiktok_verification' => [
1309 'type' => 'string',
1310 'title' => 'TikTok Site Verification',
1311 'description' => 'TikTok for Business verification code',
1312 'pattern' => '^[a-zA-Z0-9_-]{20,}$',
1313 'default' => ''
1314 ],
1315 'enable_youtube' => [
1316 'type' => 'boolean',
1317 'title' => 'Enable YouTube',
1318 'description' => 'Enable YouTube-specific optimizations',
1319 'default' => false
1320 ],
1321 'youtube_channel_id' => [
1322 'type' => 'string',
1323 'title' => 'YouTube Channel ID',
1324 'description' => 'YouTube channel ID for content attribution',
1325 'pattern' => '^UC[a-zA-Z0-9_-]{22}$',
1326 'default' => ''
1327 ],
1328 'enable_whatsapp' => [
1329 'type' => 'boolean',
1330 'title' => 'Enable WhatsApp Business',
1331 'description' => 'Enable WhatsApp Business optimizations',
1332 'default' => false
1333 ],
1334 'whatsapp_business_id' => [
1335 'type' => 'string',
1336 'title' => 'WhatsApp Business ID',
1337 'description' => 'WhatsApp Business account ID',
1338 'pattern' => '^[0-9]{10,15}$',
1339 'default' => ''
1340 ],
1341 'auto_generate_descriptions' => [
1342 'type' => 'boolean',
1343 'title' => 'Auto-generate Descriptions',
1344 'description' => 'Automatically generate descriptions from content',
1345 'default' => true
1346 ],
1347 'fallback_to_excerpt' => [
1348 'type' => 'boolean',
1349 'title' => 'Fallback to Excerpt',
1350 'description' => 'Use post excerpt as fallback for descriptions',
1351 'default' => true
1352 ],
1353 'strip_html_tags' => [
1354 'type' => 'boolean',
1355 'title' => 'Strip HTML Tags',
1356 'description' => 'Remove HTML tags from generated descriptions',
1357 'default' => true
1358 ],
1359 'max_description_length' => [
1360 'type' => 'integer',
1361 'title' => 'Max Description Length',
1362 'description' => 'Maximum length for generated descriptions',
1363 'minimum' => 50,
1364 'maximum' => 300,
1365 'default' => 160
1366 ],
1367 'custom_og_tags' => [
1368 'type' => 'object',
1369 'title' => 'Custom Open Graph Tags',
1370 'description' => 'Additional custom Open Graph meta tags',
1371 'default' => []
1372 ],
1373 'image_optimization' => [
1374 'type' => 'boolean',
1375 'title' => 'Enable Image Optimization',
1376 'description' => 'Optimize images for social media platforms',
1377 'default' => true
1378 ],
1379 'auto_generate' => [
1380 'type' => 'boolean',
1381 'title' => 'Auto-generate Tags',
1382 'description' => 'Automatically generate social meta tags from content',
1383 'default' => true
1384 ]
1385 ];
1386 }
1387
1388 /**
1389 * Extract content data for social meta generation
1390 *
1391 * @since 1.0.0
1392 *
1393 * @param string $context_type The context type
1394 * @param int|null $context_id Optional. Context ID
1395 * @param array $settings Social meta settings
1396 * @return array Extracted content data
1397 */
1398 private function extract_social_content_data(string $context_type, ?int $context_id, array $settings, ?string $fallback_title = null, ?string $fallback_description = null): array {
1399 $data = [
1400 'title' => '',
1401 'description' => '',
1402 'url' => '',
1403 'image' => '',
1404 'twitter_title' => '', // Separate field for a Twitter-specific title
1405 'twitter_image' => '', // Separate field for Twitter-specific images
1406 'type' => 'website',
1407 'author' => [],
1408 'published_time' => '',
1409 'modified_time' => '',
1410 'site_name' => $settings['og_site_name'] ?? get_bloginfo('name')
1411 ];
1412
1413 if ($context_type === 'site') {
1414 // Site-wide data with Social Media tab settings priority.
1415 //
1416 // og:title priority: an explicitly-configured OG Site Name wins;
1417 // otherwise mirror the effective SEO <title> (what search shows),
1418 // then the blogname. og_site_name is always present because it is
1419 // merged from a default equal to the blogname, so a value matching
1420 // the blogname is treated as "not explicitly overridden" and we fall
1421 // through to the passed effective SEO title. (og:site_name itself is
1422 // set separately from og_site_name and is unaffected.)
1423 $blogname = get_bloginfo('name');
1424 $og_site_name = $settings['og_site_name'] ?? '';
1425 if ($og_site_name !== '' && $og_site_name !== $blogname) {
1426 $data['title'] = $og_site_name;
1427 } elseif ($fallback_title !== null && $fallback_title !== '') {
1428 $data['title'] = $fallback_title;
1429 } else {
1430 $data['title'] = $blogname;
1431 }
1432 $data['description'] = $settings['og_description'] ?? get_bloginfo('description');
1433 // Use home_url('/') so og:url matches the homepage canonical
1434 // (class-seo-manager.php) and the WebSite schema, which both include
1435 // the trailing slash. A bare home_url() would key a different URL in
1436 // social caches than the canonical.
1437 $data['url'] = home_url('/');
1438 $data['type'] = $settings['og_type'] ?? 'website';
1439 $data['locale'] = $settings['og_locale'] ?? null;
1440
1441 // Set Open Graph image with proper fallback
1442 $data['image'] = $this->get_og_image_for_context($settings, null);
1443
1444 // Set Twitter image with proper fallback
1445 $data['twitter_image'] = $this->get_twitter_image_for_context($settings, null);
1446 } elseif ($context_id && in_array($context_type, ['post', 'page', 'product'], true)) {
1447 // Post-specific data
1448 $post = get_post($context_id);
1449 if ($post) {
1450 // Per-post Open Graph overrides from the metabox Social tab take
1451 // precedence over the derived title/description/image. These read
1452 // the same meta keys the metabox save handler and the import
1453 // migrator write to, so manual edits and migrated data flow
1454 // through one path. Title/description may hold variable tags
1455 // (e.g. %title%), resolved here to match output_basic_og_tags().
1456 $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1457 (string) get_post_meta($post->ID, '_thinkrank_og_title', true),
1458 $post->ID
1459 );
1460 $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1461 (string) get_post_meta($post->ID, '_thinkrank_og_description', true),
1462 $post->ID
1463 );
1464 $og_image_override = get_post_meta($post->ID, '_thinkrank_og_image', true);
1465
1466 // Per-post Twitter-specific title override (metabox Social tab).
1467 // Twitter Cards fall back to the og:title when this is empty, so
1468 // only capture it here; the fallback is applied in
1469 // generate_twitter_tags().
1470 $data['twitter_title'] = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1471 (string) get_post_meta($post->ID, '_thinkrank_twitter_title', true),
1472 $post->ID
1473 );
1474
1475 // Title priority: per-post OG override > effective SEO title
1476 // (document <title> / metabox preview) > post title.
1477 if ($og_title_override !== '') {
1478 $data['title'] = $og_title_override;
1479 } elseif ($fallback_title !== null && $fallback_title !== '') {
1480 $data['title'] = $fallback_title;
1481 } else {
1482 $data['title'] = get_the_title($post);
1483 }
1484 // Description priority: per-post OG override > effective meta
1485 // description (meta tag / metabox preview) > derived excerpt.
1486 if ($og_description_override !== '') {
1487 $data['description'] = $og_description_override;
1488 } elseif ($fallback_description !== null && $fallback_description !== '') {
1489 $data['description'] = $fallback_description;
1490 } else {
1491 $data['description'] = $this->get_social_description($post);
1492 }
1493 $data['url'] = get_permalink($post);
1494 $data['type'] = $settings['og_type'] ?? $this->determine_og_type($context_type, []);
1495 $data['published_time'] = get_the_date('c', $post);
1496 $data['modified_time'] = get_the_modified_date('c', $post);
1497 $data['post_id'] = $post->ID;
1498
1499 // Author data
1500 $author_id = $post->post_author;
1501 $data['author'] = [
1502 'name' => get_the_author_meta('display_name', $author_id),
1503 'url' => get_author_posts_url($author_id),
1504 'twitter' => get_the_author_meta('twitter', $author_id)
1505 ];
1506
1507 // Set Open Graph image: per-post override first, then the
1508 // featured-image/default fallback chain.
1509 $data['image'] = $og_image_override !== ''
1510 ? $og_image_override
1511 : $this->get_og_image_for_context($settings, $post);
1512
1513 // Set Twitter image with proper fallback
1514 $data['twitter_image'] = $this->get_twitter_image_for_context($settings, $post);
1515 }
1516 } else {
1517 // Archive-style contexts (category, tag, author, search, date).
1518 // They carry no object of their own, but the site-wide default
1519 // image still applies — without this they fell through to the raw
1520 // logo/site-icon fallback in generate_og_tags() and ignored a
1521 // configured default OG image.
1522 $data['image'] = $this->get_og_image_for_context($settings, null);
1523 $data['twitter_image'] = $this->get_twitter_image_for_context($settings, null);
1524 }
1525
1526 return $data;
1527 }
1528
1529 /**
1530 * Get Open Graph image for context with proper fallback
1531 *
1532 * @since 1.0.0
1533 *
1534 * @param array $settings Social meta settings
1535 * @param \WP_Post|null $post Optional. Post object for post-specific images
1536 * @return string Image URL or empty string
1537 */
1538 private function get_og_image_for_context(array $settings, ?\WP_Post $post = null): string {
1539 // For posts, check featured image first
1540 if ($post) {
1541 $image_id = get_post_thumbnail_id($post);
1542 if ($image_id) {
1543 $image_data = wp_get_attachment_image_src($image_id, 'large');
1544 if (!empty($image_data[0])) {
1545 return $image_data[0];
1546 }
1547 }
1548 }
1549
1550 // Fallback to configured Open Graph image
1551 if (!empty($settings['default_og_image'])) {
1552 return $settings['default_og_image'];
1553 }
1554
1555 // Final fallback to generic default image
1556 if (!empty($settings['default_image'])) {
1557 return $settings['default_image'];
1558 }
1559
1560 // Last-resort fallback to the site logo / site icon. Resolving it here
1561 // (rather than late inside generate_og_tags()) writes it back to the
1562 // shared $data['image'], so generate_twitter_tags() and
1563 // determine_twitter_card_type() see the same image: twitter:image is
1564 // emitted and the card is promoted to summary_large_image, and the
1565 // image is routed through optimize_image_for_platform() so
1566 // og:image:width/height/type/alt companions are produced.
1567 return $this->get_default_social_image();
1568 }
1569
1570 /**
1571 * Get Twitter image for context with proper fallback
1572 *
1573 * @since 1.0.0
1574 *
1575 * @param array $settings Social meta settings
1576 * @param \WP_Post|null $post Optional. Post object for post-specific images
1577 * @return string Image URL or empty string
1578 */
1579 private function get_twitter_image_for_context(array $settings, ?\WP_Post $post = null): string {
1580 // For posts, check for post-specific Twitter image meta first (if implemented)
1581 if ($post) {
1582 // Check for post-specific Twitter image meta (future enhancement)
1583 $post_twitter_image = get_post_meta($post->ID, '_thinkrank_twitter_image', true);
1584 if (!empty($post_twitter_image)) {
1585 return $post_twitter_image;
1586 }
1587
1588 // Check featured image as fallback for posts
1589 $image_id = get_post_thumbnail_id($post);
1590 if ($image_id) {
1591 $image_data = wp_get_attachment_image_src($image_id, 'large');
1592 if (!empty($image_data[0])) {
1593 return $image_data[0];
1594 }
1595 }
1596 }
1597
1598 // Prioritize Twitter-specific default image
1599 if (!empty($settings['default_twitter_image'])) {
1600 return $settings['default_twitter_image'];
1601 }
1602
1603 // Fallback to Open Graph default image
1604 if (!empty($settings['default_og_image'])) {
1605 return $settings['default_og_image'];
1606 }
1607
1608 // Final fallback to generic default image
1609 if (!empty($settings['default_image'])) {
1610 return $settings['default_image'];
1611 }
1612
1613 return '';
1614 }
1615
1616 /**
1617 * Get social media description for post
1618 *
1619 * @since 1.0.0
1620 *
1621 * @param \WP_Post $post Post object
1622 * @return string Social media description
1623 */
1624 private function get_social_description(\WP_Post $post): string {
1625 // Try excerpt first
1626 $description = get_the_excerpt($post);
1627
1628 // If no excerpt, generate from content
1629 if (empty($description)) {
1630 $content = wp_strip_all_tags($post->post_content);
1631 $description = wp_trim_words($content, 30, '...');
1632 }
1633
1634 // If still empty, use site description
1635 if (empty($description)) {
1636 $description = get_bloginfo('description');
1637 }
1638
1639 return $description;
1640 }
1641
1642 /**
1643 * Determine Open Graph type based on context
1644 *
1645 * @since 1.0.0
1646 *
1647 * @param string $context Context type
1648 * @param array $data Content data
1649 * @return string OG type
1650 */
1651 private function determine_og_type(string $context, array $data): string {
1652 switch ($context) {
1653 case 'post':
1654 return 'article';
1655 case 'product':
1656 return 'product';
1657 case 'page':
1658 case 'site':
1659 default:
1660 return 'website';
1661 }
1662 }
1663
1664 /**
1665 * Determine Twitter Card type based on content
1666 *
1667 * @since 1.0.0
1668 *
1669 * @param array $data Content data
1670 * @param string $context Context type
1671 * @return string Twitter Card type
1672 */
1673 private function determine_twitter_card_type(array $data, string $context): string {
1674 // Use a large-image card when a Twitter image will actually be emitted.
1675 // twitter:image resolves to the twitter-specific image first, then the OG
1676 // image, so key the card type off the same precedence.
1677 $twitter_image = !empty($data['twitter_image']) ? $data['twitter_image'] : ($data['image'] ?? '');
1678 return !empty($twitter_image) ? 'summary_large_image' : 'summary';
1679 }
1680
1681 /**
1682 * Optimize title for platform requirements
1683 *
1684 * @since 1.0.0
1685 *
1686 * @param string $title Original title
1687 * @param string $platform Target platform
1688 * @return string Optimized title
1689 */
1690 private function optimize_title_for_platform(string $title, string $platform): string {
1691 if (empty($title)) {
1692 return get_bloginfo('name');
1693 }
1694
1695 $max_length = $this->supported_platforms[$platform]['title_max_length'] ?? 60;
1696
1697 // Multibyte-safe: byte-based substr() would split characters in
1698 // CJK/Bengali/accented titles (WP ships an mbstring fallback).
1699 if (mb_strlen($title) <= $max_length) {
1700 return $title;
1701 }
1702
1703 // Truncate at word boundary
1704 $truncated = wp_trim_words($title, 10, '');
1705 if (mb_strlen($truncated) <= $max_length) {
1706 return $truncated;
1707 }
1708
1709 // Hard truncate if necessary
1710 return mb_substr($title, 0, $max_length - 3) . '...';
1711 }
1712
1713 /**
1714 * Optimize description for platform requirements
1715 *
1716 * @since 1.0.0
1717 *
1718 * @param string $description Original description
1719 * @param string $platform Target platform
1720 * @return string Optimized description
1721 */
1722 private function optimize_description_for_platform(string $description, string $platform): string {
1723 if (empty($description)) {
1724 return get_bloginfo('description');
1725 }
1726
1727 $max_length = $this->supported_platforms[$platform]['description_max_length'] ?? 160;
1728
1729 // Multibyte-safe: byte-based substr() would split characters in
1730 // CJK/Bengali/accented descriptions (WP ships an mbstring fallback).
1731 if (mb_strlen($description) <= $max_length) {
1732 return $description;
1733 }
1734
1735 // Truncate at word boundary
1736 $truncated = wp_trim_words($description, 25, '');
1737 if (mb_strlen($truncated) <= $max_length) {
1738 return $truncated;
1739 }
1740
1741 // Hard truncate if necessary
1742 return mb_substr($description, 0, $max_length - 3) . '...';
1743 }
1744
1745 /**
1746 * Optimize image for platform requirements
1747 *
1748 * @since 1.0.0
1749 *
1750 * @param string $image_url Image URL
1751 * @param string $platform Target platform
1752 * @return array Optimized image data
1753 */
1754 private function optimize_image_for_platform(string $image_url, string $platform): array {
1755 $image_data = [
1756 'url' => $image_url,
1757 'width' => '',
1758 'height' => '',
1759 'alt' => '',
1760 'type' => '',
1761 'valid' => false,
1762 'warnings' => []
1763 ];
1764
1765 if (empty($image_url)) {
1766 return $image_data;
1767 }
1768
1769 // Get image metadata
1770 $attachment_id = attachment_url_to_postid($image_url);
1771 if ($attachment_id) {
1772 $image_meta = wp_get_attachment_metadata($attachment_id);
1773 $image_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
1774 $mime_type = get_post_mime_type($attachment_id);
1775
1776 if ($image_meta && isset($image_meta['width'], $image_meta['height'])) {
1777 $width = (int) $image_meta['width'];
1778 $height = (int) $image_meta['height'];
1779
1780 $image_data['alt'] = $image_alt ?: '';
1781 $image_data['type'] = $mime_type ?: '';
1782
1783 // SVGs and other vector uploads store 0x0 metadata. Dimension
1784 // checks are meaningless there and dividing by 0 is fatal.
1785 if ($width > 0 && $height > 0) {
1786 $image_data['width'] = $width;
1787 $image_data['height'] = $height;
1788
1789 // Validate against platform requirements
1790 $platform_spec = $this->supported_platforms[$platform] ?? [];
1791 $min_width = $platform_spec['image_min_width'] ?? 300;
1792 $min_height = $platform_spec['image_min_height'] ?? 200;
1793
1794 if ($width >= $min_width && $height >= $min_height) {
1795 $image_data['valid'] = true;
1796 } else {
1797 $image_data['warnings'][] = "Image dimensions ({$width}x{$height}) are below recommended minimum ({$min_width}x{$min_height}) for {$platform}";
1798 }
1799
1800 // Check aspect ratio if specified
1801 if (isset($platform_spec['image_recommended_ratio'])) {
1802 $actual_ratio = $width / $height;
1803 $recommended_ratio = $platform_spec['image_recommended_ratio'];
1804 $ratio_tolerance = 0.1;
1805
1806 if (abs($actual_ratio - $recommended_ratio) > $ratio_tolerance) {
1807 $image_data['warnings'][] = sprintf(
1808 "Image aspect ratio (%.2f) differs from recommended ratio (%.2f) for %s",
1809 $actual_ratio,
1810 $recommended_ratio,
1811 $platform
1812 );
1813 }
1814 }
1815 }
1816 }
1817 }
1818
1819 return $image_data;
1820 }
1821
1822 /**
1823 * Get default social image
1824 *
1825 * @since 1.0.0
1826 *
1827 * @return string Default social image URL
1828 */
1829 private function get_default_social_image(): string {
1830 // Try custom logo first
1831 $custom_logo_id = get_theme_mod('custom_logo');
1832 if ($custom_logo_id) {
1833 $logo_data = wp_get_attachment_image_src($custom_logo_id, 'large');
1834 if ($logo_data) {
1835 return $logo_data[0];
1836 }
1837 }
1838
1839 // Try site icon
1840 $site_icon_id = get_option('site_icon');
1841 if ($site_icon_id) {
1842 $icon_data = wp_get_attachment_image_src($site_icon_id, 'large');
1843 if ($icon_data) {
1844 return $icon_data[0];
1845 }
1846 }
1847
1848 return '';
1849 }
1850
1851 /**
1852 * Get Open Graph locale
1853 *
1854 * @since 1.0.0
1855 *
1856 * @return string OG locale
1857 */
1858 private function get_og_locale(): string {
1859 /**
1860 * Filter the locale used for og:locale.
1861 *
1862 * Defaults to get_locale(), which only tracks the active language once
1863 * that language's translation files are installed — on a multilingual
1864 * site without them every translated URL still reports the default
1865 * locale. The multilingual integration answers with the locale its
1866 * provider reports for the language actually being viewed.
1867 *
1868 * @since 1.23.0
1869 *
1870 * @param string $locale Locale for the current request.
1871 */
1872 $locale = (string) apply_filters('thinkrank_og_locale', get_locale());
1873
1874 // Convert WordPress locale to OG locale format for the few that differ
1875 // from the xx_YY form (e.g. bare 'ja').
1876 $og_locale_map = [
1877 'ja' => 'ja_JP',
1878 ];
1879
1880 if (isset($og_locale_map[$locale])) {
1881 return $og_locale_map[$locale];
1882 }
1883
1884 // Fall back to the actual site locale (normalized to xx_YY) rather than
1885 // mislabeling every unmapped language as en_US.
1886 if (preg_match('/^[a-z]{2,3}_[A-Z]{2}$/', $locale)) {
1887 return $locale;
1888 }
1889
1890 // Bare language code (e.g. 'nl') → best-effort xx_XX.
1891 if (preg_match('/^([a-z]{2,3})$/', $locale, $m)) {
1892 return $m[1] . '_' . strtoupper($m[1]);
1893 }
1894
1895 return 'en_US';
1896 }
1897
1898 /**
1899 * Get current URL
1900 *
1901 * @since 1.0.0
1902 *
1903 * @return string Current URL
1904 */
1905 private function get_current_url(): string {
1906 if (is_admin()) {
1907 return home_url();
1908 }
1909
1910 global $wp;
1911 return home_url(add_query_arg([], $wp->request));
1912 }
1913
1914 /**
1915 * Get Twitter site handle
1916 *
1917 * @since 1.0.0
1918 *
1919 * @return string Twitter site handle
1920 */
1921 private function get_twitter_site_handle(): string {
1922 $settings = $this->get_settings('site');
1923 $username = $settings['twitter_username'] ?? '';
1924
1925 if (empty($username)) {
1926 return '';
1927 }
1928
1929 // Ensure username starts with @ for meta tag output
1930 return '@' . ltrim($username, '@');
1931 }
1932
1933 /**
1934 * Get Twitter creator handle
1935 *
1936 * @since 1.0.0
1937 *
1938 * @return string Twitter creator handle
1939 */
1940 private function get_twitter_creator_handle(): string {
1941 $settings = $this->get_settings('site');
1942 $creator = $settings['twitter_creator'] ?? '';
1943
1944 if (empty($creator)) {
1945 return '';
1946 }
1947
1948 // Ensure creator starts with @ for meta tag output
1949 return '@' . ltrim($creator, '@');
1950 }
1951
1952 /**
1953 * Add context-specific Open Graph tags
1954 *
1955 * @since 1.0.0
1956 *
1957 * @param array $og_tags OG tags array
1958 * @param string $context Context type
1959 * @param array $data Content data
1960 * @param string $og_type OG type
1961 * @return array Updated OG tags
1962 */
1963 private function add_context_specific_og_tags(array $og_tags, string $context, array $data, string $og_type): array {
1964 switch ($og_type) {
1965 case 'article':
1966 if (!empty($data['author']['name'])) {
1967 $og_tags['article:author'] = $data['author']['name'];
1968 }
1969 if (!empty($data['published_time'])) {
1970 $og_tags['article:published_time'] = $data['published_time'];
1971 }
1972 if (!empty($data['modified_time'])) {
1973 $og_tags['article:modified_time'] = $data['modified_time'];
1974 }
1975 // article:section — the post's primary category (parity with the
1976 // basic emitter, which the active path previously omitted).
1977 if (!empty($data['post_id'])) {
1978 $categories = get_the_category((int) $data['post_id']);
1979 if (!empty($categories) && !is_wp_error($categories)) {
1980 $og_tags['article:section'] = $categories[0]->name;
1981 }
1982 }
1983 break;
1984 case 'product':
1985 // Product-specific tags would be added here
1986 // This could be extended with price, availability, etc.
1987 break;
1988 }
1989
1990 // Add local business Open Graph tags if business data is available
1991 $og_tags = $this->add_local_business_og_tags($og_tags, $data);
1992
1993 return $og_tags;
1994 }
1995
1996 /**
1997 * Add local business Open Graph tags
1998 *
1999 * @since 1.0.0
2000 *
2001 * @param array $og_tags OG tags array
2002 * @param array $data Content data
2003 * @return array Updated OG tags with local business information
2004 */
2005 private function add_local_business_og_tags(array $og_tags, array $data): array {
2006 // Get business data from Site Identity settings
2007 $business_data = $this->get_local_business_data();
2008
2009 if (empty($business_data) || empty($business_data['business_name'])) {
2010 return $og_tags;
2011 }
2012
2013 // Add business contact data Open Graph tags
2014 if (!empty($business_data['business_address'])) {
2015 $og_tags['business:contact_data:street_address'] = $business_data['business_address'];
2016 }
2017
2018 if (!empty($business_data['business_city'])) {
2019 $og_tags['business:contact_data:locality'] = $business_data['business_city'];
2020 }
2021
2022 if (!empty($business_data['business_state'])) {
2023 $og_tags['business:contact_data:region'] = $business_data['business_state'];
2024 }
2025
2026 if (!empty($business_data['business_postal_code'])) {
2027 $og_tags['business:contact_data:postal_code'] = $business_data['business_postal_code'];
2028 }
2029
2030 if (!empty($business_data['business_country'])) {
2031 $og_tags['business:contact_data:country_name'] = $business_data['business_country'];
2032 }
2033
2034 if (!empty($business_data['business_phone'])) {
2035 $og_tags['business:contact_data:phone_number'] = $business_data['business_phone'];
2036 }
2037
2038 if (!empty($business_data['business_email'])) {
2039 $og_tags['business:contact_data:email'] = $business_data['business_email'];
2040 }
2041
2042 // Add business hours if available
2043 if (!empty($business_data['business_hours']) && is_array($business_data['business_hours'])) {
2044 $formatted_hours = $this->format_business_hours_for_og($business_data['business_hours']);
2045 if (!empty($formatted_hours)) {
2046 $og_tags['business:hours'] = $formatted_hours;
2047 }
2048 }
2049
2050 // Add business website
2051 if (!empty($business_data['business_website'])) {
2052 $og_tags['business:contact_data:website'] = $business_data['business_website'];
2053 }
2054
2055 // Add coordinates if available
2056 if (!empty($business_data['business_latitude']) && !empty($business_data['business_longitude'])) {
2057 $og_tags['place:location:latitude'] = $business_data['business_latitude'];
2058 $og_tags['place:location:longitude'] = $business_data['business_longitude'];
2059 }
2060
2061 return $og_tags;
2062 }
2063
2064 /**
2065 * Get local business data from Site Identity settings
2066 *
2067 * @since 1.0.0
2068 *
2069 * @return array Business data array
2070 */
2071 private function get_local_business_data(): array {
2072 // Try to get Site Identity Manager
2073 if (!class_exists('ThinkRank\\SEO\\Site_Identity_Manager')) {
2074 require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-site-identity-manager.php';
2075 }
2076
2077 $site_identity_manager = new \ThinkRank\SEO\Site_Identity_Manager();
2078 $settings = $site_identity_manager->get_settings('site');
2079
2080 // Only return data if local SEO is enabled
2081 if (empty($settings['local_seo_enabled'])) {
2082 return [];
2083 }
2084
2085 return [
2086 'business_name' => $settings['business_name'] ?? '',
2087 'business_address' => $settings['business_address'] ?? '',
2088 'business_city' => $settings['business_city'] ?? '',
2089 'business_state' => $settings['business_state'] ?? '',
2090 'business_postal_code' => $settings['business_postal_code'] ?? '',
2091 'business_country' => $settings['business_country'] ?? '',
2092 'business_phone' => $settings['business_phone'] ?? '',
2093 'business_email' => $settings['business_email'] ?? '',
2094 'business_hours' => $settings['business_hours'] ?? [],
2095 'business_website' => $settings['business_website'] ?? home_url(),
2096 'business_latitude' => $settings['business_latitude'] ?? '',
2097 'business_longitude' => $settings['business_longitude'] ?? ''
2098 ];
2099 }
2100
2101 /**
2102 * Format business hours for Open Graph tags
2103 *
2104 * @since 1.0.0
2105 *
2106 * @param array $business_hours Business hours array
2107 * @return string Formatted hours string
2108 */
2109 private function format_business_hours_for_og(array $business_hours): string {
2110 $formatted_days = [];
2111
2112 $day_names = [
2113 'monday' => 'Monday',
2114 'tuesday' => 'Tuesday',
2115 'wednesday' => 'Wednesday',
2116 'thursday' => 'Thursday',
2117 'friday' => 'Friday',
2118 'saturday' => 'Saturday',
2119 'sunday' => 'Sunday'
2120 ];
2121
2122 foreach ($day_names as $day => $display_name) {
2123 if (isset($business_hours[$day]) && !empty($business_hours[$day])) {
2124 $day_data = $business_hours[$day];
2125
2126 if (!empty($day_data['closed']) || empty($day_data['open']) || empty($day_data['close'])) {
2127 $formatted_days[] = $display_name . ': Closed';
2128 } else {
2129 $formatted_days[] = $display_name . ': ' . $day_data['open'] . ' - ' . $day_data['close'];
2130 }
2131 }
2132 }
2133
2134 return implode('; ', $formatted_days);
2135 }
2136
2137 /**
2138 * Apply platform-specific optimizations
2139 *
2140 * @since 1.0.0
2141 *
2142 * @param array $og_tags OG tags array
2143 * @param string $platform Target platform
2144 * @param array $data Content data
2145 * @return array Optimized OG tags
2146 */
2147 private function apply_platform_specific_optimizations(array $og_tags, string $platform, array $data): array {
2148 $settings = $this->get_settings('site');
2149
2150 switch ($platform) {
2151 case 'linkedin':
2152 // LinkedIn prefers professional content
2153 if ($settings['enable_linkedin'] ?? false) {
2154 if (isset($og_tags['og:description'])) {
2155 $og_tags['og:description'] = $this->make_description_professional($og_tags['og:description']);
2156 }
2157 // Add LinkedIn-specific type if appropriate
2158 if ($og_tags['og:type'] === 'article') {
2159 $og_tags['article:author'] = $data['author'] ?? '';
2160 }
2161 }
2162 break;
2163
2164 case 'pinterest':
2165 // Pinterest prefers descriptive content
2166 if ($settings['enable_pinterest'] ?? false) {
2167 if (isset($og_tags['og:description'])) {
2168 $og_tags['og:description'] = $this->make_description_descriptive($og_tags['og:description']);
2169 }
2170 // Pinterest prefers article type for rich pins
2171 if (in_array($og_tags['og:type'], ['website', 'blog'], true)) {
2172 $og_tags['og:type'] = 'article';
2173 }
2174 }
2175 break;
2176
2177 case 'instagram':
2178 // Instagram optimizations
2179 if ($settings['enable_instagram'] ?? false) {
2180 // Instagram prefers square or vertical images
2181 if (isset($og_tags['og:description'])) {
2182 $og_tags['og:description'] = $this->make_description_engaging($og_tags['og:description']);
2183 }
2184 }
2185 break;
2186
2187 case 'tiktok':
2188 // TikTok optimizations
2189 if ($settings['enable_tiktok'] ?? false) {
2190 // TikTok prefers short, catchy descriptions
2191 if (isset($og_tags['og:description'])) {
2192 $og_tags['og:description'] = $this->make_description_catchy($og_tags['og:description']);
2193 }
2194 }
2195 break;
2196 }
2197
2198 return $og_tags;
2199 }
2200
2201 /**
2202 * Make description more professional for LinkedIn
2203 *
2204 * @since 1.0.0
2205 *
2206 * @param string $description Original description
2207 * @return string Professional description
2208 */
2209 private function make_description_professional(string $description): string {
2210 // Remove casual language and emojis, add professional tone
2211 $description = preg_replace('/[^\w\s\.,!?-]/', '', $description);
2212
2213 // Add professional keywords if not present
2214 $professional_words = ['insights', 'expertise', 'professional', 'industry', 'business'];
2215 if (!preg_match('/\b(' . implode('|', $professional_words) . ')\b/i', $description)) {
2216 $description = 'Professional insights: ' . $description;
2217 }
2218
2219 return $description;
2220 }
2221
2222 /**
2223 * Make description more descriptive for Pinterest
2224 *
2225 * @since 1.0.0
2226 *
2227 * @param string $description Original description
2228 * @return string Descriptive description
2229 */
2230 private function make_description_descriptive(string $description): string {
2231 // Pinterest users love detailed, searchable descriptions
2232 $descriptive_words = ['discover', 'explore', 'learn', 'find', 'ideas'];
2233
2234 if (!preg_match('/\b(' . implode('|', $descriptive_words) . ')\b/i', $description)) {
2235 $description = 'Discover ' . lcfirst($description);
2236 }
2237
2238 return $description;
2239 }
2240
2241 /**
2242 * Make description engaging for Instagram
2243 *
2244 * @since 1.0.0
2245 *
2246 * @param string $description Original description
2247 * @return string Engaging description
2248 */
2249 private function make_description_engaging(string $description): string {
2250 // Instagram prefers engaging, visual language
2251 $engaging_words = ['amazing', 'stunning', 'beautiful', 'incredible', 'inspiring'];
2252
2253 if (!preg_match('/\b(' . implode('|', $engaging_words) . ')\b/i', $description)) {
2254 $description = '' . $description;
2255 }
2256
2257 return $description;
2258 }
2259
2260 /**
2261 * Make description catchy for TikTok
2262 *
2263 * @since 1.0.0
2264 *
2265 * @param string $description Original description
2266 * @return string Catchy description
2267 */
2268 private function make_description_catchy(string $description): string {
2269 // TikTok prefers short, catchy descriptions
2270 $catchy_words = ['viral', 'trending', 'must-see', 'epic', 'mind-blowing'];
2271
2272 // Limit to 100 characters for TikTok
2273 if (strlen($description) > 100) {
2274 $description = substr($description, 0, 97) . '...';
2275 }
2276
2277 if (!preg_match('/\b(' . implode('|', $catchy_words) . ')\b/i', $description)) {
2278 $description = '🔥 ' . $description;
2279 }
2280
2281 return $description;
2282 }
2283
2284 /**
2285 * Add Twitter Card specific tags
2286 *
2287 * @since 1.0.0
2288 *
2289 * @param array $twitter_tags Twitter tags array
2290 * @param string $card_type Card type
2291 * @param array $data Content data
2292 * @param string $context Context type
2293 * @return array Updated Twitter tags
2294 */
2295 private function add_twitter_card_specific_tags(array $twitter_tags, string $card_type, array $data, string $context): array {
2296 // The content extractor only produces summary / summary_large_image
2297 // cards, so the player/app card variants were dead code that read keys
2298 // (video_url, app_name, …) the extractor never sets. Kept as a filterable
2299 // extension point for add-ons that do populate richer card data.
2300 return apply_filters('thinkrank_twitter_card_specific_tags', $twitter_tags, $card_type, $data, $context);
2301 }
2302
2303 /**
2304 * Generate Open Graph preview
2305 *
2306 * @since 1.0.0
2307 *
2308 * @param array $og_tags OG tags
2309 * @param string $platform Platform name
2310 * @param array $preview Preview array
2311 * @return array Updated preview
2312 */
2313 private function generate_og_preview(array $og_tags, string $platform, array $preview): array {
2314 $preview['title'] = $og_tags['og:title'] ?? '';
2315 $preview['description'] = $og_tags['og:description'] ?? '';
2316 $preview['image'] = $og_tags['og:image'] ?? '';
2317 $preview['preview_url'] = $og_tags['og:url'] ?? '';
2318
2319 // Validate required fields
2320 $required_fields = ['og:title', 'og:type', 'og:image', 'og:url'];
2321 $missing_fields = [];
2322
2323 foreach ($required_fields as $field) {
2324 if (empty($og_tags[$field])) {
2325 $missing_fields[] = $field;
2326 }
2327 }
2328
2329 if (empty($missing_fields)) {
2330 $preview['valid'] = true;
2331 } else {
2332 $preview['warnings'][] = 'Missing required fields: ' . implode(', ', $missing_fields);
2333 }
2334
2335 // Platform-specific validation
2336 $platform_spec = $this->supported_platforms[$platform] ?? [];
2337 if (isset($platform_spec['title_max_length']) && strlen($preview['title']) > $platform_spec['title_max_length']) {
2338 $preview['warnings'][] = "Title exceeds {$platform} maximum length of {$platform_spec['title_max_length']} characters";
2339 }
2340
2341 return $preview;
2342 }
2343
2344 /**
2345 * Generate Twitter preview
2346 *
2347 * @since 1.0.0
2348 *
2349 * @param array $twitter_tags Twitter tags
2350 * @param array $preview Preview array
2351 * @return array Updated preview
2352 */
2353 private function generate_twitter_preview(array $twitter_tags, array $preview): array {
2354 $preview['title'] = $twitter_tags['twitter:title'] ?? '';
2355 $preview['description'] = $twitter_tags['twitter:description'] ?? '';
2356 $preview['image'] = $twitter_tags['twitter:image'] ?? '';
2357
2358 // Validate required fields
2359 $required_fields = ['twitter:card', 'twitter:title'];
2360 $missing_fields = [];
2361
2362 foreach ($required_fields as $field) {
2363 if (empty($twitter_tags[$field])) {
2364 $missing_fields[] = $field;
2365 }
2366 }
2367
2368 if (empty($missing_fields)) {
2369 $preview['valid'] = true;
2370 } else {
2371 $preview['warnings'][] = 'Missing required fields: ' . implode(', ', $missing_fields);
2372 }
2373
2374 // Twitter-specific validation
2375 $twitter_spec = $this->supported_platforms['twitter'];
2376 if (strlen($preview['title']) > $twitter_spec['title_max_length']) {
2377 $preview['warnings'][] = "Title exceeds Twitter maximum length of {$twitter_spec['title_max_length']} characters";
2378 }
2379
2380 return $preview;
2381 }
2382
2383 /**
2384 * Generate Pinterest preview
2385 *
2386 * @since 1.0.0
2387 *
2388 * @param array $og_tags OG tags
2389 * @param array $preview Preview array
2390 * @return array Updated preview
2391 */
2392 private function generate_pinterest_preview(array $og_tags, array $preview): array {
2393 $preview['title'] = $og_tags['og:title'] ?? '';
2394 $preview['description'] = $og_tags['og:description'] ?? '';
2395 $preview['image'] = $og_tags['og:image'] ?? '';
2396 $preview['preview_url'] = $og_tags['og:url'] ?? '';
2397
2398 // Validate required fields for Pinterest
2399 $required_fields = ['og:title', 'og:image', 'og:url'];
2400 $missing_fields = [];
2401
2402 foreach ($required_fields as $field) {
2403 if (empty($og_tags[$field])) {
2404 $missing_fields[] = $field;
2405 }
2406 }
2407
2408 if (empty($missing_fields)) {
2409 $preview['valid'] = true;
2410 } else {
2411 $preview['warnings'][] = 'Missing required fields: ' . implode(', ', $missing_fields);
2412 }
2413
2414 // Pinterest-specific validation and suggestions
2415 $pinterest_spec = $this->supported_platforms['pinterest'] ?? [];
2416
2417 // Title length validation
2418 if (isset($pinterest_spec['title_max_length']) && strlen($preview['title']) > $pinterest_spec['title_max_length']) {
2419 $preview['warnings'][] = "Title exceeds Pinterest maximum length of {$pinterest_spec['title_max_length']} characters";
2420 }
2421
2422 // Description length validation
2423 if (isset($pinterest_spec['description_max_length']) && strlen($preview['description']) > $pinterest_spec['description_max_length']) {
2424 $preview['warnings'][] = "Description exceeds Pinterest maximum length of {$pinterest_spec['description_max_length']} characters";
2425 }
2426
2427 // Image dimension suggestions for Pinterest
2428 if (!empty($preview['image'])) {
2429 $image_data = $this->optimize_image_for_platform($preview['image'], 'pinterest');
2430 if (!empty($image_data['width']) && !empty($image_data['height'])) {
2431 $aspect_ratio = $image_data['width'] / $image_data['height'];
2432
2433 // Pinterest prefers vertical images (2:3 ratio is optimal)
2434 if ($aspect_ratio > 1) {
2435 $preview['suggestions'][] = 'Pinterest performs better with vertical images (2:3 aspect ratio recommended)';
2436 } elseif ($aspect_ratio < 0.6) {
2437 $preview['suggestions'][] = 'Image is very tall - consider a 2:3 aspect ratio for optimal Pinterest performance';
2438 }
2439
2440 // Minimum size recommendations
2441 if ($image_data['width'] < 600) {
2442 $preview['suggestions'][] = 'Pinterest recommends images at least 600px wide for better quality';
2443 }
2444 }
2445 }
2446
2447 return $preview;
2448 }
2449
2450 /**
2451 * Generate platform-specific meta tags
2452 *
2453 * Platform IDs and verification codes are owned by the Social Platforms tab
2454 * (ThinkRank\API\Social_Platforms_Endpoint), which stores them in core
2455 * Settings (wp_options) with the sensitive codes encrypted at rest. The
2456 * social_meta settings table this manager normally reads no longer receives
2457 * these values from the UI, so we resolve each key from core Settings first
2458 * and fall back to any legacy value still present in the passed-in table
2459 * settings — otherwise the verification tags would never render.
2460 *
2461 * @since 1.0.0
2462 *
2463 * @param array $settings Settings array (social_meta table) — legacy fallback.
2464 * @return array Platform-specific meta tags
2465 */
2466 private function generate_platform_meta_tags(array $settings): array {
2467 $platform_tags = [];
2468
2469 $core = \ThinkRank\Core\Settings::instance();
2470 // Core Settings (decrypted for sensitive keys) wins; the table value is a
2471 // backward-compat fallback for installs that saved these before the UI
2472 // moved to the Social Platforms tab.
2473 $resolve = static function (string $key) use ($core, $settings): string {
2474 $value = (string) $core->get($key, '');
2475 if ('' === $value) {
2476 $value = (string) ($settings[$key] ?? '');
2477 }
2478 return $value;
2479 };
2480
2481 // Facebook meta tags
2482 $facebook_app_id = $resolve('facebook_app_id');
2483 if ('' !== $facebook_app_id) {
2484 $platform_tags['fb:app_id'] = $facebook_app_id;
2485 }
2486
2487 $facebook_admins = $resolve('facebook_admins');
2488 if ('' !== $facebook_admins) {
2489 $platform_tags['fb:admins'] = $facebook_admins;
2490 }
2491
2492 // Pinterest site verification
2493 $pinterest = $resolve('pinterest_site_verification');
2494 if ('' !== $pinterest) {
2495 $platform_tags['pinterest-site-verification'] = $pinterest;
2496 }
2497
2498 // Instagram verification
2499 $instagram = $resolve('instagram_verification');
2500 if ('' !== $instagram) {
2501 $platform_tags['instagram-site-verification'] = $instagram;
2502 }
2503
2504 // TikTok verification
2505 $tiktok = $resolve('tiktok_verification');
2506 if ('' !== $tiktok) {
2507 $platform_tags['tiktok-site-verification'] = $tiktok;
2508 }
2509
2510 // YouTube channel verification
2511 $youtube = $resolve('youtube_channel_id');
2512 if ('' !== $youtube) {
2513 $platform_tags['youtube-channel-id'] = $youtube;
2514 }
2515
2516 // WhatsApp Business verification
2517 $whatsapp = $resolve('whatsapp_business_id');
2518 if ('' !== $whatsapp) {
2519 $platform_tags['whatsapp-business-id'] = $whatsapp;
2520 }
2521
2522 return $platform_tags;
2523 }
2524
2525 /**
2526 * Convert OG, Twitter, and Platform tags to HTML meta tags
2527 *
2528 * @since 1.0.0
2529 *
2530 * @param array $og_tags Open Graph tags
2531 * @param array $twitter_tags Twitter tags
2532 * @param array $platform_tags Platform-specific tags
2533 * @return array HTML meta tags
2534 */
2535 private function convert_to_meta_tags(array $og_tags, array $twitter_tags, array $platform_tags = []): array {
2536 $meta_tags = [];
2537
2538 // Convert OG tags
2539 foreach ($og_tags as $property => $content) {
2540 if (!empty($content)) {
2541 $meta_tags[] = [
2542 'property' => esc_attr($property),
2543 'content' => esc_attr($content)
2544 ];
2545 }
2546 }
2547
2548 // Convert Twitter tags
2549 foreach ($twitter_tags as $name => $content) {
2550 if (!empty($content)) {
2551 $meta_tags[] = [
2552 'name' => esc_attr($name),
2553 'content' => esc_attr($content)
2554 ];
2555 }
2556 }
2557
2558 // Convert Platform tags
2559 foreach ($platform_tags as $name => $content) {
2560 if (!empty($content)) {
2561 // Determine if it should be property or name attribute
2562 if (strpos($name, 'fb:') === 0) {
2563 // Facebook tags use property attribute
2564 $meta_tags[] = [
2565 'property' => esc_attr($name),
2566 'content' => esc_attr($content)
2567 ];
2568 } else {
2569 // Other platform tags use name attribute
2570 $meta_tags[] = [
2571 'name' => esc_attr($name),
2572 'content' => esc_attr($content)
2573 ];
2574 }
2575 }
2576 }
2577
2578 return $meta_tags;
2579 }
2580
2581 /**
2582 * Validate social image
2583 *
2584 * @since 1.0.0
2585 *
2586 * @param string $image_url Image URL to validate
2587 * @return array Validation results
2588 */
2589 private function validate_social_image(string $image_url): array {
2590 $validation = [
2591 'valid' => false,
2592 'warnings' => [],
2593 'suggestions' => []
2594 ];
2595
2596 if (empty($image_url)) {
2597 $validation['warnings'][] = 'No image provided';
2598 return $validation;
2599 }
2600
2601 // Check if URL is valid
2602 if (!filter_var($image_url, FILTER_VALIDATE_URL)) {
2603 $validation['warnings'][] = 'Invalid image URL';
2604 return $validation;
2605 }
2606
2607 // Get image metadata if it's a local attachment
2608 $attachment_id = attachment_url_to_postid($image_url);
2609 if ($attachment_id) {
2610 $image_meta = wp_get_attachment_metadata($attachment_id);
2611 $meta_width = isset($image_meta['width']) ? (int) $image_meta['width'] : 0;
2612 $meta_height = isset($image_meta['height']) ? (int) $image_meta['height'] : 0;
2613
2614 // SVGs and other vector uploads store 0x0 metadata — skip the
2615 // dimension/ratio checks instead of dividing by 0.
2616 if ($image_meta && $meta_width > 0 && $meta_height > 0) {
2617 // Check minimum dimensions for major platforms
2618 $min_width = 600; // Facebook minimum
2619 $min_height = 315; // Facebook minimum
2620
2621 if ($meta_width >= $min_width && $meta_height >= $min_height) {
2622 $validation['valid'] = true;
2623 } else {
2624 $validation['warnings'][] = "Image dimensions ({$meta_width}x{$meta_height}) are below recommended minimum ({$min_width}x{$min_height})";
2625 }
2626
2627 // Check file size
2628 $file_path = get_attached_file($attachment_id);
2629 if ($file_path && file_exists($file_path)) {
2630 $file_size = filesize($file_path);
2631 $max_size = 5 * 1024 * 1024; // 5MB
2632
2633 if ($file_size > $max_size) {
2634 $validation['warnings'][] = 'Image file size exceeds 5MB, may not display on some platforms';
2635 }
2636 }
2637
2638 // Check aspect ratio
2639 $aspect_ratio = $meta_width / $meta_height;
2640 if ($aspect_ratio < 1.5 || $aspect_ratio > 2.5) {
2641 $validation['suggestions'][] = 'Consider using an image with 1.91:1 aspect ratio for optimal display';
2642 }
2643 }
2644 } else {
2645 $validation['suggestions'][] = 'External images may not be optimized for social media platforms';
2646 }
2647
2648 return $validation;
2649 }
2650 }
2651