*/ private $sortable = array( 'name', 'views', 'clicks', 'ctr', 'ads' ); /** * Constructor. * * @param Adsanity_For_MainWP_Client $client Transport client. * @param Adsanity_For_MainWP_Aggregator $aggregator Cross-site aggregator. * @param string $page_slug Extension page slug. */ public function __construct( Adsanity_For_MainWP_Client $client, Adsanity_For_MainWP_Aggregator $aggregator, string $page_slug ) { $this->client = $client; $this->aggregator = $aggregator; $this->page_slug = $page_slug; } /** * Render the extension page (tabbed: Network dashboard + Alerts). * * @return void */ public function render_extension_page(): void { do_action( 'mainwp_pageheader_extensions', $this->page_slug ); // Re-assert MainWP's own extension gate at render time. MainWP registers // every page (including this one) at the 'read' capability and leaves // per-user restriction to its permission layer, so check that layer here // rather than trusting the bare page registration. Fails closed if the // permission API is unavailable. if ( ! function_exists( 'mainwp_current_user_can' ) || ! mainwp_current_user_can( 'extension', 'adsanity-for-mainwp' ) ) { echo '

' . esc_html__( 'You do not have permission to access AdSanity for MainWP.', 'adsanity-for-mainwp' ) . '

'; do_action( 'mainwp_pagefooter_extensions', $this->page_slug ); return; } if ( ! $this->client->mainwp_available() ) { echo '

' . esc_html__( 'MainWP dashboard is not available. Activate MainWP to use this extension.', 'adsanity-for-mainwp' ) . '

'; do_action( 'mainwp_pagefooter_extensions', $this->page_slug ); return; } $tab = $this->current_tab(); // One MainWP-style padded segment supplies the themed background and the // page inset (matching every other MainWP page); the tab menu + panels // live inside it. Both panels render server-side — Semantic's .ui.tab CSS // hides the inactive one, so it degrades to URL-driven tabs without JS, // while the JS init makes switching instant. echo '
'; $this->render_tab_nav( $tab ); printf( '
', 'dashboard' === $tab ? ' active' : '' ); $this->render_dashboard_view(); echo '
'; printf( '
', 'alerts' === $tab ? ' active' : '' ); $this->render_alerts_view(); echo '
'; echo '
'; do_action( 'mainwp_pagefooter_extensions', $this->page_slug ); } /** * Render the network dashboard tab body. * * @return void */ private function render_dashboard_view(): void { list( $start, $end ) = $this->selected_range(); list( $orderby, $order ) = $this->selected_sort(); $force = $this->refresh_requested(); // Only reach out to the fleet on a trusted request: the nonce-verified // refresh, a default (unparameterized) range, or a range/sort link this // screen generated (those carry the range nonce). A hand-crafted // ?start=&end= URL is served from cache only and never triggers a fresh // N-site fan-out. $allow_remote = $force || $this->range_request_is_trusted(); $data = $this->aggregator->network_stats( $start, $end, $force, $allow_remote ); $this->render_range_form( $start, $end ); if ( ! empty( $data['deferred'] ) ) { echo '

' . esc_html__( 'This date range isn’t loaded yet. Adjust the range and press Apply, or use “Refresh data”, to fetch it from your sites.', 'adsanity-for-mainwp' ) . '

'; return; } $this->render_totals( $data['totals'], $data['sites'] ); $this->render_chart( isset( $data['series'] ) && is_array( $data['series'] ) ? $data['series'] : array() ); $this->render_site_table( $data['sites'], $orderby, $order, $start, $end ); $this->render_footer_meta( $data['generated'] ); } /** * Whether the current request may trigger a live cross-site fan-out. * * True when no custom range was supplied (the default trailing window shown * on a normal page load) or when the request carries this screen's range * nonce — the Apply button, the presets, and the sortable column links all * include it. A bare, hand-edited ?start=&end= URL is therefore served from * cache only, so it cannot amplify into an N-site HTTP sweep. * * @return bool */ private function range_request_is_trusted(): bool { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- this method IS the nonce verification. $has_custom_range = isset( $_GET['start'] ) || isset( $_GET['end'] ); $nonce = isset( $_GET['adsanity_mwp_rnonce'] ) ? sanitize_key( wp_unslash( $_GET['adsanity_mwp_rnonce'] ) ) : ''; // phpcs:enable WordPress.Security.NonceVerification.Recommended if ( ! $has_custom_range ) { return true; } return (bool) wp_verify_nonce( $nonce, 'adsanity_mwp_range' ); } /** * Render the alerts tab body. * * @return void */ private function render_alerts_view(): void { $alerts = $this->aggregator->alerts( $this->refresh_requested() ); $refresh_url = wp_nonce_url( add_query_arg( array( 'page' => $this->page_slug, 'tab' => 'alerts', 'adsanity_mwp_refresh' => 1, ), admin_url( 'admin.php' ) ), 'adsanity_mwp_refresh' ); printf( '

%s

', esc_url( $refresh_url ), esc_html__( 'Refresh data', 'adsanity-for-mainwp' ) ); $this->render_alerts( $alerts ); $this->render_footer_meta( isset( $alerts['generated'] ) ? (int) $alerts['generated'] : 0 ); } /** * Render the per-site "AdSanity" drill-down subpage (Manage Sites > AdSanity). * * MainWP passes the current site via $_GET['id']. * * @return void */ public function render_site_subpage(): void { do_action( 'mainwp_pageheader_sites', 'AdSanity' ); echo '
'; echo '

' . esc_html__( 'AdSanity', 'adsanity-for-mainwp' ) . '

'; // Gate the per-site drill-down on both this extension's access right and // MainWP's individual-site dashboard right (the right MainWP itself uses // to gate per-site views). Fails closed if the permission API is absent. if ( ! function_exists( 'mainwp_current_user_can' ) || ! mainwp_current_user_can( 'extension', 'adsanity-for-mainwp' ) || ! mainwp_current_user_can( 'dashboard', 'access_individual_dashboard' ) ) { echo '

' . esc_html__( 'You do not have permission to view AdSanity data for this site.', 'adsanity-for-mainwp' ) . '

'; do_action( 'mainwp_pagefooter_sites', 'AdSanity' ); return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- MainWP-provided site context, read-only. $site_id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0; if ( $site_id <= 0 ) { echo '

' . esc_html__( 'No site selected.', 'adsanity-for-mainwp' ) . '

'; do_action( 'mainwp_pagefooter_sites', 'AdSanity' ); return; } $meta = $this->client->call_child( $site_id, 'meta' ); $stats = $this->client->call_child( $site_id, 'stats' ); $inv = $this->client->call_child( $site_id, 'inventory' ); if ( empty( $meta['ok'] ) && empty( $inv['ok'] ) ) { $error = ! empty( $meta['error'] ) ? (string) $meta['error'] : 'unknown'; echo '

' . esc_html( sprintf( /* translators: %s: error label */ __( 'Could not reach the AdSanity Connector on this site (%s). Confirm AdSanity and the Connector are active.', 'adsanity-for-mainwp' ), $this->error_label( $error ) ) ) . '

'; do_action( 'mainwp_pagefooter_sites', 'AdSanity' ); return; } if ( ! empty( $meta['ok'] ) ) { $m = $meta['data']; $addon = count( isset( $m['addons'] ) && is_array( $m['addons'] ) ? $m['addons'] : array() ); printf( '

%1$s %2$s · %3$s %4$s · %5$s

', esc_html__( 'AdSanity core', 'adsanity-for-mainwp' ), esc_html( (string) ( $m['adsanity_version'] ?? '' ) ), esc_html__( 'Connector', 'adsanity-for-mainwp' ), esc_html( (string) ( $m['connector_version'] ?? '' ) ), esc_html( sprintf( /* translators: %d: add-on count */ _n( '%d active add-on', '%d active add-ons', $addon, 'adsanity-for-mainwp' ), $addon ) ) ); } if ( ! empty( $stats['ok'] ) ) { $d = $stats['data']; $this->render_stat_cards( array( array( 'icon' => 'eye', 'value' => number_format_i18n( (int) ( $d['total_views'] ?? 0 ) ), 'label' => __( 'Impressions (30d)', 'adsanity-for-mainwp' ), ), array( 'icon' => 'mouse pointer', 'value' => number_format_i18n( (int) ( $d['total_clicks'] ?? 0 ) ), 'label' => __( 'Clicks (30d)', 'adsanity-for-mainwp' ), ), array( 'icon' => 'percent', 'value' => number_format_i18n( (float) ( $d['total_ctr'] ?? 0 ), 2 ) . '%', 'label' => __( 'CTR', 'adsanity-for-mainwp' ), ), ) ); $this->render_chart( isset( $d['series'] ) && is_array( $d['series'] ) ? $d['series'] : array() ); } echo '

' . esc_html__( 'Inventory', 'adsanity-for-mainwp' ) . '

'; if ( ! empty( $inv['ok'] ) && isset( $inv['data']['ads'] ) && is_array( $inv['data']['ads'] ) ) { $this->render_inventory_table( $inv['data']['ads'] ); } else { echo '

' . esc_html__( 'Inventory unavailable.', 'adsanity-for-mainwp' ) . '

'; } echo ''; do_action( 'mainwp_pagefooter_sites', 'AdSanity' ); } /** * Render the AdSanity overview metabox (MainWP widget). * * Site-aware: MainWP fires `mainwp_getmetaboxes` on both the network * overview page (site id 0 → fleet rollup) and an individual site's * overview page (that site's id → its own inventory). Both read cached * data, so neither adds a per-page-load fan-out. * * @param int $site_id Current site id from MainWP (0 on the network overview). * @return void */ public function render_metabox( int $site_id ): void { if ( $site_id > 0 ) { $this->render_site_metabox( $site_id ); return; } $snap = Adsanity_For_MainWP_Aggregator::overview_snapshot(); $page_url = add_query_arg( array( 'page' => $this->page_slug ), admin_url( 'admin.php' ) ); // Mirror MainWP's built-in overview widgets exactly (e.g. Clients, // Recent Posts): the `ui header handle-drag` inside `mainwp-widget-header` // supplies both the drag handle and the themed title/divider styling, the // body sits in `mainwp-scrolly-overflow`, and the action lives in a // `mainwp-widget-footer` grid. Everything uses Semantic vocabulary so it // themes for light + dark without this extension's stylesheet (which is // not enqueued on the MainWP overview page where this widget renders). echo '
'; echo '

'; echo esc_html__( 'AdSanity', 'adsanity-for-mainwp' ); echo '
' . esc_html__( 'Ad inventory across your fleet', 'adsanity-for-mainwp' ) . '
'; echo '

'; echo '
'; echo '
'; if ( empty( $snap ) ) { echo '

' . esc_html__( 'No fleet data yet — it loads automatically the next time MainWP syncs your sites.', 'adsanity-for-mainwp' ) . '

'; } else { $reporting = (int) ( $snap['sites_reporting'] ?? 0 ); $total = (int) ( $snap['sites_total'] ?? 0 ); // Match MainWP's Connection Status / Site Hardening widgets: each // metric is a `ui card` (icon + large number + label) inside a // responsive `ui mainwp-cards small cards` group. These are the cheap // inventory counts the Connector piggybacks on each sync. $cards = array( array( 'icon' => 'bullhorn', 'value' => number_format_i18n( (int) ( $snap['published'] ?? 0 ) ), 'label' => __( 'Published ads', 'adsanity-for-mainwp' ), ), array( 'icon' => 'clock', 'value' => number_format_i18n( (int) ( $snap['expiring'] ?? 0 ) ), 'label' => __( 'Expiring soon', 'adsanity-for-mainwp' ), ), array( 'icon' => 'server', 'value' => number_format_i18n( $reporting ) . '/' . number_format_i18n( $total ), 'label' => __( 'Sites reporting', 'adsanity-for-mainwp' ), ), ); echo '
'; foreach ( $cards as $card ) { echo '
'; printf( '
%2$s
', esc_attr( $card['icon'] ), esc_html( $card['value'] ) ); echo '
' . esc_html( $card['label'] ) . '
'; echo '
'; } echo '
'; $needs_attention = (int) ( $snap['needs_attention'] ?? 0 ); if ( $needs_attention > 0 ) { printf( '

%s

', esc_html( sprintf( /* translators: %d: count of sites */ _n( '%d site needs attention', '%d sites need attention', $needs_attention, 'adsanity-for-mainwp' ), $needs_attention ) ) ); } elseif ( $reporting > 0 ) { printf( '

%s

', esc_html__( 'All connectors current', 'adsanity-for-mainwp' ) ); } else { echo '

' . esc_html__( 'Waiting for connector data from synced sites.', 'adsanity-for-mainwp' ) . '

'; } } echo '
'; echo ''; } /** * Render the AdSanity metabox for a single managed site. * * Shows that one site's inventory from its stored sync summary (not the * fleet rollup). Empty until the site has synced with the Connector. * * @param int $site_id Managed-site id. * @return void */ private function render_site_metabox( int $site_id ): void { $summary = Adsanity_For_MainWP_Aggregator::site_summary( $site_id ); // Deep-link to this site's own AdSanity subpage (Manage Sites > AdSanity), // not the network rollup. MainWP derives the slug as 'ManageSites' + the // subpage slug and passes the site via ?id=. $page_url = add_query_arg( array( 'page' => 'ManageSitesAdSanity', 'id' => $site_id, ), admin_url( 'admin.php' ) ); echo '
'; echo '

'; echo esc_html__( 'AdSanity', 'adsanity-for-mainwp' ); echo '
' . esc_html__( 'Ad inventory on this site', 'adsanity-for-mainwp' ) . '
'; echo '

'; echo '
'; echo '
'; if ( empty( $summary ) ) { echo '

' . esc_html__( 'No AdSanity data yet — it loads automatically the next time MainWP syncs this site.', 'adsanity-for-mainwp' ) . '

'; } else { $cards = array( array( 'icon' => 'bullhorn', 'value' => number_format_i18n( (int) ( $summary['published'] ?? 0 ) ), 'label' => __( 'Published ads', 'adsanity-for-mainwp' ), ), array( 'icon' => 'clock', 'value' => number_format_i18n( (int) ( $summary['expiring'] ?? 0 ) ), 'label' => __( 'Expiring soon', 'adsanity-for-mainwp' ), ), ); echo '
'; foreach ( $cards as $card ) { echo '
'; printf( '
%2$s
', esc_attr( $card['icon'] ), esc_html( $card['value'] ) ); echo '
' . esc_html( $card['label'] ) . '
'; echo '
'; } echo '
'; if ( empty( $summary['active'] ) ) { printf( '

%s

', esc_html__( 'AdSanity is inactive on this site', 'adsanity-for-mainwp' ) ); } else { $bits = array(); if ( ! empty( $summary['version'] ) ) { /* translators: %s: AdSanity core version */ $bits[] = sprintf( __( 'AdSanity %s', 'adsanity-for-mainwp' ), (string) $summary['version'] ); } if ( ! empty( $summary['connector'] ) ) { /* translators: %s: Connector version */ $bits[] = sprintf( __( 'Connector %s', 'adsanity-for-mainwp' ), (string) $summary['connector'] ); } if ( ! empty( $bits ) ) { echo '

' . esc_html( implode( ' · ', $bits ) ) . '

'; } } } echo '
'; echo ''; } /** * Render a row of stat cards (icon + value + label). * * Uses the same `ui mainwp-cards` markup as the overview metabox widget so * the reporting screens read consistently with it (and theme for light + * dark without bespoke CSS). * * @param array $cards Card definitions. * @return void */ private function render_stat_cards( array $cards ): void { echo '
'; foreach ( $cards as $card ) { echo '
'; printf( '
%2$s
', esc_attr( $card['icon'] ), esc_html( $card['value'] ) ); echo '
' . esc_html( $card['label'] ) . '
'; echo '
'; } echo '
'; } /** * Render a dependency-free inline SVG trend chart of the daily series. * * Impressions and clicks are each scaled to their own range so both trends * are visible; the legend states this. * * @param array $series Daily points: date (ts), views, clicks. * @return void */ private function render_chart( array $series ): void { $points = array(); foreach ( $series as $p ) { $points[] = array( 'date' => isset( $p['date'] ) ? (int) $p['date'] : 0, 'views' => isset( $p['views'] ) ? (int) $p['views'] : 0, 'clicks' => isset( $p['clicks'] ) ? (int) $p['clicks'] : 0, ); } if ( count( $points ) < 2 ) { return; // Not enough data points to draw a trend. } $width = 720; $height = 200; $pad_x = 8; $pad_top = 12; $pad_bot = 22; $plot_w = $width - ( 2 * $pad_x ); $plot_h = $height - $pad_top - $pad_bot; $count = count( $points ); $base_y = $pad_top + $plot_h; $max_view = 1; $max_clk = 1; foreach ( $points as $p ) { $max_view = max( $max_view, $p['views'] ); $max_clk = max( $max_clk, $p['clicks'] ); } $view_pts = array(); $clk_pts = array(); foreach ( $points as $i => $p ) { $x = $pad_x + ( $i / ( $count - 1 ) ) * $plot_w; $view_pts[] = array( $x, $base_y - ( $p['views'] / $max_view ) * $plot_h ); $clk_pts[] = array( $x, $base_y - ( $p['clicks'] / $max_clk ) * $plot_h ); } $view_path = $this->smooth_path( $view_pts ); $clk_path = $this->smooth_path( $clk_pts ); // Close the impressions curve down to the baseline for the area fill. $area_path = $view_path . sprintf( ' L %.1f,%.1f L %.1f,%.1f Z', $pad_x + $plot_w, $base_y, $pad_x, $base_y ); $date_format = (string) get_option( 'date_format', 'M j' ); $first_label = date_i18n( $date_format, $points[0]['date'] ); $last_label = date_i18n( $date_format, $points[ $count - 1 ]['date'] ); $svg = ''; $svg .= ''; $svg .= ''; $svg .= ''; $svg .= '' . esc_html( $first_label ) . ''; $svg .= '' . esc_html( $last_label ) . ''; $svg .= ''; echo '
'; echo $svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG assembled from sanitized numeric coordinates + escaped labels. echo '
'; printf( '%s', esc_html( sprintf( /* translators: %s: peak value */ __( 'Impressions (peak %s)', 'adsanity-for-mainwp' ), number_format_i18n( $max_view ) ) ) ); printf( '%s', esc_html( sprintf( /* translators: %s: peak value */ __( 'Clicks (peak %s)', 'adsanity-for-mainwp' ), number_format_i18n( $max_clk ) ) ) ); echo '' . esc_html__( 'Each line scaled to its own range.', 'adsanity-for-mainwp' ) . ''; echo '
'; echo '
'; } /** * Build a smooth SVG path through a list of points. * * Expresses a Catmull-Rom spline as cubic Béziers so the trend line curves * through each data point instead of drawing jagged straight segments. * Endpoints clamp to themselves so the curve starts and ends cleanly. * * @param array $pts Ordered [ x, y ] coordinate pairs. * @return string The path `d` attribute value (empty for fewer than two points). */ private function smooth_path( array $pts ): string { $n = count( $pts ); if ( $n < 2 ) { return ''; } $d = sprintf( 'M %.1f,%.1f', $pts[0][0], $pts[0][1] ); for ( $i = 0; $i < $n - 1; $i++ ) { $p0 = $pts[ max( $i - 1, 0 ) ]; $p1 = $pts[ $i ]; $p2 = $pts[ $i + 1 ]; $p3 = $pts[ min( $i + 2, $n - 1 ) ]; $c1x = $p1[0] + ( $p2[0] - $p0[0] ) / 6; $c1y = $p1[1] + ( $p2[1] - $p0[1] ) / 6; $c2x = $p2[0] - ( $p3[0] - $p1[0] ) / 6; $c2y = $p2[1] - ( $p3[1] - $p1[1] ) / 6; $d .= sprintf( ' C %.1f,%.1f %.1f,%.1f %.1f,%.1f', $c1x, $c1y, $c2x, $c2y, $p2[0], $p2[1] ); } return $d; } /** * Render an inventory table for a single site's ads. * * @param array $ads Ad rows from the inventory handler. * @return void */ private function render_inventory_table( array $ads ): void { if ( empty( $ads ) ) { echo '

' . esc_html__( 'No ads found.', 'adsanity-for-mainwp' ) . '

'; return; } $date_format = (string) get_option( 'date_format', 'Y-m-d' ); echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; foreach ( $ads as $ad ) { $end = isset( $ad['end_date'] ) ? (int) $ad['end_date'] : null; $groups = isset( $ad['groups'] ) && is_array( $ad['groups'] ) ? array_map( 'strval', $ad['groups'] ) : array(); echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- label markup built from an escaped date in expiry_cell(). echo ''; } echo '
' . esc_html__( 'Ad', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Type', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Size', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Status', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Groups', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Expires', 'adsanity-for-mainwp' ) . '
' . esc_html( (string) ( $ad['title'] ?? '' ) ) . '' . esc_html( (string) ( $ad['type'] ?? '' ) ) . '' . esc_html( (string) ( $ad['size'] ?? '' ) ) . '' . esc_html( (string) ( $ad['status'] ?? '' ) ) . '' . esc_html( implode( ', ', $groups ) ) . '' . $this->expiry_cell( $end, $date_format ) . '
'; } /** * Render the "Expires" cell for an inventory row. * * Mirrors the Alerts "Expiring ads" rollup: an end date within the coming * week is wrapped in a red label, within 30 days a yellow label (the same * `ui small {color} label` markup and 7/30-day thresholds the aggregator * uses for the alerts list). Dates further out, already past, or absent * render as plain text so the colored labels stay an "expiring soon" signal. * * @param int|null $end Ad end-date timestamp, or null when the ad never expires. * @param string $date_format Date format for display. * @return string The cell's inner HTML (escaped). */ private function expiry_cell( ?int $end, string $date_format ): string { if ( null === $end ) { return '—'; } $label = esc_html( date_i18n( $date_format, $end ) ); $now = time(); $week = $now + 7 * DAY_IN_SECONDS; $month = $now + 30 * DAY_IN_SECONDS; if ( $end < $now || $end > $month ) { return $label; } $color = ( $end <= $week ) ? 'red' : 'yellow'; return sprintf( '
%s
', esc_attr( $color ), $label ); } /** * Resolve the active extension tab from the request. * * @return string 'dashboard' or 'alerts'. */ private function current_tab(): string { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only tab switch. $tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'dashboard'; return in_array( $tab, array( 'dashboard', 'alerts' ), true ) ? $tab : 'dashboard'; } /** * Render the extension's tab navigation. * * @param string $active The active tab key. * @return void */ private function render_tab_nav( string $active ): void { $tabs = array( 'dashboard' => __( 'Network', 'adsanity-for-mainwp' ), 'alerts' => __( 'Alerts', 'adsanity-for-mainwp' ), ); echo ''; } /** * Render the alerts content from an aggregated alerts payload. * * Kept separate from the data fetch so it renders any well-formed alerts * array (and is unit-testable with synthetic data). * * @param array $alerts Alerts payload from the aggregator. * @return void */ private function render_alerts( array $alerts ): void { $expiring = isset( $alerts['expiring'] ) && is_array( $alerts['expiring'] ) ? $alerts['expiring'] : array(); $versions = isset( $alerts['version_issues'] ) && is_array( $alerts['version_issues'] ) ? $alerts['version_issues'] : array(); $connectors = isset( $alerts['connector_issues'] ) && is_array( $alerts['connector_issues'] ) ? $alerts['connector_issues'] : array(); if ( empty( $expiring ) && empty( $versions ) && empty( $connectors ) ) { echo '

' . esc_html__( 'No alerts. Every managed site is reporting and healthy.', 'adsanity-for-mainwp' ) . '

'; return; } $date_format = (string) get_option( 'date_format', 'Y-m-d' ); echo '

' . esc_html__( 'Expiring ads', 'adsanity-for-mainwp' ) . '

'; if ( empty( $expiring ) ) { echo '

' . esc_html__( 'No ads expiring in the next 30 days.', 'adsanity-for-mainwp' ) . '

'; } else { echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; foreach ( $expiring as $e ) { $when_html = ( 'week' === ( $e['when'] ?? '' ) ) ? '
' . esc_html__( 'This week', 'adsanity-for-mainwp' ) . '
' : '
' . esc_html__( 'This month', 'adsanity-for-mainwp' ) . '
'; echo ''; echo ''; echo ''; echo ''; echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- pre-escaped above. echo ''; } echo '
' . esc_html__( 'Ad', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Site', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Expires', 'adsanity-for-mainwp' ) . '' . esc_html__( 'When', 'adsanity-for-mainwp' ) . '
' . esc_html( (string) ( $e['ad']['title'] ?? '' ) ) . '' . esc_html( (string) ( $e['site']['name'] ?? '' ) ) . '' . esc_html( date_i18n( $date_format, (int) ( $e['end_date'] ?? 0 ) ) ) . '' . $when_html . '
'; } if ( ! empty( $versions ) ) { echo '

' . esc_html__( 'Sites on an outdated AdSanity', 'adsanity-for-mainwp' ) . '

'; echo ''; echo ''; echo ''; echo ''; echo ''; foreach ( $versions as $v ) { echo ''; echo ''; echo ''; echo ''; echo ''; } echo '
' . esc_html__( 'Site', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Installed', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Newest in fleet', 'adsanity-for-mainwp' ) . '
' . esc_html( (string) ( $v['site']['name'] ?? '' ) ) . '' . esc_html( (string) ( $v['core'] ?? '' ) ) . '' . esc_html( (string) ( $v['latest'] ?? '' ) ) . '
'; } if ( ! empty( $connectors ) ) { echo '

' . esc_html__( 'Connector / AdSanity issues', 'adsanity-for-mainwp' ) . '

'; echo ''; echo ''; echo ''; echo ''; foreach ( $connectors as $c ) { echo ''; echo ''; echo ''; echo ''; } echo '
' . esc_html__( 'Site', 'adsanity-for-mainwp' ) . '' . esc_html__( 'Issue', 'adsanity-for-mainwp' ) . '
' . esc_html( (string) ( $c['site']['name'] ?? '' ) ) . '' . esc_html( $this->issue_label( (string) ( $c['issue'] ?? '' ) ) ) . '
'; } } /** * Human-friendly label for a connector/core issue code. * * @param string $issue Issue code. * @return string */ private function issue_label( string $issue ): string { $labels = array( 'connector_unreachable' => __( 'Connector not responding (missing/old, or AdSanity inactive)', 'adsanity-for-mainwp' ), 'core_inactive' => __( 'AdSanity core inactive', 'adsanity-for-mainwp' ), ); return isset( $labels[ $issue ] ) ? $labels[ $issue ] : $issue; } /** * Resolve the selected date range from the request (default: trailing 30 days). * * @return array{0:int,1:int} [ start_ts, end_ts ] */ private function selected_range(): array { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only range filter, no state change. $start_raw = isset( $_GET['start'] ) ? sanitize_text_field( wp_unslash( $_GET['start'] ) ) : ''; $end_raw = isset( $_GET['end'] ) ? sanitize_text_field( wp_unslash( $_GET['end'] ) ) : ''; // phpcs:enable WordPress.Security.NonceVerification.Recommended $end = ( '' !== $end_raw ) ? strtotime( $end_raw . ' 23:59:59' ) : 0; $start = ( '' !== $start_raw ) ? strtotime( $start_raw . ' 00:00:00' ) : 0; if ( ! $end ) { $end = time(); } if ( ! $start || $start > $end ) { $start = $end - ( 30 * DAY_IN_SECONDS ); } // Cap the span so a hand-crafted range can't request an unbounded // cross-site query window (see self::MAX_RANGE_DAYS). $max_span = self::MAX_RANGE_DAYS * DAY_IN_SECONDS; if ( $end - $start > $max_span ) { $start = $end - $max_span; } return array( $start, $end ); } /** * Resolve the selected sort column + direction from the request. * * @return array{0:string,1:string} [ orderby, order ] */ private function selected_sort(): array { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only sort, no state change. $orderby = isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : 'views'; $order = isset( $_GET['order'] ) && 'asc' === strtolower( sanitize_key( wp_unslash( $_GET['order'] ) ) ) ? 'asc' : 'desc'; // phpcs:enable WordPress.Security.NonceVerification.Recommended if ( ! in_array( $orderby, $this->sortable, true ) ) { $orderby = 'views'; } return array( $orderby, $order ); } /** * Whether a (nonce-verified) cache refresh was requested. * * @return bool */ private function refresh_requested(): bool { if ( ! isset( $_GET['adsanity_mwp_refresh'] ) ) { return false; } $nonce = isset( $_GET['_wpnonce'] ) ? sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ) : ''; return (bool) wp_verify_nonce( $nonce, 'adsanity_mwp_refresh' ); } /** * Render the date-range filter form. * * @param int $start Start timestamp. * @param int $end End timestamp. * @return void */ private function render_range_form( int $start, int $end ): void { echo '
'; printf( '', esc_attr( $this->page_slug ) ); printf( '', esc_attr( wp_create_nonce( 'adsanity_mwp_range' ) ) ); printf( '', esc_html__( 'From', 'adsanity-for-mainwp' ), esc_attr( gmdate( 'Y-m-d', $start ) ) ); printf( '', esc_html__( 'To', 'adsanity-for-mainwp' ), esc_attr( gmdate( 'Y-m-d', $end ) ) ); echo ''; echo ''; foreach ( array( 7, 30, 90 ) as $days ) { printf( '', (int) $days, esc_html( sprintf( /* translators: %d: number of days */ _n( '%dd', '%dd', $days, 'adsanity-for-mainwp' ), $days ) ) ); } echo ''; $refresh_url = wp_nonce_url( add_query_arg( array( 'page' => $this->page_slug, 'start' => gmdate( 'Y-m-d', $start ), 'end' => gmdate( 'Y-m-d', $end ), 'adsanity_mwp_refresh' => 1, ), admin_url( 'admin.php' ) ), 'adsanity_mwp_refresh' ); printf( '%s', esc_url( $refresh_url ), esc_html__( 'Refresh data', 'adsanity-for-mainwp' ) ); echo '
'; } /** * Render the aggregate totals. * * @param array $totals Aggregate totals (views/clicks/ctr). * @param array $sites Per-site rows (for the reporting count). * @return void */ private function render_totals( array $totals, array $sites ): void { $reporting = 0; foreach ( $sites as $row ) { if ( ! empty( $row['ok'] ) ) { ++$reporting; } } $cards = array( array( 'icon' => 'eye', 'value' => number_format_i18n( (int) $totals['views'] ), 'label' => __( 'Impressions', 'adsanity-for-mainwp' ), ), array( 'icon' => 'mouse pointer', 'value' => number_format_i18n( (int) $totals['clicks'] ), 'label' => __( 'Clicks', 'adsanity-for-mainwp' ), ), array( 'icon' => 'percent', 'value' => number_format_i18n( (float) $totals['ctr'], 2 ) . '%', 'label' => __( 'CTR', 'adsanity-for-mainwp' ), ), array( 'icon' => 'server', 'value' => sprintf( '%d / %d', $reporting, count( $sites ) ), 'label' => __( 'Sites reporting', 'adsanity-for-mainwp' ), ), ); $this->render_stat_cards( $cards ); } /** * Render the sortable per-site table. * * @param array $sites Per-site rows. * @param string $orderby Active sort column. * @param string $order Active sort direction. * @param int $start Selected range start (to preserve in sort links). * @param int $end Selected range end. * @return void */ private function render_site_table( array $sites, string $orderby, string $order, int $start, int $end ): void { if ( empty( $sites ) ) { echo '

' . esc_html__( 'No managed sites found. Add sites to MainWP and install the AdSanity MainWP Connector on each.', 'adsanity-for-mainwp' ) . '

'; return; } $sites = $this->sort_rows( $sites, $orderby, $order ); $columns = array( 'name' => __( 'Site', 'adsanity-for-mainwp' ), 'ads' => __( 'Ads', 'adsanity-for-mainwp' ), 'views' => __( 'Impressions', 'adsanity-for-mainwp' ), 'clicks' => __( 'Clicks', 'adsanity-for-mainwp' ), 'ctr' => __( 'CTR', 'adsanity-for-mainwp' ), ); echo ''; echo ''; foreach ( $columns as $key => $label ) { echo $this->sortable_header( $label, $key, $orderby, $order, $start, $end ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built from esc_url/esc_html internally. } echo ''; echo ''; foreach ( $sites as $row ) { $ok = ! empty( $row['ok'] ); $drilldown = add_query_arg( array( 'page' => 'ManageSitesAdSanity', 'id' => (int) $row['id'], ), admin_url( 'admin.php' ) ); echo ''; printf( '', esc_url( $drilldown ), esc_html( '' !== $row['name'] ? $row['name'] : $row['url'] ), esc_url( (string) $row['url'] ), esc_attr__( 'Open site in a new tab', 'adsanity-for-mainwp' ) ); echo ''; echo ''; echo ''; echo ''; if ( $ok ) { echo ''; } else { printf( '', esc_attr( isset( $row['error'] ) ? (string) $row['error'] : '' ), esc_html( $this->error_label( isset( $row['error'] ) ? (string) $row['error'] : 'unknown' ) ) ); } echo ''; } echo '
' . esc_html__( 'Status', 'adsanity-for-mainwp' ) . '
%2$s ↗' . esc_html( number_format_i18n( (int) $row['ads'] ) ) . '' . esc_html( number_format_i18n( (int) $row['views'] ) ) . '' . esc_html( number_format_i18n( (int) $row['clicks'] ) ) . '' . esc_html( number_format_i18n( (float) $row['ctr'], 2 ) . '%' ) . '' . esc_html__( 'Connected', 'adsanity-for-mainwp' ) . '%s
'; } /** * Render the "last updated" footer line. * * @param int $generated Timestamp the data was generated. * @return void */ private function render_footer_meta( int $generated ): void { if ( $generated <= 0 ) { return; } printf( '

%s

', esc_html( sprintf( /* translators: %s: human-readable time difference */ __( 'Data cached %s ago. Use "Refresh data" to fetch live.', 'adsanity-for-mainwp' ), human_time_diff( $generated, time() ) ) ) ); } /** * Build a sortable column header cell. * * @param string $label Column label. * @param string $key Column sort key. * @param string $orderby Active sort column. * @param string $order Active sort direction. * @param int $start Range start (preserved in link). * @param int $end Range end (preserved in link). * @return string The `` markup. */ private function sortable_header( string $label, string $key, string $orderby, string $order, int $start, int $end ): string { $next_order = ( $orderby === $key && 'asc' === $order ) ? 'desc' : 'asc'; $indicator = ''; if ( $orderby === $key ) { $indicator = ( 'asc' === $order ) ? ' ↑' : ' ↓'; } $url = add_query_arg( array( 'page' => $this->page_slug, 'start' => gmdate( 'Y-m-d', $start ), 'end' => gmdate( 'Y-m-d', $end ), 'orderby' => $key, 'order' => $next_order, 'adsanity_mwp_rnonce' => wp_create_nonce( 'adsanity_mwp_range' ), ), admin_url( 'admin.php' ) ); return sprintf( '%s%s', esc_url( $url ), esc_html( $label ), esc_html( $indicator ) ); } /** * Sort per-site rows by the active column + direction. * * @param array $sites Rows. * @param string $orderby Column. * @param string $order Direction. * @return array */ private function sort_rows( array $sites, string $orderby, string $order ): array { usort( $sites, static function ( $a, $b ) use ( $orderby ) { if ( 'name' === $orderby ) { $a_name = ( '' !== (string) $a['name'] ) ? (string) $a['name'] : (string) $a['url']; $b_name = ( '' !== (string) $b['name'] ) ? (string) $b['name'] : (string) $b['url']; return strcasecmp( $a_name, $b_name ); } return ( $a[ $orderby ] ?? 0 ) <=> ( $b[ $orderby ] ?? 0 ); } ); if ( 'desc' === $order ) { $sites = array_reverse( $sites ); } return $sites; } /** * Human-friendly label for a per-site error code. * * @param string $error Machine error code. * @return string */ private function error_label( string $error ): string { $labels = array( 'connector_absent' => __( 'Connector missing/old', 'adsanity-for-mainwp' ), 'core_unavailable' => __( 'AdSanity inactive', 'adsanity-for-mainwp' ), 'no_response' => __( 'No response', 'adsanity-for-mainwp' ), 'mainwp_unavailable' => __( 'MainWP error', 'adsanity-for-mainwp' ), ); return isset( $labels[ $error ] ) ? $labels[ $error ] : sprintf( /* translators: %s: machine error code */ __( 'Error: %s', 'adsanity-for-mainwp' ), $error ); } }