PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 2.7.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v2.7.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
← All changes | includes/seo/class-analytics-manager.php +176 -457 1.26.02.7.0 View file →
@@ -16,9 +16,8 @@
16 16
17 17 namespace ThinkRank\SEO;
18 18
19 19 use ThinkRank\Core\Settings_Manager;
20 -use ThinkRank\Core\Plan_Config;
21 20 use ThinkRank\Integrations\Google_Analytics_Client;
22 21 use ThinkRank\Integrations\Google_Search_Console_Client;
23 22 use ThinkRank\Integrations\Google_PageSpeed_Client;
24 23 use ThinkRank\Integrations\Google_Search_Analytics_Client;
@@ -88,8 +87,45 @@
88 87 */
89 88 private static bool $token_refreshed_this_request = false;
90 89
91 90 /**
91 + * Single-flight lock for the OAuth refresh exchange.
92 + *
93 + * @var string
94 + */
95 + private const REFRESH_LOCK = 'thinkrank_token_refresh_lock';
96 +
97 + /**
98 + * How long a held refresh lock stays valid. Longer than the request
99 + * timeout below, so a request that dies mid-exchange still frees it.
100 + *
101 + * @var int
102 + */
103 + private const REFRESH_LOCK_TTL = 60;
104 +
105 + /**
106 + * Set after a failed exchange; suppresses retries until it expires.
107 + *
108 + * @var string
109 + */
110 + private const REFRESH_BACKOFF = 'thinkrank_token_refresh_backoff';
111 +
112 + /**
113 + * How long to stay quiet after a failed exchange.
114 + *
115 + * @var int
116 + */
117 + private const REFRESH_BACKOFF_TTL = 300;
118 +
119 + /**
120 + * Timeout for the refresh exchange. A healthy proxy answers in ~1s; the
121 + * old 30s meant one outage held a request open for half a minute.
122 + *
123 + * @var int
124 + */
125 + private const REFRESH_TIMEOUT = 10;
126 +
127 + /**
92 128 * Constructor
93 129 *
94 130 * @param Settings_Manager|null $settings_manager Settings manager instance
95 131 */
@@ -108,10 +144,11 @@
108 144 public function init(): void {
109 145 // Register custom cron interval (45 minutes)
110 146 add_filter('cron_schedules', [$this, 'add_cron_intervals']);
111 147
112 - // Initialize Google API clients
113 - add_action('init', [$this, 'initialize_clients']);
148 + // Initialize Google API clients — but only in the contexts that can use
149 + // them. See maybe_initialize_clients().
150 + add_action('init', [$this, 'maybe_initialize_clients']);
114 151
115 152 // Initialize token refresh scheduling
116 153 add_action('init', [$this, 'init_token_refresh']);
117 154
@@ -131,11 +168,16 @@
131 168 * @param array $schedules Existing cron schedules
132 169 * @return array Modified cron schedules
133 170 */
134 171 public function add_cron_intervals(array $schedules): array {
172 + // Only translate once `init` has run: wp_get_schedules() can be reached
173 + // before then (wp_schedule_event() at plugin boot does), and translating
174 + // that early trips the _load_textdomain_just_in_time notice on WP 6.7+.
135 175 $schedules['thinkrank_45min'] = [
136 176 'interval' => 2700, // 45 minutes in seconds
137 - 'display' => __('Every 45 Minutes', 'thinkrank')
177 + 'display' => did_action('init')
178 + ? __('Every 45 Minutes', 'thinkrank')
179 + : 'Every 45 Minutes'
138 180 ];
139 181 return $schedules;
140 182 }
141 183
@@ -172,8 +214,43 @@
172 214 return $this->get_setting('search_console_property', get_site_url());
173 215 }
174 216
175 217 /**
218 + * Initialize the Google clients on `init`, in the contexts that use them.
219 + *
220 + * initialize_clients() refreshes the OAuth token, which is a blocking
221 + * outbound POST to the OAuth proxy. Hooked unconditionally it ran on every
222 + * anonymous front-end request, so a proxy outage became a site-wide TTFB
223 + * collapse — with each visitor waiting for the network call, and none of
224 + * them able to use a Google client anyway. No front-end code path reads
225 + * one: every consumer is a REST endpoint, a cron callback or WP-CLI, and
226 + * each either calls initialize_clients() itself or goes through
227 + * get_search_console_client(), which initializes lazily (#383).
228 + *
229 + * @since 2.0.1
230 + * @return void
231 + */
232 + public function maybe_initialize_clients(): void {
233 + $wanted = is_admin()
234 + || wp_doing_cron()
235 + || (defined('REST_REQUEST') && REST_REQUEST)
236 + || (defined('WP_CLI') && WP_CLI);
237 +
238 + /**
239 + * Filter whether the Google API clients are initialized for this request.
240 + *
241 + * @since 2.0.1
242 + *
243 + * @param bool $wanted Whether to initialize the clients.
244 + */
245 + if (!apply_filters('thinkrank_initialize_google_clients', $wanted)) {
246 + return;
247 + }
248 +
249 + $this->initialize_clients();
250 + }
251 +
252 + /**
176 253 * Initialize Google API clients
177 254 * Following AI_Manager client initialization pattern
178 255 *
179 256 * @return void
@@ -370,10 +447,30 @@
370 447 // Calculate absolute expiration time (created + relative seconds)
371 448 $expiration_time = $created + $expires_in;
372 449
373 450 // Refresh if forced, expired, or expiring within 5 minutes (300 seconds)
374 - if ($force || $current_time >= ($expiration_time - 300)) {
451 + if (!$force && $current_time < ($expiration_time - 300)) {
452 + return;
453 + }
375 454
455 + // A failed exchange leaves google_token_created untouched, so the
456 + // expiry condition above stays true and the next request tries again.
457 + // Without a backoff a proxy outage means one blocking network call per
458 + // request, forever. A forced refresh — the user reconnecting — is a
459 + // deliberate act and skips the wait (#383).
460 + if (!$force && get_transient(self::REFRESH_BACKOFF)) {
461 + return;
462 + }
463 +
464 + // One exchange at a time. Concurrent callers past the expiry threshold
465 + // would otherwise all refresh at once and invalidate each other's
466 + // in-flight grants; the losers fall through with the current token and
467 + // pick up the new one on their next read.
468 + if (!$force && !$this->acquire_refresh_lock()) {
469 + return;
470 + }
471 +
472 + try {
376 473 // The proxy owns the Google app credentials; we only ever hand it
377 474 // the refresh token and let it perform the exchange.
378 475 $response = wp_remote_post(Google_OAuth_Proxy::get_proxy_url(), [
379 476 'headers' => [
@@ -384,12 +481,13 @@
384 481 'action' => 'refresh',
385 482 'refresh_token' => $refresh_token,
386 483 'site' => home_url(),
387 484 ]),
388 - 'timeout' => 30
485 + 'timeout' => self::REFRESH_TIMEOUT
389 486 ]);
390 487
391 488 if (is_wp_error($response)) {
489 + $this->back_off_refresh();
392 490 return;
393 491 }
394 492
395 493 $body = wp_remote_retrieve_body($response);
@@ -402,12 +500,15 @@
402 500 // the site is connected — otherwise the UI shows "Connected"
403 501 // while every API call 401s.
404 502 if (($data['error'] ?? '') === 'invalid_grant') {
405 503 Google_OAuth_Proxy::mark_revoked();
504 + return;
406 505 }
407 506
408 507 // Any other failure (network blip, proxy 502) is transient;
409 - // leave the credentials alone and let the next run retry.
508 + // leave the credentials alone and let the next run retry —
509 + // after the backoff, not on the very next request.
510 + $this->back_off_refresh();
410 511 return;
411 512 }
412 513
413 514 // Update settings with new token data
@@ -423,15 +524,79 @@
423 524 'google_refresh_token' => $data['refresh_token']
424 525 ], 'integrations');
425 526 }
426 527
528 + // A success clears any backoff a previous failure left behind.
529 + delete_transient(self::REFRESH_BACKOFF);
530 +
427 531 // Drop the memoized settings merge so subsequent reads (e.g.
428 532 // re-initializing clients) see the fresh token.
429 533 $this->merged_settings = null;
534 + } finally {
535 + $this->release_refresh_lock();
430 536 }
431 537 }
432 538
433 539 /**
540 + * Take the single-flight lock for the refresh exchange.
541 + *
542 + * @since 2.0.1
543 + * @return bool True when this request holds the lock.
544 + */
545 + private function acquire_refresh_lock(): bool {
546 + // With a persistent object cache, add is atomic — memcached and Redis
547 + // both fail an ADD on an existing key — so exactly one caller wins.
548 + if (wp_using_ext_object_cache()) {
549 + return (bool) wp_cache_add(self::REFRESH_LOCK, time(), 'thinkrank', self::REFRESH_LOCK_TTL);
550 + }
551 +
552 + // Without one, the options table is the shared store, and the unique
553 + // index on option_name gives add_option() the same all-or-nothing
554 + // result. set_transient() would not: it is an update, so every
555 + // concurrent caller would "win".
556 + if (add_option(self::REFRESH_LOCK, time(), '', 'no')) {
557 + return true;
558 + }
559 +
560 + // Reclaim a lock whose holder died before releasing it.
561 + $held = (int) get_option(self::REFRESH_LOCK);
562 +
563 + if ($held > 0 && (time() - $held) > self::REFRESH_LOCK_TTL) {
564 + delete_option(self::REFRESH_LOCK);
565 +
566 + return (bool) add_option(self::REFRESH_LOCK, time(), '', 'no');
567 + }
568 +
569 + return false;
570 + }
571 +
572 + /**
573 + * Release the single-flight lock.
574 + *
575 + * @since 2.0.1
576 + * @return void
577 + */
578 + private function release_refresh_lock(): void {
579 + if (wp_using_ext_object_cache()) {
580 + wp_cache_delete(self::REFRESH_LOCK, 'thinkrank');
581 +
582 + return;
583 + }
584 +
585 + delete_option(self::REFRESH_LOCK);
586 + }
587 +
588 + /**
589 + * Stop retrying the exchange for a while after a failure.
590 + *
591 + * @since 2.0.1
592 + * @return void
593 + */
594 + private function back_off_refresh(): void {
595 + set_transient(self::REFRESH_BACKOFF, time(), self::REFRESH_BACKOFF_TTL);
596 + }
597 +
598 + /**
434 599 * Test all Google API connections
435 600 * Following ThinkRank test_connection patterns
436 601 *
437 602 * @return array Connection test results
@@ -502,8 +667,10 @@
502 667 * Combines data from all Google APIs with caching
503 668 *
504 669 * @param string $date_range Date range for data
505 670 * @return array Dashboard data
671 + *
672 + * @throws \Exception On failure.
506 673 */
507 674 public function get_dashboard_data(string $date_range = '30d'): array {
508 675 $cache_key = "analytics_dashboard_v5_{$date_range}";
509 676 $cached_data = get_transient($cache_key);
@@ -543,10 +710,8 @@
543 710 // 401s are re-thrown so the token-refresh retry below runs.
544 711 if ($this->analytics_client) {
545 712 try {
546 713 $dashboard_data['traffic'] = $this->analytics_client->get_traffic_data($date_range);
547 - $dashboard_data['organic_traffic'] = $this->analytics_client->get_organic_traffic($date_range);
548 - $dashboard_data['top_pages'] = $this->analytics_client->get_top_pages(10, $date_range);
549 714 } catch (\Exception $ga_error) {
550 715 if ($ga_error->getCode() === 401) {
551 716 throw $ga_error;
552 717 }
@@ -604,10 +769,8 @@
604 769 $dashboard_data['search_performance'] = array_merge($search_performance, [
605 770 'totals' => $totals,
606 771 'position_distribution' => $position_distribution
607 772 ]);
608 -
609 - $dashboard_data['page_performance'] = $this->search_console_client->get_page_performance($site_url, $date_range, 10);
610 773 } // Closing Search Console block
611 774
612 775 // If successful, break loop
613 776 break;
@@ -757,9 +920,9 @@
757 920 * @var array|null
758 921 */
759 922 private ?array $merged_settings = null;
760 923
761 - private function get_setting(string $key, $default = '') {
924 + private function get_setting(string $key, $fallback = '') {
762 925 if ($this->merged_settings === null) {
763 926 // Merge settings to allow access to both categories. Memoized:
764 927 // this getter is called many times per request and each category
765 928 // read decrypts every sensitive option again.
@@ -768,9 +931,9 @@
768 931 $this->settings_manager->get_settings('seo_analytics')
769 932 );
770 933 }
771 934
772 - return $this->merged_settings[$key] ?? $default;
935 + return $this->merged_settings[$key] ?? $fallback;
773 936 }
774 937
775 938 /**
776 939 * One-click setup for Google Search Console verification
@@ -805,44 +968,8 @@
805 968 }
806 969 }
807 970
808 971 /**
809 - * Get site indexing status
810 - *
811 - * @return array Indexing status data
812 - */
813 - public function get_indexing_status(): array {
814 - $cache_key = 'indexing_status';
815 - $cached_data = get_transient($cache_key);
816 -
817 - if ($cached_data !== false) {
818 - return $cached_data;
819 - }
820 -
821 - $indexing_data = [
822 - 'status' => 'unknown',
823 - 'last_updated' => current_time('mysql')
824 - ];
825 -
826 - try {
827 - if ($this->search_console_client) {
828 - $site_url = $this->get_setting('search_console_property', get_site_url());
829 - $indexing_data = $this->search_console_client->get_indexing_status($site_url);
830 - }
831 - } catch (\Exception $e) {
832 - $indexing_data['error'] = $e->getMessage();
833 - }
834 -
835 - // Cache successful results for 1 hour. Errors are never cached, so a
836 - // transient Google failure isn't served as "no data" for a full hour.
837 - if (empty($indexing_data['error'])) {
838 - set_transient($cache_key, $indexing_data, 3600);
839 - }
840 -
841 - return $indexing_data;
842 - }
843 -
844 - /**
845 972 * Force refresh of all cached data
846 973 *
847 974 * @return array Refresh results
848 975 */
@@ -859,11 +986,8 @@
859 986 'analytics_dashboard_v5_180d',
860 987 'seo_opportunities_7d',
861 988 'seo_opportunities_30d',
862 989 'seo_opportunities_90d',
863 - 'seo_insights_7d',
864 - 'seo_insights_30d',
865 - 'seo_insights_90d',
866 990 'indexing_status',
867 991 'thinkrank_dashboard_cwv'
868 992 ];
869 993
@@ -931,411 +1055,6 @@
931 1055 */
932 1056 public function cleanup_cache(): void {
933 1057 // WordPress handles transient cleanup automatically
934 1058 // This method is for future custom cache cleanup if needed
935 - }
936 -
937 - // ========================================
938 - // SEO Intelligence Enhancement Methods
939 - // ========================================
940 -
941 - /**
942 - * Get intelligent dashboard data with trends and insights
943 - *
944 - * @param string $date_range Date range for analysis
945 - * @return array Enhanced dashboard data with intelligence
946 - */
947 - public function get_intelligent_dashboard_data(string $date_range = '30d'): array {
948 - // Get base dashboard data
949 - $dashboard_data = $this->get_dashboard_data($date_range);
950 -
951 - // Check if there's an error in the data
952 - if (isset($dashboard_data['error'])) {
953 - return [
954 - 'success' => false,
955 - 'data' => null,
956 - 'message' => 'Failed to retrieve dashboard data: ' . $dashboard_data['error'],
957 - 'timestamp' => current_time('mysql')
958 - ];
959 - }
960 -
961 - // Check if we have real data available
962 - if (!$this->has_real_data($dashboard_data)) {
963 - return [
964 - 'success' => false,
965 - 'data' => null,
966 - 'message' => 'No analytics data available yet. Please ensure your Google Analytics and Search Console are properly configured and have collected data.',
967 - 'timestamp' => current_time('mysql')
968 - ];
969 - }
970 -
971 - // Intelligence engine is a Pro-only feature. The four SEO_* classes ship
972 - // in Free too (the PSR-4 autoloader would resolve them), so class_exists()
973 - // can't gate this — check the real Pro signal instead.
974 - if (!Plan_Config::is_pro()) {
975 - return [
976 - 'success' => false,
977 - 'data' => null,
978 - 'message' => 'Intelligent dashboard requires ThinkRank Pro.',
979 - 'timestamp' => current_time('mysql')
980 - ];
981 - }
982 -
983 - $trend_analyzer = new SEO_Trend_Analyzer();
984 - $scoring_engine = new SEO_Scoring_Engine();
985 - $insight_generator = new SEO_Insight_Generator();
986 -
987 - $data = $dashboard_data;
988 -
989 - // Generate trend analysis
990 - $current_data = $data;
991 - $historical_data = $this->get_historical_data($date_range);
992 -
993 - $trends = [
994 - 'traffic_trends' => $trend_analyzer->analyze_traffic_trends($current_data, $historical_data),
995 - 'keyword_trends' => $trend_analyzer->analyze_keyword_trends($data['search_performance'] ?? [], $date_range),
996 - 'content_trends' => $trend_analyzer->analyze_content_trends($data, $data['search_performance'] ?? [])
997 - ];
998 -
999 - // Calculate SEO health score
1000 - $seo_health = $scoring_engine->calculate_seo_health_score($data, $data['search_performance'] ?? []);
1001 -
1002 - // Generate insights
1003 - $insights = [
1004 - 'traffic_insights' => $insight_generator->generate_traffic_insights($trends['traffic_trends']),
1005 - 'keyword_insights' => $insight_generator->generate_keyword_insights($trends['keyword_trends']),
1006 - 'content_insights' => $insight_generator->generate_content_insights($trends['content_trends'])
1007 - ];
1008 -
1009 - // Combine all intelligence data
1010 - $enhanced_data = array_merge($data, [
1011 - 'intelligence' => [
1012 - 'trends' => $trends,
1013 - 'seo_health_score' => $seo_health,
1014 - 'insights' => $insights,
1015 - 'last_analyzed' => current_time('mysql')
1016 - ]
1017 - ]);
1018 -
1019 - return [
1020 - 'success' => true,
1021 - 'data' => $enhanced_data,
1022 - 'message' => 'Intelligent dashboard data retrieved successfully'
1023 - ];
1024 - }
1025 -
1026 - /**
1027 - * Get intelligent SEO opportunities with prioritization
1028 - *
1029 - * @param string $date_range Date range for analysis
1030 - * @return array Enhanced opportunities with intelligence
1031 - */
1032 - public function get_intelligent_seo_opportunities(string $date_range = '30d'): array {
1033 - // Get base opportunities data
1034 - $opportunities_data = $this->get_seo_opportunities($date_range);
1035 -
1036 - // Check if there's an error in the data
1037 - if (isset($opportunities_data['error'])) {
1038 - return [
1039 - 'success' => false,
1040 - 'data' => null,
1041 - 'message' => 'Failed to retrieve opportunities data: ' . $opportunities_data['error'],
1042 - 'timestamp' => current_time('mysql')
1043 - ];
1044 - }
1045 -
1046 - // The opportunities payload itself has no search_performance key — that
1047 - // data lives in the (cached) dashboard payload. Pull it from there both
1048 - // for the availability check and as input for the opportunity detectors;
1049 - // checking $opportunities_data['search_performance'] here used to make
1050 - // this method always bail with "No Search Console data available".
1051 - $dashboard_data = $this->get_dashboard_data($date_range);
1052 - $search_performance = $dashboard_data['search_performance'] ?? [];
1053 - $opportunities_data['search_performance'] = $search_performance;
1054 -
1055 - $has_search_data = !empty($search_performance['rows']) ||
1056 - ($search_performance['total_clicks'] ?? 0) > 0 ||
1057 - ($search_performance['total_impressions'] ?? 0) > 0;
1058 -
1059 - if (!$has_search_data) {
1060 - return [
1061 - 'success' => false,
1062 - 'data' => null,
1063 - 'message' => 'No Search Console data available yet. Please ensure your Search Console is properly configured and has collected data.',
1064 - 'timestamp' => current_time('mysql')
1065 - ];
1066 - }
1067 -
1068 - // Intelligence engine is a Pro-only feature — gate on the real Pro signal,
1069 - // not class_exists() (the classes ship in Free and would autoload).
1070 - if (!Plan_Config::is_pro()) {
1071 - return [
1072 - 'success' => false,
1073 - 'data' => null,
1074 - 'message' => 'Intelligent opportunities require ThinkRank Pro.',
1075 - 'timestamp' => current_time('mysql')
1076 - ];
1077 - }
1078 -
1079 - $opportunity_detector = new SEO_Opportunity_Detector();
1080 - $scoring_engine = new SEO_Scoring_Engine();
1081 -
1082 - $data = $opportunities_data;
1083 -
1084 - // Detect intelligent opportunities
1085 - $search_console_data = $data['search_performance'] ?? [];
1086 - $analytics_data = $data;
1087 -
1088 - $intelligent_opportunities = [
1089 - 'quick_wins' => $opportunity_detector->detect_quick_wins($search_console_data, $analytics_data),
1090 - 'content_opportunities' => $opportunity_detector->identify_content_opportunities($search_console_data, $analytics_data),
1091 - 'keyword_opportunities' => $scoring_engine->score_keyword_opportunities($search_console_data)
1092 - ];
1093 -
1094 - // Prioritize all opportunities. prioritize_opportunities() expects
1095 - // category => [opportunities]; calculate_impact_effort_matrix() expects a flat list.
1096 - $opportunities_by_category = [
1097 - 'quick_wins' => $intelligent_opportunities['quick_wins']['opportunities'] ?? [],
1098 - 'content' => $intelligent_opportunities['content_opportunities']['opportunities'] ?? [],
1099 - 'keywords' => $intelligent_opportunities['keyword_opportunities']['opportunities'] ?? [],
1100 - ];
1101 - $all_opportunities = array_merge(...array_values($opportunities_by_category));
1102 -
1103 - $prioritized = $opportunity_detector->prioritize_opportunities($opportunities_by_category);
1104 - $impact_matrix = $opportunity_detector->calculate_impact_effort_matrix($all_opportunities);
1105 -
1106 - // Enhance original data with intelligence
1107 - $enhanced_data = array_merge($data, [
1108 - 'intelligent_opportunities' => $intelligent_opportunities,
1109 - 'prioritized_opportunities' => $prioritized,
1110 - 'impact_effort_matrix' => $impact_matrix,
1111 - 'opportunity_summary' => $this->generate_opportunity_summary($intelligent_opportunities),
1112 - 'last_analyzed' => current_time('mysql')
1113 - ]);
1114 -
1115 - return [
1116 - 'success' => true,
1117 - 'data' => $enhanced_data,
1118 - 'message' => 'Intelligent SEO opportunities retrieved successfully'
1119 - ];
1120 - }
1121 -
1122 - /**
1123 - * Get SEO performance insights
1124 - *
1125 - * @param string $date_range Date range for analysis
1126 - * @return array SEO insights data
1127 - */
1128 - public function get_seo_insights(string $date_range = '30d'): array {
1129 - $cache_key = "seo_insights_{$date_range}";
1130 - $cached_data = get_transient($cache_key);
1131 -
1132 - if ($cached_data !== false) {
1133 - return [
1134 - 'success' => true,
1135 - 'data' => $cached_data,
1136 - 'cached' => true,
1137 - 'message' => 'SEO insights retrieved from cache'
1138 - ];
1139 - }
1140 -
1141 - try {
1142 - // Get dashboard data for analysis
1143 - $dashboard_result = $this->get_intelligent_dashboard_data($date_range);
1144 -
1145 - if (!$dashboard_result['success']) {
1146 - return $dashboard_result;
1147 - }
1148 -
1149 - $dashboard_data = $dashboard_result['data'];
1150 - $intelligence = $dashboard_data['intelligence'] ?? [];
1151 -
1152 - // Insights are a Pro-only feature — gate on the real Pro signal,
1153 - // not class_exists() (SEO_Insight_Generator ships in Free too).
1154 - if (!Plan_Config::is_pro()) {
1155 - return [
1156 - 'success' => false,
1157 - 'data' => null,
1158 - 'message' => 'SEO insights require ThinkRank Pro.',
1159 - 'timestamp' => current_time('mysql')
1160 - ];
1161 - }
1162 -
1163 - $insight_generator = new SEO_Insight_Generator();
1164 -
1165 - // Collect all insights
1166 - $all_insights = [];
1167 -
1168 - if (!empty($intelligence['insights']['traffic_insights']['insights'])) {
1169 - $all_insights = array_merge($all_insights, $intelligence['insights']['traffic_insights']['insights']);
1170 - }
1171 -
1172 - if (!empty($intelligence['insights']['keyword_insights']['insights'])) {
1173 - $all_insights = array_merge($all_insights, $intelligence['insights']['keyword_insights']['insights']);
1174 - }
1175 -
1176 - if (!empty($intelligence['insights']['content_insights']['insights'])) {
1177 - $all_insights = array_merge($all_insights, $intelligence['insights']['content_insights']['insights']);
1178 - }
1179 -
1180 - // Format and prioritize insights
1181 - $formatted_insights = $insight_generator->format_insights_for_display($all_insights);
1182 - $prioritized_insights = $insight_generator->prioritize_insights_by_impact($formatted_insights);
1183 -
1184 - $insights_data = [
1185 - 'insights' => $prioritized_insights['prioritized_insights'],
1186 - 'summary' => [
1187 - 'total_insights' => count($formatted_insights),
1188 - 'high_impact_count' => $prioritized_insights['high_impact_count'],
1189 - 'action_required_count' => $prioritized_insights['action_required_count']
1190 - ],
1191 - 'seo_health_score' => $intelligence['seo_health_score'] ?? null,
1192 - 'generated_at' => current_time('mysql')
1193 - ];
1194 -
1195 - // Cache the results
1196 - set_transient($cache_key, $insights_data, $this->cache_duration);
1197 -
1198 - return [
1199 - 'success' => true,
1200 - 'data' => $insights_data,
1201 - 'cached' => false,
1202 - 'message' => 'SEO insights generated successfully'
1203 - ];
1204 - } catch (\Exception $e) {
1205 - return [
1206 - 'success' => false,
1207 - 'error' => 'Failed to generate SEO insights: ' . $e->getMessage(),
1208 - 'data' => null
1209 - ];
1210 - }
1211 - }
1212 -
1213 - /**
1214 - * Check if real analytics data is available
1215 - *
1216 - * @param array $dashboard_data Dashboard data to check
1217 - * @return bool True if real data is available
1218 - */
1219 - private function has_real_data(array $dashboard_data): bool {
1220 - // Check if we have meaningful traffic data
1221 - $traffic = $dashboard_data['traffic'] ?? [];
1222 - $search_performance = $dashboard_data['search_performance'] ?? [];
1223 -
1224 - $has_traffic = !empty($traffic) && (
1225 - ($traffic['sessions'] ?? 0) > 0 ||
1226 - ($traffic['pageviews'] ?? 0) > 0 ||
1227 - ($traffic['active_users'] ?? 0) > 0
1228 - );
1229 -
1230 - $has_search_data = !empty($search_performance) && (
1231 - !empty($search_performance['rows']) ||
1232 - ($search_performance['total_clicks'] ?? 0) > 0 ||
1233 - ($search_performance['total_impressions'] ?? 0) > 0
1234 - );
1235 -
1236 - return $has_traffic || $has_search_data;
1237 - }
1238 -
1239 - /**
1240 - * Get historical data for trend comparison
1241 - *
1242 - * @param string $current_range Current date range
1243 - * @return array Historical data
1244 - */
1245 - private function get_historical_data(string $current_range): array {
1246 - // Calculate previous period based on current range
1247 - $previous_range = $this->calculate_previous_period($current_range);
1248 -
1249 - // Try to get actual historical data from previous period
1250 - $historical_data = $this->get_dashboard_data($previous_range);
1251 -
1252 - // Return the actual historical data (may be empty if no real data available)
1253 - return [
1254 - 'sessions' => $historical_data['traffic']['sessions'] ?? 0,
1255 - 'pageviews' => $historical_data['traffic']['pageviews'] ?? 0,
1256 - 'organic_traffic' => $historical_data['organic_traffic'] ?? ['organic_traffic' => ['sessions' => 0]],
1257 - 'bounce_rate' => $historical_data['traffic']['bounce_rate'] ?? 0,
1258 - 'avg_session_duration' => $historical_data['traffic']['avg_session_duration'] ?? 0
1259 - ];
1260 - }
1261 -
1262 - /**
1263 - * Calculate previous period for comparison
1264 - *
1265 - * @param string $current_range Current range
1266 - * @return string Previous period range
1267 - */
1268 - private function calculate_previous_period(string $current_range): string {
1269 - // Simple mapping for now - could be enhanced with actual date calculations
1270 - $period_mapping = [
1271 - '7d' => '14d',
1272 - '30d' => '60d',
1273 - '90d' => '180d'
1274 - ];
1275 -
1276 - return $period_mapping[$current_range] ?? '60d';
1277 - }
1278 -
1279 - /**
1280 - * Generate opportunity summary
1281 - *
1282 - * @param array $opportunities All opportunities
1283 - * @return array Opportunity summary
1284 - */
1285 - private function generate_opportunity_summary(array $opportunities): array {
1286 - $quick_wins_count = count($opportunities['quick_wins']['opportunities'] ?? []);
1287 - $content_opportunities_count = count($opportunities['content_opportunities']['opportunities'] ?? []);
1288 - $keyword_opportunities_count = count($opportunities['keyword_opportunities']['opportunities'] ?? []);
1289 -
1290 - $total_opportunities = $quick_wins_count + $content_opportunities_count + $keyword_opportunities_count;
1291 -
1292 - $potential_clicks = 0;
1293 - if (!empty($opportunities['quick_wins']['potential_additional_clicks'])) {
1294 - $potential_clicks = $opportunities['quick_wins']['potential_additional_clicks'];
1295 - }
1296 -
1297 - return [
1298 - 'total_opportunities' => $total_opportunities,
1299 - 'quick_wins_count' => $quick_wins_count,
1300 - 'content_opportunities_count' => $content_opportunities_count,
1301 - 'keyword_opportunities_count' => $keyword_opportunities_count,
1302 - 'potential_additional_clicks' => $potential_clicks,
1303 - 'priority_recommendation' => $quick_wins_count > 0 ?
1304 - 'Focus on quick wins first for immediate impact' :
1305 - 'Focus on content optimization for long-term growth'
1306 - ];
1307 - }
1308 -
1309 - /**
1310 - * Clear intelligence cache
1311 - *
1312 - * @return array Clear result
1313 - */
1314 - public function clear_intelligence_cache(): array {
1315 - $intelligence_cache_keys = [
1316 - 'seo_insights_7d',
1317 - 'seo_insights_30d',
1318 - 'seo_insights_90d',
1319 - 'intelligent_dashboard_7d',
1320 - 'intelligent_dashboard_30d',
1321 - 'intelligent_dashboard_90d',
1322 - 'intelligent_opportunities_7d',
1323 - 'intelligent_opportunities_30d',
1324 - 'intelligent_opportunities_90d'
1325 - ];
1326 -
1327 - $cleared = 0;
1328 - foreach ($intelligence_cache_keys as $key) {
1329 - if (delete_transient($key)) {
1330 - $cleared++;
1331 - }
1332 - }
1333 -
1334 - return [
1335 - 'success' => true,
1336 - 'message' => "Cleared {$cleared} intelligence cache entries",
1337 - 'cleared_count' => $cleared,
1338 - 'timestamp' => current_time('mysql')
1339 - ];
1340 1059 }
1341 1060 }