400 ) ); } $state = wp_generate_password( 40, false ); set_transient( self::OPT_STATE, $state, 10 * MINUTE_IN_SECONDS ); return $base . '/start?' . http_build_query( array( 'state' => $state, 'return' => $this->redirect_uri(), 'site' => home_url( '/' ), 'v' => defined( 'AIRANKSUITE_VERSION' ) ? AIRANKSUITE_VERSION : '', ) ); } /** * Step 3: the browser is back with a one-time handoff id. Claim the tokens * server-to-server — they never travel through the browser — and store * them exactly as an own-credentials connection would. */ public function proxy_claim( string $handoff, string $state ): bool|WP_Error { $expected = (string) get_transient( self::OPT_STATE ); delete_transient( self::OPT_STATE ); if ( '' === $expected || ! hash_equals( $expected, $state ) ) { return new WP_Error( 'airanksuite_gsc_state', __( 'Sign-in state mismatch — please try again.', 'ai-rank-suite' ) ); } $handoff = preg_replace( '/[^A-Za-z0-9_\-]/', '', $handoff ) ?? ''; if ( '' === $handoff ) { return new WP_Error( 'airanksuite_gsc_handoff', __( 'The sign-in did not complete.', 'ai-rank-suite' ) ); } $response = wp_remote_post( self::proxy_url() . '/claim', array( 'timeout' => 15, 'body' => array( 'handoff' => $handoff, 'state' => $state, 'site' => home_url( '/' ) ), ) ); $stored = $this->store_token_response( $response, null ); if ( true === $stored ) { update_option( self::OPT_MODE, 'proxy', false ); } return $stored; } /** * Persist OAuth client credentials (secret encrypted). */ public function save_credentials( string $client_id, string $client_secret ): void { update_option( self::OPT_CREDS, array( 'client_id' => sanitize_text_field( $client_id ), 'client_secret' => Secret::encrypt( sanitize_text_field( $client_secret ) ), ), false ); } /** @return array{client_id: string, client_secret: string}|null */ private function credentials(): ?array { $stored = get_option( self::OPT_CREDS ); if ( ! is_array( $stored ) || empty( $stored['client_id'] ) || empty( $stored['client_secret'] ) ) { return null; } $secret = Secret::decrypt( (string) $stored['client_secret'] ); if ( null === $secret ) { return null; } return array( 'client_id' => (string) $stored['client_id'], 'client_secret' => $secret, ); } public function has_credentials(): bool { return null !== $this->credentials(); } public function connected(): bool { // A proxy connection has tokens but no customer-side credentials. return is_array( get_option( self::OPT_TOKENS ) ) && ( 'proxy' === $this->mode() || $this->has_credentials() ); } public function property(): string { return (string) get_option( self::OPT_SITE, '' ); } public function set_property( string $site ): void { update_option( self::OPT_SITE, sanitize_text_field( $site ), false ); $this->clear_report_cache(); } /** * OAuth consent URL (state = nonce, verified in callback). */ public function auth_url(): string|WP_Error { $creds = $this->credentials(); if ( null === $creds ) { return new WP_Error( 'airanksuite_gsc_no_credentials', __( 'Save your Google OAuth credentials first.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $args = array( 'client_id' => $creds['client_id'], 'redirect_uri' => $this->redirect_uri(), 'response_type' => 'code', 'scope' => self::SCOPE, 'access_type' => 'offline', 'prompt' => 'consent', 'state' => wp_create_nonce( 'airanksuite_gsc_oauth' ), ); return 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query( $args ); } /** * Exchange the authorization code (admin-post callback). */ public function handle_callback( string $code, string $state ): bool|WP_Error { if ( ! wp_verify_nonce( $state, 'airanksuite_gsc_oauth' ) ) { return new WP_Error( 'airanksuite_gsc_state', __( 'OAuth state mismatch — please retry the connection.', 'ai-rank-suite' ) ); } $creds = $this->credentials(); if ( null === $creds ) { return new WP_Error( 'airanksuite_gsc_no_credentials', __( 'Missing credentials.', 'ai-rank-suite' ) ); } $response = wp_remote_post( 'https://oauth2.googleapis.com/token', array( 'timeout' => 15, 'body' => array( 'code' => $code, 'client_id' => $creds['client_id'], 'client_secret' => $creds['client_secret'], 'redirect_uri' => $this->redirect_uri(), 'grant_type' => 'authorization_code', ), ) ); $stored = $this->store_token_response( $response, null ); if ( true === $stored ) { update_option( self::OPT_MODE, 'own', false ); } return $stored; } /** * Valid access token (refreshes when expired). */ private function access_token(): string|WP_Error { $tokens = get_option( self::OPT_TOKENS ); if ( ! is_array( $tokens ) || empty( $tokens['access_token'] ) ) { return new WP_Error( 'airanksuite_gsc_not_connected', __( 'Search Console is not connected.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } if ( time() < (int) ( $tokens['expires_at'] ?? 0 ) - 60 ) { $token = Secret::decrypt( (string) $tokens['access_token'] ); if ( null !== $token ) { return $token; } } // Refresh. $refresh = isset( $tokens['refresh_token'] ) ? Secret::decrypt( (string) $tokens['refresh_token'] ) : null; if ( null === $refresh ) { return new WP_Error( 'airanksuite_gsc_refresh_failed', __( 'Reconnect Search Console — the stored token can no longer be refreshed.', 'ai-rank-suite' ), array( 'status' => 401 ) ); } if ( 'proxy' === $this->mode() && self::proxy_available() ) { // The refresh grant needs the client secret, which lives with the // connect service — so the service performs it and returns the new // access token; the refresh token itself never leaves this site // except to that one endpoint over TLS. $response = wp_remote_post( self::proxy_url() . '/refresh', array( 'timeout' => 15, 'body' => array( 'refresh_token' => $refresh, 'site' => home_url( '/' ) ), ) ); } else { $creds = $this->credentials(); if ( null === $creds ) { return new WP_Error( 'airanksuite_gsc_refresh_failed', __( 'Reconnect Search Console — the stored token can no longer be refreshed.', 'ai-rank-suite' ), array( 'status' => 401 ) ); } $response = wp_remote_post( 'https://oauth2.googleapis.com/token', array( 'timeout' => 15, 'body' => array( 'client_id' => $creds['client_id'], 'client_secret' => $creds['client_secret'], 'refresh_token' => $refresh, 'grant_type' => 'refresh_token', ), ) ); } $stored = $this->store_token_response( $response, $refresh ); if ( $stored instanceof WP_Error ) { return $stored; } $tokens = get_option( self::OPT_TOKENS ); $token = is_array( $tokens ) ? Secret::decrypt( (string) $tokens['access_token'] ) : null; return null === $token ? new WP_Error( 'airanksuite_gsc_token', __( 'Token decryption failed.', 'ai-rank-suite' ) ) : $token; } /** * @param array|WP_Error $response HTTP response. * @param string|null $known_refresh Existing refresh token to keep when Google omits it. */ private function store_token_response( $response, ?string $known_refresh ): bool|WP_Error { if ( $response instanceof WP_Error ) { return $response; } $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $body ) || empty( $body['access_token'] ) ) { $msg = is_array( $body ) && isset( $body['error_description'] ) ? (string) $body['error_description'] : __( 'Google did not return a token.', 'ai-rank-suite' ); return new WP_Error( 'airanksuite_gsc_token_error', $msg ); } /* * An empty refresh_token in the response is not a rotation. * * Google omits the field on a renewal, so `?? $known_refresh` was * right for the absent case — but a present-and-empty value slipped * past it and would overwrite the token we still need, killing the * connection on the first renewal instead of the fiftieth. */ $sent = isset( $body['refresh_token'] ) ? trim( (string) $body['refresh_token'] ) : ''; $refresh = '' !== $sent ? $sent : (string) ( $known_refresh ?? '' ); update_option( self::OPT_TOKENS, array( 'access_token' => Secret::encrypt( (string) $body['access_token'] ), 'refresh_token' => '' !== $refresh ? Secret::encrypt( $refresh ) : '', 'expires_at' => time() + (int) ( $body['expires_in'] ?? 3600 ), ), false ); return true; } /** * After a successful sign-in, pick the accounts that belong to this site. * * The person who clicked "Sign in with Google" has, on average, one site * and no idea what a "property" is. Their Search Console account knows the * answer: find the property whose host is this site's host (a domain * property beats a URL-prefix one, because it covers every variant), and * the GA4 property whose web stream points at this site — which also * yields the measurement id, so tracking can start without a single id * being copied out of another tab. * * Everything here is best-effort: whatever cannot be matched stays * unset and the screens offer the manual dropdown exactly as before. * * @return array{property: string, ga4_property: string, ga4_measurement: string} */ public function auto_configure(): array { $picked = array( 'property' => '', 'ga4_property' => '', 'ga4_measurement' => '', ); $host = strtolower( (string) wp_parse_url( home_url( '/' ), PHP_URL_HOST ) ); $bare = preg_replace( '/^www\./', '', $host ) ?? $host; // --- Search Console ------------------------------------------------- $sites = $this->sites(); if ( is_array( $sites ) && '' === $this->property() ) { $best = ''; foreach ( $sites as $site ) { if ( str_starts_with( $site, 'sc-domain:' ) ) { $site_host = strtolower( substr( $site, 10 ) ); if ( $site_host === $bare ) { $best = $site; // A domain property covers every variant — take it and stop. break; } } else { $site_host = strtolower( (string) wp_parse_url( $site, PHP_URL_HOST ) ); if ( '' === $best && in_array( $site_host, array( $host, 'www.' . $bare, $bare ), true ) ) { $best = $site; } } } if ( '' !== $best ) { $this->set_property( $best ); } } $picked['property'] = $this->property(); // --- GA4 ------------------------------------------------------------ $summaries = $this->get( 'https://analyticsadmin.googleapis.com/v1beta/accountSummaries?pageSize=200' ); if ( ! ( $summaries instanceof WP_Error ) ) { $properties = array(); foreach ( (array) ( $summaries['accountSummaries'] ?? array() ) as $account ) { foreach ( (array) ( $account['propertySummaries'] ?? array() ) as $property ) { $name = (string) ( $property['property'] ?? '' ); if ( '' === $name ) { continue; } $properties[ $name ] = (string) ( $property['displayName'] ?? '' ); } } /* * Ask the likely ones first. * * Only the data streams say which site a property measures, and * that is one API call per property. A real account has dozens — * the first one tested here had fifty-five — so walking the list * in Google's order and stopping after twenty would have missed * the right property on the very account it was built for. * * The display name is a strong hint, because people name a * property after the site: "setupco" for setupco.ae. Sort by how * well the name matches this host, then spend the call budget on * the top of that list. */ $needle = preg_replace( '/\.[a-z.]+$/', '', $bare ) ?? $bare; // setupco.ae → setupco uasort( $properties, static function ( string $a, string $b ) use ( $bare, $needle ): int { $score = static function ( string $label ) use ( $bare, $needle ): int { $label = strtolower( trim( $label ) ); if ( '' === $label ) { return 0; } if ( $label === $bare || $label === $needle ) { return 3; } if ( str_contains( $label, $bare ) ) { return 2; } if ( '' !== $needle && str_contains( $label, $needle ) ) { return 1; } return 0; }; return $score( $b ) <=> $score( $a ); } ); foreach ( array_slice( array_keys( $properties ), 0, 25 ) as $property_name ) { $streams = $this->get( 'https://analyticsadmin.googleapis.com/v1beta/' . $property_name . '/dataStreams?pageSize=50' ); if ( $streams instanceof WP_Error ) { break; // One denial means they all fail — stop asking. } foreach ( (array) ( $streams['dataStreams'] ?? array() ) as $stream ) { $uri = (string) ( $stream['webStreamData']['defaultUri'] ?? '' ); if ( '' === $uri ) { continue; } $stream_host = strtolower( (string) wp_parse_url( $uri, PHP_URL_HOST ) ); if ( in_array( $stream_host, array( $host, 'www.' . $bare, $bare ), true ) ) { $picked['ga4_property'] = (string) str_replace( 'properties/', '', $property_name ); $picked['ga4_measurement'] = (string) ( $stream['webStreamData']['measurementId'] ?? '' ); break 2; } } } if ( '' !== $picked['ga4_property'] ) { $options = \AiRankSuite\Kernel::service( \AiRankSuite\Support\Options::class ); $settings = $options->get( 'analytics', \AiRankSuite\Modules\Analytics\AnalyticsModule::defaults() ); if ( '' === trim( (string) ( $settings['property_id'] ?? '' ) ) ) { $settings['property_id'] = $picked['ga4_property']; if ( '' === trim( (string) ( $settings['measurement_id'] ?? '' ) ) && '' !== $picked['ga4_measurement'] ) { $settings['measurement_id'] = $picked['ga4_measurement']; } $options->set( 'analytics', $settings, \AiRankSuite\Modules\Analytics\AnalyticsModule::defaults() ); } } } return $picked; } public function disconnect(): void { delete_option( self::OPT_TOKENS ); delete_option( self::OPT_SITE ); delete_option( self::OPT_MODE ); $this->clear_report_cache(); } /** * Verified properties of the connected account. * * @return array|WP_Error */ public function sites(): array|WP_Error { $data = $this->api_get( 'https://www.googleapis.com/webmasters/v3/sites' ); if ( $data instanceof WP_Error ) { return $data; } $sites = array(); foreach ( (array) ( $data['siteEntry'] ?? array() ) as $entry ) { if ( in_array( $entry['permissionLevel'] ?? '', array( 'siteOwner', 'siteFullUser', 'siteRestrictedUser' ), true ) ) { $sites[] = (string) $entry['siteUrl']; } } sort( $sites ); return $sites; } /** * Search Analytics report (cached 6h). * * @return array|WP_Error */ public function performance( int $days = 28 ): array|WP_Error { $site = $this->property(); if ( '' === $site ) { return new WP_Error( 'airanksuite_gsc_no_property', __( 'Select a Search Console property first.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $cache_key = 'airanksuite_gsc_report_' . md5( $site . '|' . $days ); $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } $end = gmdate( 'Y-m-d', time() - 2 * DAY_IN_SECONDS ); // GSC data lags ~2 days. $start = gmdate( 'Y-m-d', time() - ( $days + 2 ) * DAY_IN_SECONDS ); $by_date = $this->query( $site, $start, $end, array( 'date' ), 1000 ); if ( $by_date instanceof WP_Error ) { return $by_date; } // Enough rows for the segments below to mean something. Ten is a // leaderboard; five hundred is a data set you can find a pattern in, // and Search Console returns it in the same single request. $queries = $this->query( $site, $start, $end, array( 'query' ), 500 ); $pages = $this->query( $site, $start, $end, array( 'page' ), 250 ); // The same length of period immediately before this one, so every // number on the screen can carry a direction rather than a level. $prev_end = gmdate( 'Y-m-d', strtotime( $start . ' -1 day' ) ); $prev_start = gmdate( 'Y-m-d', strtotime( $start . ' -' . $days . ' day' ) ); $prev_pages = $this->query( $site, $prev_start, $prev_end, array( 'page' ), 250 ); $prev_total = $this->query( $site, $prev_start, $prev_end, array( 'date' ), 1000 ); $series = array(); $totals = array( 'clicks' => 0, 'impressions' => 0, 'ctr' => 0.0, 'position' => 0.0, ); $rows = (array) ( $by_date['rows'] ?? array() ); foreach ( $rows as $row ) { $series[] = array( 'date' => (string) ( $row['keys'][0] ?? '' ), 'clicks' => (int) ( $row['clicks'] ?? 0 ), 'impressions' => (int) ( $row['impressions'] ?? 0 ), ); $totals['clicks'] += (int) ( $row['clicks'] ?? 0 ); $totals['impressions'] += (int) ( $row['impressions'] ?? 0 ); $totals['position'] += (float) ( $row['position'] ?? 0 ); } $count = max( 1, count( $rows ) ); $totals['position'] = round( $totals['position'] / $count, 1 ); $totals['ctr'] = $totals['impressions'] > 0 ? round( 100 * $totals['clicks'] / $totals['impressions'], 2 ) : 0.0; $query_rows = $this->rows( $queries ); $page_rows = $this->rows( $pages ); // Previous-period totals, for the deltas on the KPI tiles. $before = array( 'clicks' => 0, 'impressions' => 0, 'position' => 0.0 ); $prev_rows = ( $prev_total instanceof WP_Error ) ? array() : (array) ( $prev_total['rows'] ?? array() ); foreach ( $prev_rows as $row ) { $before['clicks'] += (int) ( $row['clicks'] ?? 0 ); $before['impressions'] += (int) ( $row['impressions'] ?? 0 ); $before['position'] += (float) ( $row['position'] ?? 0 ); } $before['position'] = count( $prev_rows ) > 0 ? round( $before['position'] / count( $prev_rows ), 1 ) : 0.0; $before['ctr'] = $before['impressions'] > 0 ? round( 100 * $before['clicks'] / $before['impressions'], 2 ) : 0.0; $report = array( 'site' => $site, 'days' => $days, 'from' => $start, 'to' => $end, 'totals' => $totals, 'previous' => $before, 'series' => $series, 'queries' => array_slice( $query_rows, 0, 100 ), 'pages' => array_slice( $page_rows, 0, 100 ), // The four questions the raw numbers cannot answer on their own. 'questions' => Insights::questions( $query_rows ), 'striking' => Insights::striking( $query_rows ), 'ignored' => Insights::ignored( $page_rows ), 'movement' => Insights::movement( $page_rows, $this->rows( $prev_pages ) ), 'sampled' => array( 'queries' => count( $query_rows ), 'pages' => count( $page_rows ), ), ); set_transient( $cache_key, $report, 6 * HOUR_IN_SECONDS ); return $report; } public function clear_report_cache(): void { foreach ( array( 7, 28, 90 ) as $days ) { delete_transient( 'airanksuite_gsc_report_' . md5( $this->property() . '|' . $days ) ); } } /** * @param array|WP_Error $result Query result. * @return array> */ private function rows( $result ): array { if ( $result instanceof WP_Error || ! is_array( $result ) ) { return array(); } $out = array(); foreach ( (array) ( $result['rows'] ?? array() ) as $row ) { $out[] = array( 'key' => (string) ( $row['keys'][0] ?? '' ), 'clicks' => (int) ( $row['clicks'] ?? 0 ), 'impressions' => (int) ( $row['impressions'] ?? 0 ), 'ctr' => round( 100 * (float) ( $row['ctr'] ?? 0 ), 2 ), 'position' => round( (float) ( $row['position'] ?? 0 ), 1 ), ); } return $out; } /** * Public wrapper so other modules (rank tracker, reports) can query too. * * @param array $dimensions Dimensions. * @return array|WP_Error */ public function query_range( string $site, string $start, string $end, array $dimensions, int $limit = 500 ): array|WP_Error { return $this->query( $site, $start, $end, $dimensions, $limit ); } /** * Authenticated GET against any Google API the granted scopes allow. * * @return array|WP_Error */ public function get( string $url ): array|WP_Error { return $this->api_get( $url ); } /** * Authenticated POST against any Google API the granted scopes allow. * * @param array $payload Request body. * @return array|WP_Error */ public function post( string $url, array $payload ): array|WP_Error { return $this->api_post( $url, $payload ); } /** @return array|WP_Error */ private function query( string $site, string $start, string $end, array $dimensions, int $limit ): array|WP_Error { return $this->api_post( 'https://www.googleapis.com/webmasters/v3/sites/' . rawurlencode( $site ) . '/searchAnalytics/query', array( 'startDate' => $start, 'endDate' => $end, 'dimensions' => $dimensions, 'rowLimit' => $limit, ) ); } /** @return array|WP_Error */ private function api_get( string $url ): array|WP_Error { return $this->api( 'GET', $url, null ); } /** @return array|WP_Error */ private function api_post( string $url, array $payload ): array|WP_Error { return $this->api( 'POST', $url, $payload ); } /** @return array|WP_Error */ private function api( string $method, string $url, ?array $payload ): array|WP_Error { $token = $this->access_token(); if ( $token instanceof WP_Error ) { return $token; } $args = array( 'method' => $method, 'timeout' => 20, 'headers' => array( 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', ), ); if ( null !== $payload ) { $args['body'] = wp_json_encode( $payload ); } $response = wp_remote_request( $url, $args ); if ( $response instanceof WP_Error ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( $code >= 400 || ! is_array( $body ) ) { $msg = is_array( $body ) && isset( $body['error']['message'] ) ? (string) $body['error']['message'] : sprintf( 'Google API error (HTTP %d).', $code ); return new WP_Error( 'airanksuite_gsc_api_error', $msg, array( 'status' => 502 ) ); } return $body; } }