key(); } public function key_hint(): ?string { $key = $this->key(); return null === $key ? null : '••••' . substr( $key, -4 ); } private function key(): ?string { $stored = get_option( self::OPT_KEY ); if ( ! is_string( $stored ) || '' === $stored ) { return null; } $key = Secret::decrypt( $stored ); return is_string( $key ) && '' !== $key ? $key : null; } /** * The site URL Bing knows this site by. Bing matches on the exact * registered spelling, so the stored home URL is normalised once here * rather than in four call sites. */ private function site(): string { return untrailingslashit( (string) home_url() ); } /** * One API call. * * @param array $args Query arguments besides the key. * @return array|WP_Error */ private function call( string $method, array $args = array(), string $verb = 'GET', ?array $body = null ): array|WP_Error { $key = $this->key(); if ( null === $key ) { return new WP_Error( 'airanksuite_bing_no_key', __( 'No Bing Webmaster API key stored. Add one under Indexing → Bing.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $url = add_query_arg( array_merge( array( 'apikey' => $key ), $args ), self::ENDPOINT . $method ); $options = array( 'timeout' => 25, 'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ), ); $response = 'POST' === $verb ? wp_remote_post( $url, array_merge( $options, array( 'body' => wp_json_encode( $body ?? array() ) ) ) ) : wp_remote_get( $url, $options ); if ( $response instanceof WP_Error ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $data = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( $code >= 400 || ! is_array( $data ) ) { // Bing returns its errors inside a 200 as often as not, so both // shapes are unwrapped here rather than at each call site. $message = is_array( $data ) ? (string) ( $data['Message'] ?? $data['ErrorCode'] ?? '' ) : ''; return new WP_Error( 'airanksuite_bing_http', '' !== $message ? $message /* translators: %d: HTTP status code. */ : sprintf( __( 'Bing Webmaster Tools returned HTTP %d.', 'ai-rank-suite' ), $code ), array( 'status' => 502 ) ); } if ( isset( $data['ErrorCode'] ) && 0 !== (int) $data['ErrorCode'] ) { return new WP_Error( 'airanksuite_bing_api', (string) ( $data['Message'] ?? __( 'Bing rejected the request.', 'ai-rank-suite' ) ), array( 'status' => 502 ) ); } return $data; } /** * Verify the key by asking for the sites it can see — the cheapest call * that proves both the key and the site registration. * * @return array|WP_Error */ public function verify(): array|WP_Error { $data = $this->call( 'GetUserSites' ); if ( $data instanceof WP_Error ) { return $data; } $sites = array(); foreach ( (array) ( $data['d'] ?? array() ) as $site ) { $url = (string) ( $site['Url'] ?? '' ); if ( '' !== $url ) { $sites[] = untrailingslashit( $url ); } } return array( 'ok' => true, 'sites' => $sites, // A key that works but does not list this site is the failure mode // people actually hit, and it looks identical to success unless we // say so. 'registered' => in_array( $this->site(), $sites, true ), 'site' => $this->site(), ); } /** * Clicks, impressions and average position, newest day first. * * @return array|WP_Error */ public function stats( bool $refresh = false ): array|WP_Error { $cache_key = self::CACHE . 'stats'; if ( ! $refresh ) { $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } } $data = $this->call( 'GetRankAndTrafficStats', array( 'siteUrl' => $this->site() ) ); if ( $data instanceof WP_Error ) { return $data; } $rows = array(); foreach ( (array) ( $data['d'] ?? array() ) as $row ) { $rows[] = array( 'date' => self::date( (string) ( $row['Date'] ?? '' ) ), 'clicks' => (int) ( $row['Clicks'] ?? 0 ), 'impressions' => (int) ( $row['Impressions'] ?? 0 ), 'position' => (float) ( $row['AvgImpressionPosition'] ?? 0 ), 'crawled' => (int) ( $row['CrawledPages'] ?? 0 ), 'indexed' => (int) ( $row['InIndex'] ?? 0 ), ); } // Bing returns oldest-first; every chart in the product reads // newest-last, so normalise here rather than in the component. usort( $rows, static fn( array $a, array $b ): int => strcmp( $a['date'], $b['date'] ) ); $clicks = array_sum( array_column( $rows, 'clicks' ) ); $impressions = array_sum( array_column( $rows, 'impressions' ) ); $result = array( 'rows' => $rows, 'clicks' => $clicks, 'impressions' => $impressions, 'ctr' => $impressions > 0 ? round( ( $clicks / $impressions ) * 100, 2 ) : 0.0, 'indexed' => (int) ( end( $rows )['indexed'] ?? 0 ), 'fetched_at' => time(), ); set_transient( $cache_key, $result, 6 * HOUR_IN_SECONDS ); return $result; } /** * The queries Bing already shows this site for. * * @return array|WP_Error */ public function keywords( bool $refresh = false ): array|WP_Error { $cache_key = self::CACHE . 'kw'; if ( ! $refresh ) { $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } } $data = $this->call( 'GetQueryStats', array( 'siteUrl' => $this->site() ) ); if ( $data instanceof WP_Error ) { return $data; } $rows = array(); foreach ( (array) ( $data['d'] ?? array() ) as $row ) { $query = trim( (string) ( $row['Query'] ?? '' ) ); if ( '' === $query ) { continue; } $rows[] = array( 'query' => $query, 'clicks' => (int) ( $row['Clicks'] ?? 0 ), 'impressions' => (int) ( $row['Impressions'] ?? 0 ), 'position' => (float) ( $row['AvgImpressionPosition'] ?? 0 ), ); } usort( $rows, static fn( array $a, array $b ): int => $b['impressions'] <=> $a['impressions'] ); $rows = array_slice( $rows, 0, 200 ); $result = array( 'rows' => $rows, 'fetched_at' => time(), ); set_transient( $cache_key, $result, 6 * HOUR_IN_SECONDS ); return $result; } /** * How many URLs may still be submitted today. * * @return array|WP_Error */ public function quota(): array|WP_Error { $data = $this->call( 'GetUrlSubmissionQuota', array( 'siteUrl' => $this->site() ) ); if ( $data instanceof WP_Error ) { return $data; } $quota = (array) ( $data['d'] ?? array() ); return array( 'daily' => (int) ( $quota['DailyQuota'] ?? 0 ), 'monthly' => (int) ( $quota['MonthlyQuota'] ?? 0 ), ); } /** * Push URLs straight into the index. * * @param list $urls URLs on this site. * @return array|WP_Error */ public function submit( array $urls ): array|WP_Error { $home = untrailingslashit( (string) home_url() ); $clean = array(); foreach ( $urls as $url ) { $url = esc_url_raw( trim( (string) $url ) ); // Submitting a URL on somebody else's domain is both useless and a // good way to get the key suspended. if ( '' !== $url && 0 === strpos( $url, $home ) ) { $clean[] = $url; } } $clean = array_values( array_unique( $clean ) ); if ( empty( $clean ) ) { return new WP_Error( 'airanksuite_bing_no_urls', __( 'No submittable URLs — every URL must be on this site.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } // Bing accepts 500 per call; the daily quota is usually far lower, so // the cap here is about the request, not about the allowance. $clean = array_slice( $clean, 0, 500 ); $data = $this->call( 'SubmitUrlBatch', array(), 'POST', array( 'siteUrl' => $this->site(), 'urlList' => $clean, ) ); if ( $data instanceof WP_Error ) { return $data; } return array( 'submitted' => count( $clean ), 'urls' => $clean, ); } /** * Bing dates arrive as /Date(1699920000000)/ or as ISO. Both become Y-m-d. */ private static function date( string $raw ): string { if ( preg_match( '#/Date\((\d+)#', $raw, $m ) ) { return gmdate( 'Y-m-d', (int) ( (int) $m[1] / 1000 ) ); } $time = strtotime( $raw ); return false !== $time ? gmdate( 'Y-m-d', $time ) : ''; } }