client = $client; } /** * Aggregate stats across the fleet for a date range. * * @param int $start Range start (Unix timestamp). * @param int $end Range end (Unix timestamp). * @param bool $force Bypass + overwrite the cache. * @param bool $allow_remote Permit a live cross-site fan-out on a cache miss. * When false and nothing is cached, returns an * empty `deferred` shell instead of calling the * fleet (guards against untrusted requests * amplifying into an N-site HTTP sweep). * @return array{start:int,end:int,totals:array,sites:array,errors:array,generated:int,deferred?:bool} */ public function network_stats( int $start, int $end, bool $force = false, bool $allow_remote = true ): array { $cache_key = self::CACHE_PREFIX . 'stats_' . md5( $start . ':' . $end ); if ( ! $force ) { $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } } // Untrusted request with no cache to serve: return an empty shell rather // than fanning out to every managed site. if ( ! $allow_remote ) { return array( 'start' => $start, 'end' => $end, 'totals' => array( 'views' => 0, 'clicks' => 0, 'ctr' => 0.0, ), 'sites' => array(), 'series' => array(), 'errors' => array(), 'generated' => 0, 'deferred' => true, ); } $total_views = 0; $total_clicks = 0; $rows = array(); $errors = array(); $daily = array(); foreach ( $this->client->get_sites() as $site ) { $res = $this->client->call_child( $site['id'], 'stats', array( 'start' => $start, 'end' => $end, ) ); if ( empty( $res['ok'] ) ) { $error = isset( $res['error'] ) ? (string) $res['error'] : 'unknown'; $errors[] = array( 'site' => $site, 'error' => $error, ); $rows[] = array( 'id' => $site['id'], 'name' => $site['name'], 'url' => $site['url'], 'ok' => false, 'error' => $error, 'views' => 0, 'clicks' => 0, 'ctr' => 0.0, 'ads' => 0, ); continue; } $data = $res['data']; $views = isset( $data['total_views'] ) ? (int) $data['total_views'] : 0; $clicks = isset( $data['total_clicks'] ) ? (int) $data['total_clicks'] : 0; $total_views += $views; $total_clicks += $clicks; // Merge this site's daily series into the fleet-wide series. if ( isset( $data['series'] ) && is_array( $data['series'] ) ) { foreach ( $data['series'] as $point ) { $date = isset( $point['date'] ) ? (int) $point['date'] : 0; if ( $date <= 0 ) { continue; } if ( ! isset( $daily[ $date ] ) ) { $daily[ $date ] = array( 'views' => 0, 'clicks' => 0, ); } $daily[ $date ]['views'] += isset( $point['views'] ) ? (int) $point['views'] : 0; $daily[ $date ]['clicks'] += isset( $point['clicks'] ) ? (int) $point['clicks'] : 0; } } $rows[] = array( 'id' => $site['id'], 'name' => $site['name'], 'url' => $site['url'], 'ok' => true, 'views' => $views, 'clicks' => $clicks, 'ctr' => self::ctr( $clicks, $views ), 'ads' => isset( $data['ads'] ) && is_array( $data['ads'] ) ? count( $data['ads'] ) : 0, ); } ksort( $daily ); $series = array(); foreach ( $daily as $date => $counts ) { $series[] = array( 'date' => (int) $date, 'views' => (int) $counts['views'], 'clicks' => (int) $counts['clicks'], ); } $result = array( 'start' => $start, 'end' => $end, 'totals' => array( 'views' => $total_views, 'clicks' => $total_clicks, 'ctr' => self::ctr( $total_clicks, $total_views ), ), 'sites' => $rows, 'series' => $series, 'errors' => $errors, 'generated' => time(), ); set_transient( $cache_key, $result, self::CACHE_TTL ); return $result; } /** * Compute fleet-wide alerts: expiring ads, outdated core, connector issues. * * @param bool $force Bypass + overwrite the cache. * @return array{expiring:array,version_issues:array,connector_issues:array,generated:int} */ public function alerts( bool $force = false ): array { $cache_key = self::CACHE_PREFIX . 'alerts'; if ( ! $force ) { $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } } $now = time(); $week = $now + 7 * DAY_IN_SECONDS; $month = $now + 30 * DAY_IN_SECONDS; $expiring = array(); $connector_issues = array(); $version_issues = array(); $metas = array(); $latest_core = ''; foreach ( $this->client->get_sites() as $site ) { $meta = $this->client->call_child( $site['id'], 'meta' ); if ( empty( $meta['ok'] ) ) { $connector_issues[] = array( 'site' => $site, 'issue' => 'connector_unreachable', 'detail' => isset( $meta['error'] ) ? (string) $meta['error'] : 'unknown', ); continue; } $md = $meta['data']; if ( empty( $md['adsanity_active'] ) ) { $connector_issues[] = array( 'site' => $site, 'issue' => 'core_inactive', ); } $core_version = isset( $md['adsanity_version'] ) ? (string) $md['adsanity_version'] : ''; $metas[] = array( 'site' => $site, 'core' => $core_version, ); if ( '' !== $core_version && version_compare( $core_version, $latest_core, '>' ) ) { $latest_core = $core_version; } $inv = $this->client->call_child( $site['id'], 'inventory' ); if ( ! empty( $inv['ok'] ) && isset( $inv['data']['ads'] ) && is_array( $inv['data']['ads'] ) ) { foreach ( $inv['data']['ads'] as $ad ) { $end = isset( $ad['end_date'] ) ? $ad['end_date'] : null; if ( null !== $end && $end >= $now && $end <= $month ) { $expiring[] = array( 'site' => $site, 'ad' => $ad, 'when' => ( $end <= $week ) ? 'week' : 'month', 'end_date' => (int) $end, ); } } } } // Sites running an older core than the newest seen across the fleet. foreach ( $metas as $m ) { if ( '' !== $latest_core && '' !== $m['core'] && version_compare( $m['core'], $latest_core, '<' ) ) { $version_issues[] = array( 'site' => $m['site'], 'core' => $m['core'], 'latest' => $latest_core, ); } } // Soonest-expiring first. usort( $expiring, static function ( $a, $b ) { return $a['end_date'] <=> $b['end_date']; } ); $result = array( 'expiring' => $expiring, 'version_issues' => $version_issues, 'connector_issues' => $connector_issues, 'generated' => $now, ); set_transient( $cache_key, $result, self::CACHE_TTL ); return $result; } /** * Record one managed site's cheap sync summary and rebuild the snapshot. * * Called from the `mainwp_site_synced` handler with the payload the * Connector piggybacks on every regular MainWP sync. This is what keeps the * overview metabox current without any per-page-load fan-out: the numbers * refresh whenever MainWP syncs a site. * * @param int $site_id Managed-site id. * @param array $summary The Connector's `adsanity_mwp` sync summary. * @return void */ public function record_site_summary( int $site_id, array $summary ): void { if ( $site_id <= 0 ) { return; } $store = get_option( self::SITE_SUMMARIES_OPTION, array() ); if ( ! is_array( $store ) ) { $store = array(); } $store[ $site_id ] = array( 'published' => isset( $summary['ads_published'] ) ? max( 0, (int) $summary['ads_published'] ) : 0, 'expiring' => isset( $summary['ads_expiring_soon'] ) ? max( 0, (int) $summary['ads_expiring_soon'] ) : 0, 'active' => ! empty( $summary['adsanity_active'] ), 'version' => isset( $summary['adsanity_version'] ) ? (string) $summary['adsanity_version'] : '', 'connector' => isset( $summary['connector_version'] ) ? (string) $summary['connector_version'] : '', 'recorded' => time(), ); $this->rebuild_overview( $store ); } /** * Roll the stored per-site summaries up into the overview snapshot. * * Counts only sites MainWP currently manages (dropping summaries for sites * that have since been removed), and flags sites whose core is inactive or * older than the newest core version seen across the fleet. * * @param array $store Per-site summaries keyed by managed-site id. * @return void */ private function rebuild_overview( array $store ): void { $sites = $this->client->get_sites(); // Drop summaries for sites no longer managed. Only prune against a real // site list: an empty list here usually means MainWP's site-list filter // isn't available in this context (some cron paths), and pruning then // would wipe valid accumulated data. if ( ! empty( $sites ) ) { $current_ids = array(); foreach ( $sites as $site ) { $current_ids[ (int) $site['id'] ] = true; } $store = array_intersect_key( $store, $current_ids ); } update_option( self::SITE_SUMMARIES_OPTION, $store, false ); // Newest core version seen across the reporting fleet. $latest_core = ''; foreach ( $store as $row ) { if ( '' !== $row['version'] && version_compare( $row['version'], $latest_core, '>' ) ) { $latest_core = $row['version']; } } $published = 0; $expiring = 0; $reporting = 0; $needs_attention = 0; foreach ( $store as $row ) { ++$reporting; $published += (int) $row['published']; $expiring += (int) $row['expiring']; $outdated = ( '' !== $latest_core && '' !== $row['version'] && version_compare( $row['version'], $latest_core, '<' ) ); if ( empty( $row['active'] ) || $outdated ) { ++$needs_attention; } } $snapshot = array( 'published' => $published, 'expiring' => $expiring, 'sites_total' => ! empty( $sites ) ? count( $sites ) : $reporting, 'sites_reporting' => $reporting, 'needs_attention' => $needs_attention, 'generated' => time(), ); update_option( self::OVERVIEW_KEY, $snapshot, false ); } /** * Read the rolled-up overview snapshot (for the metabox). * * @return array Empty array if no site has synced a summary yet. */ public static function overview_snapshot(): array { $snapshot = get_option( self::OVERVIEW_KEY, array() ); return is_array( $snapshot ) ? $snapshot : array(); } /** * Read one managed site's stored sync summary (for the per-site metabox). * * @param int $site_id Managed-site id. * @return array Empty array if the site has no stored summary yet. */ public static function site_summary( int $site_id ): array { $store = get_option( self::SITE_SUMMARIES_OPTION, array() ); if ( ! is_array( $store ) || empty( $store[ $site_id ] ) || ! is_array( $store[ $site_id ] ) ) { return array(); } return $store[ $site_id ]; } /** * Click-through rate percentage, guarded against divide-by-zero. * * @param int $clicks Clicks. * @param int $views Views. * @return float */ private static function ctr( int $clicks, int $views ): float { if ( $views <= 0 ) { return 0.0; } return round( ( $clicks / $views ) * 100, 2 ); } }