has_license_key(); } public function has_license_key() { return '' !== $this->license_key(); } public function api_key() { return $this->license_key(); } public function license_key() { $license_key = (string) get_option(self::LICENSE_OPTION, ''); return trim((string) apply_filters('aiseo_ai_engine_license_key', $license_key)); } public function endpoint() { $endpoint = defined('AISEO_AUDITOR_API_ENDPOINT') ? AISEO_AUDITOR_API_ENDPOINT : self::ENDPOINT; return esc_url_raw((string) apply_filters('aiseo_ai_engine_endpoint', $endpoint)); } public function model() { return apply_filters('aiseo_ai_engine_model_label', self::MODEL); } public function ai_profile() { $profile = 'professional'; $profile = (string) apply_filters('aiseo_ai_engine_profile', $profile); return $this->normalize_ai_profile($profile); } public function analyze(array $page_payload) { $license_key = $this->license_key(); if ('' === $license_key) { return new WP_Error( 'aiseo_missing_license_key', __('AiVisibility site ID is missing. Reactivate the plugin before running AI analysis.', 'aivisibility-seo-geo-agent') ); } $profile = $this->ai_profile(); $profile_config = $this->profile_config($profile); $timeout = max(30, (int) apply_filters('aiseo_ai_engine_timeout', $profile_config['timeout'], $profile)); $this->maybe_extend_execution_time($timeout); $request_payload = $this->prepare_payload_for_profile($page_payload, $profile); $request_body = array( 'license_key' => $license_key, 'site' => array( 'home_url' => home_url('/'), 'site_url' => site_url('/'), 'admin_email' => get_option('admin_email'), 'language' => get_locale(), ), 'plugin' => array( 'name' => defined('AISEO_AUDITOR_NAME') ? AISEO_AUDITOR_NAME : 'AiVisibility', 'version' => defined('AISEO_AUDITOR_VERSION') ? AISEO_AUDITOR_VERSION : '', ), 'ai_profile' => $profile, 'page_payload' => $request_payload, ); $response = wp_remote_post( $this->endpoint(), array( 'timeout' => $timeout, 'redirection' => 3, 'headers' => array( 'Authorization' => 'Bearer ' . $license_key, 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-AiVisibility-License' => $license_key, 'X-AiVisibility-Site' => home_url('/'), 'User-Agent' => (defined('AISEO_AUDITOR_NAME') ? AISEO_AUDITOR_NAME : 'AiVisibility') . '/' . (defined('AISEO_AUDITOR_VERSION') ? AISEO_AUDITOR_VERSION : '') . '; ' . home_url('/'), ), 'body' => wp_json_encode($request_body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ) ); if (is_wp_error($response)) { return $this->format_transport_error($response, $timeout); } $status_code = (int) wp_remote_retrieve_response_code($response); $body = (string) wp_remote_retrieve_body($response); $decoded = json_decode($body, true); if ($status_code < 200 || $status_code >= 300) { $message = $this->response_error_message($decoded, $body); if (is_array($decoded)) { $this->maybe_store_remaining_requests($decoded); } if ($this->is_wrong_license_error($status_code, $message)) { return $this->wrong_license_error(); } if ($this->is_no_requests_error($status_code, $message)) { return $this->no_requests_error(); } return new WP_Error( 'aiseo_ai_engine_http_error', sprintf(__('AiVisibility API returned HTTP %1$d: %2$s', 'aivisibility-seo-geo-agent'), $status_code, $message) ); } if (!is_array($decoded)) { return new WP_Error( 'aiseo_ai_engine_bad_json', __('AiVisibility API response was not valid JSON.', 'aivisibility-seo-geo-agent') ); } if (isset($decoded['success']) && false === (bool) $decoded['success']) { $message = $this->response_error_message($decoded, $body); $this->maybe_store_remaining_requests($decoded); if ($this->is_wrong_license_error($status_code, $message)) { return $this->wrong_license_error(); } if ($this->is_no_requests_error($status_code, $message)) { return $this->no_requests_error(); } return new WP_Error( 'aiseo_ai_engine_error', $message ); } $this->maybe_store_remaining_requests($decoded); $report = $this->extract_report($decoded); if (!is_array($report)) { return new WP_Error( 'aiseo_ai_engine_missing_report', __('AiVisibility API response did not include a valid SEO-GEO report.', 'aivisibility-seo-geo-agent') ); } $page_url = isset($request_payload['page']['url']) && is_string($request_payload['page']['url']) ? trim($request_payload['page']['url']) : ''; $report = $this->normalize_report($report, $page_url); $report['ai_execution'] = isset($decoded['ai_execution']) && is_array($decoded['ai_execution']) ? $decoded['ai_execution'] : array(); $report['ai_execution'] = array_merge( array( 'profile' => $profile, 'endpoint' => $this->endpoint(), 'model' => isset($decoded['model']) && is_string($decoded['model']) ? $decoded['model'] : $this->model(), 'timeout' => $timeout, ), $report['ai_execution'] ); return $report; } public function autofill_strategy(array $page_payload) { $license_key = $this->license_key(); if ('' === $license_key) { return new WP_Error( 'aiseo_missing_license_key', __('AiVisibility site ID is missing. Reactivate the plugin before using AI strategy fill.', 'aivisibility-seo-geo-agent') ); } $profile = $this->ai_profile(); $profile_config = $this->profile_config($profile); $timeout = max(30, (int) apply_filters('aiseo_ai_engine_timeout', $profile_config['timeout'], $profile)); $this->maybe_extend_execution_time($timeout); $request_payload = $this->prepare_payload_for_profile($page_payload, $profile); $request_body = array( 'task' => 'strategy_autofill', 'license_key' => $license_key, 'site' => array( 'home_url' => home_url('/'), 'site_url' => site_url('/'), 'admin_email' => get_option('admin_email'), 'language' => get_locale(), ), 'plugin' => array( 'name' => defined('AISEO_AUDITOR_NAME') ? AISEO_AUDITOR_NAME : 'AiVisibility', 'version' => defined('AISEO_AUDITOR_VERSION') ? AISEO_AUDITOR_VERSION : '', ), 'ai_profile' => $profile, 'page_payload' => $request_payload, ); $response = wp_remote_post( $this->endpoint(), array( 'timeout' => $timeout, 'redirection' => 3, 'headers' => array( 'Authorization' => 'Bearer ' . $license_key, 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-AiVisibility-License' => $license_key, 'X-AiVisibility-Site' => home_url('/'), 'User-Agent' => (defined('AISEO_AUDITOR_NAME') ? AISEO_AUDITOR_NAME : 'AiVisibility') . '/' . (defined('AISEO_AUDITOR_VERSION') ? AISEO_AUDITOR_VERSION : '') . '; ' . home_url('/'), ), 'body' => wp_json_encode($request_body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ) ); if (is_wp_error($response)) { return $this->format_transport_error($response, $timeout); } $status_code = (int) wp_remote_retrieve_response_code($response); $body = (string) wp_remote_retrieve_body($response); $decoded = json_decode($body, true); if ($status_code < 200 || $status_code >= 300) { $message = $this->response_error_message($decoded, $body); if (is_array($decoded)) { $this->maybe_store_remaining_requests($decoded); } if ($this->is_wrong_license_error($status_code, $message)) { return $this->wrong_license_error(); } if ($this->is_no_requests_error($status_code, $message)) { return $this->no_requests_error(); } return new WP_Error( 'aiseo_ai_engine_http_error', sprintf(__('AiVisibility API returned HTTP %1$d: %2$s', 'aivisibility-seo-geo-agent'), $status_code, $message) ); } if (!is_array($decoded)) { return new WP_Error( 'aiseo_ai_engine_bad_json', __('AiVisibility API response was not valid JSON.', 'aivisibility-seo-geo-agent') ); } if (isset($decoded['success']) && false === (bool) $decoded['success']) { $message = $this->response_error_message($decoded, $body); $this->maybe_store_remaining_requests($decoded); if ($this->is_wrong_license_error($status_code, $message)) { return $this->wrong_license_error(); } if ($this->is_no_requests_error($status_code, $message)) { return $this->no_requests_error(); } return new WP_Error( 'aiseo_ai_engine_error', $message ); } $this->maybe_store_remaining_requests($decoded); $strategy = null; if (isset($decoded['strategy']) && is_array($decoded['strategy'])) { $strategy = $decoded['strategy']; } elseif (isset($decoded['data']['strategy']) && is_array($decoded['data']['strategy'])) { $strategy = $decoded['data']['strategy']; } if (!is_array($strategy)) { return new WP_Error( 'aiseo_ai_engine_missing_strategy', __('AiVisibility API response did not include valid strategy autofill data.', 'aivisibility-seo-geo-agent') ); } $strategy['ai_execution'] = isset($decoded['ai_execution']) && is_array($decoded['ai_execution']) ? $decoded['ai_execution'] : array(); return $strategy; } private function extract_report(array $decoded) { if (isset($decoded['report']) && is_array($decoded['report'])) { return $decoded['report']; } if (isset($decoded['data']['report']) && is_array($decoded['data']['report'])) { return $decoded['data']['report']; } if (isset($decoded['score'])) { return $decoded; } return null; } private function response_error_message($decoded, $fallback) { if (is_array($decoded)) { foreach (array('message', 'error') as $key) { if (isset($decoded[$key]) && is_string($decoded[$key]) && '' !== trim($decoded[$key])) { return trim($decoded[$key]); } } if (isset($decoded['error']['message']) && is_string($decoded['error']['message'])) { return trim($decoded['error']['message']); } } $fallback = trim(wp_strip_all_tags((string) $fallback)); return '' !== $fallback ? $this->limit_profile_text($fallback, 900) : __('Unknown AiVisibility API error.', 'aivisibility-seo-geo-agent'); } private function no_requests_error() { update_option('aiseo_requests_remaining', 0, false); return new WP_Error('aiseo_no_requests', __('No requests', 'aivisibility-seo-geo-agent')); } private function wrong_license_error() { return new WP_Error('aiseo_wrong_license', __('Site verification failed', 'aivisibility-seo-geo-agent')); } private function is_no_requests_error($status_code, $message) { $message = (string) $message; if (402 === (int) $status_code) { return true; } if (preg_match('/no\s+(?:request\s+credits?|requests?|credits?)|request\s+credits?\s+remaining/i', $message)) { return true; } return false; } private function is_wrong_license_error($status_code, $message) { $message = (string) $message; if (in_array((int) $status_code, array(401, 403), true)) { return true; } return (bool) preg_match('/wrong\s+licen[cs]e|licen[cs]e|unauthori[sz]ed|forbidden|not\s+allowed|invalid\s+(?:api\s+)?key|missing\s+(?:api\s+)?key|HTTP\s+40[13]/i', $message); } private function maybe_store_remaining_requests(array $decoded) { $remaining = null; if (isset($decoded['remaining_requests'])) { $remaining = $decoded['remaining_requests']; } elseif (isset($decoded['data']['remaining_requests'])) { $remaining = $decoded['data']['remaining_requests']; } if (null !== $remaining && is_numeric($remaining)) { update_option('aiseo_requests_remaining', max(0, absint($remaining)), false); } } private function format_transport_error(WP_Error $error, $timeout) { $message = $error->get_error_message(); if (false !== stripos($message, 'cURL error 28') || false !== stripos($message, 'timed out')) { return new WP_Error( 'aiseo_ai_engine_timeout', sprintf( __('AiVisibility API timed out after %d seconds. The page-source scan completed, but the AI Engine reply did not finish in time.', 'aivisibility-seo-geo-agent'), (int) $timeout ) ); } return new WP_Error( 'aiseo_ai_engine_transport_error', sprintf(__('AiVisibility API request failed: %s', 'aivisibility-seo-geo-agent'), $message) ); } private function maybe_extend_execution_time($timeout) { if (function_exists('set_time_limit')) { set_time_limit(max(30, (int) $timeout) + 60); } } private function profile_config($profile) { $profiles = array( 'professional' => array( 'timeout' => 2160, ), ); return isset($profiles[$profile]) ? $profiles[$profile] : $profiles['professional']; } private function prepare_payload_for_profile(array $payload, $profile) { $payload['ai_profile'] = $profile; $limits = array('string' => 2400, 'long_string' => 5000, 'array' => 55, 'depth' => 9); return $this->compact_payload_value($payload, $limits); } private function normalize_ai_profile($profile) { $profile = (string) $profile; return 'professional'; } private function compact_payload_value($value, array $limits, $key = '', $depth = 0) { if ($depth > $limits['depth']) { return is_array($value) ? array() : $value; } if (is_string($value)) { $limit = in_array($key, array('raw_sample', 'head_html_sample', 'visible_text_sample', 'raw_content_sample', 'rendered_content_sample'), true) ? $limits['long_string'] : $limits['string']; return $this->limit_profile_text($value, $limit); } if (!is_array($value)) { return $value; } $is_list = array() === $value || array_keys($value) === range(0, count($value) - 1); $output = array(); $count = 0; foreach ($value as $child_key => $child_value) { if ($is_list && $count >= $limits['array']) { break; } $output[$child_key] = $this->compact_payload_value($child_value, $limits, is_string($child_key) ? $child_key : $key, $depth + 1); $count++; } return $output; } private function limit_profile_text($text, $limit) { $text = (string) $text; if ($limit <= 0) { return $text; } if (function_exists('mb_strlen') && function_exists('mb_substr')) { if (mb_strlen($text, 'UTF-8') <= $limit) { return $text; } return mb_substr($text, 0, $limit, 'UTF-8') . '...'; } if (strlen($text) <= $limit) { return $text; } return substr($text, 0, $limit) . '...'; } private function normalize_report(array $report, $page_url = '') { $report['score'] = isset($report['score']) ? max(0, min(100, (int) $report['score'])) : 0; $valid_scopes = array('local', 'generic', 'mixed'); if (empty($report['dominant_seo_scope']) || !in_array($report['dominant_seo_scope'], $valid_scopes, true)) { $report['dominant_seo_scope'] = 'generic'; } if (!isset($report['local_seo_relevance']) || !is_string($report['local_seo_relevance'])) { $report['local_seo_relevance'] = ''; } if (!isset($report['page_intent']) || !is_array($report['page_intent'])) { $report['page_intent'] = array(); } $report['page_intent'] = array_merge( array( 'detected_intent' => '', 'target_audience' => '', 'seo_scope' => $report['dominant_seo_scope'], 'local_seo_reason' => '', 'conversion_goal' => '', ), $report['page_intent'] ); foreach (array('priority_actions', 'checks', 'selected_keywords', 'keyword_opportunities', 'image_alt_suggestions', 'suggested_meta_tags', 'suggested_open_graph_tags', 'suggested_heading_updates') as $array_key) { if (!isset($report[$array_key]) || !is_array($report[$array_key])) { $report[$array_key] = array(); } } foreach ( array( 'suggested_title', 'suggested_meta_description', 'suggested_og_title', 'suggested_og_description', 'suggested_json_ld_type', ) as $string_key ) { if (!isset($report[$string_key]) || !is_string($report[$string_key])) { $report[$string_key] = ''; } } if (!isset($report['suggested_json_ld']) || (!is_array($report['suggested_json_ld']) && !is_string($report['suggested_json_ld']))) { $report['suggested_json_ld'] = array(); } else { $report['suggested_json_ld'] = $this->normalize_suggested_json_ld($report['suggested_json_ld'], $page_url); } foreach (array('meta_tags', 'open_graph', 'rich_results_json_ld', 'headings_content', 'image_alt_audit') as $section_key) { if (!isset($report[$section_key]) || !is_array($report[$section_key])) { $report[$section_key] = array(); } $report[$section_key] = array_merge( array( 'status' => 'not_verified', 'seo_scope' => $report['dominant_seo_scope'], 'findings' => array(), 'recommendations' => array(), ), $report[$section_key] ); if (!is_array($report[$section_key]['findings'])) { $report[$section_key]['findings'] = array(); } if (!is_array($report[$section_key]['recommendations'])) { $report[$section_key]['recommendations'] = array(); } $report[$section_key]['status'] = $this->normalize_section_status($report[$section_key]); } return $report; } private function normalize_suggested_json_ld($value, $page_url = '') { if (is_string($value)) { $value = trim($value); $value = preg_replace('/^\s*]*>/i', '', $value); $value = preg_replace('/<\/script>\s*$/i', '', $value); $value = json_decode($value, true); } if (!is_array($value) || empty($value)) { return array(); } $value = $this->normalize_schema_breadcrumbs($value, $page_url); if (!is_array($value) || empty($value)) { return array(); } if (isset($value['@graph']) && is_array($value['@graph']) && empty($value['@graph'])) { return array(); } return $value; } private function normalize_schema_breadcrumbs(array $node, $page_url = '') { $is_homepage = $this->schema_page_is_homepage($page_url); if ($this->schema_type_contains($node, 'BreadcrumbList')) { if ($is_homepage) { return null; } return $this->normalize_breadcrumb_list($node, $page_url); } if ($is_homepage && array_key_exists('breadcrumb', $node)) { unset($node['breadcrumb']); } if ($this->schema_array_is_list($node)) { $normalized = array(); foreach ($node as $item) { if (is_array($item)) { $item = $this->normalize_schema_breadcrumbs($item, $page_url); if (null === $item) { continue; } } $normalized[] = $item; } return $normalized; } foreach ($node as $key => $value) { if (!is_array($value)) { continue; } $value = $this->normalize_schema_breadcrumbs($value, $page_url); if (null === $value) { unset($node[$key]); } else { $node[$key] = $value; } } return $node; } private function schema_page_is_homepage($page_url) { return $this->normalize_schema_page_url($page_url) === $this->normalize_schema_page_url(home_url('/')); } private function normalize_schema_page_url($url) { if (!is_string($url) || '' === trim($url)) { return ''; } $parts = wp_parse_url(trim($url)); if (!is_array($parts) || empty($parts['host'])) { return ''; } $host = strtolower($parts['host']); $port = isset($parts['port']) ? ':' . (int) $parts['port'] : ''; $path = isset($parts['path']) && '' !== $parts['path'] ? '/' . ltrim($parts['path'], '/') : '/'; $path = '/' === $path ? '/' : untrailingslashit($path); return $host . $port . $path; } private function normalize_breadcrumb_list(array $node, $page_url = '') { if (empty($node['itemListElement']) || !is_array($node['itemListElement']) || !$this->schema_array_is_list($node['itemListElement'])) { return null; } $items = array_values($node['itemListElement']); $last_index = count($items) - 1; if ($last_index < 1) { return null; } foreach ($items as $index => $item) { if (!is_array($item)) { return null; } $name = isset($item['name']) && is_string($item['name']) ? trim($item['name']) : ''; $item_name = isset($item['item']) && is_array($item['item']) && isset($item['item']['name']) && is_string($item['item']['name']) ? trim($item['item']['name']) : ''; if ('' === $name && '' === $item_name) { return null; } if ('' === $name) { $item['name'] = $item_name; } $item['@type'] = 'ListItem'; $item['position'] = $index + 1; if ($index < $last_index && !$this->breadcrumb_item_has_valid_url(isset($item['item']) ? $item['item'] : null)) { return null; } if ($index === $last_index) { $page_url = is_string($page_url) ? trim($page_url) : ''; if ('' === $page_url || false === wp_http_validate_url($page_url)) { return null; } $item['item'] = $page_url; } $items[$index] = $item; } $node['itemListElement'] = $items; return $node; } private function breadcrumb_item_has_valid_url($item) { if (is_string($item)) { return false !== wp_http_validate_url(trim($item)); } if (!is_array($item)) { return false; } foreach (array('@id', 'url') as $key) { if (!empty($item[$key]) && is_string($item[$key]) && false !== wp_http_validate_url(trim($item[$key]))) { return true; } } return false; } private function schema_type_contains(array $node, $type) { if (!isset($node['@type'])) { return false; } $types = is_array($node['@type']) ? $node['@type'] : array($node['@type']); foreach ($types as $candidate) { if (is_string($candidate) && 0 === strcasecmp($candidate, $type)) { return true; } } return false; } private function schema_array_is_list(array $value) { if (function_exists('array_is_list')) { return array_is_list($value); } return array() === $value || array_keys($value) === range(0, count($value) - 1); } private function normalize_section_status(array $section) { $valid_statuses = array('pass', 'needs_work', 'critical', 'not_verified'); $status = isset($section['status']) ? sanitize_key((string) $section['status']) : 'not_verified'; if (!in_array($status, $valid_statuses, true)) { $status = 'not_verified'; } $has_findings = !empty(array_filter(isset($section['findings']) && is_array($section['findings']) ? $section['findings'] : array())); $has_recommendations = !empty(array_filter(isset($section['recommendations']) && is_array($section['recommendations']) ? $section['recommendations'] : array())); if ('not_verified' === $status && ($has_findings || $has_recommendations)) { return 'needs_work'; } if ('pass' === $status && $has_recommendations) { return 'needs_work'; } return $status; } }