Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
99.12% covered (success)
99.12%
2702 / 2726
85.11% covered (warning)
85.11%
80 / 94
CRAP
0.00% covered (danger)
0.00%
0 / 1
Stats_Abilities
99.19% covered (success)
99.19%
2702 / 2724
85.11% covered (warning)
85.11%
80 / 94
495
0.00% covered (danger)
0.00%
0 / 1
 enabled_by_default
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_definition
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_abilities
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_site_overview
100.00% covered (success)
100.00%
67 / 67
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_top_content
100.00% covered (success)
100.00%
105 / 105
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_post_detail
100.00% covered (success)
100.00%
117 / 117
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_post_views
100.00% covered (success)
100.00%
61 / 61
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_visits
100.00% covered (success)
100.00%
73 / 73
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_followers
100.00% covered (success)
100.00%
59 / 59
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_author_views
100.00% covered (success)
100.00%
57 / 57
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_insights
100.00% covered (success)
100.00%
109 / 109
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_email_stats
100.00% covered (success)
100.00%
74 / 74
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_email_detail
100.00% covered (success)
100.00%
103 / 103
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_video_stats
100.00% covered (success)
100.00%
79 / 79
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_subscribers
100.00% covered (success)
100.00%
77 / 77
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_ad_stats
100.00% covered (success)
100.00%
67 / 67
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_settings
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 spec_update_settings
100.00% covered (success)
100.00%
58 / 58
100.00% covered (success)
100.00%
1 / 1
1
 settings_output_properties
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 can_view_stats
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 can_view_ads
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 can_manage_settings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_site_overview
98.63% covered (success)
98.63%
72 / 73
0.00% covered (danger)
0.00%
0 / 1
12
 get_top_content
100.00% covered (success)
100.00%
81 / 81
100.00% covered (success)
100.00%
1 / 1
29
 get_post_views
100.00% covered (success)
100.00%
37 / 37
100.00% covered (success)
100.00%
1 / 1
10
 get_post_detail
100.00% covered (success)
100.00%
115 / 115
100.00% covered (success)
100.00%
1 / 1
23
 email_summary
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_visits
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
13
 get_followers
100.00% covered (success)
100.00%
69 / 69
100.00% covered (success)
100.00%
1 / 1
22
 get_author_views
100.00% covered (success)
100.00%
42 / 42
100.00% covered (success)
100.00%
1 / 1
9
 get_insights
100.00% covered (success)
100.00%
93 / 93
100.00% covered (success)
100.00%
1 / 1
19
 get_email_stats
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
14
 get_email_detail
95.50% covered (success)
95.50%
106 / 111
0.00% covered (danger)
0.00%
0 / 1
30
 email_timeline_request
96.97% covered (success)
96.97%
32 / 33
0.00% covered (danger)
0.00%
0 / 1
6
 email_timeline
94.74% covered (success)
94.74%
36 / 38
0.00% covered (danger)
0.00%
0 / 1
10.01
 get_video_stats
100.00% covered (success)
100.00%
73 / 73
100.00% covered (success)
100.00%
1 / 1
17
 get_subscribers
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
14
 get_ad_stats
98.57% covered (success)
98.57%
69 / 70
0.00% covered (danger)
0.00%
0 / 1
16
 get_settings
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 update_settings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 compose_subcalls
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 pick_period
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 get_wpcom_stats
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 fetch_top_content_raw
96.43% covered (success)
96.43%
27 / 28
0.00% covered (danger)
0.00%
0 / 1
15
 top_content_rows
95.83% covered (success)
95.83%
23 / 24
0.00% covered (danger)
0.00%
0 / 1
12
 child_rows
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 tag_rows
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 email_rows
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
6.01
 country_rows
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
6
 location_rows
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 value_map_rows
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 utm_post_rows
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 first_period_block
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
8
 first_post
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 rows_at
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 pick_field
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 rank_and_cap
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
6
 child_items
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 item
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 subscriber_series
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 posting_calendar
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
5
 streak_summary
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
8
 all_posts_comment_followers
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 extract_post_views_series
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
11.24
 bucket_daily_views
