host => label */ public static function assistants(): array { /** * Filter the AI assistant referrer hosts. * * @param array $hosts host => label. */ return (array) apply_filters( 'airanksuite/analytics/assistant_hosts', array( 'chatgpt.com' => 'ChatGPT', 'chat.openai.com' => 'ChatGPT', 'openai.com' => 'OpenAI', 'perplexity.ai' => 'Perplexity', 'claude.ai' => 'Claude', 'gemini.google.com' => 'Gemini', 'bard.google.com' => 'Gemini', 'copilot.microsoft.com' => 'Copilot', 'bing.com/chat' => 'Copilot', 'you.com' => 'You.com', 'poe.com' => 'Poe', 'phind.com' => 'Phind', 'grok.com' => 'Grok', 'x.ai' => 'Grok', 'mistral.ai' => 'Le Chat', 'deepseek.com' => 'DeepSeek', 'kagi.com' => 'Kagi', 'arc.net' => 'Arc Search', ) ); } /** @return array */ public static function defaults(): array { return array( 'matomo_enabled' => false, 'matomo_url' => '', // https://analytics.example.com or Matomo Cloud URL. 'matomo_site_id' => 0, 'matomo_track' => false, // Inject the tracking snippet. 'matomo_cookieless' => true, ); } public function __construct( private Options $options ) {} /** @return array */ private function settings(): array { return $this->options->get( 'analytics', array() ) + self::defaults(); } public function save_token( string $token ): void { $token = trim( $token ); if ( '' === $token ) { delete_option( self::TOKEN ); return; } update_option( self::TOKEN, Secret::encrypt( $token ), false ); } public function has_token(): bool { return '' !== $this->token(); } public function token_hint(): string { $token = $this->token(); return '' === $token ? '' : str_repeat( '•', 6 ) . substr( $token, -4 ); } private function token(): string { $stored = get_option( self::TOKEN, '' ); if ( ! is_string( $stored ) || '' === $stored ) { return ''; } $token = Secret::decrypt( $stored ); return is_string( $token ) ? $token : ''; } /** Base URL with a single trailing slash and no index.php. */ private function base(): string { $url = trim( (string) $this->settings()['matomo_url'] ); $url = (string) preg_replace( '#/index\.php.*$#', '', $url ); return '' === $url ? '' : trailingslashit( $url ); } public function is_configured(): bool { return '' !== $this->base() && (int) $this->settings()['matomo_site_id'] > 0 && $this->has_token(); } /** * Call the Reporting API. * * POST, not GET: the auth token must not end up in the server access log * of every hop between here and the Matomo instance, and Matomo has * recommended POST for token_auth for years. * * @param array $args Extra API parameters. * @return array|WP_Error */ private function call( string $method, array $args = array() ): array|WP_Error { if ( ! $this->is_configured() ) { return new WP_Error( 'airanksuite_matomo_unconfigured', __( 'Matomo is not set up: it needs the URL, the site ID and an API token.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $settings = $this->settings(); $response = wp_remote_post( $this->base() . 'index.php', array( 'timeout' => 25, 'body' => array_merge( array( 'module' => 'API', 'method' => $method, 'idSite' => (int) $settings['matomo_site_id'], 'format' => 'JSON', 'token_auth' => $this->token(), ), $args ), ) ); if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( $code >= 400 ) { return new WP_Error( 'airanksuite_matomo_http', sprintf( /* translators: %d: HTTP status code. */ __( 'Matomo answered with HTTP %d.', 'ai-rank-suite' ), $code ), array( 'status' => 502 ) ); } // Matomo signals errors inside a 200 response, which is why a status // check alone is not enough. if ( is_array( $body ) && 'error' === ( $body['result'] ?? '' ) ) { return new WP_Error( 'airanksuite_matomo_api', (string) ( $body['message'] ?? __( 'Matomo rejected the request.', 'ai-rank-suite' ) ), array( 'status' => 400 ) ); } if ( ! is_array( $body ) ) { return new WP_Error( 'airanksuite_matomo_shape', __( 'Matomo returned something that is not JSON. Check the URL points at the Matomo root.', 'ai-rank-suite' ), array( 'status' => 502 ) ); } return $body; } /** * Confirm the credentials against the site they claim to describe. * * @return array|WP_Error */ public function verify(): array|WP_Error { $site = $this->call( 'SitesManager.getSiteFromId' ); if ( $site instanceof WP_Error ) { return $site; } return array( 'name' => (string) ( $site['name'] ?? '' ), 'main_url' => (string) ( $site['main_url'] ?? '' ), 'timezone' => (string) ( $site['timezone'] ?? '' ), 'currency' => (string) ( $site['currency'] ?? '' ), // A Matomo site pointed at a different domain is the single most // common misconfiguration, and it produces a report full of // somebody else's traffic rather than an error. 'matches' => self::same_host( (string) ( $site['main_url'] ?? '' ), home_url( '/' ) ), ); } private static function same_host( string $a, string $b ): bool { $ha = strtolower( (string) preg_replace( '/^www\./i', '', (string) wp_parse_url( $a, PHP_URL_HOST ) ) ); $hb = strtolower( (string) preg_replace( '/^www\./i', '', (string) wp_parse_url( $b, PHP_URL_HOST ) ) ); return '' !== $ha && $ha === $hb; } /** * The report: totals, the daily series, top pages, and the AI split. * * @return array|WP_Error */ public function report( int $days = 30 ): array|WP_Error { $days = max( 1, min( 365, $days ) ); $period = 'last' . $days; $totals = $this->call( 'VisitsSummary.get', array( 'period' => 'range', 'date' => 'last' . $days ) ); if ( $totals instanceof WP_Error ) { return $totals; } $series = $this->call( 'VisitsSummary.getVisits', array( 'period' => 'day', 'date' => $period ) ); $pages = $this->call( 'Actions.getPageUrls', array( 'period' => 'range', 'date' => 'last' . $days, 'flat' => 1, 'filter_limit' => 15 ) ); $referrers = $this->call( 'Referrers.getWebsites', array( 'period' => 'range', 'date' => 'last' . $days, 'filter_limit' => 200 ) ); $channels = $this->call( 'Referrers.getReferrerType', array( 'period' => 'range', 'date' => 'last' . $days ) ); return array( 'totals' => array( 'visits' => (int) ( $totals['nb_visits'] ?? 0 ), 'visitors' => (int) ( $totals['nb_uniq_visitors'] ?? $totals['nb_visits'] ?? 0 ), 'actions' => (int) ( $totals['nb_actions'] ?? 0 ), 'bounce' => (int) ( $totals['bounce_rate'] ?? 0 ), 'seconds' => (int) ( $totals['avg_time_on_site'] ?? 0 ), ), 'series' => $series instanceof WP_Error ? array() : self::series( (array) $series ), 'pages' => $pages instanceof WP_Error ? array() : self::pages( (array) $pages ), 'channels' => $channels instanceof WP_Error ? array() : self::channels( (array) $channels ), 'assistants' => $referrers instanceof WP_Error ? array() : self::assistant_split( (array) $referrers ), 'days' => $days, ); } /** * @param array $raw Matomo day => visits. * @return array> */ private static function series( array $raw ): array { $out = array(); foreach ( $raw as $date => $visits ) { $out[] = array( 'date' => (string) $date, 'value' => (int) $visits, ); } return $out; } /** * @param array $raw Matomo rows. * @return array> */ private static function pages( array $raw ): array { $out = array(); foreach ( $raw as $row ) { if ( ! is_array( $row ) ) { continue; } $out[] = array( 'path' => (string) ( $row['label'] ?? '' ), 'views' => (int) ( $row['nb_hits'] ?? 0 ), 'visits' => (int) ( $row['nb_visits'] ?? 0 ), 'url' => (string) ( $row['url'] ?? '' ), ); } return $out; } /** * @param array $raw Matomo rows. * @return array> */ private static function channels( array $raw ): array { $out = array(); foreach ( $raw as $row ) { if ( ! is_array( $row ) ) { continue; } $out[] = array( 'label' => (string) ( $row['label'] ?? '' ), 'visits' => (int) ( $row['nb_visits'] ?? 0 ), ); } usort( $out, static fn( $a, $b ) => $b['visits'] <=> $a['visits'] ); return $out; } /** * Pull the AI assistants out of the referring-website list. * * This is the number the whole plugin exists to move. It is reported as a * count of real visits from a named assistant, with the rest of the * referrer traffic beside it for scale — a bare "42 visits from ChatGPT" * means nothing without knowing whether the site had 200 visits or 200,000. * * @param array $raw Matomo referrer rows. * @return array */ private static function assistant_split( array $raw ): array { $hosts = self::assistants(); $by = array(); $ai = 0; $other = 0; foreach ( $raw as $row ) { if ( ! is_array( $row ) ) { continue; } $label = strtolower( (string) ( $row['label'] ?? '' ) ); $visits = (int) ( $row['nb_visits'] ?? 0 ); $matched = null; foreach ( $hosts as $host => $name ) { if ( $label === $host || str_ends_with( $label, '.' . $host ) || str_contains( $label, $host ) ) { $matched = $name; break; } } if ( null === $matched ) { $other += $visits; continue; } $by[ $matched ] = ( $by[ $matched ] ?? 0 ) + $visits; $ai += $visits; } arsort( $by ); $rows = array(); foreach ( $by as $name => $visits ) { $rows[] = array( 'name' => $name, 'visits' => $visits ); } return array( 'total' => $ai, 'other' => $other, 'share' => $ai + $other > 0 ? round( ( $ai / ( $ai + $other ) ) * 100, 1 ) : 0.0, 'engines' => $rows, ); } /** * The tracking snippet. * * Cookieless by default: Matomo can measure without setting a cookie, and * a site that chose Matomo over Google Analytics has usually chosen it for * exactly that reason. Do Not Track is honoured server-side by Matomo's own * setting; the snippet does not pretend to make that decision here. */ public function snippet(): string { $settings = $this->settings(); if ( empty( $settings['matomo_track'] ) || '' === $this->base() || (int) $settings['matomo_site_id'] < 1 ) { return ''; } // JSON is the escaping for a value that lands in a script: both arrive // as complete JavaScript literals, quotes included. $url = wp_json_encode( esc_url_raw( $this->base() ) ); $id = wp_json_encode( (string) (int) $settings['matomo_site_id'] ); $cookieless = ! empty( $settings['matomo_cookieless'] ) ? "_paq.push(['disableCookies']);\n" : ''; // The body only. The