15 ] ); if ( is_wp_error( $response ) ) { return null; } return json_decode( wp_remote_retrieve_body( $response ), true ); } private function api_get( $endpoint, $args = [] ) { return self::api_call( $endpoint, $this->get_api_key(), $args ); } /** * Bing returns dates as legacy ASP.NET AJAX strings, e.g. * "/Date(1316156400000-0700)/". The numeric portion is already a * UTC millisecond epoch, so we can parse it directly into Y-m-d. */ private static function parse_bing_date( $value ) { if ( ! $value || ! preg_match( '/-?\d+/', $value, $m ) ) { return ''; } return gmdate( 'Y-m-d', intdiv( (int) $m[0], 1000 ) ); } /** * Reshapes a raw Bing row ({Query|PageURL, Clicks, Impressions, * AvgClickPosition, Date, ...}) into the same shape AWBSEO_GSC rows * use ({keys, clicks, impressions, ctr, position}) so dashboard * rendering code can treat both sources identically. Bing has no * native CTR field, so it's derived from clicks / impressions. */ private static function normalize_rows( $rows, $key_field ) { if ( ! is_array( $rows ) ) { return []; } $out = []; foreach ( $rows as $row ) { $clicks = (int) ( $row['Clicks'] ?? 0 ); $impressions = (int) ( $row['Impressions'] ?? 0 ); $out[] = [ 'keys' => [ $row[ $key_field ] ?? '' ], 'clicks' => $clicks, 'impressions' => $impressions, 'position' => (float) ( $row['AvgClickPosition'] ?? $row['AvgImpressionPosition'] ?? 0 ), 'ctr' => $impressions > 0 ? $clicks / $impressions : 0, 'date' => self::parse_bing_date( $row['Date'] ?? '' ), ]; } return $out; } /** * Resolves a requested range into concrete start/end dates - mirrors * AWBSEO_GSC::resolve_range() so the dashboard's date picker works the * same way against both sources. Bing has no fixed reporting lag, so * $end just clamps to today. * * @return array [ $start, $end, $days ] */ private function resolve_range( $days = 28, $start = null, $end = null ) { $today = gmdate( 'Y-m-d' ); if ( $start && $end ) { $end = min( $end, $today ); if ( $start > $end ) $start = $end; $days = max( 1, (int) ( ( strtotime( $end ) - strtotime( $start ) ) / DAY_IN_SECONDS ) + 1 ); return [ $start, $end, $days ]; } $days = max( 1, (int) $days ); return [ gmdate( 'Y-m-d', strtotime( "-{$days} days" ) ), $today, $days ]; } /** * Bing's GetQueryStats/GetPageStats return one row per key per date * rather than a single date-ranged total, so we fetch everything Bing * has, drop rows outside the requested window, then group by key and * sum. Note: Bing's own data refreshes weekly, not daily like GSC. */ private function get_aggregated( $endpoint, $key_field, $days, $limit, $cache_prefix, $start = null, $end = null ) { $property = $this->get_property(); if ( ! $property ) { return []; } list( $start, $end, $days ) = $this->resolve_range( $days, $start, $end ); $cache_key = $cache_prefix . md5( $property . '_' . $start . '_' . $end . '_' . $limit ); $cached = get_transient( $cache_key ); if ( false !== $cached ) { return $cached; } $data = $this->api_get( $endpoint, [ 'siteUrl' => $property ] ); $rows = self::normalize_rows( $data['d'] ?? [], $key_field ); $rows = array_filter( $rows, function ( $row ) use ( $start, $end ) { return $row['date'] >= $start && $row['date'] <= $end; } ); $grouped = []; foreach ( $rows as $row ) { $key = $row['keys'][0]; if ( ! isset( $grouped[ $key ] ) ) { $grouped[ $key ] = [ 'keys' => [ $key ], 'clicks' => 0, 'impressions' => 0, 'position_sum' => 0, 'position_n' => 0, ]; } $grouped[ $key ]['clicks'] += $row['clicks']; $grouped[ $key ]['impressions'] += $row['impressions']; $grouped[ $key ]['position_sum'] += $row['position']; $grouped[ $key ]['position_n']++; } $result = []; foreach ( $grouped as $g ) { $result[] = [ 'keys' => $g['keys'], 'clicks' => $g['clicks'], 'impressions' => $g['impressions'], 'position' => $g['position_n'] ? $g['position_sum'] / $g['position_n'] : 0, 'ctr' => $g['impressions'] > 0 ? $g['clicks'] / $g['impressions'] : 0, ]; } usort( $result, function ( $a, $b ) { return $b['clicks'] <=> $a['clicks']; } ); $result = array_slice( $result, 0, $limit ); set_transient( $cache_key, $result, HOUR_IN_SECONDS ); return $result; } /** * Top queries by clicks over the last N days - mirrors * AWBSEO_GSC::get_top_queries(). FREE. */ public function get_top_queries( $days = 28, $limit = 10, $start = null, $end = null ) { return $this->get_aggregated( 'GetQueryStats', 'Query', $days, $limit, 'awbseo_bing_top_queries_', $start, $end ); } /** * Top pages by clicks over the last N days - mirrors * AWBSEO_GSC::get_top_pages(). FREE. */ public function get_top_pages( $days = 28, $limit = 10, $start = null, $end = null ) { return $this->get_aggregated( 'GetPageStats', 'PageURL', $days, $limit, 'awbseo_bing_top_pages_', $start, $end ); } /** * Daily clicks/impressions series for the last N days, plus the prior * N-day window's totals for period-over-period deltas - mirrors * AWBSEO_GSC::get_site_stats() so the dashboard can reuse the same * rendering code for both sources. Built from page-level stats since * that's the closest thing Bing offers to a site-wide breakdown. * Note: Bing updates this data weekly, so day-to-day movement within * the series will look "steppy" compared to GSC's daily granularity. */ public function get_site_stats( $days = 28, $start = null, $end = null ) { $property = $this->get_property(); if ( ! $property ) { return null; } list( $start, $end, $days ) = $this->resolve_range( $days, $start, $end ); $cache_key = 'awbseo_bing_site_stats_' . md5( $property . '_' . $start . '_' . $end ); $cached = get_transient( $cache_key ); if ( false !== $cached ) { return $cached; } $data = $this->api_get( 'GetPageStats', [ 'siteUrl' => $property ] ); $rows = self::normalize_rows( $data['d'] ?? [], 'PageURL' ); $prev_end = gmdate( 'Y-m-d', strtotime( $start . ' -1 day' ) ); $prev_start = gmdate( 'Y-m-d', strtotime( $prev_end . " -{$days} days" ) ); $by_date = []; $prev_clicks = 0; $prev_impr = 0; $prev_ctr_sum = 0; $prev_pos_sum = 0; $prev_days = 0; foreach ( $rows as $row ) { if ( ! $row['date'] ) { continue; } if ( $row['date'] >= $start && $row['date'] <= $end ) { if ( ! isset( $by_date[ $row['date'] ] ) ) { $by_date[ $row['date'] ] = [ 'clicks' => 0, 'impressions' => 0, 'position_sum' => 0, 'position_n' => 0 ]; } $by_date[ $row['date'] ]['clicks'] += $row['clicks']; $by_date[ $row['date'] ]['impressions'] += $row['impressions']; $by_date[ $row['date'] ]['position_sum'] += $row['position']; $by_date[ $row['date'] ]['position_n']++; } elseif ( $row['date'] >= $prev_start && $row['date'] <= $prev_end ) { $prev_clicks += $row['clicks']; $prev_impr += $row['impressions']; $prev_ctr_sum += $row['impressions'] > 0 ? $row['clicks'] / $row['impressions'] : 0; $prev_pos_sum += $row['position']; $prev_days++; } } ksort( $by_date ); $daily = []; foreach ( $by_date as $date => $vals ) { $daily[] = [ 'keys' => [ $date ], 'clicks' => $vals['clicks'], 'impressions' => $vals['impressions'], 'position' => $vals['position_n'] ? $vals['position_sum'] / $vals['position_n'] : 0, 'ctr' => $vals['impressions'] > 0 ? $vals['clicks'] / $vals['impressions'] : 0, ]; } $result = [ 'daily' => $daily, 'prev_sum' => [ 'clicks' => $prev_clicks, 'impressions' => $prev_impr, 'ctr' => $prev_days ? round( ( $prev_ctr_sum / $prev_days ) * 100, 1 ) : 0, 'position' => $prev_days ? round( $prev_pos_sum / $prev_days, 1 ) : 0, ], ]; set_transient( $cache_key, $result, HOUR_IN_SECONDS ); return $result; } /** * Deletes all cached Bing API results from the options table. * Called on connect and disconnect so stale cached data is cleared. */ public static function flush_transients() { global $wpdb; $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_awbseo\_bing\_%' OR option_name LIKE '\_transient\_timeout\_awbseo\_bing\_%'" ); } }