96.15% covered (success)
96.15%
25 / 26
0.00% covered (danger)
0.00%
0 / 1
8
 summary_window
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 compare_schema
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 pick_compare
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 compare_end_date
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
10
 months_earlier
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 overview_compare_windows
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 overview_comparison
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
5
 days_between
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 period_start
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
6.02
 normalize_visits_series
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
10.01
 period_start_date
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resolve_date
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
6
 today
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 clamp_int
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
4.84
 count_or_null
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 sum_or_null
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 site
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 visits_series_schema
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 errors_schema
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 definition_texts
100.00% covered (success)
100.00%
67 / 67
100.00% covered (success)
100.00%
1 / 1
1
 definitions
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 top_content_definitions
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
 definitions_schema
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 period_schema
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 date_schema
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 reader_meta
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 site_schema
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 as_int
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Jetpack Stats Abilities Registration.
4 *
5 * Registers Jetpack Stats abilities with the WordPress Abilities API.
6 *
7 * @package automattic/jetpack-stats
8 */
9
10namespace Automattic\Jetpack\Stats\Abilities;
11
12use Automattic\Jetpack\Stats\Settings;
13use Automattic\Jetpack\Stats\WPCOM_Stats;
14use Automattic\Jetpack\Status\Host;
15use Automattic\Jetpack\WP_Abilities\Registrar;
16use Jetpack_Options;
17use WP_Error;
18
19if ( ! defined( 'ABSPATH' ) ) {
20    exit( 0 );
21}
22
23/**
24 * Registers Jetpack Stats abilities with the WordPress Abilities API.
25 *
26 * Exposes a small, consolidated surface for reading Jetpack Stats traffic
27 * insights and managing site-level Stats settings so AI agents can
28 * answer site-owner questions through the standard `wp-abilities/v1` REST
29 * surface. Twelve abilities wrap the WPCOM Stats, subscriber and WordAds
30 * endpoints plus the `stats_options` WP option.
31 */
32class Stats_Abilities extends Registrar {
33
34    const CATEGORY_SLUG = 'jetpack-stats';
35    const ERROR_PREFIX  = Settings::ERROR_PREFIX;
36
37    /**
38     * Allowed `type` values for `get-top-content`.
39     */
40    const TOP_CONTENT_TYPES = array( 'posts', 'referrers', 'search-terms', 'clicks', 'tags', 'authors', 'countries', 'regions', 'cities', 'browsers', 'platforms', 'screen-sizes', 'utm', 'commenters', 'commented-posts', 'downloads', 'video-plays' );
41
42    /**
43     * `get-top-content` types WordPress.com reads as a number of days ending on a date, mapped to the endpoint path.
44     */
45    const DAYS_WINDOW_TYPES = array(
46        'browsers'     => 'browser',
47        'platforms'    => 'platform',
48        'screen-sizes' => 'screensize',
49        'utm'          => 'utm',
50    );
51
52    /**
53     * `get-top-content` types that rank locations below country, mapped to WordPress.com's geo mode.
54     */
55    const LOCATION_TYPES = array(
56        'regions' => 'region',
57        'cities'  => 'city',
58    );
59
60    /**
61     * `get-top-content` types that cover the site's whole history whatever the window asks.
62     */
63    const UNDATED_TYPES = array( 'tags', 'commenters', 'commented-posts' );
64
65    /**
66     * UTM parameters, and the combinations of them, WordPress.com groups views by.
67     */
68    const UTM_PARAMS = array( 'utm_source,utm_medium', 'utm_campaign,utm_source,utm_medium', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'utm_id', 'utm_source_platform', 'utm_creative_format', 'utm_marketing_tactic' );
69
70    /**
71     * Most authors WordPress.com ranks in one `stats/top-authors` response.
72     */
73    const TOP_AUTHORS_LIMIT = 20;
74
75    /**
76     * Fields `get-subscribers` can sort by.
77     */
78    const SUBSCRIBER_SORTS = array( 'date_subscribed', 'email', 'name', 'plan', 'subscription_status' );
79
80    /**
81     * Kinds of subscriber `get-subscribers` can list.
82     */
83    const SUBSCRIBER_FILTERS = array( 'all', 'email_subscriber', 'reader_subscriber', 'paid', 'comp', 'free', 'unconfirmed_subscriber', 'blocked_subscriber' );
84
85    /**
86     * Fields `get-email-stats` can sort by.
87     */
88    const EMAIL_SORTS = array( 'post_date', 'opens', 'clicks' );
89
90    /**
91     * The most posts `stats/streak` returns, the cap WordPress.com sets.
92     */
93    const STREAK_MAX_POSTS = 10000;
94
95    /**
96     * The most pages `get-video-stats` lists the video played on.
97     */
98    const VIDEO_PAGES_LIMIT = 20;
99
100    /**
101     * The windows `get-email-detail` can draw an email's timeline over, each counted from the send.
102     */
103    const EMAIL_TIMELINES = array( 'first_24_hours', 'first_7_days', 'first_30_days', 'all_time' );
104
105    /**
106     * The most monthly buckets the email timeline endpoint answers per request.
107     */
108    const EMAIL_TIMELINE_MAX_MONTHS = 120;
109
110    /**
111     * The `get-email-detail` breakdowns: each `{stat}/{field}` WordPress.com reports for one emailed post.
112     */
113    const EMAIL_BREAKDOWNS = array(
114        'opens/rate',
115        'opens/client',
116        'opens/device',
117        'opens/country',
118        'clicks/rate',
119        'clicks/client',
120        'clicks/device',
121        'clicks/country',
122        'clicks/link',
123        'clicks/user-content-link',
124    );
125
126    /**
127     * Allowed aggregation periods for top-content and video reads.
128     */
129    const PERIODS = array( 'day', 'week', 'month', 'year' );
130
131    /**
132     * Allowed aggregation periods for the timeseries whose WordPress.com endpoints also chart quarters.
133     */
134    const SERIES_PERIODS = array( 'day', 'week', 'month', 'quarter', 'year' );
135
136    /**
137     * Most UTM values an expanded top-content read lists posts for, one WordPress.com read each.
138     */
139    const UTM_EXPAND_MAX = 20;
140
141    /**
142     * Comparison presets, named as in the Stats dashboard's Compare menu.
143     */
144    const COMPARE_PRESETS = array( 'previous-period', 'previous-period-match-day-of-week', 'previous-year', 'previous-year-match-day-of-week' );
145
146    /**
147     * Allowed metric fields for `get-visits`.
148     */
149    const VISIT_FIELDS = array( 'views', 'visitors', 'likes', 'comments' );
150
151    /**
152     * Default metric fields for `get-visits` when the caller omits `fields`.
153     */
154    const DEFAULT_VISIT_FIELDS = array( 'views', 'visitors' );
155
156    /**
157     * Normalization table for `get-top-content`.
158     *
159     * Each entry describes how to project a WPCOM `days -> <date> -> <list>`
160     * (or `summary -> <list>`) array of rows into the uniform
161     * `{ rank, label, value, href?, id? }` shape. A field given as a list of keys
162     * reads the first of them that is set and not ''.
163     * `countries` (needs `country-info` join) and `tags` (rows that group
164     * several terms, no `days` envelope) are special-cased in the callback.
165     */
166    const TOP_CONTENT_MAP = array(
167        'posts'           => array(
168            'list'  => 'postviews',
169            'label' => 'title',
170            'value' => 'views',
171            'href'  => 'href',
172            'id'    => 'id',
173        ),
174        'referrers'       => array(
175            // WPCOM `stats/referrers` keys per-day data under `groups`, not `referrers` â€”
176            // each group exposes `name`, `total`, and (sometimes) `url`.
177            'list'     => 'groups',
178            'label'    => 'name',
179            'value'    => 'total',
180            'href'     => 'url',
181            'children' => 'results',
182        ),
183        'search-terms'    => array(
184            'list'  => 'search_terms',
185            'label' => 'term',
186            'value' => 'views',
187        ),
188        'clicks'          => array(
189            'list'     => 'clicks',
190            'label'    => array( 'name', 'url' ),
191            'value'    => 'views',
192            'href'     => 'url',
193            'children' => 'children',
194        ),
195        'authors'         => array(
196            'list'     => 'authors',
197            'label'    => 'name',
198            'value'    => 'views',
199            'id'       => 'author_id',
200            'children' => 'posts',
201        ),
202        'downloads'       => array(
203            'list'  => 'files',
204            'label' => array( 'filename', 'relative_url' ),
205            'value' => array( 'downloads', 'download_count' ),
206            'href'  => array( 'download_url', 'relative_url' ),
207        ),
208        'video-plays'     => array(
209            'list'  => 'plays',
210            'label' => 'title',
211            'value' => 'plays',
212            'id'    => 'post_id',
213        ),
214        'commenters'      => array(
215            'list'  => 'authors',
216            'label' => 'name',
217            'value' => 'comments',
218        ),
219        'commented-posts' => array(
220            'list'  => 'posts',
221            'label' => 'name',
222            'value' => 'comments',
223            'href'  => 'link',
224            'id'    => 'id',
225        ),
226    );
227
228    /**
229     * {@inheritDoc}
230     */
231    protected static function enabled_by_default(): bool {
232        return true;
233    }
234
235    /**
236     * {@inheritDoc}
237     */
238    public static function get_category_slug(): string {
239        return self::CATEGORY_SLUG;
240    }
241
242    /**
243     * {@inheritDoc}
244     */
245    public static function get_category_definition(): array {
246        return array(
247            // "Jetpack" is a product name and should not be translated.
248            'label'       => 'Jetpack Stats',
249            'description' => __( 'Abilities for reading Jetpack Stats traffic insights and managing site-level Stats settings.', 'jetpack-stats-pkg' ),
250        );
251    }
252
253    /**
254     * {@inheritDoc}
255     */
256    public static function get_abilities(): array {
257        return array(
258            'jetpack-stats/get-site-overview' => self::spec_get_site_overview(),
259            'jetpack-stats/get-top-content'   => self::spec_get_top_content(),
260            'jetpack-stats/get-post-views'    => self::spec_get_post_views(),
261            'jetpack-stats/get-post-detail'   => self::spec_get_post_detail(),
262            'jetpack-stats/get-visits'        => self::spec_get_visits(),
263            'jetpack-stats/get-followers'     => self::spec_get_followers(),
264            'jetpack-stats/get-author-views'  => self::spec_get_author_views(),
265            'jetpack-stats/get-insights'      => self::spec_get_insights(),
266            'jetpack-stats/get-email-stats'   => self::spec_get_email_stats(),
267            'jetpack-stats/get-email-detail'  => self::spec_get_email_detail(),
268            'jetpack-stats/get-video-stats'   => self::spec_get_video_stats(),
269            'jetpack-stats/get-subscribers'   => self::spec_get_subscribers(),
270            'jetpack-stats/get-ad-stats'      => self::spec_get_ad_stats(),
271            'jetpack-stats/get-settings'      => self::spec_get_settings(),
272            'jetpack-stats/update-settings'   => self::spec_update_settings(),
273        );
274    }
275
276    /*
277    ---------------------------------------------------------------------
278     * Ability specs
279     * ---------------------------------------------------------------------
280     */
281
282    /**
283     * Spec: jetpack-stats/get-site-overview.
284     */
285    private static function spec_get_site_overview(): array {
286        return array(
287            'label'               => __( 'Get site stats overview', 'jetpack-stats-pkg' ),
288            'description'         => __(
289                'Answer "how is my site doing right now?" in one call, from today\'s and recent Stats. With `compare`, `comparison` holds the same four figures for the earlier windows the preset names, as in the Stats dashboard\'s Compare menu: `previous-period` (yesterday, the 7 days before the last 7, the 30 days before the last 30), `previous-period-match-day-of-week` (shifted back by whole weeks), `previous-year` (the same dates a year earlier), `previous-year-match-day-of-week` (52 weeks earlier). `views_week` and `views_month` are rolling totals for the last 7 and 30 days, today included (not calendar weeks or months). `top_post` is today\'s most-viewed post or page (the home page / archives row is skipped, so `id` is always a real post ID); `top_post` and `top_referrer` are null when there is none today. Composes the WPCOM stats/visits, stats/top-posts, and stats/referrers endpoints â€” if any sub-call fails, `partial` is true and `errors` lists the failed sub-calls: `visits` (every views and visitors field), `top_posts` (`top_post`), `referrers` (`top_referrer`), and `comparison` (every `comparison` figure). Fields fed by a failed sub-call are null, as is a total covering a day WordPress.com did not report, so a 0 is a value WordPress.com reported. If every sub-call fails, returns `jetpack_stats_data_unavailable`. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: the site must be connected to WordPress.com. Results cached for ~5 minutes by WPCOM_Stats â€” safe to poll.',
290                'jetpack-stats-pkg'
291            ),
292            'input_schema'        => array(
293                'type'                 => 'object',
294                'default'              => array(),
295                'properties'           => array(
296                    'compare' => self::compare_schema(),
297                ),
298                'additionalProperties' => false,
299            ),
300            'output_schema'       => array(
301                'type'       => 'object',
302                'properties' => array(
303                    'date'           => array( 'type' => 'string' ),
304                    'site'           => self::site_schema(),
305                    'views_today'    => array( 'type' => array( 'integer', 'null' ) ),
306                    'visitors_today' => array( 'type' => array( 'integer', 'null' ) ),
307                    'views_week'     => array( 'type' => array( 'integer', 'null' ) ),
308                    'views_month'    => array( 'type' => array( 'integer', 'null' ) ),
309                    'top_post'       => array(
310                        'type'       => array( 'object', 'null' ),
311                        'properties' => array(
312                            'id'    => array( 'type' => 'integer' ),
313                            'title' => array( 'type' => 'string' ),
314                            'views' => array( 'type' => 'integer' ),
315                        ),
316                    ),
317                    'top_referrer'   => array(
318                        'type'       => array( 'object', 'null' ),
319                        'properties' => array(
320                            'name'  => array( 'type' => 'string' ),
321                            'views' => array( 'type' => 'integer' ),
322                        ),
323                    ),
324                    'comparison'     => array(
325                        'type'       => 'object',
326                        'properties' => array(
327                            'preset'         => array( 'type' => 'string' ),
328                            'views_today'    => array( 'type' => array( 'integer', 'null' ) ),
329                            'visitors_today' => array( 'type' => array( 'integer', 'null' ) ),
330                            'views_week'     => array( 'type' => array( 'integer', 'null' ) ),
331                            'views_month'    => array( 'type' => array( 'integer', 'null' ) ),
332                            'windows'        => array(
333                                'type'                 => 'object',
334                                // `today`, `week` and `month`, each the dates its figure covers.
335                                'additionalProperties' => array(
336                                    'type'       => 'object',
337                                    'properties' => array(
338                                        'from' => array( 'type' => 'string' ),
339                                        'to'   => array( 'type' => 'string' ),
340                                    ),
341                                ),
342                            ),
343                        ),
344                    ),
345                    'partial'        => array( 'type' => 'boolean' ),
346                    'errors'         => self::errors_schema(),
347                    'definitions'    => self::definitions_schema(),
348                ),
349            ),
350            'execute_callback'    => array( __CLASS__, 'get_site_overview' ),
351            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
352            'meta'                => self::reader_meta(),
353        );
354    }
355
356    /**
357     * Spec: jetpack-stats/get-top-content.
358     */
359    private static function spec_get_top_content(): array {
360        return array(
361            'label'               => __( 'Get top stats content', 'jetpack-stats-pkg' ),
362            'description'         => __(
363                'Return the top items for a chosen content type in one filtered call: posts, referrers, search terms, outbound clicks, tags/categories, authors, countries, regions, cities, browsers, platforms (operating systems), screen sizes, UTM campaign values, commenters, commented posts, downloads, or video plays. Every type returns the same item shape. `label` is human-readable (post title, referrer host, search term, place name, browser, etc.); a tags item names every tag and category it groups, and countries WordPress.com cannot place share one item. `value` is the count for that item: views for most types, clicks, comments, downloads or plays where the type says so, and for `screen-sizes` the percent of views. `country` is the ISO country code of a region or city item. `max` caps the items; `max=0` returns every item. With `expand=true`, an item that groups other rows lists them in `children`. Referrers group the pages that sent views (and the Search Engines item each engine), clicks group the links under one domain, authors group their posts, a UTM value lists the posts its views went to, and a tags item lists each tag and category (`type`), which share its views so carry no `value` of their own. Each UTM value\'s posts are a separate WordPress.com read, so with `type=utm` and `expand=true`, `max` must be 1 to 20; if some of those reads fail, those items have no `children`, `partial` is true and `errors` lists `children`. `max` caps each item\'s children too, as WordPress.com does at every level; `max=0` returns them all. `truncated` is true when more items exist than `max` returned; WordPress.com ranks at most 20 authors, so a full authors list is flagged too. `href` is present only when the item has a canonical URL, and is where a link leads rather than WordPress.com\'s href.li redirect. `id` is the post ID on posts and commented-posts items other than the home page / archives row (pass it to jetpack-stats/get-post-views); the author\'s user ID on authors items; the video\'s ID on video-plays items; and the post ID on the posts a UTM value lists. With `num` above 1, items are totals across the `num` periods ending with the one containing `date` (e.g. period=day, num=7 is the last seven days). `utm` groups views by `utm_param`. `tags` ignores `period`, `date` and `num` and covers the seven days ending yesterday; `commenters` and `commented-posts` ignore them too and count every comment ever approved. Regions, cities, browsers, platforms, screen sizes and UTM values need a Stats plan that includes them; on other sites WordPress.com refuses with `stats_error` and says so. `downloads` only works on WordPress.com sites that do not use Jetpack; elsewhere it returns `jetpack_stats_invalid_type`. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
364                'jetpack-stats-pkg'
365            ),
366            'input_schema'        => array(
367                'type'                 => 'object',
368                'required'             => array( 'type' ),
369                'properties'           => array(
370                    'type'      => array(
371                        'type'        => 'string',
372                        'description' => __( 'Which top-N surface to fetch.', 'jetpack-stats-pkg' ),
373                        'enum'        => self::TOP_CONTENT_TYPES,
374                    ),
375                    'period'    => array(
376                        'type'        => 'string',
377                        'description' => __( 'Aggregation period.', 'jetpack-stats-pkg' ),
378                        'enum'        => self::PERIODS,
379                        'default'     => 'day',
380                    ),
381                    'date'      => array(
382                        'type'        => 'string',
383                        'description' => __( 'End date (YYYY-MM-DD). Defaults to today.', 'jetpack-stats-pkg' ),
384                        'pattern'     => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
385                    ),
386                    'num'       => array(
387                        'type'        => 'integer',
388                        'description' => __( 'How many prior periods to roll up (1-90).', 'jetpack-stats-pkg' ),
389                        'minimum'     => 1,
390                        'maximum'     => 90,
391                        'default'     => 1,
392                    ),
393                    'max'       => array(
394                        'type'        => 'integer',
395                        'description' => __( 'Results cap (1-100), or 0 for every item.', 'jetpack-stats-pkg' ),
396                        'minimum'     => 0,
397                        'maximum'     => 100,
398                        'default'     => 20,
399                    ),
400                    'expand'    => array(
401                        'type'        => 'boolean',
402                        'description' => __( 'Also return the rows each item groups, as the Stats dashboard does when a row is opened: the pages and engines under a referrer, the links under a clicked domain, an author\'s posts, and the terms in a tags item.', 'jetpack-stats-pkg' ),
403                        'default'     => false,
404                    ),
405                    'utm_param' => array(
406                        'type'        => 'string',
407                        'description' => __( 'For `type=utm`: the UTM parameter, or combination of them, to group views by.', 'jetpack-stats-pkg' ),
408                        'enum'        => self::UTM_PARAMS,
409                        'default'     => 'utm_source,utm_medium',
410                    ),
411                ),
412                'additionalProperties' => false,
413            ),
414            'output_schema'       => array(
415                'type'       => 'object',
416                'properties' => array(
417                    'site'        => self::site_schema(),
418                    'type'        => array( 'type' => 'string' ),
419                    'period'      => array( 'type' => 'string' ),
420                    'date'        => array( 'type' => 'string' ),
421                    'num'         => array( 'type' => 'integer' ),
422                    'max'         => array( 'type' => 'integer' ),
423                    'expand'      => array( 'type' => 'boolean' ),
424                    'utm_param'   => array( 'type' => 'string' ),
425                    'truncated'   => array( 'type' => 'boolean' ),
426                    'items'       => array(
427                        'type'  => 'array',
428                        'items' => array(
429                            'type'       => 'object',
430                            'properties' => array(
431                                'rank'     => array( 'type' => 'integer' ),
432                                'label'    => array( 'type' => 'string' ),
433                                'value'    => array( 'type' => 'integer' ),
434                                'href'     => array( 'type' => 'string' ),
435                                'id'       => array( 'type' => 'integer' ),
436                                'country'  => array( 'type' => 'string' ),
437                                'children' => array(
438                                    'type'  => 'array',
439                                    'items' => array(
440                                        'type'       => 'object',
441                                        'properties' => array(
442                                            'label'    => array( 'type' => 'string' ),
443                                            'value'    => array( 'type' => 'integer' ),
444                                            'href'     => array( 'type' => 'string' ),
445                                            'id'       => array( 'type' => 'integer' ),
446                                            'type'     => array( 'type' => 'string' ),
447                                            // Rows a child groups in turn, in the same shape.
448                                            'children' => array( 'type' => 'array' ),
449                                        ),
450                                        'required'   => array( 'label' ),
451                                    ),
452                                ),
453                            ),
454                            'required'   => array( 'rank', 'label', 'value' ),
455                        ),
456                    ),
457                    'partial'     => array( 'type' => 'boolean' ),
458                    'errors'      => self::errors_schema(),
459                    'definitions' => self::definitions_schema(),
460                ),
461            ),
462            'execute_callback'    => array( __CLASS__, 'get_top_content' ),
463            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
464            'meta'                => self::reader_meta(),
465        );
466    }
467
468    /**
469     * Spec: jetpack-stats/get-post-detail.
470     */
471    private static function spec_get_post_detail(): array {
472        $int     = array( 'type' => array( 'integer', 'null' ) );
473        $rate    = array( 'type' => array( 'number', 'null' ) );
474        $summary = array(
475            'type'       => 'object',
476            'properties' => array(
477                'total'  => $int,
478                'unique' => $int,
479                'rate'   => $rate,
480            ),
481        );
482
483        return array(
484            'label'               => __( 'Get one post\'s stats', 'jetpack-stats-pkg' ),
485            'description'         => __(
486                'Report everything Stats knows about one post or page, as on the Stats dashboard\'s page for it: all-time `views`, `likes` and `comments` with the most recent ones, the UTM values that brought views to it, and how it did as a newsletter email. `post` names it: title, type (post, page or another type), permalink and publication date. `likes.recent` lists the most recent likers by display name and `comments.recent` the most recent approved comments, each at most `max` long. `utm` ranks the UTM values (grouped by `utm_param`) of the links that opened the post, over all time, top `max` first; it needs a Stats plan that includes UTM, so on other sites it is null, `partial` is true and `errors` lists `utm`. `email.emailed` is false when the post was never sent to subscribers (pages never are), and then every other `email` figure is null rather than 0. When it was sent, `email.sent` is how many subscribers it went to and `opens` and `clicks` hold all-time totals, unique people and rates. Composes several WPCOM endpoints â€” if one fails, `partial` is true, `errors` lists it (`views`, `likes`, `utm` or `email`) and the fields it feeds are null. Returns `jetpack_stats_post_not_found` when no post or page has that ID or the user cannot open it, like an unpublished one. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
487                'jetpack-stats-pkg'
488            ),
489            'input_schema'        => array(
490                'type'                 => 'object',
491                'required'             => array( 'post_id' ),
492                'properties'           => array(
493                    'post_id'   => array(
494                        'type'        => array( 'integer', 'string' ),
495                        'description' => __( 'The ID of the post or page. Must be positive.', 'jetpack-stats-pkg' ),
496                    ),
497                    'utm_param' => array(
498                        'type'        => 'string',
499                        'description' => __( 'The UTM parameter, or combination of them, to group the post\'s UTM views by.', 'jetpack-stats-pkg' ),
500                        'enum'        => self::UTM_PARAMS,
501                        'default'     => 'utm_source,utm_medium',
502                    ),
503                    'max'       => array(
504                        'type'        => 'integer',
505                        'description' => __( 'Cap on each list: recent likes, recent comments and UTM values (1-100).', 'jetpack-stats-pkg' ),
506                        'minimum'     => 1,
507                        'maximum'     => 100,
508                        'default'     => 10,
509                    ),
510                ),
511                'additionalProperties' => false,
512            ),
513            'output_schema'       => array(
514                'type'       => 'object',
515                'properties' => array(
516                    'site'        => self::site_schema(),
517                    'post'        => array(
518                        'type'       => 'object',
519                        'properties' => array(
520                            'id'        => array( 'type' => 'integer' ),
521                            'title'     => array( 'type' => 'string' ),
522                            'type'      => array( 'type' => 'string' ),
523                            'url'       => array( 'type' => 'string' ),
524                            'published' => array( 'type' => array( 'string', 'null' ) ),
525                        ),
526                    ),
527                    'views'       => $int,
528                    'likes'       => array(
529                        'type'       => 'object',
530                        'properties' => array(
531                            'total'  => $int,
532                            'recent' => array(
533                                'type'  => array( 'array', 'null' ),
534                                'items' => array(
535                                    'type'       => 'object',
536                                    'properties' => array(
537                                        'name' => array( 'type' => 'string' ),
538                                    ),
539                                ),
540                            ),
541                        ),
542                    ),
543                    'comments'    => array(
544                        'type'       => 'object',
545                        'properties' => array(
546                            'total'  => array( 'type' => 'integer' ),
547                            'recent' => array(
548                                'type'  => 'array',
549                                'items' => array(
550                                    'type'       => 'object',
551                                    'properties' => array(
552                                        'author'  => array( 'type' => 'string' ),
553                                        'date'    => array( 'type' => 'string' ),
554                                        'excerpt' => array( 'type' => 'string' ),
555                                        'url'     => array( 'type' => 'string' ),
556                                    ),
557                                ),
558                            ),
559                        ),
560                    ),
561                    'utm_param'   => array( 'type' => 'string' ),
562                    'utm'         => array(
563                        'type'  => array( 'array', 'null' ),
564                        'items' => array(
565                            'type'       => 'object',
566                            'properties' => array(
567                                'label' => array( 'type' => 'string' ),
568                                'value' => array( 'type' => 'integer' ),
569                            ),
570                        ),
571                    ),
572                    'email'       => array(
573                        'type'       => 'object',
574                        'properties' => array(
575                            'emailed' => array( 'type' => array( 'boolean', 'null' ) ),
576                            'sent'    => $int,
577                            'opens'   => $summary,
578                            'clicks'  => $summary,
579                        ),
580                    ),
581                    'partial'     => array( 'type' => 'boolean' ),
582                    'errors'      => self::errors_schema(),
583                    'definitions' => self::definitions_schema(),
584                ),
585            ),
586            'execute_callback'    => array( __CLASS__, 'get_post_detail' ),
587            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
588            'meta'                => self::reader_meta(),
589        );
590    }
591
592    /**
593     * Spec: jetpack-stats/get-post-views.
594     */
595    private static function spec_get_post_views(): array {
596        return array(
597            'label'               => __( 'Get views for a post', 'jetpack-stats-pkg' ),
598            'description'         => __(
599                'Return views history for a single post: total views, timeseries of per-period views, and the period metadata. `total_views` is the post\'s all-time view count; when WordPress.com does not report it, it and every `series` value are null. `series` always has `num` rows, oldest first, ending with the period that contains `date`; each row\'s `date` is the first day of its period (weeks start on Monday) and periods with no views are 0. Returns `jetpack_stats_post_not_found` when no post has that ID. Accepts post_id as integer or numeric string (the literal "0" is rejected only because WordPress has no post 0 â€” any positive numeric value is legal). `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com. Related: call jetpack-stats/get-top-content with type=posts first and pass an item\'s `id` as `post_id`.',
600                'jetpack-stats-pkg'
601            ),
602            'input_schema'        => array(
603                'type'                 => 'object',
604                'required'             => array( 'post_id' ),
605                'properties'           => array(
606                    'post_id' => array(
607                        'type'        => array( 'integer', 'string' ),
608                        'description' => __( 'The post ID to fetch views for. Must be positive.', 'jetpack-stats-pkg' ),
609                    ),
610                    'period'  => array(
611                        'type'        => 'string',
612                        'description' => __( 'Aggregation period.', 'jetpack-stats-pkg' ),
613                        'enum'        => self::SERIES_PERIODS,
614                        'default'     => 'day',
615                    ),
616                    'num'     => array(
617                        'type'        => 'integer',
618                        'description' => __( 'How many prior periods to include (1-90).', 'jetpack-stats-pkg' ),
619                        'minimum'     => 1,
620                        'maximum'     => 90,
621                        'default'     => 30,
622                    ),
623                    'date'    => array(
624                        'type'        => 'string',
625                        'description' => __( 'End date (YYYY-MM-DD). Defaults to today.', 'jetpack-stats-pkg' ),
626                        'pattern'     => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
627                    ),
628                ),
629                'additionalProperties' => false,
630            ),
631            'output_schema'       => array(
632                'type'       => 'object',
633                'properties' => array(
634                    'site'        => self::site_schema(),
635                    'post_id'     => array( 'type' => 'integer' ),
636                    'total_views' => array( 'type' => array( 'integer', 'null' ) ),
637                    'period'      => array( 'type' => 'string' ),
638                    'num'         => array( 'type' => 'integer' ),
639                    'date'        => array( 'type' => 'string' ),
640                    'series'      => array(
641                        'type'  => 'array',
642                        'items' => array(
643                            'type'       => 'object',
644                            'properties' => array(
645                                'date'  => array( 'type' => 'string' ),
646                                'views' => array( 'type' => array( 'integer', 'null' ) ),
647                            ),
648                        ),
649                    ),
650                    'definitions' => self::definitions_schema(),
651                ),
652            ),
653            'execute_callback'    => array( __CLASS__, 'get_post_views' ),
654            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
655            'meta'                => self::reader_meta(),
656        );
657    }
658
659    /**
660     * Spec: jetpack-stats/get-visits.
661     */
662    private static function spec_get_visits(): array {
663        return array(
664            'label'               => __( 'Get site visits timeseries', 'jetpack-stats-pkg' ),
665            'description'         => __(
666                'Return a site-level views/visitors/likes/comments timeseries â€” answers "is traffic trending up?". With `compare`, `comparison.series` holds the same rows for an earlier window, row for row, as in the Stats dashboard\'s Compare menu: `previous-period` (the `num` periods before), `previous-period-match-day-of-week` (daily rows shifted back by whole weeks), `previous-year` (a year earlier; weeks shift 52 weeks), `previous-year-match-day-of-week` (52 weeks earlier). The weekday presets accept only day and week periods. If WordPress.com cannot read the compared window, `comparison.series` is null, `partial` is true and `errors` lists `comparison`. Each row\'s `date` is the first day of its period (weeks start on Monday). Every series row always includes every field listed in the request (no per-row omission); a value WordPress.com did not report, or reported as negative, is null rather than 0. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
667                'jetpack-stats-pkg'
668            ),
669            'input_schema'        => array(
670                'type'                 => 'object',
671                'default'              => array(),
672                'properties'           => array(
673                    'period'  => array(
674                        'type'        => 'string',
675                        'description' => __( 'Granularity of each data point.', 'jetpack-stats-pkg' ),
676                        'enum'        => self::SERIES_PERIODS,
677                        'default'     => 'day',
678                    ),
679                    'num'     => array(
680                        'type'        => 'integer',
681                        'description' => __( 'How many data points to return (1-90).', 'jetpack-stats-pkg' ),
682                        'minimum'     => 1,
683                        'maximum'     => 90,
684                        'default'     => 30,
685                    ),
686                    'date'    => array(
687                        'type'        => 'string',
688                        'description' => __( 'End date (YYYY-MM-DD). Defaults to today.', 'jetpack-stats-pkg' ),
689                        'pattern'     => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
690                    ),
691                    'fields'  => array(
692                        'type'        => 'array',
693                        'description' => __( 'Which metrics to include in each row. Defaults to views+visitors.', 'jetpack-stats-pkg' ),
694                        'items'       => array(
695                            'type' => 'string',
696                            'enum' => self::VISIT_FIELDS,
697                        ),
698                        'default'     => self::DEFAULT_VISIT_FIELDS,
699                    ),
700                    'compare' => self::compare_schema(),
701                ),
702                'additionalProperties' => false,
703            ),
704            'output_schema'       => array(
705                'type'       => 'object',
706                'properties' => array(
707                    'site'        => self::site_schema(),
708                    'period'      => array( 'type' => 'string' ),
709                    'num'         => array( 'type' => 'integer' ),
710                    'date'        => array( 'type' => 'string' ),
711                    'fields'      => array(
712                        'type'  => 'array',
713                        'items' => array(
714                            'type' => 'string',
715                            'enum' => self::VISIT_FIELDS,
716                        ),
717                    ),
718                    'series'      => self::visits_series_schema(),
719                    'comparison'  => array(
720                        'type'       => 'object',
721                        'properties' => array(
722                            'preset' => array( 'type' => 'string' ),
723                            'date'   => array( 'type' => 'string' ),
724                            'series' => self::visits_series_schema( true ),
725                        ),
726                    ),
727                    'partial'     => array( 'type' => 'boolean' ),
728                    'errors'      => self::errors_schema(),
729                    'definitions' => self::definitions_schema(),
730                ),
731            ),
732            'execute_callback'    => array( __CLASS__, 'get_visits' ),
733            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
734            'meta'                => self::reader_meta(),
735        );
736    }
737
738    /**
739     * Spec: jetpack-stats/get-followers.
740     */
741    private static function spec_get_followers(): array {
742        return array(
743            'label'               => __( 'Get follower counts', 'jetpack-stats-pkg' ),
744            'description'         => __(
745                'Return the site\'s follower counts by source â€” answers "how is my audience growing?" in one call. `email` and `wpcom` are the site\'s email subscribers and WordPress.com followers; `comment` counts people following the comments on every post (following one post\'s comments is not counted), and is reported as unknown through `errors` when WordPress.com does not list that count on its first page; `publicize` is an object, empty when no social connection reports followers. Composes three WPCOM endpoints â€” if any sub-call fails, `partial` is true and `errors` lists the failed sub-calls: `followers` (`email` and `wpcom`), `comment_followers`, and `publicize_followers`. Counts fed by a failed sub-call are null, `publicize` included, and `total` is null whenever any count is, so a 0 is a value WordPress.com reported. `paid` counts paid subscribers, who are also in `email` or `wpcom`, and is null when the `subscriber_counts` sub-call fails. With `period`, `series` tracks the subscriber count over the last `num` periods, as the Stats dashboard\'s Subscribers chart does; it is null when the `subscriber_history` sub-call fails. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
746                'jetpack-stats-pkg'
747            ),
748            'input_schema'        => array(
749                'type'                 => 'object',
750                'default'              => array(),
751                'properties'           => array(
752                    'period' => array(
753                        'type'        => 'string',
754                        'description' => __( 'Also chart the subscriber count, one row per period.', 'jetpack-stats-pkg' ),
755                        'enum'        => self::SERIES_PERIODS,
756                    ),
757                    'date'   => self::date_schema(),
758                    'num'    => array(
759                        'type'        => 'integer',
760                        'description' => __( 'How many periods to chart, ending with the one containing `date` (1-90).', 'jetpack-stats-pkg' ),
761                        'minimum'     => 1,
762                        'maximum'     => 90,
763                        'default'     => 30,
764                    ),
765                ),
766                'additionalProperties' => false,
767            ),
768            'output_schema'       => array(
769                'type'       => 'object',
770                'properties' => array(
771                    'site'        => self::site_schema(),
772                    'total'       => array( 'type' => array( 'integer', 'null' ) ),
773                    'email'       => array( 'type' => array( 'integer', 'null' ) ),
774                    'wpcom'       => array( 'type' => array( 'integer', 'null' ) ),
775                    'comment'     => array( 'type' => array( 'integer', 'null' ) ),
776                    'paid'        => array( 'type' => array( 'integer', 'null' ) ),
777                    'publicize'   => array(
778                        'type'                 => array( 'object', 'null' ),
779                        // Follower count keyed by service slug.
780                        'additionalProperties' => array( 'type' => 'integer' ),
781                    ),
782                    'series'      => array(
783                        'type'  => array( 'array', 'null' ),
784                        'items' => array(
785                            'type'       => 'object',
786                            'properties' => array(
787                                'date'        => array( 'type' => 'string' ),
788                                'subscribers' => array( 'type' => 'integer' ),
789                                'change'      => array( 'type' => 'integer' ),
790                            ),
791                        ),
792                    ),
793                    'partial'     => array( 'type' => 'boolean' ),
794                    'errors'      => self::errors_schema(),
795                    'definitions' => self::definitions_schema(),
796                ),
797            ),
798            'execute_callback'    => array( __CLASS__, 'get_followers' ),
799            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
800            'meta'                => self::reader_meta(),
801        );
802    }
803
804    /**
805     * Spec: jetpack-stats/get-author-views.
806     */
807    private static function spec_get_author_views(): array {
808        return array(
809            'label'               => __( 'Get views for an author', 'jetpack-stats-pkg' ),
810            'description'         => __(
811                'Report one author\'s views over time, with the likes and comments their content received in the same window. `series` has one row per period, oldest first; `views`, `likes` and `comments` are totals for the whole window. `views` counts every post and page the author wrote, so it can exceed their authors item, which counts only the site\'s most-viewed posts each day. `content_counts` is the author\'s published content by post type, and `first_content_date` when they first published, in GMT. An author with 50,000 or more posts returns `stats_error`. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
812                'jetpack-stats-pkg'
813            ),
814            'input_schema'        => array(
815                'type'                 => 'object',
816                'required'             => array( 'author_id' ),
817                'properties'           => array(
818                    'author_id' => array(
819                        'type'        => 'integer',
820                        'description' => __( 'The author\'s user ID, as Stats reports it on a top author.', 'jetpack-stats-pkg' ),
821                        'minimum'     => 1,
822                    ),
823                    'period'    => self::period_schema( self::SERIES_PERIODS ),
824                    'date'      => self::date_schema(),
825                    'num'       => array(
826                        'type'        => 'integer',
827                        'description' => __( 'How many periods, ending with the one containing `date` (1-90).', 'jetpack-stats-pkg' ),
828                        'minimum'     => 1,
829                        'maximum'     => 90,
830                        'default'     => 30,
831                    ),
832                ),
833                'additionalProperties' => false,
834            ),
835            'output_schema'       => array(
836                'type'       => 'object',
837                'properties' => array(
838                    'site'               => self::site_schema(),
839                    'author'             => array(
840                        'type'       => 'object',
841                        'properties' => array(
842                            'id'   => array( 'type' => 'integer' ),
843                            'name' => array( 'type' => 'string' ),
844                        ),
845                    ),
846                    'period'             => array( 'type' => 'string' ),
847                    'date'               => array( 'type' => 'string' ),
848                    'num'                => array( 'type' => 'integer' ),
849                    'views'              => array( 'type' => 'integer' ),
850                    'likes'              => array( 'type' => 'integer' ),
851                    'comments'           => array( 'type' => 'integer' ),
852                    'series'             => self::visits_series_schema(),
853                    'content_counts'     => array(
854                        'type'                 => 'object',
855                        'additionalProperties' => array( 'type' => 'integer' ),
856                    ),
857                    'first_content_date' => array( 'type' => array( 'string', 'null' ) ),
858                    'definitions'        => self::definitions_schema(),
859                ),
860            ),
861            'execute_callback'    => array( __CLASS__, 'get_author_views' ),
862            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
863            'meta'                => self::reader_meta(),
864        );
865    }
866
867    /**
868     * Spec: jetpack-stats/get-insights.
869     */
870    private static function spec_get_insights(): array {
871        return array(
872            'label'               => __( 'Get site stats insights', 'jetpack-stats-pkg' ),
873            'description'         => __(
874                'Answer "what does the site\'s history say about its audience?" in one call, as the Stats dashboard\'s Insights page does. `all_time` holds the site\'s lifetime totals and its best day. `busiest` names the hour (0-23, site timezone) that drew the most views over the last 60 days and the weekday that drew the most over the last 10 weeks, each with its share of views. `recent` compares the last 7 and 30 days, both ending yesterday, with the windows just before them. `streak` is the posting streak: the current run of consecutive days with a published post, and the longest run in the last year. `calendar` is the posting calendar behind it, as on the Insights page\'s posting activity: each day of the last year with published posts and how many, oldest first. `years` totals each year\'s published posts and the words, likes and comments on them. `plan_usage` is the views counted toward the site\'s Stats plan this billing month against its limit (`views_limit` null for no limit). Composes five WPCOM endpoints â€” if any sub-call fails, `partial` is true, `errors` lists the failed sub-calls (`summary`, `insights`, `highlights`, `streak`, `usage`), and the fields they feed are null; `years` comes with `insights`, and `calendar` with `streak`. If every sub-call fails, returns `jetpack_stats_data_unavailable`. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
875                'jetpack-stats-pkg'
876            ),
877            'input_schema'        => array(
878                'type'                 => 'object',
879                'default'              => array(),
880                'additionalProperties' => false,
881            ),
882            'output_schema'       => array(
883                'type'       => 'object',
884                'properties' => array(
885                    'site'        => self::site_schema(),
886                    'all_time'    => array(
887                        'type'       => array( 'object', 'null' ),
888                        'properties' => array(
889                            'views'          => array( 'type' => 'integer' ),
890                            'visitors'       => array( 'type' => 'integer' ),
891                            'posts'          => array( 'type' => 'integer' ),
892                            'comments'       => array( 'type' => 'integer' ),
893                            'shares'         => array( 'type' => 'integer' ),
894                            'best_day'       => array( 'type' => array( 'string', 'null' ) ),
895                            'best_day_views' => array( 'type' => 'integer' ),
896                        ),
897                    ),
898                    'busiest'     => array(
899                        'type'       => array( 'object', 'null' ),
900                        'properties' => array(
901                            'hour'                => array( 'type' => 'integer' ),
902                            'hour_percent'        => array( 'type' => 'number' ),
903                            'day_of_week'         => array( 'type' => 'string' ),
904                            'day_of_week_percent' => array( 'type' => 'number' ),
905                        ),
906                    ),
907                    'recent'      => array(
908                        'type'                 => array( 'object', 'null' ),
909                        // Keyed by window: the last and previous 7 days, and the last and previous 30.
910                        'additionalProperties' => array(
911                            'type'       => 'object',
912                            'properties' => array(
913                                'from'     => array( 'type' => 'string' ),
914                                'to'       => array( 'type' => 'string' ),
915                                'views'    => array( 'type' => 'integer' ),
916                                'visitors' => array( 'type' => 'integer' ),
917                                'likes'    => array( 'type' => 'integer' ),
918                                'comments' => array( 'type' => 'integer' ),
919                            ),
920                        ),
921                    ),
922                    'streak'      => array(
923                        'type'       => array( 'object', 'null' ),
924                        'properties' => array(
925                            'current_length' => array( 'type' => 'integer' ),
926                            'longest_length' => array( 'type' => 'integer' ),
927                            'longest_start'  => array( 'type' => 'string' ),
928                            'longest_end'    => array( 'type' => 'string' ),
929                        ),
930                    ),
931                    'calendar'    => array(
932                        'type'       => array( 'object', 'null' ),
933                        'properties' => array(
934                            'from' => array( 'type' => 'string' ),
935                            'to'   => array( 'type' => 'string' ),
936                            'days' => array(
937                                'type'  => 'array',
938                                'items' => array(
939                                    'type'       => 'object',
940                                    'properties' => array(
941                                        'date'  => array( 'type' => 'string' ),
942                                        'posts' => array( 'type' => 'integer' ),
943                                    ),
944                                ),
945                            ),
946                        ),
947                    ),
948                    'years'       => array(
949                        'type'  => array( 'array', 'null' ),
950                        'items' => array(
951                            'type'       => 'object',
952                            'properties' => array(
953                                'year'     => array( 'type' => 'string' ),
954                                'posts'    => array( 'type' => 'integer' ),
955                                'words'    => array( 'type' => 'integer' ),
956                                'likes'    => array( 'type' => 'integer' ),
957                                'comments' => array( 'type' => 'integer' ),
958                            ),
959                        ),
960                    ),
961                    'plan_usage'  => array(
962                        'type'       => array( 'object', 'null' ),
963                        'properties' => array(
964                            'plan'         => array( 'type' => array( 'string', 'null' ) ),
965                            'views'        => array( 'type' => 'integer' ),
966                            'views_limit'  => array( 'type' => array( 'integer', 'null' ) ),
967                            'period_start' => array( 'type' => 'string' ),
968                            'period_end'   => array( 'type' => 'string' ),
969                            'over_limit'   => array( 'type' => 'boolean' ),
970                        ),
971                    ),
972                    'partial'     => array( 'type' => 'boolean' ),
973                    'errors'      => self::errors_schema(),
974                    'definitions' => self::definitions_schema(),
975                ),
976            ),
977            'execute_callback'    => array( __CLASS__, 'get_insights' ),
978            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
979            'meta'                => self::reader_meta(),
980        );
981    }
982
983    /**
984     * Spec: jetpack-stats/get-email-stats.
985     */
986    private static function spec_get_email_stats(): array {
987        return array(
988            'label'               => __( 'Get newsletter email stats', 'jetpack-stats-pkg' ),
989            'description'         => __(
990                'Report how the posts the site sent to subscribers as emails performed: for each post, the emails sent, opens and clicks, as on the Stats dashboard\'s Emails page. Posts come newest first unless `sort` says otherwise; `max` caps them. `opens` and `clicks` count every open and click; `unique_opens` and `unique_clicks` count people, and `open_rate` and `click_rate` are percents of `sent`. With `start_date` (and optionally `end_date`, up to 31 days apart) `opens` and `clicks` cover only those days, while the unique counts and rates stay all-time; without them every figure is all-time. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
991                'jetpack-stats-pkg'
992            ),
993            'input_schema'        => array(
994                'type'                 => 'object',
995                'default'              => array(),
996                'properties'           => array(
997                    'sort'       => array(
998                        'type'        => 'string',
999                        'description' => __( 'Sort posts by send date, opens or clicks.', 'jetpack-stats-pkg' ),
1000                        'enum'        => self::EMAIL_SORTS,
1001                        'default'     => 'post_date',
1002                    ),
1003                    'order'      => array(
1004                        'type'        => 'string',
1005                        'description' => __( 'Sort direction: highest or newest first (`desc`) or the reverse.', 'jetpack-stats-pkg' ),
1006                        'enum'        => array( 'desc', 'asc' ),
1007                        'default'     => 'desc',
1008                    ),
1009                    'max'        => array(
1010                        'type'        => 'integer',
1011                        'description' => __( 'Posts cap (1-100).', 'jetpack-stats-pkg' ),
1012                        'minimum'     => 1,
1013                        'maximum'     => 100,
1014                        'default'     => 10,
1015                    ),
1016                    'start_date' => array(
1017                        'type'        => 'string',
1018                        'description' => __( 'First day to count opens and clicks for (YYYY-MM-DD).', 'jetpack-stats-pkg' ),
1019                        'pattern'     => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
1020                    ),
1021                    'end_date'   => array(
1022                        'type'        => 'string',
1023                        'description' => __( 'Last day to count opens and clicks for (YYYY-MM-DD). Defaults to today when `start_date` is given.', 'jetpack-stats-pkg' ),
1024                        'pattern'     => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
1025                    ),
1026                ),
1027                'additionalProperties' => false,
1028            ),
1029            'output_schema'       => array(
1030                'type'       => 'object',
1031                'properties' => array(
1032                    'site'        => self::site_schema(),
1033                    'start_date'  => array( 'type' => 'string' ),
1034                    'end_date'    => array( 'type' => 'string' ),
1035                    'posts'       => array(
1036                        'type'  => 'array',
1037                        'items' => array(
1038                            'type'       => 'object',
1039                            'properties' => array(
1040                                'id'            => array( 'type' => 'integer' ),
1041                                'title'         => array( 'type' => 'string' ),
1042                                'href'          => array( 'type' => 'string' ),
1043                                'date'          => array( 'type' => 'string' ),
1044                                'sent'          => array( 'type' => 'integer' ),
1045                                'opens'         => array( 'type' => 'integer' ),
1046                                'unique_opens'  => array( 'type' => 'integer' ),
1047                                'open_rate'     => array( 'type' => 'number' ),
1048                                'clicks'        => array( 'type' => 'integer' ),
1049                                'unique_clicks' => array( 'type' => 'integer' ),
1050                                'click_rate'    => array( 'type' => 'number' ),
1051                            ),
1052                        ),
1053                    ),
1054                    'definitions' => self::definitions_schema(),
1055                ),
1056            ),
1057            'execute_callback'    => array( __CLASS__, 'get_email_stats' ),
1058            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
1059            'meta'                => self::reader_meta(),
1060        );
1061    }
1062
1063    /**
1064     * Spec: jetpack-stats/get-email-detail.
1065     */
1066    private static function spec_get_email_detail(): array {
1067        $rows = array(
1068            'type'  => array( 'array', 'null' ),
1069            'items' => array(
1070                'type'       => 'object',
1071                'properties' => array(
1072                    'label' => array( 'type' => 'string' ),
1073                    'value' => array( 'type' => 'integer' ),
1074                ),
1075            ),
1076        );
1077        $rate = array( 'type' => array( 'number', 'null' ) );
1078        $int  = array( 'type' => array( 'integer', 'null' ) );
1079
1080        return array(
1081            'label'               => __( 'Get one newsletter email\'s stats', 'jetpack-stats-pkg' ),
1082            'description'         => __(
1083                'Break down how one post the site sent to subscribers as an email performed, over all time since it was sent, as on the Stats dashboard\'s page for that email. `sent` is how many subscribers it went to. `opens` and `clicks` each hold the `total` count, the `unique` people, the `rate` (unique people as a percent of `sent`), and label/value rows ranked by count: `by_client` (mail app), `by_device` (operating system) and `by_country`. Each list holds its top `max` rows, so it can add up to less than `total`. `clicks.by_link` ranks the links clicked: a link in the post by its URL, and the email\'s own links by name (post title, like, comment, unsubscribe and the like). Pass `timeline` to also get the opens and clicks over time since the send, as the email page\'s chart draws them: `first_24_hours` by the hour, `first_7_days` or `first_30_days` by the day, or `all_time` by the month. `timeline.rows` has one row per bucket, oldest first, with its `date` (`YYYY-MM-DD HH:00` for hours, the first day of the month for months), `opens` and `clicks`; rows stop at the current bucket, so a recent email has fewer. Without `timeline`, `timeline` is null. Composes ten WPCOM endpoints, twelve with `timeline` â€” if any sub-call fails, `partial` is true, `errors` lists the failed sub-calls by `{stat}/{field}` (such as `opens/rate`, `clicks/link` or `opens/timeline`), and the fields they feed are null. If every sub-call fails, returns `jetpack_stats_data_unavailable`; an unknown post returns `jetpack_stats_post_not_found`. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
1084                'jetpack-stats-pkg'
1085            ),
1086            'input_schema'        => array(
1087                'type'                 => 'object',
1088                'required'             => array( 'post_id' ),
1089                'properties'           => array(
1090                    'post_id'  => array(
1091                        'type'        => array( 'integer', 'string' ),
1092                        'description' => __( 'The ID of the post the site emailed, as email stats report it. Must be positive.', 'jetpack-stats-pkg' ),
1093                    ),
1094                    'max'      => array(
1095                        'type'        => 'integer',
1096                        'description' => __( 'Rows cap for each breakdown (1-100).', 'jetpack-stats-pkg' ),
1097                        'minimum'     => 1,
1098                        'maximum'     => 100,
1099                        'default'     => 10,
1100                    ),
1101                    'timeline' => array(
1102                        'type'        => 'string',
1103                        'description' => __( 'The window since the send to chart opens and clicks over. Omit to skip the timeline.', 'jetpack-stats-pkg' ),
1104                        'enum'        => self::EMAIL_TIMELINES,
1105                    ),
1106                ),
1107                'additionalProperties' => false,
1108            ),
1109            'output_schema'       => array(
1110                'type'       => 'object',
1111                'properties' => array(
1112                    'site'        => self::site_schema(),
1113                    'post_id'     => array( 'type' => 'integer' ),
1114                    'sent'        => $int,
1115                    'opens'       => array(
1116                        'type'       => 'object',
1117                        'properties' => array(
1118                            'total'      => $int,
1119                            'unique'     => $int,
1120                            'rate'       => $rate,
1121                            'by_client'  => $rows,
1122                            'by_device'  => $rows,
1123                            'by_country' => $rows,
1124                        ),
1125                    ),
1126                    'clicks'      => array(
1127                        'type'       => 'object',
1128                        'properties' => array(
1129                            'total'      => $int,
1130                            'unique'     => $int,
1131                            'rate'       => $rate,
1132                            'by_client'  => $rows,
1133                            'by_device'  => $rows,
1134                            'by_country' => $rows,
1135                            'by_link'    => $rows,
1136                        ),
1137                    ),
1138                    'timeline'    => array(
1139                        'type'       => array( 'object', 'null' ),
1140                        'properties' => array(
1141                            'window' => array(
1142                                'type' => 'string',
1143                                'enum' => self::EMAIL_TIMELINES,
1144                            ),
1145                            'unit'   => array(
1146                                'type' => 'string',
1147                                'enum' => array( 'hour', 'day', 'month' ),
1148                            ),
1149                            'rows'   => array(
1150                                'type'  => 'array',
1151                                'items' => array(
1152                                    'type'       => 'object',
1153                                    'properties' => array(
1154                                        'date'   => array( 'type' => 'string' ),
1155                                        'opens'  => $int,
1156                                        'clicks' => $int,
1157                                    ),
1158                                ),
1159                            ),
1160                        ),
1161                    ),
1162                    'partial'     => array( 'type' => 'boolean' ),
1163                    'errors'      => self::errors_schema(),
1164                    'definitions' => self::definitions_schema(),
1165                ),
1166            ),
1167            'execute_callback'    => array( __CLASS__, 'get_email_detail' ),
1168            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
1169            'meta'                => self::reader_meta(),
1170        );
1171    }
1172
1173    /**
1174     * Spec: jetpack-stats/get-video-stats.
1175     */
1176    private static function spec_get_video_stats(): array {
1177        $figures = array(
1178            'plays'          => array( 'type' => 'integer' ),
1179            'impressions'    => array( 'type' => 'integer' ),
1180            'hours_watched'  => array( 'type' => 'number' ),
1181            'retention_rate' => array( 'type' => array( 'number', 'null' ) ),
1182        );
1183
1184        return array(
1185            'label'               => __( 'Get stats for a video', 'jetpack-stats-pkg' ),
1186            'description'         => __(
1187                'Read how often one video was loaded, played and watched over time, and where, as on the Stats dashboard\'s page for that video. Each `series` row and the window `total` hold `plays`, `impressions`, `hours_watched` and `retention_rate`; `retention_rate` is null when the video\'s length is unknown. `pages` lists up to 20 pages the video was played on; a page on this site carries its `post_id` and `title`, and one elsewhere has them null. `series` has one row per period, oldest first, ending with the period that contains `date`; each row\'s `date` is the first day of its period (weeks start on Monday). Returns `jetpack_stats_video_not_found` when no video has that ID. `site` is the WordPress.com blog ID and home URL of the site whose Stats were read. `definitions` explains, in plain words, each metric and time window in the response â€” read it before reporting a number. Precondition: site must be connected to WordPress.com.',
1188                'jetpack-stats-pkg'
1189            ),
1190            'input_schema'        => array(
1191                'type'                 => 'object',
1192                'required'             => array( 'video_id' ),
1193                'properties'           => array(
1194                    'video_id' => array(
1195                        'type'        => array( 'integer', 'string' ),
1196                        'description' => __( 'The video\'s attachment ID, as video-plays top content items report it. Must be positive.', 'jetpack-stats-pkg' ),
1197                    ),
1198                    'period'   => array(
1199                        'type'        => 'string',
1200                        'description' => __( 'Aggregation period.', 'jetpack-stats-pkg' ),
1201                        'enum'        => self::PERIODS,
1202                        'default'     => 'day',
1203                    ),
1204                    'num'      => array(
1205                        'type'        => 'integer',
1206                        'description' => __( 'How many periods to include (1-90).', 'jetpack-stats-pkg' ),
1207                        'minimum'     => 1,
1208                        'maximum'     => 90,
1209                        'default'     => 30,
1210                    ),
1211                    'date'     => array(
1212                        'type'        => 'string',
1213                        'description' => __( 'End date (YYYY-MM-DD). Defaults to today.', 'jetpack-stats-pkg' ),
1214                        'pattern'     => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
1215                    ),
1216                ),
1217                'additionalProperties' => false,
1218            ),
1219            'output_schema'       => array(
1220                'type'       => 'object',
1221                'properties' => array(
1222                    'site'        => self::site_schema(),
1223                    'video_id'    => array( 'type' => 'integer' ),
1224                    'title'       => array( 'type' => 'string' ),
1225                    'period'      => array( 'type' => 'string' ),
1226                    'num'         => array( 'type' => 'integer' ),
1227                    'date'        => array( 'type' => 'string' ),
1228                    'total'       => array(
1229                        'type'       => 'object',
1230                        'properties' => $figures,
1231                    ),
1232                    'series'      => array(
1233                        'type'  => 'array',
1234                        'items' => array(
1235                            'type'       => 'object',
1236                            'properties' => array( 'date' => array( 'type' => 'string' ) ) + $figures,
1237                        ),
1238                    ),
1239                    'pages'       => array(
1240                        'type'  => 'array',
1241                        'items' => array(
1242                            'type'       => 'object',
1243                            'properties' => array(
1244                                'url'     => array( 'type' => 'string' ),
1245                                'post_id' => array( 'type' => array( 'integer', 'null' ) ),
1246                                'title'   => array( 'type' => array( 'string', 'null' ) ),
1247                            ),
1248                        ),
1249                    ),
1250                    'definitions' => self::definitions_schema(),
1251                ),
1252            ),
1253            'execute_callback'    => array( __CLASS__, 'get_video_stats' ),
1254            'permission_callback' => array( __CLASS__, 'can_view_stats' ),
1255            'meta'                => self::reader_meta(),
1256        );
1257    }
1258
1259    /**
1260     * Spec: jetpack-stats/get-subscribers.
1261     */
1262    private static function spec_get_subscribers(): array {
1263        return array(
1264            'label'               => __( 'List subscribers', 'jetpack-stats-pkg' ),
1265            'description'         => __(
1266                'List the people subscribed to the site, one page at a time, newest first unless `sort` says otherwise â€” the Subscribers page of the Stats dashboard. Each subscriber carries their email address, so treat the list as personal data: report counts and names unless the site owner asks for addresses. `email_subscriber` is true for someone who gets posts by email rather than only in the Reader; `status` is WordPress.com\'s subscription status. `total` counts every subscriber the `filter` and `search` match, across all pages. Only users who can manage the site may list subscribers. `site` is the WordPress.com blog ID and home URL of the site whose subscribers were read. Precondition: site must be connected to WordPress.com.',
1267                'jetpack-stats-pkg'
1268            ),
1269            'input_schema'        => array(
1270                'type'                 => 'object',
1271                'default'              => array(),
1272                'properties'           => array(
1273                    'page'     => array(
1274                        'type'        => 'integer',
1275                        'description' => __( 'Page of results, from 1.', 'jetpack-stats-pkg' ),
1276                        'minimum'     => 1,
1277                        'default'     => 1,
1278                    ),
1279                    'per_page' => array(
1280                        'type'        => 'integer',
1281                        'description' => __( 'Subscribers per page (1-100).', 'jetpack-stats-pkg' ),
1282                        'minimum'     => 1,
1283                        'maximum'     => 100,
1284                        'default'     => 20,
1285                    ),
1286                    'search'   => array(
1287                        'type'        => 'string',
1288                        'description' => __( 'Match subscribers by name or email address.', 'jetpack-stats-pkg' ),
1289                    ),
1290                    'filter'   => array(
1291                        'type'        => 'string',
1292                        'description' => __( 'Which subscribers to list: email subscribers, Reader-only followers, paid, complimentary, free, unconfirmed, or blocked.', 'jetpack-stats-pkg' ),
1293                        'enum'        => self::SUBSCRIBER_FILTERS,
1294                        'default'     => 'all',
1295                    ),
1296                    'sort'     => array(
1297                        'type'        => 'string',
1298                        'description' => __( 'Sort subscribers by subscription date, email, name, plan or status.', 'jetpack-stats-pkg' ),
1299                        'enum'        => self::SUBSCRIBER_SORTS,
1300                        'default'     => 'date_subscribed',
1301                    ),
1302                    'order'    => array(
1303                        'type'        => 'string',
1304                        'description' => __( 'Sort direction: newest or last first (`desc`) or the reverse.', 'jetpack-stats-pkg' ),
1305                        'enum'        => array( 'desc', 'asc' ),
1306                        'default'     => 'desc',
1307                    ),
1308                ),
1309                'additionalProperties' => false,
1310            ),
1311            'output_schema'       => array(
1312                'type'       => 'object',
1313                'properties' => array(
1314                    'site'        => self::site_schema(),
1315                    'total'       => array( 'type' => 'integer' ),
1316                    'page'        => array( 'type' => 'integer' ),
1317                    'pages'       => array( 'type' => 'integer' ),
1318                    'subscribers' => array(
1319                        'type'  => 'array',
1320                        'items' => array(
1321                            'type'       => 'object',
1322                            'properties' => array(
1323                                'subscription_id'  => array( 'type' => 'integer' ),
1324                                'user_id'          => array( 'type' => array( 'integer', 'null' ) ),
1325                                'name'             => array( 'type' => 'string' ),
1326                                'email'            => array( 'type' => 'string' ),
1327                                'url'              => array( 'type' => 'string' ),
1328                                'subscribed_at'    => array( 'type' => 'string' ),
1329                                'status'           => array( 'type' => 'string' ),
1330                                'email_subscriber' => array( 'type' => 'boolean' ),
1331                            ),
1332                        ),
1333                    ),
1334                ),
1335            ),
1336            'execute_callback'    => array( __CLASS__, 'get_subscribers' ),
1337            'permission_callback' => array( __CLASS__, 'can_manage_settings' ),
1338            'meta'                => self::reader_meta(),
1339        );
1340    }
1341
1342    /**
1343     * Spec: jetpack-stats/get-ad-stats.
1344     */
1345    private static function spec_get_ad_stats(): array {
1346        return array(
1347            'label'               => __( 'Get ad stats', 'jetpack-stats-pkg' ),
1348            'description'         => __(
1349                'Report the site\'s WordAds performance, as on the Stats dashboard\'s Ads page: ad impressions, revenue and CPM per period, and the earnings WordAds has recorded by month. `series` has one row per period, oldest first, ending with the one containing `date`; `revenue` is in US dollars and `cpm` is revenue per thousand impressions. `earnings.total` is everything the site has earned, `earnings.owed` the part not yet paid out, and `earnings.months` each month\'s amount, newest first. Composes two WPCOM endpoints â€” if one fails, `partial` is true, `errors` names it (`stats` or `earnings`), and what it feeds is null; if both fail, returns `jetpack_stats_data_unavailable`. A site not in WordAds reports empty figures. Only users who can manage the site or its ads may read them. `site` is the WordPress.com blog ID and home URL of the site whose ads were read. Precondition: site must be connected to WordPress.com.',
1350                'jetpack-stats-pkg'
1351            ),
1352            'input_schema'        => array(
1353                'type'                 => 'object',
1354                'default'              => array(),
1355                'properties'           => array(
1356                    'period' => self::period_schema( self::SERIES_PERIODS ),
1357                    'date'   => self::date_schema(),
1358                    'num'    => array(
1359                        'type'        => 'integer',
1360                        'description' => __( 'How many periods, ending with the one containing `date` (1-90).', 'jetpack-stats-pkg' ),
1361                        'minimum'     => 1,
1362                        'maximum'     => 90,
1363                        'default'     => 30,
1364                    ),
1365                ),
1366                'additionalProperties' => false,
1367            ),
1368            'output_schema'       => array(
1369                'type'       => 'object',
1370                'properties' => array(
1371                    'site'     => self::site_schema(),
1372                    'period'   => array( 'type' => 'string' ),
1373                    'date'     => array( 'type' => 'string' ),
1374                    'num'      => array( 'type' => 'integer' ),
1375                    'series'   => array(
1376                        'type'  => array( 'array', 'null' ),
1377                        'items' => array(
1378                            'type'       => 'object',
1379                            'properties' => array(
1380                                'date'        => array( 'type' => 'string' ),
1381                                'impressions' => array( 'type' => 'integer' ),
1382                                'revenue'     => array( 'type' => 'number' ),
1383                                'cpm'         => array( 'type' => 'number' ),
1384                            ),
1385                        ),
1386                    ),
1387                    'earnings' => array(
1388                        'type'       => array( 'object', 'null' ),
1389                        'properties' => array(
1390                            'total'  => array( 'type' => 'number' ),
1391                            'owed'   => array( 'type' => 'number' ),
1392                            'months' => array(
1393                                'type'  => 'array',
1394                                'items' => array(
1395                                    'type'       => 'object',
1396                                    'properties' => array(
1397                                        'month'  => array( 'type' => 'string' ),
1398                                        'amount' => array( 'type' => 'number' ),
1399                                        'paid'   => array( 'type' => 'boolean' ),
1400                                    ),
1401                                ),
1402                            ),
1403                        ),
1404                    ),
1405                    'partial'  => array( 'type' => 'boolean' ),
1406                    'errors'   => self::errors_schema(),
1407                ),
1408            ),
1409            'execute_callback'    => array( __CLASS__, 'get_ad_stats' ),
1410            'permission_callback' => array( __CLASS__, 'can_view_ads' ),
1411            'meta'                => self::reader_meta(),
1412        );
1413    }
1414
1415    /**
1416     * Spec: jetpack-stats/get-settings.
1417     */
1418    private static function spec_get_settings(): array {
1419        return array(
1420            'label'               => __( 'Get Stats settings', 'jetpack-stats-pkg' ),
1421            'description'         => __(
1422                'Read the current Jetpack Stats settings: who sees the Stats admin bar + menu, whose visits are counted, and DNT behavior. `roles` is an array of role slugs that can view Stats; `count_roles` is an array of role slugs whose visits are counted. Call jetpack-stats/update-settings to change any of these.',
1423                'jetpack-stats-pkg'
1424            ),
1425            'input_schema'        => array(
1426                'type'                 => 'object',
1427                'default'              => array(),
1428                'additionalProperties' => false,
1429            ),
1430            'output_schema'       => array(
1431                'type'       => 'object',
1432                'properties' => self::settings_output_properties(),
1433            ),
1434            'execute_callback'    => array( __CLASS__, 'get_settings' ),
1435            'permission_callback' => array( __CLASS__, 'can_manage_settings' ),
1436            'meta'                => self::reader_meta(),
1437        );
1438    }
1439
1440    /**
1441     * Spec: jetpack-stats/update-settings.
1442     */
1443    private static function spec_update_settings(): array {
1444        return array(
1445            'label'               => __( 'Update Stats settings', 'jetpack-stats-pkg' ),
1446            'description'         => __(
1447                'Update one or more Jetpack Stats settings. All fields are optional; only fields present in the call are written, and unrelated keys are preserved. Idempotent â€” setting a value to its current state returns changed=false. Role slugs added to `roles` or `count_roles` must be registered roles on the site; unknown slugs return jetpack_stats_invalid_role. A slug that is already saved is kept even when its role no longer exists. Narrowing `roles` can revoke Stats access for whole groups of users â€” confirm with the user before removing roles.',
1448                'jetpack-stats-pkg'
1449            ),
1450            'input_schema'        => array(
1451                'type'                 => 'object',
1452                'properties'           => array(
1453                    'admin_bar'    => array(
1454                        'type'        => 'boolean',
1455                        'description' => __( 'Whether to show the Stats item in the admin bar for users who can view Stats.', 'jetpack-stats-pkg' ),
1456                    ),
1457                    'roles'        => array(
1458                        'type'        => 'array',
1459                        'description' => __( 'Role slugs that can view Stats. Must be non-empty; each added slug must be a registered role. `administrator` is always kept.', 'jetpack-stats-pkg' ),
1460                        'items'       => array( 'type' => 'string' ),
1461                        'minItems'    => 1,
1462                    ),
1463                    'count_roles'  => array(
1464                        'type'        => 'array',
1465                        'description' => __( 'Role slugs whose visits are counted. May be empty (count visits from all users).', 'jetpack-stats-pkg' ),
1466                        'items'       => array( 'type' => 'string' ),
1467                    ),
1468                    'do_not_track' => array(
1469                        'type'        => 'boolean',
1470                        'description' => __( 'Whether to honor the browser Do Not Track header.', 'jetpack-stats-pkg' ),
1471                    ),
1472                ),
1473                'additionalProperties' => false,
1474                'minProperties'        => 1,
1475            ),
1476            'output_schema'       => array(
1477                'type'       => 'object',
1478                'properties' => array(
1479                    'changed'  => array( 'type' => 'boolean' ),
1480                    'settings' => array(
1481                        'type'       => 'object',
1482                        'properties' => self::settings_output_properties(),
1483                    ),
1484                ),
1485            ),
1486            'execute_callback'    => array( __CLASS__, 'update_settings' ),
1487            'permission_callback' => array( __CLASS__, 'can_manage_settings' ),
1488            'meta'                => array(
1489                'annotations'  => array(
1490                    'readonly'    => false,
1491                    'destructive' => true,
1492                    'idempotent'  => true,
1493                ),
1494                'public'       => true,
1495                'show_in_rest' => true,
1496                'mcp'          => array(
1497                    'public' => true,
1498                    'type'   => 'tool', // default is already "tool", but can be explicit.
1499                ),
1500            ),
1501        );
1502    }
1503
1504    /**
1505     * Output schema properties shared by get-settings and update-settings' `settings` field.
1506     */
1507    private static function settings_output_properties(): array {
1508        return array(
1509            'admin_bar'    => array( 'type' => 'boolean' ),
1510            'roles'        => array(
1511                'type'  => 'array',
1512                'items' => array( 'type' => 'string' ),
1513            ),
1514            'count_roles'  => array(
1515                'type'  => 'array',
1516                'items' => array( 'type' => 'string' ),
1517            ),
1518            'do_not_track' => array( 'type' => 'boolean' ),
1519        );
1520    }
1521
1522    /*
1523    ---------------------------------------------------------------------
1524     * Permission callbacks
1525     * ---------------------------------------------------------------------
1526     */
1527
1528    /**
1529     * Read-side permission: view_stats.
1530     *
1531     * The Stats package's `Main::map_meta_caps` maps `view_stats` to the
1532     * user's `read` capability when their role is listed in
1533     * `stats_options['roles']`. Honored on self-hosted sites.
1534     *
1535     * @return bool
1536     */
1537    public static function can_view_stats(): bool {
1538        return current_user_can( 'view_stats' );
1539    }
1540
1541    /**
1542     * Ads permission: manage_options or activate_wordads, as on the Stats dashboard's Ads page.
1543     *
1544     * @return bool
1545     */
1546    public static function can_view_ads(): bool {
1547        return current_user_can( 'manage_options' ) || current_user_can( 'activate_wordads' ); // phpcs:ignore WordPress.WP.Capabilities.Unknown -- WordPress.com grants it to the site's ad managers.
1548    }
1549
1550    /**
1551     * Settings permission, for reads and writes: manage_options, as on the Stats settings screen.
1552     *
1553     * The `stats_options` WP option includes the very roles that gate `view_stats`,
1554     * so users who can only view stats must not read or change it.
1555     *
1556     * @return bool
1557     */
1558    public static function can_manage_settings(): bool {
1559        return current_user_can( 'manage_options' );
1560    }
1561
1562    /*
1563    ---------------------------------------------------------------------
1564     * Execute callbacks
1565     * ---------------------------------------------------------------------
1566     */
1567
1568    /**
1569     * Execute: get-site-overview.
1570     *
1571     * @param array|null $input Ignored â€” zero-arg ability.
1572     * @return array|WP_Error
1573     */
1574    public static function get_site_overview( $input = null ) {
1575        $input  = is_array( $input ) ? $input : array();
1576        $preset = self::pick_compare( $input['compare'] ?? null );
1577        if ( is_wp_error( $preset ) ) {
1578            return $preset;
1579        }
1580        $stats = self::get_wpcom_stats();
1581        $today = self::today();
1582        $day   = array(
1583            'period' => 'day',
1584            'date'   => $today,
1585        );
1586
1587        // A few rows, so a post can be found below the home page / archives row.
1588        $post_rows = 10;
1589
1590        $subcalls = array(
1591            'visits'    => $stats->get_visits(
1592                array(
1593                    'unit'        => 'day',
1594                    'quantity'    => 30,
1595                    'date'        => $today,
1596                    'stat_fields' => 'views,visitors',
1597                )
1598            ),
1599            'top_posts' => $stats->get_top_posts( $day + array( 'max' => $post_rows ) ),
1600            'referrers' => $stats->get_referrers( $day + array( 'max' => 1 ) ),
1601        );
1602
1603        $windows = null === $preset ? array() : self::overview_compare_windows( $today, $preset );
1604        if ( $windows ) {
1605            // One read covers the earliest to the latest day the compared windows need.
1606            $first                  = min( array_column( $windows, 'from' ) );
1607            $last                   = max( array_column( $windows, 'to' ) );
1608            $subcalls['comparison'] = $stats->get_visits(
1609                array(
1610                    'unit'        => 'day',
1611                    'quantity'    => self::days_between( $first, $last ) + 1,
1612                    'date'        => $last,
1613                    'stat_fields' => 'views,visitors',
1614                )
1615            );
1616        }
1617
1618        $composed = self::compose_subcalls(
1619            $subcalls,
1620            __( 'Stats data could not be fetched from WordPress.com. Confirm the site is connected and try again.', 'jetpack-stats-pkg' )
1621        );
1622        if ( is_wp_error( $composed ) ) {
1623            return $composed;
1624        }
1625        $values = $composed['values'];
1626        $errors = $composed['errors'];
1627
1628        // The series ends today, so its last row is today and its last 7 rows are the last 7 days.
1629        $days     = self::normalize_visits_series( $values['visits'], array( 'views', 'visitors' ) );
1630        $last_day = end( $days );
1631        $last_day = false === $last_day ? array() : $last_day;
1632        $top_post = self::first_post( self::rank_and_cap( self::top_content_rows( 'posts', $values['top_posts'] ), $post_rows ) );
1633        $top_ref  = self::rank_and_cap( self::top_content_rows( 'referrers', $values['referrers'] ), 1 )[0] ?? null;
1634
1635        $out = array(
1636            'site'           => self::site(),
1637            'date'           => $today,
1638            'views_today'    => $last_day['views'] ?? null,
1639            'visitors_today' => $last_day['visitors'] ?? null,
1640            'views_week'     => self::sum_or_null( array_slice( $days, -7 ), 'views' ),
1641            'views_month'    => self::sum_or_null( $days, 'views' ),
1642            'top_post'       => null === $top_post ? null : array(
1643                'id'    => $top_post['id'],
1644                'title' => $top_post['label'],
1645                'views' => $top_post['value'],
1646            ),
1647            'top_referrer'   => null === $top_ref ? null : array(
1648                'name'  => $top_ref['label'],
1649                'views' => $top_ref['value'],
1650            ),
1651            'partial'        => ! empty( $errors ),
1652            'definitions'    => self::definitions( array( 'date', 'views', 'visitors', 'views_today', 'visitors_today', 'views_week', 'views_month', 'top_post', 'top_referrer' ) ),
1653        );
1654
1655        if ( null !== $preset && $windows ) {
1656            $out['comparison']                = self::overview_comparison( $preset, $windows, $values['comparison'], in_array( 'comparison', $errors, true ) );
1657            $out['definitions']['comparison'] = self::definition_texts()['comparison_overview'];
1658        }
1659
1660        if ( ! empty( $errors ) ) {
1661            $out['errors'] = $errors;
1662        }
1663
1664        return $out;
1665    }
1666
1667    /**
1668     * Execute: get-top-content.
1669     *
1670     * @param array|null $input Input matching the ability's input_schema.
1671     * @return array|WP_Error
1672     */
1673    public static function get_top_content( $input = null ) {
1674        $input = is_array( $input ) ? $input : array();
1675
1676        if ( ! isset( $input['type'] ) || ! in_array( $input['type'], self::TOP_CONTENT_TYPES, true ) ) {
1677            return new WP_Error(
1678                self::ERROR_PREFIX . 'missing_type',
1679                sprintf(
1680                    /* translators: %s: comma-separated list of valid type values. */
1681                    __( 'A `type` is required. Valid values: %s.', 'jetpack-stats-pkg' ),
1682                    implode( ', ', self::TOP_CONTENT_TYPES )
1683                )
1684            );
1685        }
1686
1687        // WordPress.com answers stats/file-downloads with a 404 for every Jetpack-connected site.
1688        if ( 'downloads' === $input['type'] && ! ( new Host() )->is_wpcom_simple() ) {
1689            return new WP_Error(
1690                self::ERROR_PREFIX . 'invalid_type',
1691                __( 'WordPress.com does not keep file download stats for Jetpack-connected sites. Choose another type.', 'jetpack-stats-pkg' )
1692            );
1693        }
1694
1695        $type   = $input['type'];
1696        $period = self::pick_period( $input['period'] ?? null );
1697        $date   = self::resolve_date( $input['date'] ?? null );
1698        $num    = self::clamp_int( $input['num'] ?? 1, 1, 90, 1 );
1699        $max    = self::clamp_int( $input['max'] ?? 20, 0, 100, 20 );
1700        $expand = true === ( $input['expand'] ?? false );
1701        if ( is_wp_error( $date ) ) {
1702            return $date;
1703        }
1704
1705        $utm_param = isset( $input['utm_param'] ) && in_array( $input['utm_param'], self::UTM_PARAMS, true ) ? $input['utm_param'] : self::UTM_PARAMS[0];
1706        // Each UTM value's posts are a separate read, so an expanded list stays short.
1707        $utm_posts = 'utm' === $type && $expand;
1708        if ( $utm_posts && ( 0 === $max || $max > self::UTM_EXPAND_MAX ) ) {
1709            return new WP_Error(
1710                self::ERROR_PREFIX . 'invalid_max',
1711                sprintf(
1712                    /* translators: %d: the largest `max` an expanded UTM list accepts. */
1713                    __( 'With type=utm and expand=true, `max` must be between 1 and %d.', 'jetpack-stats-pkg' ),
1714                    self::UTM_EXPAND_MAX
1715                )
1716            );
1717        }
1718
1719        $args = array(
1720            'period' => $period,
1721            'date'   => $date,
1722            // WordPress.com returns every row for max=0; otherwise one extra row shows whether the list was cut.
1723            'max'    => 0 === $max ? 0 : $max + 1,
1724        );
1725        if ( isset( self::DAYS_WINDOW_TYPES[ $type ] ) ) {
1726            // These endpoints take the window as a number of days ending on a date.
1727            $window = self::summary_window( $period, $num, $date );
1728            $args   = array(
1729                'date' => $window['date'],
1730                'days' => $window['num'],
1731                'max'  => $args['max'],
1732            );
1733        } elseif ( $num > 1 ) {
1734            // Without `summarize`, WPCOM returns each period separately and only the first would be read.
1735            // Several summarized endpoints ignore `period` and read `num` as days, so ask for the days the periods cover.
1736            $args = array_merge( $args, self::summary_window( $period, $num, $date ) );
1737        }
1738
1739        $stats = self::get_wpcom_stats();
1740        $raw   = self::fetch_top_content_raw( $stats, $type, $args, $utm_param );
1741        if ( is_wp_error( $raw ) ) {
1742            return $raw;
1743        }
1744
1745        $summarized = isset( $args['summarize'] );
1746        $rows       = self::top_content_rows( $type, $raw, $summarized );
1747        $errors     = array();
1748        if ( $utm_posts ) {
1749            $values = array_slice( array_keys( is_array( $raw['top_utm_values'] ?? null ) ? $raw['top_utm_values'] : array() ), 0, $max );
1750            foreach ( $values as $i => $value ) {
1751                $posts = $stats->get_utm_top_posts( $utm_param, (string) $value, array( 'max' => $max ) + $args );
1752                if ( is_wp_error( $posts ) ) {
1753                    $errors = array( 'children' );
1754                    continue;
1755                }
1756                $rows[ $i ]['children'] = self::utm_post_rows( $posts );
1757            }
1758        }
1759        // Countries drops and folds rows, so whether WordPress.com held more is read from its own list.
1760        $sent = 'countries' === $type ? count( self::rows_at( self::first_period_block( $raw, $summarized ), 'views' ) ) : count( $rows );
1761        // WordPress.com stops at its authors cap without saying whether more authors had views.
1762        $capped = 'authors' === $type && $sent >= self::TOP_AUTHORS_LIMIT && ( 0 === $max || $max >= self::TOP_AUTHORS_LIMIT );
1763
1764        $out = array(
1765            'site'        => self::site(),
1766            'type'        => $type,
1767            'period'      => $period,
1768            'date'        => $date,
1769            'num'         => $num,
1770            'max'         => $max,
1771            'expand'      => $expand,
1772            'truncated'   => $capped || ( $max > 0 && $sent > $max ),
1773            'items'       => self::rank_and_cap( $rows, $max, $expand ),
1774            'definitions' => self::top_content_definitions( $type, $expand ),
1775        );
1776        if ( 'utm' === $type ) {
1777            $out['utm_param'] = $utm_param;
1778        }
1779        if ( ! empty( $errors ) ) {
1780            $out['partial'] = true;
1781            $out['errors']  = $errors;
1782        }
1783        return $out;
1784    }
1785
1786    /**
1787     * Execute: get-post-views.
1788     *
1789     * @param array|null $input Input matching the ability's input_schema.
1790     * @return array|WP_Error
1791     */
1792    public static function get_post_views( $input = null ) {
1793        $input = is_array( $input ) ? $input : array();
1794
1795        // Use isset()+is_numeric() â€” NOT empty() â€” so the literal "0" is rejected by the `> 0` check, not by a truthiness accident.
1796        if ( ! isset( $input['post_id'] ) || ! is_numeric( $input['post_id'] ) || (int) $input['post_id'] <= 0 ) {
1797            return new WP_Error(
1798                self::ERROR_PREFIX . 'missing_post_id',
1799                __( 'A positive post_id is required.', 'jetpack-stats-pkg' )
1800            );
1801        }
1802
1803        $post_id = (int) $input['post_id'];
1804        $period  = self::pick_period( $input['period'] ?? null, self::SERIES_PERIODS );
1805        $num     = self::clamp_int( $input['num'] ?? 30, 1, 90, 30 );
1806        $date    = self::resolve_date( $input['date'] ?? null );
1807        if ( is_wp_error( $date ) ) {
1808            return $date;
1809        }
1810
1811        // WPCOM answers an unknown post with the same generic failure as an outage.
1812        if ( ! get_post( $post_id ) ) {
1813            return new WP_Error(
1814                self::ERROR_PREFIX . 'post_not_found',
1815                __( 'No post exists with that post_id.', 'jetpack-stats-pkg' ),
1816                array( 'status' => 404 )
1817            );
1818        }
1819
1820        // The endpoint takes no period or date: `data` is every day since publication.
1821        $stats = self::get_wpcom_stats();
1822        $raw   = $stats->get_post_views( $post_id );
1823        if ( is_wp_error( $raw ) ) {
1824            return $raw;
1825        }
1826
1827        $total  = self::count_or_null( $raw['views'] ?? null );
1828        $series = self::bucket_daily_views( self::extract_post_views_series( $raw ), $period, $num, $date );
1829        if ( null === $total ) {
1830            // A body without the post's total is not one whose days can be read as zero.
1831            foreach ( $series as $i => $row ) {
1832                $series[ $i ]['views'] = null;
1833            }
1834        }
1835
1836        return array(
1837            'site'        => self::site(),
1838            'post_id'     => $post_id,
1839            'total_views' => $total,
1840            'period'      => $period,
1841            'num'         => $num,
1842            'date'        => $date,
1843            'series'      => $series,
1844            'definitions' => self::definitions( array( 'total_views', 'series', 'views' ) ),
1845        );
1846    }
1847
1848    /**
1849     * Execute: get-post-detail.
1850     *
1851     * @param array|null $input Input matching the ability's input_schema.
1852     * @return array|WP_Error
1853     */
1854    public static function get_post_detail( $input = null ) {
1855        $input = is_array( $input ) ? $input : array();
1856        if ( ! isset( $input['post_id'] ) || ! is_numeric( $input['post_id'] ) || (int) $input['post_id'] <= 0 ) {
1857            return new WP_Error(
1858                self::ERROR_PREFIX . 'missing_post_id',
1859                __( 'A positive post_id is required.', 'jetpack-stats-pkg' )
1860            );
1861        }
1862        $post_id   = (int) $input['post_id'];
1863        $max       = self::clamp_int( $input['max'] ?? 10, 1, 100, 10 );
1864        $utm_param = isset( $input['utm_param'] ) && in_array( $input['utm_param'], self::UTM_PARAMS, true ) ? $input['utm_param'] : self::UTM_PARAMS[0];
1865        $post      = get_post( $post_id );
1866        // WPCOM answers an unknown post with zeros, which would read as a post nobody saw. Stats access can go to any
1867        // role, so a post the caller cannot open on the site is unknown to them too: its title and comments stay private.
1868        if ( ! $post || ( ! is_post_publicly_viewable( $post ) && ! current_user_can( 'read_post', $post->ID ) ) ) {
1869            return new WP_Error(
1870                self::ERROR_PREFIX . 'post_not_found',
1871                __( 'No post exists with that post_id.', 'jetpack-stats-pkg' ),
1872                array( 'status' => 404 )
1873            );
1874        }
1875
1876        // Only posts go out as newsletters, so a page's email figures need no request.
1877        $emailable = 'post' === $post->post_type;
1878        $stats     = self::get_wpcom_stats();
1879        $results   = array(
1880            'views' => $stats->get_post_views( $post_id ),
1881            'likes' => $stats->get_post_likes( $post_id ),
1882            'utm'   => $stats->get_utm_views(
1883                $utm_param,
1884                array(
1885                    'post_id' => $post_id,
1886                    'days'    => -1,
1887                    'max'     => $max,
1888                )
1889            ),
1890        );
1891        if ( $emailable ) {
1892            $results['email/opens']  = $stats->get_email_breakdown( $post_id, 'opens', 'rate' );
1893            $results['email/clicks'] = $stats->get_email_breakdown( $post_id, 'clicks', 'rate' );
1894        }
1895        $composed = self::compose_subcalls(
1896            $results,
1897            __( 'Stats for that post could not be fetched from WordPress.com. Confirm the site is connected and try again.', 'jetpack-stats-pkg' )
1898        );
1899        if ( is_wp_error( $composed ) ) {
1900            return $composed;
1901        }
1902        $values = $composed['values'];
1903        $errors = array_values( array_unique( preg_replace( '#/.*$#', '', $composed['errors'] ) ) );
1904        $failed = static function ( string $tag ) use ( $errors ): bool {
1905            return in_array( $tag, $errors, true );
1906        };
1907
1908        $likes = array(
1909            'total'  => null,
1910            'recent' => null,
1911        );
1912        if ( ! $failed( 'likes' ) ) {
1913            $likers = array();
1914            foreach ( array_slice( self::rows_at( $values['likes'], 'likes' ), 0, $max ) as $liker ) {
1915                $likers[] = array( 'name' => html_entity_decode( (string) ( $liker['name'] ?? '' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
1916            }
1917            $likes = array(
1918                'total'  => self::count_or_null( $values['likes']['found'] ?? null ),
1919                'recent' => $likers,
1920            );
1921        }
1922
1923        $comments = array();
1924        foreach ( get_comments(
1925            array(
1926                'post_id' => $post_id,
1927                'status'  => 'approve',
1928                'number'  => $max,
1929                'orderby' => 'comment_date_gmt',
1930                'order'   => 'DESC',
1931            )
1932        ) as $comment ) {
1933            $comments[] = array(
1934                'author'  => (string) $comment->comment_author,
1935                'date'    => (string) mysql2date( 'c', $comment->comment_date ),
1936                'excerpt' => wp_trim_words( $comment->comment_content, 30, '…' ),
1937                'url'     => (string) get_comment_link( $comment ),
1938            );
1939        }
1940
1941        $email = array(
1942            'emailed' => false,
1943            'sent'    => null,
1944            'opens'   => self::email_summary( null ),
1945            'clicks'  => self::email_summary( null ),
1946        );
1947        if ( $emailable && $failed( 'email' ) ) {
1948            $email['emailed'] = null;
1949        } elseif ( $emailable ) {
1950            $opens  = $values['email/opens'];
1951            $clicks = $values['email/clicks'];
1952            // The Stats dashboard's own test: a post nobody was sent, opened or clicked was never emailed.
1953            if ( 0 < self::as_int( $opens, 'total_sends' ) + self::as_int( $opens, 'total_opens' ) + self::as_int( $clicks, 'total_clicks' ) ) {
1954                $email = array(
1955                    'emailed' => true,
1956                    'sent'    => self::as_int( $opens, 'total_sends' ),
1957                    'opens'   => self::email_summary( array( $opens['total_opens'] ?? 0, $opens['unique_opens'] ?? 0, $opens['opens_rate'] ?? 0 ) ),
1958                    'clicks'  => self::email_summary( array( $clicks['total_clicks'] ?? 0, $clicks['unique_clicks'] ?? 0, $clicks['clicks_rate'] ?? 0 ) ),
1959                );
1960            }
1961        }
1962
1963        $published = in_array( $post->post_status, array( 'publish', 'private' ), true ) ? (string) mysql2date( 'c', $post->post_date ) : null;
1964        $out       = array(
1965            'site'        => self::site(),
1966            'post'        => array(
1967                'id'        => $post_id,
1968                'title'     => html_entity_decode( $post->post_title, ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
1969                'type'      => $post->post_type,
1970                'url'       => (string) get_permalink( $post ),
1971                'published' => $published,
1972            ),
1973            'views'       => $failed( 'views' ) ? null : self::count_or_null( $values['views']['views'] ?? null ),
1974            'likes'       => $likes,
1975            'comments'    => array(
1976                'total'  => (int) get_comments_number( $post ),
1977                'recent' => $comments,
1978            ),
1979            'utm_param'   => $utm_param,
1980            'utm'         => $failed( 'utm' ) ? null : array_slice( self::value_map_rows( $values['utm']['top_utm_values'] ?? null ), 0, $max ),
1981            'email'       => $email,
1982            'partial'     => ! empty( $errors ),
1983            'definitions' => self::definitions( array( 'post_detail', 'sent' ) ),
1984        );
1985        if ( ! empty( $errors ) ) {
1986            $out['errors'] = $errors;
1987        }
1988        return $out;
1989    }
1990
1991    /**
1992     * An email's all-time opens or clicks: total, unique people and rate as a percent, or every figure null.
1993     *
1994     * @param array|null $figures `[ total, unique, rate as a fraction ]`, or null when unknown or never emailed.
1995     * @return array{total: int|null, unique: int|null, rate: float|null}
1996     */
1997    private static function email_summary( ?array $figures ): array {
1998        return array(
1999            'total'  => null === $figures ? null : (int) $figures[0],
2000            'unique' => null === $figures ? null : (int) $figures[1],
2001            'rate'   => null === $figures ? null : round( (float) $figures[2] * 100, 2 ),
2002        );
2003    }
2004
2005    /**
2006     * Execute: get-visits.
2007     *
2008     * @param array|null $input Input matching the ability's input_schema.
2009     * @return array|WP_Error
2010     */
2011    public static function get_visits( $input = null ) {
2012        $input = is_array( $input ) ? $input : array();
2013
2014        $period = self::pick_period( $input['period'] ?? null, self::SERIES_PERIODS );
2015        $num    = self::clamp_int( $input['num'] ?? 30, 1, 90, 30 );
2016        $date   = self::resolve_date( $input['date'] ?? null );
2017        if ( is_wp_error( $date ) ) {
2018            return $date;
2019        }
2020
2021        // Pass user input FIRST to array_intersect so caller-supplied field order is preserved.
2022        $fields = isset( $input['fields'] ) && is_array( $input['fields'] )
2023            ? array_values( array_intersect( $input['fields'], self::VISIT_FIELDS ) )
2024            : array();
2025        if ( empty( $fields ) ) {
2026            $fields = self::DEFAULT_VISIT_FIELDS;
2027        }
2028
2029        $preset = self::pick_compare( $input['compare'] ?? null );
2030        if ( is_wp_error( $preset ) ) {
2031            return $preset;
2032        }
2033        $compare_date = null === $preset ? null : self::compare_end_date( $date, $preset, $period, $num );
2034        if ( is_wp_error( $compare_date ) ) {
2035            return $compare_date;
2036        }
2037
2038        $args = array(
2039            'unit'        => $period,
2040            'quantity'    => $num,
2041            'date'        => $date,
2042            'stat_fields' => implode( ',', $fields ),
2043        );
2044
2045        $stats = self::get_wpcom_stats();
2046        $raw   = $stats->get_visits( $args );
2047        if ( is_wp_error( $raw ) ) {
2048            return $raw;
2049        }
2050
2051        $out = array(
2052            'site'   => self::site(),
2053            'period' => $period,
2054            'num'    => $num,
2055            'date'   => $date,
2056            'fields' => $fields,
2057            'series' => self::normalize_visits_series( $raw, $fields ),
2058        );
2059
2060        $out['definitions'] = self::definitions( array_merge( array( 'series' ), $fields ) );
2061        if ( null !== $compare_date ) {
2062            // The same periods, shifted back by whole periods, so row i compares with row i.
2063            $compare_raw                      = $stats->get_visits( array( 'date' => $compare_date ) + $args );
2064            $out['comparison']                = array(
2065                'preset' => $preset,
2066                'date'   => $compare_date,
2067                'series' => is_wp_error( $compare_raw ) ? null : self::normalize_visits_series( $compare_raw, $fields ),
2068            );
2069            $out['definitions']['comparison'] = self::definition_texts()['comparison_series'];
2070            if ( is_wp_error( $compare_raw ) ) {
2071                $out['partial'] = true;
2072                $out['errors']  = array( 'comparison' );
2073            }
2074        }
2075
2076        return $out;
2077    }
2078
2079    /**
2080     * Execute: get-followers.
2081     *
2082     * @param array|null $input Ignored â€” zero-arg ability.
2083     * @return array|WP_Error
2084     */
2085    public static function get_followers( $input = null ) {
2086        $input  = is_array( $input ) ? $input : array();
2087        $period = isset( $input['period'] ) && in_array( $input['period'], self::SERIES_PERIODS, true ) ? $input['period'] : null;
2088        $date   = self::resolve_date( $input['date'] ?? null );
2089        if ( is_wp_error( $date ) ) {
2090            return $date;
2091        }
2092        $stats = self::get_wpcom_stats();
2093
2094        $calls = array(
2095            'followers'           => $stats->get_followers(
2096                array(
2097                    'type' => 'all',
2098                    'max'  => 1,
2099                )
2100            ),
2101            'comment_followers'   => $stats->get_comment_followers(),
2102            'publicize_followers' => $stats->get_publicize_followers(),
2103            'subscriber_counts'   => $stats->get_subscriber_counts(),
2104        );
2105        if ( null !== $period ) {
2106            $calls['subscriber_history'] = $stats->get_subscriber_history(
2107                array(
2108                    'unit'     => $period,
2109                    'quantity' => self::clamp_int( $input['num'] ?? 30, 1, 90, 30 ),
2110                    'date'     => $date,
2111                )
2112            );
2113        }
2114
2115        $composed = self::compose_subcalls(
2116            $calls,
2117            __( 'Follower data could not be fetched from WordPress.com. Confirm the site is connected and try again.', 'jetpack-stats-pkg' )
2118        );
2119        if ( is_wp_error( $composed ) ) {
2120            return $composed;
2121        }
2122        $followers         = $composed['values']['followers'];
2123        $comment_followers = $composed['values']['comment_followers'];
2124        $publicize         = $composed['values']['publicize_followers'];
2125        $errors            = $composed['errors'];
2126
2127        // The counts are totals on the response; `subscribers` is only a page of rows.
2128        $email   = self::count_or_null( $followers['total_email'] ?? null );
2129        $wpcom   = self::count_or_null( $followers['total_wpcom'] ?? null );
2130        $comment = null;
2131        if ( ! in_array( 'comment_followers', $errors, true ) ) {
2132            $comment = self::all_posts_comment_followers( $comment_followers );
2133            if ( null === $comment ) {
2134                $errors[] = 'comment_followers';
2135            }
2136        }
2137
2138        $publicize_by_service = null;
2139        if ( ! in_array( 'publicize_followers', $errors, true ) ) {
2140            $publicize_by_service = array();
2141            foreach ( self::rows_at( $publicize, 'services' ) as $row ) {
2142                if ( isset( $row['service'] ) && isset( $row['followers'] ) ) {
2143                    $publicize_by_service[ (string) $row['service'] ] = (int) $row['followers'];
2144                }
2145            }
2146        }
2147
2148        $total = null;
2149        if ( null !== $email && null !== $wpcom && null !== $comment && null !== $publicize_by_service ) {
2150            $total = $email + $wpcom + $comment + array_sum( $publicize_by_service );
2151        }
2152
2153        $out   = array(
2154            'site'      => self::site(),
2155            'total'     => $total,
2156            'email'     => $email,
2157            'wpcom'     => $wpcom,
2158            'comment'   => $comment,
2159            // An empty PHP array would encode as `[]`, not the object the schema promises.
2160            'publicize' => null === $publicize_by_service ? null : (object) $publicize_by_service,
2161            'paid'      => in_array( 'subscriber_counts', $errors, true ) ? null : self::count_or_null( $composed['values']['subscriber_counts']['counts']['paid_subscribers'] ?? null ),
2162        );
2163        $terms = array( 'total', 'email', 'wpcom', 'comment', 'publicize', 'paid' );
2164        if ( null !== $period ) {
2165            $out['series'] = in_array( 'subscriber_history', $errors, true ) ? null : self::subscriber_series( $composed['values']['subscriber_history'] );
2166            $terms[]       = 'subscriber_series';
2167        }
2168        $out['partial']     = ! empty( $errors );
2169        $out['definitions'] = self::definitions( $terms );
2170
2171        if ( ! empty( $errors ) ) {
2172            $out['errors'] = $errors;
2173        }
2174
2175        return $out;
2176    }
2177
2178    /**
2179     * Execute: get-author-views.
2180     *
2181     * @param array|null $input Input matching the ability's input_schema.
2182     * @return array|WP_Error
2183     */
2184    public static function get_author_views( $input = null ) {
2185        $input = is_array( $input ) ? $input : array();
2186        if ( ! isset( $input['author_id'] ) || ! is_numeric( $input['author_id'] ) || (int) $input['author_id'] <= 0 ) {
2187            return new WP_Error(
2188                self::ERROR_PREFIX . 'missing_author_id',
2189                __( 'A positive author_id is required.', 'jetpack-stats-pkg' )
2190            );
2191        }
2192
2193        $author_id = (int) $input['author_id'];
2194        $period    = self::pick_period( $input['period'] ?? null, self::SERIES_PERIODS );
2195        $num       = self::clamp_int( $input['num'] ?? 30, 1, 90, 30 );
2196        $date      = self::resolve_date( $input['date'] ?? null );
2197        if ( is_wp_error( $date ) ) {
2198            return $date;
2199        }
2200
2201        $raw = self::get_wpcom_stats()->get_author_views(
2202            $author_id,
2203            array(
2204                'period' => $period,
2205                'date'   => $date,
2206                'num'    => $num,
2207            )
2208        );
2209        if ( is_wp_error( $raw ) ) {
2210            return $raw;
2211        }
2212
2213        $counts = array();
2214        foreach ( (array) ( $raw['content_counts'] ?? array() ) as $post_type => $count ) {
2215            $counts[ (string) $post_type ] = (int) $count;
2216        }
2217
2218        return array(
2219            'site'               => self::site(),
2220            'author'             => array(
2221                'id'   => $author_id,
2222                'name' => html_entity_decode( (string) ( $raw['author']['name'] ?? '' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
2223            ),
2224            'period'             => $period,
2225            'date'               => $date,
2226            'num'                => $num,
2227            'views'              => self::as_int( $raw, 'views' ),
2228            'likes'              => self::as_int( $raw, 'likes' ),
2229            'comments'           => self::as_int( $raw, 'comments' ),
2230            'series'             => self::normalize_visits_series( $raw, array( 'views' ) ),
2231            // An empty PHP array would encode as `[]`, not the object the schema promises.
2232            'content_counts'     => (object) $counts,
2233            'first_content_date' => is_string( $raw['first_content_date'] ?? null ) ? $raw['first_content_date'] : null,
2234            'definitions'        => self::definitions( array( 'views', 'author_views', 'series' ) ),
2235        );
2236    }
2237
2238    /**
2239     * Execute: get-insights.
2240     *
2241     * @param array|null $input Ignored â€” zero-arg ability.
2242     * @return array|WP_Error
2243     */
2244    public static function get_insights( $input = null ) {
2245        unset( $input );
2246        $stats = self::get_wpcom_stats();
2247        $today = self::today();
2248        // The streaks are found among the calendar's days, so it needs every post of the year.
2249        $calendar_from = gmdate( 'Y-m-d', strtotime( $today . ' -1 year +1 day' ) );
2250
2251        $composed = self::compose_subcalls(
2252            array(
2253                'summary'    => $stats->get_stats(),
2254                'insights'   => $stats->get_insights(),
2255                'highlights' => $stats->get_highlights(),
2256                'streak'     => $stats->get_streak(
2257                    array(
2258                        'startDate' => $calendar_from,
2259                        'endDate'   => $today,
2260                        'max'       => self::STREAK_MAX_POSTS,
2261                    )
2262                ),
2263                'usage'      => $stats->get_stats_usage(),
2264            ),
2265            __( 'Stats insights could not be fetched from WordPress.com. Confirm the site is connected and try again.', 'jetpack-stats-pkg' )
2266        );
2267        if ( is_wp_error( $composed ) ) {
2268            return $composed;
2269        }
2270        $values = $composed['values'];
2271        $errors = $composed['errors'];
2272        $failed = static function ( string $tag ) use ( $errors ): bool {
2273            return in_array( $tag, $errors, true );
2274        };
2275
2276        $summary  = is_array( $values['summary']['stats'] ?? null ) ? $values['summary']['stats'] : array();
2277        $insights = $values['insights'];
2278        $usage    = $values['usage'];
2279
2280        $recent = array();
2281        foreach ( array(
2282            'last_7_days'      => 'past_seven_days',
2283            'previous_7_days'  => 'between_past_eight_and_fifteen_days',
2284            'last_30_days'     => 'past_thirty_days',
2285            'previous_30_days' => 'between_past_thirty_one_and_sixty_days',
2286        ) as $key => $wpcom_key ) {
2287            $window         = is_array( $values['highlights'][ $wpcom_key ] ?? null ) ? $values['highlights'][ $wpcom_key ] : array();
2288            $recent[ $key ] = array(
2289                'from'     => (string) ( $window['range']['start'] ?? '' ),
2290                'to'       => (string) ( $window['range']['end'] ?? '' ),
2291                'views'    => self::as_int( $window, 'views' ),
2292                'visitors' => self::as_int( $window, 'visitors' ),
2293                'likes'    => self::as_int( $window, 'likes' ),
2294                'comments' => self::as_int( $window, 'comments' ),
2295            );
2296        }
2297
2298        $years = array();
2299        foreach ( self::rows_at( $insights, 'years' ) as $year ) {
2300            $years[] = array(
2301                'year'     => (string) ( $year['year'] ?? '' ),
2302                'posts'    => self::as_int( $year, 'total_posts' ),
2303                'words'    => self::as_int( $year, 'total_words' ),
2304                'likes'    => self::as_int( $year, 'total_likes' ),
2305                'comments' => self::as_int( $year, 'total_comments' ),
2306            );
2307        }
2308
2309        $calendar = $failed( 'streak' ) ? null : self::posting_calendar( $values['streak'], $calendar_from, $today );
2310
2311        $weekdays = array( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' );
2312        $weekday  = (int) ( $insights['highest_day_of_week'] ?? -1 );
2313
2314        $out = array(
2315            'site'        => self::site(),
2316            'all_time'    => $failed( 'summary' ) ? null : array(
2317                'views'          => self::as_int( $summary, 'views' ),
2318                'visitors'       => self::as_int( $summary, 'visitors' ),
2319                'posts'          => self::as_int( $summary, 'posts' ),
2320                'comments'       => self::as_int( $summary, 'comments' ),
2321                'shares'         => self::as_int( $summary, 'shares' ),
2322                'best_day'       => is_string( $summary['views_best_day'] ?? null ) && '' !== $summary['views_best_day'] ? $summary['views_best_day'] : null,
2323                'best_day_views' => self::as_int( $summary, 'views_best_day_total' ),
2324            ),
2325            'busiest'     => $failed( 'insights' ) || ! isset( $weekdays[ $weekday ] ) ? null : array(
2326                'hour'                => self::as_int( $insights, 'highest_hour' ),
2327                'hour_percent'        => round( (float) ( $insights['highest_hour_percent'] ?? 0 ), 1 ),
2328                'day_of_week'         => $weekdays[ $weekday ],
2329                'day_of_week_percent' => round( (float) ( $insights['highest_day_percent'] ?? 0 ), 1 ),
2330            ),
2331            'recent'      => $failed( 'highlights' ) ? null : $recent,
2332            'streak'      => null === $calendar ? null : self::streak_summary( $calendar['days'], $today ),
2333            'calendar'    => $calendar,
2334            'years'       => $failed( 'insights' ) ? null : $years,
2335            'plan_usage'  => $failed( 'usage' ) ? null : array(
2336                'plan'         => is_string( $usage['current_tier']['slug'] ?? null ) ? $usage['current_tier']['slug'] : null,
2337                'views'        => self::as_int( is_array( $usage['current_usage'] ?? null ) ? $usage['current_usage'] : array(), 'views_count' ),
2338                'views_limit'  => self::count_or_null( $usage['views_limit'] ?? null ),
2339                'period_start' => (string) ( $usage['current_usage']['current_start'] ?? '' ),
2340                'period_end'   => (string) ( $usage['current_usage']['next_start'] ?? '' ),
2341                'over_limit'   => true === ( $usage['is_over_limit'] ?? false ),
2342            ),
2343            'partial'     => ! empty( $errors ),
2344            'definitions' => self::definitions( array( 'views', 'visitors', 'all_time', 'busiest', 'recent', 'streak', 'calendar', 'years', 'plan_usage' ) ),
2345        );
2346        if ( ! empty( $errors ) ) {
2347            $out['errors'] = $errors;
2348        }
2349        return $out;
2350    }
2351
2352    /**
2353     * Execute: get-email-stats.
2354     *
2355     * @param array|null $input Input matching the ability's input_schema.
2356     * @return array|WP_Error
2357     */
2358    public static function get_email_stats( $input = null ) {
2359        $input = is_array( $input ) ? $input : array();
2360        $args  = array(
2361            'quantity'   => self::clamp_int( $input['max'] ?? 10, 1, 100, 10 ),
2362            'sort_field' => isset( $input['sort'] ) && in_array( $input['sort'], self::EMAIL_SORTS, true ) ? $input['sort'] : 'post_date',
2363            'sort_order' => 'asc' === ( $input['order'] ?? null ) ? 'asc' : 'desc',
2364        );
2365        foreach ( array( 'start_date', 'end_date' ) as $key ) {
2366            if ( isset( $input[ $key ] ) ) {
2367                $day = self::resolve_date( $input[ $key ] );
2368                if ( is_wp_error( $day ) || '' === $input[ $key ] ) {
2369                    return new WP_Error(
2370                        self::ERROR_PREFIX . 'invalid_date',
2371                        /* translators: %s: the input field name. */
2372                        sprintf( __( '`%s` must be a real day in YYYY-MM-DD format, such as 2026-04-23.', 'jetpack-stats-pkg' ), $key )
2373                    );
2374                }
2375                $args[ $key ] = $day;
2376            }
2377        }
2378
2379        $raw = self::get_wpcom_stats()->get_email_summary( $args );
2380        if ( is_wp_error( $raw ) ) {
2381            return $raw;
2382        }
2383
2384        $posts = array();
2385        foreach ( self::rows_at( $raw, 'posts' ) as $row ) {
2386            $posts[] = array(
2387                'id'            => self::as_int( $row, 'id' ),
2388                'title'         => html_entity_decode( (string) ( $row['title'] ?? '' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
2389                'href'          => (string) ( $row['href'] ?? '' ),
2390                'date'          => (string) ( $row['date'] ?? '' ),
2391                'sent'          => self::as_int( $row, 'total_sends' ),
2392                'opens'         => self::as_int( $row, 'opens' ),
2393                'unique_opens'  => self::as_int( $row, 'unique_opens' ),
2394                'open_rate'     => (float) ( $row['opens_rate'] ?? 0 ),
2395                'clicks'        => self::as_int( $row, 'clicks' ),
2396                'unique_clicks' => self::as_int( $row, 'unique_clicks' ),
2397                'click_rate'    => (float) ( $row['clicks_rate'] ?? 0 ),
2398            );
2399        }
2400
2401        $out = array( 'site' => self::site() );
2402        foreach ( array( 'start_date', 'end_date' ) as $key ) {
2403            if ( is_string( $raw[ $key ] ?? null ) ) {
2404                $out[ $key ] = $raw[ $key ];
2405            }
2406        }
2407        $out['posts']       = $posts;
2408        $out['definitions'] = self::definitions( array( 'sent', 'opens', 'clicks', 'email_rates', isset( $out['start_date'] ) ? 'email_window' : 'email_all_time' ) );
2409        return $out;
2410    }
2411
2412    /**
2413     * Execute: get-email-detail.
2414     *
2415     * @param array|null $input Input matching the ability's input_schema.
2416     * @return array|WP_Error
2417     */
2418    public static function get_email_detail( $input = null ) {
2419        $input = is_array( $input ) ? $input : array();
2420        if ( ! isset( $input['post_id'] ) || ! is_numeric( $input['post_id'] ) || (int) $input['post_id'] <= 0 ) {
2421            return new WP_Error(
2422                self::ERROR_PREFIX . 'missing_post_id',
2423                __( 'A positive post_id is required.', 'jetpack-stats-pkg' )
2424            );
2425        }
2426        $post_id = (int) $input['post_id'];
2427        $max     = self::clamp_int( $input['max'] ?? 10, 1, 100, 10 );
2428        $post    = get_post( $post_id );
2429        // WPCOM answers an unknown post with zeros, which would read as an email nobody opened.
2430        if ( ! $post ) {
2431            return new WP_Error(
2432                self::ERROR_PREFIX . 'post_not_found',
2433                __( 'No post exists with that post_id.', 'jetpack-stats-pkg' ),
2434                array( 'status' => 404 )
2435            );
2436        }
2437
2438        $stats   = self::get_wpcom_stats();
2439        $results = array();
2440        foreach ( self::EMAIL_BREAKDOWNS as $breakdown ) {
2441            list( $stat, $field )  = explode( '/', $breakdown );
2442            $results[ $breakdown ] = $stats->get_email_breakdown( $post_id, $stat, $field );
2443        }
2444        $window   = isset( $input['timeline'] ) && in_array( $input['timeline'], self::EMAIL_TIMELINES, true ) ? $input['timeline'] : null;
2445        $timeline = null === $window ? null : self::email_timeline_request( $post, $window );
2446        if ( null !== $timeline ) {
2447            foreach ( array( 'opens', 'clicks' ) as $stat ) {
2448                $results[ "$stat/timeline" ] = $stats->get_email_timeline( $post_id, $stat, $timeline['args'] );
2449            }
2450        }
2451        $composed = self::compose_subcalls(
2452            $results,
2453            __( 'Stats for that email could not be fetched from WordPress.com. Confirm the site is connected and try again.', 'jetpack-stats-pkg' )
2454        );
2455        if ( is_wp_error( $composed ) ) {
2456            return $composed;
2457        }
2458        $values  = $composed['values'];
2459        $errors  = $composed['errors'];
2460        $rows    = static function ( string $breakdown, string $key, callable $label ) use ( $values, $errors, $max ): ?array {
2461            if ( in_array( $breakdown, $errors, true ) ) {
2462                return null;
2463            }
2464            $block = is_array( $values[ $breakdown ][ $key ] ?? null ) ? $values[ $breakdown ][ $key ] : array();
2465            return self::email_rows( self::rows_at( $block, 'data' ), $label, $max );
2466        };
2467        $as_is   = static function ( string $value ): string {
2468            return $value;
2469        };
2470        $country = static function ( string $breakdown ) use ( $values ): callable {
2471            $names   = is_array( $values[ $breakdown ]['countries-info'] ?? null ) ? $values[ $breakdown ]['countries-info'] : array();
2472            $unknown = __( 'Unknown', 'jetpack-stats-pkg' );
2473            return static function ( string $code ) use ( $names, $unknown ): string {
2474                $name = $names[ $code ]['country_full'] ?? null;
2475                return is_string( $name ) && '' !== $name ? $name : $unknown;
2476            };
2477        };
2478        $rate    = static function ( string $breakdown, string $total, string $unique, string $rate ) use ( $values, $errors ): array {
2479            if ( in_array( $breakdown, $errors, true ) ) {
2480                return array(
2481                    'total'  => null,
2482                    'unique' => null,
2483                    'rate'   => null,
2484                );
2485            }
2486            $raw = $values[ $breakdown ];
2487            return array(
2488                'total'  => self::as_int( $raw, $total ),
2489                'unique' => self::as_int( $raw, $unique ),
2490                'rate'   => round( (float) ( $raw[ $rate ] ?? 0 ) * 100, 2 ),
2491            );
2492        };
2493
2494        // The email's own links come by name; `user_link` totals the post's links, which come by URL.
2495        $link_names = array(
2496            'post-url'            => __( 'Post title', 'jetpack-stats-pkg' ),
2497            'header-post'         => __( 'Post header', 'jetpack-stats-pkg' ),
2498            'like-post'           => __( 'Like', 'jetpack-stats-pkg' ),
2499            'comment-post'        => __( 'Comment', 'jetpack-stats-pkg' ),
2500            'reader-url'          => __( 'Read in the Reader', 'jetpack-stats-pkg' ),
2501            'manage-subscription' => __( 'Manage subscription', 'jetpack-stats-pkg' ),
2502            'remove-subscription' => __( 'Unsubscribe', 'jetpack-stats-pkg' ),
2503        );
2504        $links      = null;
2505        if ( ! in_array( 'clicks/link', $errors, true ) || ! in_array( 'clicks/user-content-link', $errors, true ) ) {
2506            $links = self::email_rows(
2507                array_merge(
2508                    self::rows_at( is_array( $values['clicks/link']['links'] ?? null ) ? $values['clicks/link']['links'] : array(), 'data' ),
2509                    self::rows_at( is_array( $values['clicks/user-content-link']['user-content-links'] ?? null ) ? $values['clicks/user-content-link']['user-content-links'] : array(), 'data' )
2510                ),
2511                static function ( string $link ) use ( $link_names ): ?string {
2512                    return 'user_link' === $link ? null : ( $link_names[ $link ] ?? $link );
2513                },
2514                $max
2515            );
2516        }
2517
2518        $sent = null;
2519        foreach ( array( 'opens/rate', 'clicks/rate' ) as $breakdown ) {
2520            if ( null === $sent && ! in_array( $breakdown, $errors, true ) ) {
2521                $sent = self::as_int( $values[ $breakdown ], 'total_sends' );
2522            }
2523        }
2524
2525        $out = array(
2526            'site'        => self::site(),
2527            'post_id'     => $post_id,
2528            'sent'        => $sent,
2529            'opens'       => $rate( 'opens/rate', 'total_opens', 'unique_opens', 'opens_rate' ) + array(
2530                'by_client'  => $rows( 'opens/client', 'clients', $as_is ),
2531                'by_device'  => $rows( 'opens/device', 'devices', $as_is ),
2532                'by_country' => $rows( 'opens/country', 'countries', $country( 'opens/country' ) ),
2533            ),
2534            'clicks'      => $rate( 'clicks/rate', 'total_clicks', 'unique_clicks', 'clicks_rate' ) + array(
2535                'by_client'  => $rows( 'clicks/client', 'clients', $as_is ),
2536                'by_device'  => $rows( 'clicks/device', 'devices', $as_is ),
2537                'by_country' => $rows( 'clicks/country', 'countries', $country( 'clicks/country' ) ),
2538                'by_link'    => $links,
2539            ),
2540            'timeline'    => null === $timeline ? null : self::email_timeline( $window, $timeline, $values, $errors ),
2541            'partial'     => ! empty( $errors ),
2542            'definitions' => self::definitions( null === $timeline ? array( 'sent', 'email_detail' ) : array( 'sent', 'email_detail', 'email_timeline' ) ),
2543        );
2544        if ( ! empty( $errors ) ) {
2545            $out['errors'] = $errors;
2546        }
2547        return $out;
2548    }
2549
2550    /**
2551     * The timeline request for one window of an email: WordPress.com reads `date` as the first
2552     * bucket and returns `quantity` buckets going forward, in the site's timezone.
2553     *
2554     * Hourly buckets start at the send day's midnight, so the request spans the hours before the
2555     * send and `skip` drops them. Monthly buckets run from the send month through this one.
2556     *
2557     * @param \WP_Post $post   The emailed post; it was sent when it was published.
2558     * @param string   $window One of EMAIL_TIMELINES.
2559     * @return array{args: array, skip: int}|null Null when the post has no publish date.
2560     */
2561    private static function email_timeline_request( \WP_Post $post, string $window ): ?array {
2562        $sent = get_post_datetime( $post );
2563        if ( ! $sent ) {
2564            return null;
2565        }
2566        $day = $sent->format( 'Y-m-d' );
2567        switch ( $window ) {
2568            case 'first_24_hours':
2569                $hour = (int) $sent->format( 'G' );
2570                $args = array(
2571                    'period'   => 'hour',
2572                    'quantity' => $hour + 24,
2573                    'date'     => $day,
2574                );
2575                return array(
2576                    'args' => $args,
2577                    'skip' => $hour,
2578                );
2579            case 'all_time':
2580                $now    = current_datetime();
2581                $months = ( (int) $now->format( 'Y' ) - (int) $sent->format( 'Y' ) ) * 12 + (int) $now->format( 'n' ) - (int) $sent->format( 'n' ) + 1;
2582                $args   = array(
2583                    'period'   => 'month',
2584                    'quantity' => max( 1, min( self::EMAIL_TIMELINE_MAX_MONTHS, $months ) ),
2585                    'date'     => $sent->format( 'Y-m-01' ),
2586                );
2587                break;
2588            default:
2589                $args = array(
2590                    'period'   => 'day',
2591                    'quantity' => 'first_7_days' === $window ? 7 : 30,
2592                    'date'     => $day,
2593                );
2594        }
2595        return array(
2596            'args' => $args,
2597            'skip' => 0,
2598        );
2599    }
2600
2601    /**
2602     * Merge an email's opens and clicks timelines into one row per bucket, oldest first.
2603     *
2604     * WordPress.com answers buckets that have not started yet with zeros, so rows stop at the
2605     * current one; a sent email that is younger than its window has fewer rows.
2606     *
2607     * @param string $window   One of EMAIL_TIMELINES.
2608     * @param array  $request  The request email_timeline_request() built.
2609     * @param array  $values   Sub-call responses keyed `{stat}/{field}`.
2610     * @param array  $errors   The sub-calls that failed.
2611     * @return array{window: string, unit: string, rows: array}|null Null when both timelines failed.
2612     */
2613    private static function email_timeline( string $window, array $request, array $values, array $errors ): ?array {
2614        $unit = $request['args']['period'];
2615        $now  = current_datetime()->format(
2616            array(
2617                'hour'  => 'Y-m-d H:00',
2618                'day'   => 'Y-m-d',
2619                'month' => 'Y-m-01',
2620            )[ $unit ]
2621        );
2622        $rows = array();
2623        $read = 0;
2624        foreach ( array( 'opens', 'clicks' ) as $stat ) {
2625            if ( in_array( "$stat/timeline", $errors, true ) ) {
2626                continue;
2627            }
2628            ++$read;
2629            $block  = is_array( $values[ "$stat/timeline" ]['timeline'] ?? null ) ? $values[ "$stat/timeline" ]['timeline'] : array();
2630            $fields = is_array( $block['fields'] ?? null ) ? $block['fields'] : array();
2631            $hour   = array_search( 'hour', $fields, true );
2632            $count  = array_search( "{$stat}_count", $fields, true );
2633            foreach ( array_slice( self::rows_at( $block, 'data' ), $request['skip'] ) as $row ) {
2634                $date = (string) ( $row[0] ?? '' );
2635                if ( false !== $hour ) {
2636                    $date .= sprintf( ' %02d:00', (int) ( $row[ $hour ] ?? 0 ) );
2637                }
2638                if ( $date > $now ) {
2639                    break;
2640                }
2641                $rows[ $date ]        ??= array(
2642                    'date'   => $date,
2643                    'opens'  => null,
2644                    'clicks' => null,
2645                );
2646                $rows[ $date ][ $stat ] = false === $count ? 0 : (int) ( $row[ $count ] ?? 0 );
2647            }
2648        }
2649        if ( 0 === $read ) {
2650            return null;
2651        }
2652        ksort( $rows );
2653        return array(
2654            'window' => $window,
2655            'unit'   => $unit,
2656            'rows'   => array_values( $rows ),
2657        );
2658    }
2659
2660    /**
2661     * Execute: get-video-stats.
2662     *
2663     * @param array|null $input Input matching the ability's input_schema.
2664     * @return array|WP_Error
2665     */
2666    public static function get_video_stats( $input = null ) {
2667        $input = is_array( $input ) ? $input : array();
2668        if ( ! isset( $input['video_id'] ) || ! is_numeric( $input['video_id'] ) || (int) $input['video_id'] <= 0 ) {
2669            return new WP_Error(
2670                self::ERROR_PREFIX . 'missing_video_id',
2671                __( 'A positive video_id is required.', 'jetpack-stats-pkg' )
2672            );
2673        }
2674        $video_id = (int) $input['video_id'];
2675        $period   = self::pick_period( $input['period'] ?? null );
2676        $num      = self::clamp_int( $input['num'] ?? 30, 1, 90, 30 );
2677        $date     = self::resolve_date( $input['date'] ?? null );
2678        if ( is_wp_error( $date ) ) {
2679            return $date;
2680        }
2681        $video = get_post( $video_id );
2682        if ( ! $video || 'attachment' !== $video->post_type ) {
2683            return new WP_Error(
2684                self::ERROR_PREFIX . 'video_not_found',
2685                __( 'No video exists with that video_id.', 'jetpack-stats-pkg' ),
2686                array( 'status' => 404 )
2687            );
2688        }
2689
2690        $raw = self::get_wpcom_stats()->get_video_details(
2691            $video_id,
2692            array(
2693                'statType' => 'all',
2694                'period'   => $period,
2695                'num'      => $num,
2696                'date'     => $date,
2697            )
2698        );
2699        if ( is_wp_error( $raw ) ) {
2700            return $raw;
2701        }
2702
2703        $fields  = is_array( $raw['fields'] ?? null ) ? $raw['fields'] : array();
2704        $figures = static function ( callable $at ): array {
2705            $retention = $at( 'retention_rate' );
2706            return array(
2707                'plays'          => (int) $at( 'plays' ),
2708                'impressions'    => (int) $at( 'impressions' ),
2709                'hours_watched'  => (float) $at( 'watch_time' ),
2710                // WPCOM sends null when it does not know the video's length.
2711                'retention_rate' => is_numeric( $retention ) ? round( (float) $retention, 1 ) : null,
2712            );
2713        };
2714        $series  = array();
2715        foreach ( self::rows_at( $raw, 'data' ) as $row ) {
2716            $series[] = array( 'date' => (string) ( $row[0] ?? '' ) ) + $figures(
2717                static function ( string $field ) use ( $fields, $row ) {
2718                    $column = array_search( $field, $fields, true );
2719                    return false === $column ? null : ( $row[ $column ] ?? null );
2720                }
2721            );
2722        }
2723        $total  = is_array( $raw['total'] ?? null ) ? $raw['total'] : array();
2724        $totals = $figures(
2725            static function ( string $field ) use ( $total ) {
2726                return $total[ $field ] ?? null;
2727            }
2728        );
2729        $pages  = array();
2730        foreach ( array_slice( self::rows_at( $raw, 'pages_detail' ), 0, self::VIDEO_PAGES_LIMIT ) as $page ) {
2731            $pages[] = array(
2732                'url'     => (string) ( $page['url'] ?? '' ),
2733                'post_id' => isset( $page['post_id'] ) ? (int) $page['post_id'] : null,
2734                'title'   => isset( $page['title'] ) ? html_entity_decode( (string) $page['title'], ENT_QUOTES | ENT_HTML5, 'UTF-8' ) : null,
2735            );
2736        }
2737
2738        return array(
2739            'site'        => self::site(),
2740            'video_id'    => $video_id,
2741            'title'       => get_the_title( $video ),
2742            'period'      => $period,
2743            'num'         => $num,
2744            'date'        => $date,
2745            'total'       => $totals,
2746            'series'      => $series,
2747            'pages'       => $pages,
2748            'definitions' => self::definitions( array( 'video_plays', 'series' ) ),
2749        );
2750    }
2751
2752    /**
2753     * Execute: get-subscribers.
2754     *
2755     * @param array|null $input Input matching the ability's input_schema.
2756     * @return array|WP_Error
2757     */
2758    public static function get_subscribers( $input = null ) {
2759        $input = is_array( $input ) ? $input : array();
2760        $args  = array(
2761            'page'       => self::clamp_int( $input['page'] ?? 1, 1, PHP_INT_MAX, 1 ),
2762            'per_page'   => self::clamp_int( $input['per_page'] ?? 20, 1, 100, 20 ),
2763            'sort'       => isset( $input['sort'] ) && in_array( $input['sort'], self::SUBSCRIBER_SORTS, true ) ? $input['sort'] : 'date_subscribed',
2764            'sort_order' => 'asc' === ( $input['order'] ?? null ) ? 'asc' : 'desc',
2765        );
2766        if ( isset( $input['filter'] ) && in_array( $input['filter'], self::SUBSCRIBER_FILTERS, true ) && 'all' !== $input['filter'] ) {
2767            $args['filter'] = $input['filter'];
2768        }
2769        if ( isset( $input['search'] ) && is_string( $input['search'] ) && '' !== trim( $input['search'] ) ) {
2770            $args['search'] = trim( $input['search'] );
2771        }
2772
2773        $raw = self::get_wpcom_stats()->get_subscribers( $args );
2774        if ( is_wp_error( $raw ) ) {
2775            return $raw;
2776        }
2777
2778        $subscribers = array();
2779        foreach ( self::rows_at( $raw, 'subscribers' ) as $row ) {
2780            $user_id       = self::as_int( $row, 'user_id' );
2781            $subscribers[] = array(
2782                'subscription_id'  => self::as_int( $row, 'subscription_id' ),
2783                'user_id'          => $user_id > 0 ? $user_id : null,
2784                'name'             => html_entity_decode( (string) ( $row['display_name'] ?? '' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
2785                'email'            => (string) ( $row['email_address'] ?? '' ),
2786                'url'              => (string) ( $row['url'] ?? '' ),
2787                'subscribed_at'    => (string) ( $row['date_subscribed'] ?? '' ),
2788                'status'           => (string) ( $row['subscription_status'] ?? '' ),
2789                'email_subscriber' => true === ( $row['is_email_subscriber'] ?? false ),
2790            );
2791        }
2792
2793        return array(
2794            'site'        => self::site(),
2795            'total'       => self::as_int( $raw, 'total' ),
2796            'page'        => $args['page'],
2797            'pages'       => self::as_int( $raw, 'pages' ),
2798            'subscribers' => $subscribers,
2799        );
2800    }
2801
2802    /**
2803     * Execute: get-ad-stats.
2804     *
2805     * @param array|null $input Input matching the ability's input_schema.
2806     * @return array|WP_Error
2807     */
2808    public static function get_ad_stats( $input = null ) {
2809        $input  = is_array( $input ) ? $input : array();
2810        $period = self::pick_period( $input['period'] ?? null, self::SERIES_PERIODS );
2811        $num    = self::clamp_int( $input['num'] ?? 30, 1, 90, 30 );
2812        $date   = self::resolve_date( $input['date'] ?? null );
2813        if ( is_wp_error( $date ) ) {
2814            return $date;
2815        }
2816
2817        $stats    = self::get_wpcom_stats();
2818        $composed = self::compose_subcalls(
2819            array(
2820                'stats'    => $stats->get_wordads_stats(
2821                    array(
2822                        'unit'     => $period,
2823                        'quantity' => $num,
2824                        'date'     => $date,
2825                    )
2826                ),
2827                'earnings' => $stats->get_wordads_earnings(),
2828            ),
2829            __( 'WordAds data could not be fetched from WordPress.com. Confirm the site is connected and try again.', 'jetpack-stats-pkg' )
2830        );
2831        if ( is_wp_error( $composed ) ) {
2832            return $composed;
2833        }
2834        $errors = $composed['errors'];
2835
2836        $series = null;
2837        if ( ! in_array( 'stats', $errors, true ) ) {
2838            $raw    = $composed['values']['stats'];
2839            $fields = array_flip( is_array( $raw['fields'] ?? null ) ? $raw['fields'] : array() );
2840            $series = array();
2841            foreach ( is_array( $raw['data'] ?? null ) ? $raw['data'] : array() as $row ) {
2842                if ( ! is_array( $row ) ) {
2843                    continue;
2844                }
2845                $series[] = array(
2846                    'date'        => self::period_start_date( (string) ( $row[ $fields['period'] ?? 0 ] ?? '' ) ),
2847                    'impressions' => (int) ( $row[ $fields['impressions'] ?? 1 ] ?? 0 ),
2848                    'revenue'     => round( (float) ( $row[ $fields['revenue'] ?? 2 ] ?? 0 ), 2 ),
2849                    'cpm'         => round( (float) ( $row[ $fields['cpm'] ?? 3 ] ?? 0 ), 2 ),
2850                );
2851            }
2852        }
2853
2854        $earnings = null;
2855        if ( ! in_array( 'earnings', $errors, true ) ) {
2856            $raw    = is_array( $composed['values']['earnings']['earnings'] ?? null ) ? $composed['values']['earnings']['earnings'] : array();
2857            $months = array();
2858            // WordAds, sponsored posts and adjustments each list amounts by `YYYY-MM`; a month is paid once every part of it is.
2859            foreach ( array( 'wordads', 'sponsored', 'adjustment' ) as $network ) {
2860                foreach ( self::rows_at( $raw, $network ) as $month => $row ) {
2861                    $month            = (string) $month;
2862                    $paid             = 1 === (int) ( $row['status'] ?? 0 );
2863                    $months[ $month ] = array(
2864                        'month'  => $month,
2865                        'amount' => ( $months[ $month ]['amount'] ?? 0 ) + (float) ( $row['amount'] ?? 0 ),
2866                        'paid'   => ( $months[ $month ]['paid'] ?? true ) && $paid,
2867                    );
2868                }
2869            }
2870            krsort( $months );
2871            foreach ( $months as $month => $row ) {
2872                $months[ $month ]['amount'] = round( $row['amount'], 2 );
2873            }
2874            $earnings = array(
2875                'total'  => round( (float) ( $raw['total_earnings'] ?? 0 ), 2 ),
2876                'owed'   => round( (float) ( $raw['total_amount_owed'] ?? 0 ), 2 ),
2877                'months' => array_values( $months ),
2878            );
2879        }
2880
2881        $out = array(
2882            'site'     => self::site(),
2883            'period'   => $period,
2884            'date'     => $date,
2885            'num'      => $num,
2886            'series'   => $series,
2887            'earnings' => $earnings,
2888            'partial'  => ! empty( $errors ),
2889        );
2890        if ( ! empty( $errors ) ) {
2891            $out['errors'] = $errors;
2892        }
2893        return $out;
2894    }
2895
2896    /**
2897     * Execute: get-settings.
2898     *
2899     * @param array|null $input Ignored â€” zero-arg ability.
2900     * @return array
2901     */
2902    public static function get_settings( $input = null ) {
2903        unset( $input );
2904        return Settings::get( Settings::KEYS );
2905    }
2906
2907    /**
2908     * Execute: update-settings.
2909     *
2910     * @param array|null $input Input matching the ability's input_schema.
2911     * @return array|WP_Error
2912     */
2913    public static function update_settings( $input = null ) {
2914        return Settings::update( is_array( $input ) ? $input : array(), Settings::KEYS );
2915    }
2916
2917    /*
2918    ---------------------------------------------------------------------
2919     * Helpers
2920     * ---------------------------------------------------------------------
2921     */
2922
2923    /**
2924     * Compose multiple WPCOM sub-call results into a partial-tolerant envelope.
2925     *
2926     * An array result is kept as-is. Anything else â€” a WP_Error, or the decoded
2927     * body of a response that was not a JSON object â€” is replaced with `[]` and
2928     * its key recorded under `errors`. Returns `jetpack_stats_data_unavailable`
2929     * if every sub-call failed.
2930     *
2931     * @param array  $named_results       Map of error-tag => sub-call result.
2932     * @param string $all_failed_message  Message for the all-failed WP_Error.
2933     * @return array{values: array<string, array>, errors: string[]}|WP_Error
2934     */
2935    private static function compose_subcalls( array $named_results, string $all_failed_message ) {
2936        $values = array();
2937        $errors = array();
2938        foreach ( $named_results as $tag => $result ) {
2939            if ( is_array( $result ) ) {
2940                $values[ $tag ] = $result;
2941            } else {
2942                $errors[]       = (string) $tag;
2943                $values[ $tag ] = array();
2944            }
2945        }
2946
2947        if ( count( $errors ) === count( $named_results ) ) {
2948            return new WP_Error( self::ERROR_PREFIX . 'data_unavailable', $all_failed_message );
2949        }
2950
2951        return array(
2952            'values' => $values,
2953            'errors' => $errors,
2954        );
2955    }
2956
2957    /**
2958     * Resolve an aggregation period from raw input, defaulting to `day`.
2959     *
2960     * @param mixed $raw     Raw input value.
2961     * @param array $allowed The periods the ability accepts.
2962     * @return string One of `$allowed`.
2963     */
2964    private static function pick_period( $raw, array $allowed = self::PERIODS ): string {
2965        return is_string( $raw ) && in_array( $raw, $allowed, true ) ? $raw : 'day';
2966    }
2967
2968    /**
2969     * Return a WPCOM_Stats instance. Filterable for tests.
2970     *
2971     * @return WPCOM_Stats
2972     */
2973    protected static function get_wpcom_stats(): WPCOM_Stats {
2974        /**
2975         * Filters the WPCOM_Stats instance used by the Stats abilities.
2976         *
2977         * @since 0.19.0
2978         *
2979         * @param WPCOM_Stats $wpcom_stats The default instance.
2980         */
2981        $instance = apply_filters( 'jetpack_stats_abilities_wpcom_stats', new WPCOM_Stats() );
2982        return $instance instanceof WPCOM_Stats ? $instance : new WPCOM_Stats();
2983    }
2984
2985    /**
2986     * Dispatch top-content raw fetch to the right WPCOM_Stats method.
2987     *
2988     * @param WPCOM_Stats $stats Client.
2989     * @param string      $type  Content type enum.
2990     * @param array       $args      Pre-built `{ period, date, max, num?, summarize? }` args, or `{ date, days, max }` for
2991     *                               the DAYS_WINDOW_TYPES â€” `tags` takes only `max`, and the comment types none.
2992     * @param string      $utm_param UTM parameter or combination, for `utm`.
2993     * @return array|WP_Error
2994     */
2995    private static function fetch_top_content_raw( WPCOM_Stats $stats, string $type, array $args, string $utm_param = '' ) {
2996        if ( isset( self::LOCATION_TYPES[ $type ] ) ) {
2997            return $stats->get_views_by_location( self::LOCATION_TYPES[ $type ], $args );
2998        }
2999        if ( 'utm' === $type ) {
3000            return $stats->get_utm_views( $utm_param, $args );
3001        }
3002        if ( isset( self::DAYS_WINDOW_TYPES[ $type ] ) ) {
3003            return $stats->get_device_views( self::DAYS_WINDOW_TYPES[ $type ], $args );
3004        }
3005
3006        switch ( $type ) {
3007            case 'commenters':
3008            case 'commented-posts':
3009                return $stats->get_top_comments();
3010            case 'posts':
3011                return $stats->get_top_posts( $args );
3012            case 'referrers':
3013                return $stats->get_referrers( $args );
3014            case 'search-terms':
3015                return $stats->get_search_terms( $args );
3016            case 'clicks':
3017                return $stats->get_clicks( $args );
3018            case 'tags':
3019                // get_tags has a narrower arg surface â€” pass only `max`.
3020                return $stats->get_tags( array( 'max' => $args['max'] ) );
3021            case 'authors':
3022                return $stats->get_top_authors( $args );
3023            case 'countries':
3024                return $stats->get_views_by_country( $args );
3025            case 'downloads':
3026                return $stats->get_file_downloads( $args );
3027            case 'video-plays':
3028                return $stats->get_video_plays( $args );
3029        }
3030
3031        return new WP_Error( self::ERROR_PREFIX . 'invalid_type', __( 'Unknown top-content type.', 'jetpack-stats-pkg' ) );
3032    }
3033
3034    /**
3035     * Project a WPCOM top-content response into label/value rows, in WordPress.com's order.
3036     *
3037     * Most `type` values follow the `days -> <date> -> <list-key>` shape (or
3038     * `summary -> <list-key>` when summarized) and project through
3039     * `TOP_CONTENT_MAP`. `tags` and `countries` are special-cased.
3040     *
3041     * @param string $type       Content type enum.
3042     * @param array  $raw        Raw WPCOM response.
3043     * @param bool   $summarized Whether the request asked WPCOM to `summarize`.
3044     * @return array List of { label, value, href?, id? } rows.
3045     */
3046    private static function top_content_rows( string $type, array $raw, bool $summarized = false ): array {
3047        if ( 'tags' === $type ) {
3048            return self::tag_rows( $raw );
3049        }
3050
3051        $day_data = self::first_period_block( $raw, $summarized );
3052
3053        if ( 'countries' === $type ) {
3054            return self::country_rows( $day_data, self::rows_at( $raw, 'country-info' ) );
3055        }
3056        if ( isset( self::LOCATION_TYPES[ $type ] ) ) {
3057            return self::location_rows( $day_data );
3058        }
3059        if ( isset( self::DAYS_WINDOW_TYPES[ $type ] ) ) {
3060            return self::value_map_rows( $raw[ 'utm' === $type ? 'top_utm_values' : 'top_values' ] ?? null );
3061        }
3062        if ( in_array( $type, array( 'commenters', 'commented-posts' ), true ) ) {
3063            // These lists are not split into periods.
3064            $day_data = $raw;
3065        }
3066
3067        $map = self::TOP_CONTENT_MAP[ $type ] ?? null;
3068        if ( null === $map ) {
3069            return array();
3070        }
3071
3072        $rows = array();
3073        foreach ( self::rows_at( $day_data, $map['list'] ) as $row ) {
3074            $rows[] = array(
3075                'label'    => self::pick_field( $row, $map['label'] ),
3076                'value'    => self::pick_field( $row, $map['value'] ),
3077                'href'     => isset( $map['href'] ) ? self::pick_field( $row, $map['href'] ) : null,
3078                'id'       => isset( $map['id'] ) ? self::pick_field( $row, $map['id'] ) : null,
3079                'children' => isset( $map['children'] ) ? self::child_rows( $row[ $map['children'] ] ?? null ) : array(),
3080            );
3081        }
3082        return $rows;
3083    }
3084
3085    /**
3086     * Project the rows a referrer, click or author row groups, and the rows those group in turn.
3087     *
3088     * A referrer group with nothing under it reports `results` as `{ views }` rather than a list, so it has none.
3089     *
3090     * @param mixed $list Raw list of `{ name|title, url, views, children? }`, or anything else for none.
3091     * @return array Rows of `{ label, value, href, children }`.
3092     */
3093    private static function child_rows( $list ): array {
3094        if ( ! is_array( $list ) || array_values( $list ) !== $list ) {
3095            return array();
3096        }
3097        $rows = array();
3098        foreach ( array_filter( $list, 'is_array' ) as $row ) {
3099            $rows[] = array(
3100                'label'    => self::pick_field( $row, array( 'name', 'title', 'url' ) ),
3101                'value'    => $row['views'] ?? 0,
3102                'href'     => self::pick_field( $row, 'url' ),
3103                'children' => self::child_rows( $row['children'] ?? null ),
3104            );
3105        }
3106        return $rows;
3107    }
3108
3109    /**
3110     * Project `stats/tags` rows, which carry no `days` envelope, into label/value rows.
3111     *
3112     * Each row groups one or more tags and categories under a shared view count, so
3113     * its label names them all; only a single-term row has one URL to link to.
3114     *
3115     * @param array $raw Raw WPCOM response: `{ tags: [ { tags: [ { type, name, link } ], views } ] }`.
3116     * @return array
3117     */
3118    private static function tag_rows( array $raw ): array {
3119        $rows = array();
3120        foreach ( self::rows_at( $raw, 'tags' ) as $row ) {
3121            $terms  = self::rows_at( $row, 'tags' );
3122            $rows[] = array(
3123                'label'    => implode( ', ', array_column( $terms, 'name' ) ),
3124                'value'    => $row['views'] ?? 0,
3125                'href'     => 1 === count( $terms ) ? ( array_column( $terms, 'link' )[0] ?? null ) : null,
3126                'children' => 1 === count( $terms ) ? array() : array_map(
3127                    function ( $term ) {
3128                        return array(
3129                            'label' => $term['name'] ?? '',
3130                            'href'  => $term['link'] ?? null,
3131                            'type'  => $term['type'] ?? null,
3132                        );
3133                    },
3134                    array_values( $terms )
3135                ),
3136            );
3137        }
3138        return $rows;
3139    }
3140
3141    /**
3142     * Project WordPress.com's `[ name, count ]` email rows into the top `$max` label/value rows, most first.
3143     *
3144     * Rows whose names share a label merge; a null label drops the row.
3145     *
3146     * @param array    $tuples `[ name, count ]` rows.
3147     * @param callable $label  Maps a row's name to its label, or null to drop it.
3148     * @param int      $max    Rows cap.
3149     * @return array
3150     */
3151    private static function email_rows( array $tuples, callable $label, int $max ): array {
3152        $values = array();
3153        foreach ( $tuples as $tuple ) {
3154            if ( ! is_array( $tuple ) || ! isset( $tuple[0] ) ) {
3155                continue;
3156            }
3157            $name = $label( (string) $tuple[0] );
3158            if ( null !== $name ) {
3159                $values[ $name ] = ( $values[ $name ] ?? 0 ) + (int) ( $tuple[1] ?? 0 );
3160            }
3161        }
3162        arsort( $values );
3163
3164        $rows = array();
3165        foreach ( array_slice( $values, 0, $max, true ) as $name => $value ) {
3166            $rows[] = array(
3167                'label' => (string) $name,
3168                'value' => $value,
3169            );
3170        }
3171        return $rows;
3172    }
3173
3174    /**
3175     * Project a `stats/country-views` period block into label/value rows named by `country-info`.
3176     *
3177     * Codes WordPress.com cannot name (AP and the legacy UK get `country_full: false`, and `-` marks
3178     * a failed lookup) share one "Unknown" row; the A1, A2 and ZZ pseudo-codes name no place and are dropped.
3179     *
3180     * @param array $day_data     Period block holding the `views` rows.
3181     * @param array $country_info Map of country code => `{ country_full }`.
3182     * @return array
3183     */
3184    private static function country_rows( array $day_data, array $country_info ): array {
3185        $unknown = __( 'Unknown', 'jetpack-stats-pkg' );
3186        $views   = array();
3187        foreach ( self::rows_at( $day_data, 'views' ) as $row ) {
3188            $code = (string) ( $row['country_code'] ?? '' );
3189            if ( in_array( $code, array( 'A1', 'A2', 'ZZ' ), true ) ) {
3190                continue;
3191            }
3192            $name            = $country_info[ $code ]['country_full'] ?? null;
3193            $label           = is_string( $name ) && '' !== $name ? $name : $unknown;
3194            $views[ $label ] = ( $views[ $label ] ?? 0 ) + (int) ( $row['views'] ?? 0 );
3195        }
3196        // Folding rows into "Unknown" can lift it above rows WordPress.com ranked higher.
3197        arsort( $views );
3198
3199        $rows = array();
3200        foreach ( $views as $label => $value ) {
3201            $rows[] = array(
3202                'label' => (string) $label,
3203                'value' => $value,
3204            );
3205        }
3206        return $rows;
3207    }
3208
3209    /**
3210     * Project a `stats/location-views/{region,city}` period block into label/value rows.
3211     *
3212     * @param array $day_data Period block holding the `views` rows of `{ location, views, country_code }`.
3213     * @return array
3214     */
3215    private static function location_rows( array $day_data ): array {
3216        $rows = array();
3217        foreach ( self::rows_at( $day_data, 'views' ) as $row ) {
3218            $rows[] = array(
3219                'label'   => (string) ( $row['location'] ?? '' ),
3220                'value'   => $row['views'] ?? 0,
3221                'country' => $row['country_code'] ?? null,
3222            );
3223        }
3224        return $rows;
3225    }
3226
3227    /**
3228     * Project a WordPress.com `{ value: count }` map into label/value rows, in its order.
3229     *
3230     * A UTM combination is keyed by the JSON list of its values, which reads as `google / cpc`.
3231     *
3232     * @param mixed $map Map of value => count, or anything else for none.
3233     * @return array
3234     */
3235    private static function value_map_rows( $map ): array {
3236        if ( ! is_array( $map ) ) {
3237            return array();
3238        }
3239        $rows = array();
3240        foreach ( $map as $label => $count ) {
3241            $label  = (string) $label;
3242            $values = json_decode( $label, true );
3243            $rows[] = array(
3244                'label' => is_array( $values ) ? implode( ' / ', array_map( 'strval', $values ) ) : $label,
3245                'value' => (int) round( (float) $count ),
3246            );
3247        }
3248        return $rows;
3249    }
3250
3251    /**
3252     * Project the posts one UTM value's views went to.
3253     *
3254     * @param array $raw `stats/utm/<param>/top_posts` response.
3255     * @return array Rows of `{ label, value, href, id }`.
3256     */
3257    private static function utm_post_rows( array $raw ): array {
3258        $rows = array();
3259        foreach ( self::rows_at( $raw, 'top_posts' ) as $post ) {
3260            $rows[] = array(
3261                'label' => (string) ( $post['title'] ?? '' ),
3262                'value' => (int) ( $post['views'] ?? 0 ),
3263                'href'  => $post['href'] ?? null,
3264                'id'    => (int) ( $post['id'] ?? 0 ),
3265            );
3266        }
3267        return $rows;
3268    }
3269
3270    /**
3271     * Return the block of a WPCOM list response that holds the rows to report.
3272     *
3273     * A `summarize=1` request totals the periods under `summary` (`days -> summary`
3274     * for video plays); otherwise each period sits under `days -> <date>`, and a
3275     * single-period request has exactly one of those.
3276     *
3277     * @param array $raw        Raw WPCOM response.
3278     * @param bool  $summarized Whether the request asked WPCOM to `summarize`.
3279     * @return array The period block, or [].
3280     */
3281    private static function first_period_block( array $raw, bool $summarized = false ): array {
3282        if ( $summarized ) {
3283            $summary = ! empty( $raw['summary'] ) ? $raw['summary'] : ( $raw['days']['summary'] ?? array() );
3284            return is_array( $summary ) ? $summary : array();
3285        }
3286        if ( ! isset( $raw['days'] ) || ! is_array( $raw['days'] ) || empty( $raw['days'] ) ) {
3287            return array();
3288        }
3289        $first = reset( $raw['days'] );
3290        return is_array( $first ) ? $first : array();
3291    }
3292
3293    /**
3294     * Return the first posts item that is a post or page, skipping the home page / archives row.
3295     *
3296     * @param array $items Items from rank_and_cap().
3297     * @return array|null
3298     */
3299    private static function first_post( array $items ): ?array {
3300        foreach ( $items as $item ) {
3301            if ( isset( $item['id'] ) ) {
3302                return $item;
3303            }
3304        }
3305        return null;
3306    }
3307
3308    /**
3309     * Return the rows of the list (or the entries of the map) at `$key`, skipping any that are not arrays.
3310     *
3311     * @param array  $arr Array holding the list.
3312     * @param string $key Key of the list.
3313     * @return array[]
3314     */
3315    private static function rows_at( array $arr, string $key ): array {
3316        $list = $arr[ $key ] ?? null;
3317        return is_array( $list ) ? array_filter( $list, 'is_array' ) : array();
3318    }
3319
3320    /**
3321     * Read the first of the given keys that is present and non-empty on a row.
3322     *
3323     * @param array           $row  Row from a WPCOM list.
3324     * @param string|string[] $keys Key, or keys in order of preference.
3325     * @return mixed|null
3326     */
3327    private static function pick_field( array $row, $keys ) {
3328        foreach ( (array) $keys as $key ) {
3329            if ( isset( $row[ $key ] ) && '' !== $row[ $key ] ) {
3330                return $row[ $key ];
3331            }
3332        }
3333        return null;
3334    }
3335
3336    /**
3337     * Cap rows and turn them into ranked items, dropping empty `href`s and non-positive `id`s.
3338     *
3339     * @param array $rows   Rows of `{ label, value, href?, id?, children? }`.
3340     * @param int   $max    Result cap; 0 keeps every row.
3341     * @param bool  $expand Whether to keep each row's `children`.
3342     * @return array Items of `{ rank, label, value, href?, id?, children? }`.
3343     */
3344    private static function rank_and_cap( array $rows, int $max, bool $expand = false ): array {
3345        $items = array();
3346        foreach ( 0 === $max ? $rows : array_slice( $rows, 0, $max ) as $i => $row ) {
3347            $item = array( 'rank' => $i + 1 ) + self::item( $row );
3348            $id   = (int) ( $row['id'] ?? 0 );
3349            if ( $id > 0 ) {
3350                $item['id'] = $id;
3351            }
3352            if ( $expand && ! empty( $row['children'] ) ) {
3353                $item['children'] = self::child_items( $row['children'], $max );
3354            }
3355            $items[] = $item;
3356        }
3357        return $items;
3358    }
3359
3360    /**
3361     * Turn child rows into items, nested as WordPress.com nests them.
3362     *
3363     * WordPress.com caps every level at the requested `max`, which is one more than the cap asked for.
3364     *
3365     * @param array $rows Rows of `{ label, value?, href?, id?, type?, children? }`.
3366     * @param int   $max  Cap per level; 0 keeps every row.
3367     * @return array Items of `{ label, value?, href?, id?, type?, children? }`.
3368     */
3369    private static function child_items( array $rows, int $max ): array {
3370        $items = array();
3371        foreach ( 0 === $max ? $rows : array_slice( $rows, 0, $max ) as $row ) {
3372            $item = self::item( $row );
3373            if ( (int) ( $row['id'] ?? 0 ) > 0 ) {
3374                $item['id'] = (int) $row['id'];
3375            }
3376            if ( ! empty( $row['type'] ) ) {
3377                $item['type'] = (string) $row['type'];
3378            }
3379            if ( ! empty( $row['children'] ) ) {
3380                $item['children'] = self::child_items( $row['children'], $max );
3381            }
3382            $items[] = $item;
3383        }
3384        return $items;
3385    }
3386
3387    /**
3388     * The label, value and href of one row; a row without a `value` key (a term in a tags item) gets none.
3389     *
3390     * @param array $row Row of `{ label, value?, href? }`.
3391     * @return array
3392     */
3393    private static function item( array $row ): array {
3394        // WordPress.com sends titles and names HTML-encoded.
3395        $item = array( 'label' => html_entity_decode( (string) ( $row['label'] ?? '' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
3396        if ( array_key_exists( 'value', $row ) ) {
3397            $item['value'] = (int) ( $row['value'] ?? 0 );
3398        }
3399        if ( ! empty( $row['country'] ) ) {
3400            $item['country'] = (string) $row['country'];
3401        }
3402        if ( isset( $row['href'] ) && '' !== $row['href'] ) {
3403            // Links off a WordPress.com site go through the href.li redirector; report where they lead.
3404            $item['href'] = (string) preg_replace( '#^https?://href\.li/\?#', '', (string) $row['href'] );
3405        }
3406        return $item;
3407    }
3408
3409    /**
3410     * Project a `stats/subscribers` response into `{ date, subscribers, change }` rows, oldest first.
3411     *
3412     * WordPress.com lists the periods newest first.
3413     *
3414     * @param array $raw Raw response: `{ fields: [ period, subscribers, subscribers_change ], data: [ [ â€¦ ] ] }`.
3415     * @return array
3416     */
3417    private static function subscriber_series( array $raw ): array {
3418        $fields = array_flip( is_array( $raw['fields'] ?? null ) ? $raw['fields'] : array() );
3419        $series = array();
3420        foreach ( is_array( $raw['data'] ?? null ) ? $raw['data'] : array() as $row ) {
3421            if ( ! is_array( $row ) ) {
3422                continue;
3423            }
3424            $series[] = array(
3425                'date'        => self::period_start_date( (string) ( $row[ $fields['period'] ?? 0 ] ?? '' ) ),
3426                'subscribers' => (int) ( $row[ $fields['subscribers'] ?? 1 ] ?? 0 ),
3427                'change'      => (int) ( $row[ $fields['subscribers_change'] ?? 2 ] ?? 0 ),
3428            );
3429        }
3430        usort(
3431            $series,
3432            static function ( $a, $b ) {
3433                return strcmp( $a['date'], $b['date'] );
3434            }
3435        );
3436        return $series;
3437    }
3438
3439    /**
3440     * Count the posts the site published each day, from the WPCOM streak response.
3441     *
3442     * WPCOM keys each publish time, as a Unix timestamp, to the posts published then.
3443     *
3444     * @param array  $streak Raw WPCOM streak response: `{ data: { timestamp: posts } }`.
3445     * @param string $from   First day asked for, YYYY-MM-DD.
3446     * @param string $to     Last day asked for, YYYY-MM-DD.
3447     * @return array `{ from, to, days: [ { date, posts } ] }`, days oldest first.
3448     */
3449    private static function posting_calendar( array $streak, string $from, string $to ): array {
3450        $counts = array();
3451        $posts  = 0;
3452        foreach ( is_array( $streak['data'] ?? null ) ? $streak['data'] : array() as $timestamp => $count ) {
3453            $day            = wp_date( 'Y-m-d', (int) $timestamp );
3454            $counts[ $day ] = ( $counts[ $day ] ?? 0 ) + (int) $count;
3455            $posts         += (int) $count;
3456        }
3457        ksort( $counts );
3458        // At the cap WPCOM drops the oldest posts, so the calendar starts at the oldest day it returned.
3459        if ( $posts >= self::STREAK_MAX_POSTS ) {
3460            $from = (string) array_key_first( $counts );
3461        }
3462
3463        $days = array();
3464        foreach ( $counts as $date => $count ) {
3465            $days[] = array(
3466                'date'  => (string) $date,
3467                'posts' => $count,
3468            );
3469        }
3470        return array(
3471            'from' => $from,
3472            'to'   => $to,
3473            'days' => $days,
3474        );
3475    }
3476
3477    /**
3478     * Find the current and longest posting streaks among the calendar's days.
3479     *
3480     * The current run counts only while it reaches today or yesterday.
3481     *
3482     * @param array  $days  The calendar's `{ date, posts }` days, oldest first.
3483     * @param string $today The site's today, YYYY-MM-DD.
3484     * @return array `{ current_length, longest_length, longest_start, longest_end }`.
3485     */
3486    private static function streak_summary( array $days, string $today ): array {
3487        $longest = array(
3488            'longest_length' => 0,
3489            'longest_start'  => '',
3490            'longest_end'    => '',
3491        );
3492        $run     = 0;
3493        $start   = '';
3494        $last    = '';
3495        foreach ( $days as $day ) {
3496            $date = $day['date'];
3497            $run  = '' !== $last && gmdate( 'Y-m-d', strtotime( $last . ' +1 day' ) ) === $date ? $run + 1 : 1;
3498            if ( 1 === $run ) {
3499                $start = $date;
3500            }
3501            if ( $run > $longest['longest_length'] ) {
3502                $longest = array(
3503                    'longest_length' => $run,
3504                    'longest_start'  => $start,
3505                    'longest_end'    => $date,
3506                );
3507            }
3508            $last = $date;
3509        }
3510        $ongoing = '' !== $last && $last >= gmdate( 'Y-m-d', strtotime( $today . ' -1 day' ) );
3511
3512        return array( 'current_length' => $ongoing ? $run : 0 ) + $longest;
3513    }
3514
3515    /**
3516     * Count the people following the comments on every post.
3517     *
3518     * WordPress.com lists them as an "All Posts" row with id 0. Each other row counts one post's
3519     * followers, so summing rows counts people twice, and `total` counts rows rather than people.
3520     * Rows are ranked by followers, 20 to a page, so the "All Posts" row can sit on a later page.
3521     *
3522     * @param array $raw Raw WPCOM comment-followers response (first page).
3523     * @return int|null Null when the row may be on a later page, so the count is unknown.
3524     */
3525    private static function all_posts_comment_followers( array $raw ): ?int {
3526        foreach ( self::rows_at( $raw, 'posts' ) as $row ) {
3527            if ( isset( $row['id'] ) && 0 === (int) $row['id'] ) {
3528                return self::as_int( $row, 'followers' );
3529            }
3530        }
3531        return self::as_int( $raw, 'pages' ) > 1 ? null : 0;
3532    }
3533
3534    /**
3535     * Extract a post-views series from the WPCOM get_post_views response.
3536     *
3537     * WPCOM returns `data` as a list of `[date, views]` tuples under the
3538     * `fields` header. We normalize to `[{ date, views }]`.
3539     *
3540     * @param array $raw Raw WPCOM response.
3541     * @return array
3542     */
3543    private static function extract_post_views_series( array $raw ): array {
3544        if ( ! isset( $raw['data'] ) || ! is_array( $raw['data'] ) ) {
3545            return array();
3546        }
3547
3548        $fields    = isset( $raw['fields'] ) && is_array( $raw['fields'] ) ? $raw['fields'] : array( 'period', 'views' );
3549        $date_idx  = array_search( 'period', $fields, true );
3550        $views_idx = array_search( 'views', $fields, true );
3551        if ( false === $date_idx || false === $views_idx ) {
3552            // If either column is missing from the WPCOM response, the positional
3553            // fallback is unsafe (we might collide date/views on column 0). Drop
3554            // to empty rather than emit lies.
3555            return array();
3556        }
3557
3558        $series = array();
3559        foreach ( $raw['data'] as $row ) {
3560            if ( ! is_array( $row ) ) {
3561                continue;
3562            }
3563            $series[] = array(
3564                'date'  => isset( $row[ $date_idx ] ) ? (string) $row[ $date_idx ] : '',
3565                'views' => isset( $row[ $views_idx ] ) ? (int) $row[ $views_idx ] : 0,
3566            );
3567        }
3568        return $series;
3569    }
3570
3571    /**
3572     * Total a daily views series into the `$num` periods ending with the one containing `$date`.
3573     *
3574     * @param array  $daily  Rows of `{ date: YYYY-MM-DD, views }`.
3575     * @param string $period One of self::SERIES_PERIODS.
3576     * @param int    $num    Number of periods to return.
3577     * @param string $date   YYYY-MM-DD inside the last period.
3578     * @return array Rows of `{ date, views }`, oldest first, each dated by its period's first day.
3579     */
3580    private static function bucket_daily_views( array $daily, string $period, int $num, string $date ): array {
3581        $start = self::period_start( $date, $period );
3582        if ( null === $start ) {
3583            return array();
3584        }
3585
3586        $step   = array(
3587            'day'     => '-1 day',
3588            'week'    => '-7 days',
3589            'month'   => '-1 month',
3590            'quarter' => '-3 months',
3591            'year'    => '-1 year',
3592        )[ $period ];
3593        $totals = array();
3594        for ( $i = 0; $i < $num; $i++ ) {
3595            $totals[ $start->format( 'Y-m-d' ) ] = 0;
3596            $start                               = $start->modify( $step );
3597        }
3598
3599        foreach ( $daily as $row ) {
3600            $row_start = self::period_start( $row['date'], $period );
3601            $key       = null === $row_start ? null : $row_start->format( 'Y-m-d' );
3602            if ( null !== $key && isset( $totals[ $key ] ) ) {
3603                $totals[ $key ] += (int) $row['views'];
3604            }
3605        }
3606
3607        $series = array();
3608        foreach ( array_reverse( $totals, true ) as $day => $views ) {
3609            $series[] = array(
3610                'date'  => $day,
3611                'views' => $views,
3612            );
3613        }
3614        return $series;
3615    }
3616
3617    /**
3618     * The days covering `$num` periods ending with the one containing `$date`, as summarized request args.
3619     *
3620     * With `summarize=1`, WPCOM's top-posts, referrers, clicks, country-views and video-plays ignore `period`
3621     * and read `num` as days, and top-authors and file-downloads return nothing for longer periods. Every one
3622     * of them totals `num` days ending on `date`, so the window is sent that way. The last period runs to its
3623     * end or to today, whichever is first, unless `$date` itself is later.
3624     *
3625     * @param string $period One of self::PERIODS.
3626     * @param int    $num    Number of periods, 2 or more.
3627     * @param string $date   YYYY-MM-DD inside the last period.
3628     * @return array `{ period: 'day', date, num, summarize: 1 }`.
3629     */
3630    private static function summary_window( string $period, int $num, string $date ): array {
3631        $utc        = new \DateTimeZone( 'UTC' );
3632        $requested  = \DateTimeImmutable::createFromFormat( '!Y-m-d', $date, $utc );
3633        $today      = \DateTimeImmutable::createFromFormat( '!Y-m-d', self::today(), $utc );
3634        $last_start = self::period_start( $date, $period );
3635        $first      = $last_start->modify( '-' . ( $num - 1 ) . ' ' . $period );
3636        $end        = max( $requested, min( $last_start->modify( '+1 ' . $period . ' -1 day' ), $today ) );
3637
3638        return array(
3639            'period'    => 'day',
3640            'date'      => $end->format( 'Y-m-d' ),
3641            'num'       => (int) $first->diff( $end )->days + 1,
3642            'summarize' => 1,
3643        );
3644    }
3645
3646    /**
3647     * Input schema for `compare`.
3648     *
3649     * @return array
3650     */
3651    private static function compare_schema(): array {
3652        return array(
3653            'type'        => 'string',
3654            'description' => __( 'Also return the same figures for an earlier window, as the Stats dashboard\'s Compare menu does: the window just before, the window just before shifted by whole weeks so weekdays line up, the same dates a year earlier, or 52 weeks earlier so weekdays line up.', 'jetpack-stats-pkg' ),
3655            'enum'        => self::COMPARE_PRESETS,
3656        );
3657    }
3658
3659    /**
3660     * Resolve the `compare` input.
3661     *
3662     * @param mixed $raw Raw input value.
3663     * @return string|null|WP_Error A preset, null when none was asked for, or jetpack_stats_invalid_compare.
3664     */
3665    private static function pick_compare( $raw ) {
3666        if ( null === $raw || '' === $raw ) {
3667            return null;
3668        }
3669        if ( is_string( $raw ) && in_array( $raw, self::COMPARE_PRESETS, true ) ) {
3670            return $raw;
3671        }
3672        return new WP_Error(
3673            self::ERROR_PREFIX . 'invalid_compare',
3674            sprintf(
3675                /* translators: %s: comma-separated list of valid compare values. */
3676                __( 'Unknown `compare` preset. Valid values: %s.', 'jetpack-stats-pkg' ),
3677                implode( ', ', self::COMPARE_PRESETS )
3678            )
3679        );
3680    }
3681
3682    /**
3683     * End date of the window a preset compares with, for `num` periods ending with the one containing `date`.
3684     *
3685     * The shifts are the dashboard's: the previous period steps back by the window's length, a weekday
3686     * match rounds that up to whole weeks, the previous year keeps the calendar date and a weekday-matched
3687     * year steps back 52 weeks. Weeks, months, quarters and years step back whole periods. WordPress.com ends the
3688     * last row on `date`, so shifting `date` itself ends both last rows at the same point in their period.
3689     * Weeks already line up by weekday; months and years cannot.
3690     *
3691     * @param string $date   YYYY-MM-DD.
3692     * @param string $preset One of self::COMPARE_PRESETS.
3693     * @param string $period One of self::SERIES_PERIODS.
3694     * @param int    $num    Number of periods in the window.
3695     * @return string|WP_Error YYYY-MM-DD, or jetpack_stats_invalid_compare for a weekday match on months, quarters or years.
3696     */
3697    private static function compare_end_date( string $date, string $preset, string $period, int $num ) {
3698        $day       = \DateTimeImmutable::createFromFormat( '!Y-m-d', $date, new \DateTimeZone( 'UTC' ) );
3699        $by_week   = in_array( $preset, array( 'previous-period-match-day-of-week', 'previous-year-match-day-of-week' ), true );
3700        $prev_year = in_array( $preset, array( 'previous-year', 'previous-year-match-day-of-week' ), true );
3701
3702        if ( $by_week && in_array( $period, array( 'month', 'quarter', 'year' ), true ) ) {
3703            return new WP_Error(
3704                self::ERROR_PREFIX . 'invalid_compare',
3705                __( 'Months, quarters and years cannot line up by weekday. Use previous-period or previous-year.', 'jetpack-stats-pkg' )
3706            );
3707        }
3708
3709        switch ( $period ) {
3710            case 'day':
3711                if ( 'previous-year' === $preset ) {
3712                    return self::months_earlier( $day, 12 )->format( 'Y-m-d' );
3713                }
3714                $days = $prev_year ? 364 : ( $by_week ? (int) ceil( $num / 7 ) * 7 : $num );
3715                return $day->modify( "-{$days} days" )->format( 'Y-m-d' );
3716            case 'week':
3717                return $day->modify( '-' . ( $prev_year ? 52 : $num ) . ' weeks' )->format( 'Y-m-d' );
3718        }
3719
3720        $length = array(
3721            'month'   => 1,
3722            'quarter' => 3,
3723            'year'    => 12,
3724        )[ $period ];
3725        $months = $prev_year ? 12 : $length * $num;
3726        return self::months_earlier( $day, $months )->format( 'Y-m-d' );
3727    }
3728
3729    /**
3730     * The same day some months earlier, clamped to that month's length; a month's last day stays its last.
3731     *
3732     * @param \DateTimeImmutable $day    Day.
3733     * @param int                $months Months to step back.
3734     * @return \DateTimeImmutable
3735     */
3736    private static function months_earlier( \DateTimeImmutable $day, int $months ): \DateTimeImmutable {
3737        $first = $day->modify( 'first day of this month' )->modify( "-{$months} months" );
3738        $last  = (int) $first->format( 't' );
3739        $date  = (int) $day->format( 'j' ) === (int) $day->format( 't' ) ? $last : min( (int) $day->format( 'j' ), $last );
3740        return $first->setDate( (int) $first->format( 'Y' ), (int) $first->format( 'n' ), $date );
3741    }
3742
3743    /**
3744     * The windows the overview compares today, the last 7 days and the last 30 days with.
3745     *
3746     * @param string $today  YYYY-MM-DD.
3747     * @param string $preset One of self::COMPARE_PRESETS.
3748     * @return array<string, array{from: string, to: string, days: int}> Keyed `today`, `week`, `month`.
3749     */
3750    private static function overview_compare_windows( string $today, string $preset ): array {
3751        $windows = array();
3752        foreach ( array(
3753            'today' => 1,
3754            'week'  => 7,
3755            'month' => 30,
3756        ) as $name => $days ) {
3757            $to               = (string) self::compare_end_date( $today, $preset, 'day', $days );
3758            $windows[ $name ] = array(
3759                'from' => \DateTimeImmutable::createFromFormat( '!Y-m-d', $to, new \DateTimeZone( 'UTC' ) )->modify( '-' . ( $days - 1 ) . ' days' )->format( 'Y-m-d' ),
3760                'to'   => $to,
3761                'days' => $days,
3762            );
3763        }
3764        return $windows;
3765    }
3766
3767    /**
3768     * The overview's figures for the compared windows, read from one daily `stats/visits` response.
3769     *
3770     * @param string $preset  One of self::COMPARE_PRESETS.
3771     * @param array  $windows From overview_compare_windows().
3772     * @param array  $raw     Daily `stats/visits` response covering every window.
3773     * @param bool   $failed  Whether that read failed.
3774     * @return array
3775     */
3776    private static function overview_comparison( string $preset, array $windows, array $raw, bool $failed ): array {
3777        $rows = $failed ? array() : self::normalize_visits_series( $raw, array( 'views', 'visitors' ) );
3778        $in   = array();
3779        foreach ( $windows as $name => $window ) {
3780            $in[ $name ] = array_filter(
3781                $rows,
3782                function ( $row ) use ( $window ) {
3783                    return $row['date'] >= $window['from'] && $row['date'] <= $window['to'];
3784                }
3785            );
3786            // A window WordPress.com did not report every day of has no total.
3787            if ( count( $in[ $name ] ) !== $window['days'] ) {
3788                $in[ $name ] = array();
3789            }
3790        }
3791
3792        return array(
3793            'preset'         => $preset,
3794            'views_today'    => self::sum_or_null( $in['today'], 'views' ),
3795            'visitors_today' => self::sum_or_null( $in['today'], 'visitors' ),
3796            'views_week'     => self::sum_or_null( $in['week'], 'views' ),
3797            'views_month'    => self::sum_or_null( $in['month'], 'views' ),
3798            'windows'        => array_map(
3799                function ( $window ) {
3800                    return array(
3801                        'from' => $window['from'],
3802                        'to'   => $window['to'],
3803                    );
3804                },
3805                $windows
3806            ),
3807        );
3808    }
3809
3810    /**
3811     * Whole days from one date to a later one.
3812     *
3813     * @param string $from YYYY-MM-DD.
3814     * @param string $to   YYYY-MM-DD.
3815     * @return int
3816     */
3817    private static function days_between( string $from, string $to ): int {
3818        $utc = new \DateTimeZone( 'UTC' );
3819        return (int) \DateTimeImmutable::createFromFormat( '!Y-m-d', $from, $utc )->diff( \DateTimeImmutable::createFromFormat( '!Y-m-d', $to, $utc ) )->days;
3820    }
3821
3822    /**
3823     * First day of the period containing a date; weeks start on Monday, as in WordPress.com Stats.
3824     *
3825     * @param string $date   YYYY-MM-DD.
3826     * @param string $period One of self::SERIES_PERIODS.
3827     * @return \DateTimeImmutable|null Null when the date cannot be parsed.
3828     */
3829    private static function period_start( string $date, string $period ): ?\DateTimeImmutable {
3830        $day = \DateTimeImmutable::createFromFormat( '!Y-m-d', $date, new \DateTimeZone( 'UTC' ) );
3831        if ( false === $day ) {
3832            return null;
3833        }
3834
3835        switch ( $period ) {
3836            case 'week':
3837                return $day->modify( '-' . ( (int) $day->format( 'N' ) - 1 ) . ' days' );
3838            case 'month':
3839                return $day->modify( 'first day of this month' );
3840            case 'quarter':
3841                return $day->setDate( (int) $day->format( 'Y' ), 3 * intdiv( (int) $day->format( 'n' ) - 1, 3 ) + 1, 1 );
3842            case 'year':
3843                return $day->setDate( (int) $day->format( 'Y' ), 1, 1 );
3844        }
3845        return $day;
3846    }
3847
3848    /**
3849     * Normalize the WPCOM get_visits response into `[{ date, <field>: int, ... }]`.
3850     *
3851     * @param array $raw    Raw WPCOM response.
3852     * @param array $fields Requested metric fields.
3853     * @return array
3854     */
3855    private static function normalize_visits_series( array $raw, array $fields ): array {
3856        if ( ! isset( $raw['data'] ) || ! is_array( $raw['data'] ) ) {
3857            return array();
3858        }
3859
3860        $raw_fields = isset( $raw['fields'] ) && is_array( $raw['fields'] ) ? $raw['fields'] : array();
3861        $field_idx  = array();
3862        foreach ( $raw_fields as $idx => $name ) {
3863            $field_idx[ (string) $name ] = $idx;
3864        }
3865        $date_idx = $field_idx['period'] ?? 0;
3866
3867        $series = array();
3868        foreach ( $raw['data'] as $row ) {
3869            if ( ! is_array( $row ) ) {
3870                continue;
3871            }
3872            $entry = array(
3873                'date' => self::period_start_date( (string) ( $row[ $date_idx ] ?? '' ) ),
3874            );
3875            foreach ( $fields as $field ) {
3876                $idx             = $field_idx[ $field ] ?? null;
3877                $entry[ $field ] = self::count_or_null( null === $idx ? null : ( $row[ $idx ] ?? null ) );
3878            }
3879            $series[] = $entry;
3880        }
3881        return $series;
3882    }
3883
3884    /**
3885     * Turn a `stats/visits` period label into the first day of its period.
3886     *
3887     * Weeks come labelled with their Monday as `2026W10W19`; every other period already is a YYYY-MM-DD date.
3888     *
3889     * @param string $label Period label from WordPress.com.
3890     * @return string
3891     */
3892    private static function period_start_date( string $label ): string {
3893        return (string) preg_replace( '/^(\d{4})W(\d{2})W(\d{2})$/', '$1-$2-$3', $label );
3894    }
3895
3896    /**
3897     * Resolve the `date` input, defaulting to today when it is absent.
3898     *
3899     * @param mixed $raw Raw input value.
3900     * @return string|WP_Error YYYY-MM-DD, or jetpack_stats_invalid_date when it is not a real day.
3901     */
3902    private static function resolve_date( $raw ) {
3903        if ( null === $raw || '' === $raw ) {
3904            return self::today();
3905        }
3906        if ( is_string( $raw ) && 1 === preg_match( '/^(\d{4})-(\d{2})-(\d{2})\z/', $raw, $m ) && checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) ) {
3907            return $raw;
3908        }
3909        return new WP_Error(
3910            self::ERROR_PREFIX . 'invalid_date',
3911            __( 'The `date` must be a real day in YYYY-MM-DD format, such as 2026-04-23.', 'jetpack-stats-pkg' )
3912        );
3913    }
3914
3915    /**
3916     * Return today in the site's timezone, which is how WordPress.com Stats splits days.
3917     *
3918     * Not wp_date(): plugins filter its output into other calendars.
3919     *
3920     * @return string YYYY-MM-DD.
3921     */
3922    private static function today(): string {
3923        return current_time( 'Y-m-d' );
3924    }
3925
3926    /**
3927     * Clamp an integer into [$min, $max] with a default on bad input.
3928     *
3929     * @param mixed $raw     Raw input.
3930     * @param int   $min     Minimum.
3931     * @param int   $max     Maximum.
3932     * @param int   $default Default on bad input.
3933     * @return int
3934     */
3935    private static function clamp_int( $raw, int $min, int $max, int $default ): int {
3936        if ( ! is_numeric( $raw ) ) {
3937            return $default;
3938        }
3939        $v = (int) $raw;
3940        if ( $v < $min ) {
3941            return $min;
3942        }
3943        if ( $v > $max ) {
3944            return $max;
3945        }
3946        return $v;
3947    }
3948
3949    /**
3950     * Read a count WordPress.com reported, or null when it did not report one.
3951     *
3952     * A negative count is never a real one, so treat it as unknown too.
3953     *
3954     * @param mixed $raw Raw value.
3955     * @return int|null
3956     */
3957    private static function count_or_null( $raw ): ?int {
3958        return is_numeric( $raw ) && (int) $raw >= 0 ? (int) $raw : null;
3959    }
3960
3961    /**
3962     * Total a field over rows, or null when there are none or any of them is unknown.
3963     *
3964     * Every row must carry the field, as normalize_visits_series() rows do.
3965     *
3966     * @param array  $rows  Rows of `{ <field>: int|null }`.
3967     * @param string $field Field to total.
3968     * @return int|null
3969     */
3970    private static function sum_or_null( array $rows, string $field ): ?int {
3971        $values = array_column( $rows, $field );
3972        if ( empty( $rows ) || in_array( null, $values, true ) ) {
3973            return null;
3974        }
3975        return (int) array_sum( $values );
3976    }
3977
3978    /**
3979     * The site whose Stats a response reports, so an agent can confirm it read the site it asked for.
3980     *
3981     * `id` is the WordPress.com blog ID WPCOM_Stats queries.
3982     *
3983     * @return array{id: int, url: string}
3984     */
3985    private static function site(): array {
3986        return array(
3987            'id'  => (int) Jetpack_Options::get_option( 'id' ),
3988            'url' => home_url(),
3989        );
3990    }
3991
3992    /**
3993     * Output schema for a visits `series`: one row per period, carrying every name in `fields`.
3994     *
3995     * @param bool $nullable Whether the series is null when WordPress.com could not be read.
3996     * @return array
3997     */
3998    private static function visits_series_schema( bool $nullable = false ): array {
3999        return array(
4000            'type'  => $nullable ? array( 'array', 'null' ) : 'array',
4001            'items' => array(
4002                'type'                 => 'object',
4003                'properties'           => array(
4004                    'date' => array( 'type' => 'string' ),
4005                ),
4006                'additionalProperties' => array( 'type' => array( 'integer', 'null' ) ),
4007            ),
4008        );
4009    }
4010
4011    /**
4012     * Output schema for `errors`: the names of the WordPress.com sub-calls that failed.
4013     *
4014     * @return array
4015     */
4016    private static function errors_schema(): array {
4017        return array(
4018            'type'  => 'array',
4019            'items' => array( 'type' => 'string' ),
4020        );
4021    }
4022
4023    /**
4024     * Plain-language meaning of each metric and time window the readers return, keyed by term.
4025     *
4026     * The readers' numbers differ in window (a day, a rolling week, all time) and in what they count,
4027     * and agents misread them without this: a 7-day rolling total reported as "this week", or daily
4028     * visitors added up as if they were unique people.
4029     *
4030     * @return array<string, string>
4031     */
4032    private static function definition_texts(): array {
4033        return array(
4034            'views'                 => __( 'A view is one load of a page on the site in a browser that runs the Stats script. Feeds, previews, embeds and API reads are not views; logged-in visits count only for the roles chosen in the Stats settings; bots that run JavaScript can be counted.', 'jetpack-stats-pkg' ),
4035            'visitors'              => __( 'Visitors are the unique browsers seen in one row\'s period. Each row counts its own uniques, so adding rows together overcounts people who came back; there is no unique total across rows.', 'jetpack-stats-pkg' ),
4036            'likes'                 => __( 'Likes given to the site\'s posts during the row\'s period.', 'jetpack-stats-pkg' ),
4037            'comments'              => __( 'Comments posted on the site during the row\'s period.', 'jetpack-stats-pkg' ),
4038            'series'                => __( 'One row per period (day, week from Monday to Sunday, month, quarter from January, April, July or October, or year) in the site\'s timezone, oldest first. A row\'s `date` is the first day of its period; the last row is the period containing the requested `date`, so it may be incomplete.', 'jetpack-stats-pkg' ),
4039            'date'                  => __( 'Today in the site\'s timezone.', 'jetpack-stats-pkg' ),
4040            'views_today'           => __( 'Views so far today, in the site\'s timezone.', 'jetpack-stats-pkg' ),
4041            'visitors_today'        => __( 'Unique visitors so far today, in the site\'s timezone.', 'jetpack-stats-pkg' ),
4042            'views_week'            => __( 'Views over the last 7 days, today included: a rolling total, not the calendar week.', 'jetpack-stats-pkg' ),
4043            'views_month'           => __( 'Views over the last 30 days, today included: a rolling total, not the calendar month.', 'jetpack-stats-pkg' ),
4044            'streak'                => __( 'Consecutive days with at least one published post, in the site\'s timezone. The current streak is 0 unless it reaches today or yesterday; the longest is the longest within the last year.', 'jetpack-stats-pkg' ),
4045            'calendar'              => __( 'Days from `from` to `to` (the last year, today included, in the site\'s timezone) on which the site published posts, with how many; a day missing from `days` had none. Counts published posts only, not pages.', 'jetpack-stats-pkg' ),
4046            'top_post'              => __( 'The post or page with the most views today, not counting the home page.', 'jetpack-stats-pkg' ),
4047            'top_referrer'          => __( 'The referrer that sent the most views today.', 'jetpack-stats-pkg' ),
4048            'total_views'           => __( 'All-time views of the post since it was published, not limited to the series window.', 'jetpack-stats-pkg' ),
4049            'window_top_content'    => __( 'Item values are totals across the `num` periods ending with the one containing `date`, in the site\'s timezone. The current period may be incomplete.', 'jetpack-stats-pkg' ),
4050            'window_tags'           => __( 'Tags and categories cover the seven days ending yesterday, whatever `period`, `date` and `num` say.', 'jetpack-stats-pkg' ),
4051            'value_posts'           => __( 'An item\'s `value` is the views of that post or page; the home page and archives share one item.', 'jetpack-stats-pkg' ),
4052            'value_referrers'       => __( 'An item\'s `value` is the views that arrived from that referrer.', 'jetpack-stats-pkg' ),
4053            'value_search-terms'    => __( 'An item\'s `value` is the views from searches for that term. Search engines hide most terms, so this list is a small sample.', 'jetpack-stats-pkg' ),
4054            'value_clicks'          => __( 'An item\'s `value` is the clicks on links leading off the site to that destination.', 'jetpack-stats-pkg' ),
4055            'children_referrers'    => __( 'An item\'s `children` are the pages, apps or search engines within that referrer that sent the views, each with its own `value`; a child can group further rows. Each item lists at most `max` children, its top ones, so they can add up to less than the item.', 'jetpack-stats-pkg' ),
4056            'children_clicks'       => __( 'An item\'s `children` are the links under that domain that were clicked, each with its own `value`. Each item lists at most `max` children, its top ones, so they can add up to less than the item.', 'jetpack-stats-pkg' ),
4057            'children_tags'         => __( 'An item\'s `children` are the tags and categories it groups. Posts filed under all of them share the item\'s `value`, so a child has none of its own.', 'jetpack-stats-pkg' ),
4058            'value_tags'            => __( 'An item\'s `value` is the views of posts filed under those tags and categories.', 'jetpack-stats-pkg' ),
4059            'value_authors'         => __( 'An item\'s `value` is the views of that author\'s posts and pages.', 'jetpack-stats-pkg' ),
4060            'value_countries'       => __( 'An item\'s `value` is the views from visitors in that country.', 'jetpack-stats-pkg' ),
4061            'value_regions'         => __( 'An item\'s `value` is the views from visitors in that region; `country` is the region\'s country.', 'jetpack-stats-pkg' ),
4062            'value_cities'          => __( 'An item\'s `value` is the views from visitors in that city; `country` is the city\'s country. Cities that share a name within a country share one item.', 'jetpack-stats-pkg' ),
4063            'value_browsers'        => __( 'An item\'s `value` is the views from that browser.', 'jetpack-stats-pkg' ),
4064            'value_platforms'       => __( 'An item\'s `value` is the views from that operating system.', 'jetpack-stats-pkg' ),
4065            'value_screen-sizes'    => __( 'An item\'s `value` is the percent of views from screens of that size, rounded to a whole number: a share, not a count.', 'jetpack-stats-pkg' ),
4066            'value_utm'             => __( 'An item\'s `value` is the views of pages opened from a link tagged with those UTM values, listed in the order `utm_param` names them.', 'jetpack-stats-pkg' ),
4067            'value_commenters'      => __( 'An item\'s `value` is every approved comment that person has left on the site. WordPress.com picks the people from the latest 2,000 comments, so a long-quiet commenter can be missing.', 'jetpack-stats-pkg' ),
4068            'value_commented-posts' => __( 'An item\'s `value` is the approved comments on that post. WordPress.com ranks the latest 1,000 published posts.', 'jetpack-stats-pkg' ),
4069            'window_comments'       => __( 'Comment counts cover the site\'s whole history, whatever `period`, `date` and `num` say.', 'jetpack-stats-pkg' ),
4070            'children_utm'          => __( 'An item\'s `children` are the posts and pages opened from links tagged with those UTM values, each with its own `value` of views and, for a post, its `id`. Each item lists at most `max` children, its top ones, so they can add up to less than the item.', 'jetpack-stats-pkg' ),
4071            'children_authors'      => __( 'An item\'s `children` are the author\'s posts and pages that had views, each with its own `value`. Each item lists at most `max` children, its top ones, so they can add up to less than the item.', 'jetpack-stats-pkg' ),
4072            'value_downloads'       => __( 'An item\'s `value` is the downloads of that file.', 'jetpack-stats-pkg' ),
4073            'value_video-plays'     => __( 'An item\'s `value` is the plays of that video.', 'jetpack-stats-pkg' ),
4074            'total'                 => __( 'The sum of `email`, `wpcom`, `comment` and every `publicize` count. One person following in several ways is counted once for each, and the total is null when any count is unknown.', 'jetpack-stats-pkg' ),
4075            'email'                 => __( 'People subscribed to the site by email, now.', 'jetpack-stats-pkg' ),
4076            'wpcom'                 => __( 'WordPress.com users following the site in the Reader, now.', 'jetpack-stats-pkg' ),
4077            'comment'               => __( 'People following the comments on every post, now. Following one post\'s comments is not counted.', 'jetpack-stats-pkg' ),
4078            'publicize'             => __( 'Followers of each connected social media account, now.', 'jetpack-stats-pkg' ),
4079            'author_views'          => __( 'The author\'s `views` are views of every post and page they wrote, in any status; `likes` and `comments` are those their content received in the same window, not all time.', 'jetpack-stats-pkg' ),
4080            'all_time'              => __( 'Totals since the site started counting Stats: views, unique visitors summed day by day, published posts, approved comments and social shares. `best_day` is the day with the most views ever.', 'jetpack-stats-pkg' ),
4081            'busiest'               => __( 'The hour of the day (in the site\'s timezone) with the most views over the last 60 days, and the weekday with the most over the last 10 weeks, each with its percent of the views in that span.', 'jetpack-stats-pkg' ),
4082            'recent'                => __( 'The last 7 and 30 days end yesterday, so today is not included; each `previous_` window is the same number of days just before. Visitors are unique within each window.', 'jetpack-stats-pkg' ),
4083            'years'                 => __( 'Each year\'s published posts, the words in them, and the likes and comments those posts have received since.', 'jetpack-stats-pkg' ),
4084            'plan_usage'            => __( 'Views counted toward the site\'s Stats plan from `period_start` up to `period_end`, when the count resets. `views_limit` is null when the plan has no limit.', 'jetpack-stats-pkg' ),
4085            'sent'                  => __( '`sent` is how many subscribers the post was emailed to.', 'jetpack-stats-pkg' ),
4086            'opens'                 => __( '`opens` counts every time the email was opened, including repeat opens by one person; `unique_opens` counts people. Mail apps that load images automatically or block them make opens approximate.', 'jetpack-stats-pkg' ),
4087            'clicks'                => __( '`clicks` counts every click on a link in the email; `unique_clicks` counts people.', 'jetpack-stats-pkg' ),
4088            'email_rates'           => __( '`open_rate` and `click_rate` are unique opens and unique clicks as a percent of `sent`, over all time.', 'jetpack-stats-pkg' ),
4089            'email_window'          => __( '`opens` and `clicks` count only the days from `start_date` to `end_date`; unique counts and rates are all-time.', 'jetpack-stats-pkg' ),
4090            'email_all_time'        => __( 'Every figure covers all time since the post was sent.', 'jetpack-stats-pkg' ),
4091            'video_plays'           => __( '`plays` counts each time the video was started, wherever it was played: on the site or embedded elsewhere. `impressions` counts each time a player loaded the video ready to play; not every player reports loads, so `impressions` can be lower than `plays`. `hours_watched` is the playback time across all plays, in hours. `retention_rate` is the average share of the video watched per play, as a percent of its length; it passes 100 when people rewatch, skip back or let the video loop. `total` adds up the `series` rows, except `retention_rate`, which is worked out from the whole window\'s plays and playback time.', 'jetpack-stats-pkg' ),
4092            'post_detail'           => __( '`views`, `likes` and `comments` cover all time since the post was published; `comments` counts approved comments, pingbacks and trackbacks included. `utm` counts views of the post opened from links tagged with those UTM values, over all time. `email` covers all time since the post was sent: `total` counts every open or click, repeat ones by one person included, `unique` counts people, and `rate` is `unique` as a percent of `sent`; mail apps that load images automatically or block them make opens approximate.', 'jetpack-stats-pkg' ),
4093            'email_detail'          => __( 'Every figure covers all time since the post was sent. `total` counts every open or click, repeat ones by one person included, and `unique` counts people; `rate` is `unique` as a percent of `sent`. Mail apps that load images automatically or block them make opens approximate. `by_client` is the mail app, `by_device` the operating system and `by_country` where the email was opened or clicked; each row counts opens or clicks, not people.', 'jetpack-stats-pkg' ),
4094            'email_timeline'        => __( '`timeline` counts opens and clicks in each bucket of the window since the email was sent, repeat ones by one person included, in the site\'s timezone. The window starts at the send: `first_24_hours` runs 24 hours from the send hour, the others from the send day. `all_time` buckets by calendar month.', 'jetpack-stats-pkg' ),
4095            'paid'                  => __( 'People with a paid subscription to the site, now. They are also counted in `email` or `wpcom`.', 'jetpack-stats-pkg' ),
4096            'subscriber_series'     => __( 'One row per period, oldest first: `subscribers` is the count at the end of the period and `change` the net gain or loss during it.', 'jetpack-stats-pkg' ),
4097            'comparison_series'     => __( 'The same figures for the window `compare` names, ending on `comparison.date`: row i of `comparison.series` is the earlier period matching row i of `series`. Weeks, months and years shift by whole periods, so a previous year of weeks is 52 weeks earlier, and both last rows end at the same point in their period.', 'jetpack-stats-pkg' ),
4098            'comparison_overview'   => __( 'The same figures for the windows `compare` names, listed in `comparison.windows`: today, the 7 days and the 30 days, each shifted back. The current figures include today so far while the compared windows are whole days, so early in the day today trails its comparison. A figure is null when WordPress.com did not report every day of its window.', 'jetpack-stats-pkg' ),
4099        );
4100    }
4101
4102    /**
4103     * The definitions block for a response.
4104     *
4105     * @param string[] $terms Terms the response uses, in order.
4106     * @return array<string, string>
4107     */
4108    private static function definitions( array $terms ): array {
4109        return array_intersect_key( self::definition_texts(), array_flip( $terms ) );
4110    }
4111
4112    /**
4113     * The definitions block for get-top-content: what an item's `value` counts for this type, and the window it covers.
4114     *
4115     * @param string $type   Content type enum.
4116     * @param bool   $expand Whether the items carry `children`.
4117     * @return array<string, string>
4118     */
4119    private static function top_content_definitions( string $type, bool $expand = false ): array {
4120        $texts  = self::definition_texts();
4121        $window = 'window_top_content';
4122        if ( 'tags' === $type ) {
4123            $window = 'window_tags';
4124        } elseif ( in_array( $type, self::UNDATED_TYPES, true ) ) {
4125            $window = 'window_comments';
4126        }
4127        $out = array(
4128            'value' => $texts[ 'value_' . $type ],
4129            'items' => $texts[ $window ],
4130        );
4131        if ( $expand && isset( $texts[ 'children_' . $type ] ) ) {
4132            $out['children'] = $texts[ 'children_' . $type ];
4133        }
4134        // Clicks, comments, downloads and plays are not views.
4135        if ( ! in_array( $type, array( 'clicks', 'commenters', 'commented-posts', 'downloads', 'video-plays' ), true ) ) {
4136            $out['views'] = $texts['views'];
4137        }
4138        return $out;
4139    }
4140
4141    /**
4142     * Output schema for `definitions`.
4143     *
4144     * @return array
4145     */
4146    private static function definitions_schema(): array {
4147        return array(
4148            'type'                 => 'object',
4149            'additionalProperties' => array( 'type' => 'string' ),
4150        );
4151    }
4152
4153    /**
4154     * Input schema for `period`.
4155     *
4156     * @param array $periods The periods the ability accepts.
4157     * @return array
4158     */
4159    private static function period_schema( array $periods = self::PERIODS ): array {
4160        return array(
4161            'type'        => 'string',
4162            'description' => __( 'Aggregation period.', 'jetpack-stats-pkg' ),
4163            'enum'        => $periods,
4164            'default'     => 'day',
4165        );
4166    }
4167
4168    /**
4169     * Input schema for `date`.
4170     *
4171     * @return array
4172     */
4173    private static function date_schema(): array {
4174        return array(
4175            'type'        => 'string',
4176            'description' => __( 'End date (YYYY-MM-DD). Defaults to today.', 'jetpack-stats-pkg' ),
4177            'pattern'     => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$',
4178        );
4179    }
4180
4181    /**
4182     * The `meta` of a read-only ability, public over MCP.
4183     *
4184     * @return array
4185     */
4186    private static function reader_meta(): array {
4187        return array(
4188            'annotations'  => array(
4189                'readonly'    => true,
4190                'destructive' => false,
4191                'idempotent'  => true,
4192            ),
4193            'public'       => true,
4194            'show_in_rest' => true,
4195            'mcp'          => array(
4196                'public' => true,
4197                'type'   => 'tool',
4198            ),
4199        );
4200    }
4201
4202    /**
4203     * Output schema for `site`.
4204     *
4205     * @return array
4206     */
4207    private static function site_schema(): array {
4208        return array(
4209            'type'       => 'object',
4210            'properties' => array(
4211                'id'  => array( 'type' => 'integer' ),
4212                'url' => array( 'type' => 'string' ),
4213            ),
4214        );
4215    }
4216
4217    /**
4218     * Safely read an int field from an array.
4219     *
4220     * @param array  $arr Array.
4221     * @param string $key Key.
4222     * @return int
4223     */
4224    private static function as_int( array $arr, string $key ): int {
4225        return isset( $arr[ $key ] ) ? (int) $arr[ $key ] : 0;
4226    }
4227}