Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
63.40% covered (warning)
63.40%
556 / 877
40.48% covered (danger)
40.48%
17 / 42
CRAP
0.00% covered (danger)
0.00%
0 / 1
REST_Controller
63.40% covered (warning)
63.40%
556 / 877
40.48% covered (danger)
40.48%
17 / 42
645.62
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_rest_routes
100.00% covered (success)
100.00%
369 / 369
100.00% covered (success)
100.00%
1 / 1
1
 can_user_view_general_stats_callback
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 can_user_manage_stats_settings_callback
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 can_user_view_wordads_stats_callback
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 get_stats_resource
98.00% covered (success)
98.00%
49 / 50
0.00% covered (danger)
0.00%
0 / 1
21
 get_single_post_likes
75.00% covered (warning)
75.00%
18 / 24
0.00% covered (danger)
0.00%
0 / 1
4.25
 get_single_resource_stats
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 get_single_post
21.43% covered (danger)
21.43%
3 / 14
0.00% covered (danger)
0.00%
0 / 1
7.37
 get_site_stats
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_site_posts
72.73% covered (warning)
72.73%
16 / 22
0.00% covered (danger)
0.00%
0 / 1
4.32
 get_site_subscribers_counts
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 get_site_plan_usage
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 get_stats_settings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 update_stats_settings
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 get_stats_settings_keys
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_stats_settings_response
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
3.01
 post_user_feedback
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
6
 site_has_never_published_post
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 get_wordads_earnings
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 get_wordads_stats
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 get_email_stats_list
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 get_email_opens_stats_single
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
42
 get_email_clicks_stats_single
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
72
 get_email_stats_time_series
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 get_utm_stats_time_series
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 get_devices_stats_time_series
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 get_location_stats
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 update_notice_status
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_notice_status
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_referrer_spam_list
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 mark_referrer_spam
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 unmark_referrer_spam
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 update_dashboard_modules
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
2
 get_dashboard_modules
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
2
 update_dashboard_module_settings
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
2
 get_dashboard_module_settings
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
2
 run_commercial_classification
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
2
 get_site_purchases
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 get_forbidden_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 filter_and_build_query_string
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2/**
3 * The Stats Rest Controller class.
4 * Registers the REST routes for Odyssey Stats.
5 *
6 * @package automattic/jetpack-stats-admin
7 */
8
9namespace Automattic\Jetpack\Stats_Admin;
10
11use Automattic\Jetpack\Constants;
12use Automattic\Jetpack\Stats\Settings as Stats_Settings;
13use Automattic\Jetpack\Stats\WPCOM_Stats;
14use Jetpack_Options;
15use WP_Error;
16use WP_REST_Request;
17use WP_REST_Server;
18
19/**
20 * Registers the REST routes for Stats.
21 * It bascially forwards the requests to the WordPress.com REST API.
22 */
23class REST_Controller {
24    const JETPACK_STATS_DASHBOARD_MODULES_CACHE_KEY         = 'jetpack_stats_dashboard_modules_cache_key';
25    const JETPACK_STATS_DASHBOARD_MODULE_SETTINGS_CACHE_KEY = 'jetpack_stats_dashboard_module_settings_cache_key';
26
27    /**
28     * Namespace for the REST API.
29     *
30     * @var string
31     */
32    public static $namespace = 'jetpack/v4/stats-app';
33
34    /**
35     * Hold an instance of WPCOM_Stats.
36     *
37     * @var WPCOM_Stats
38     */
39    protected $wpcom_stats;
40
41    /**
42     * Constructor
43     */
44    public function __construct() {
45        $this->wpcom_stats = new WPCOM_Stats();
46    }
47
48    /**
49     * Registers the REST routes on the `rest_api_init` hook.
50     *
51     * Instantiated here, rather than eagerly, so the controller class only loads
52     * on requests that reach `rest_api_init`. Static so the callback can be
53     * unregistered.
54     *
55     * @access public
56     */
57    public static function register() {
58        ( new self() )->register_rest_routes();
59    }
60
61    /**
62     * Registers the REST routes for Odyssey Stats.
63     *
64     * Odyssey Stats is built from `wp-calypso`, which leverages the `public-api.wordpress.com` API.
65     * The current Site ID is added as part of the route, so that the front end doesn't have to handle the differences.
66     *
67     * @access public
68     * @static
69     */
70    public function register_rest_routes() {
71        // Stats for single resource type.
72        register_rest_route(
73            static::$namespace,
74            sprintf( '/sites/%d/stats/(?P<resource>[\-\w]+)/(?P<resource_id>[\d]+)', Jetpack_Options::get_option( 'id' ) ),
75            array(
76                'methods'             => WP_REST_Server::READABLE,
77                'callback'            => array( $this, 'get_single_resource_stats' ),
78                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
79            )
80        );
81
82        // Stats for a resource type.
83        register_rest_route(
84            static::$namespace,
85            sprintf( '/sites/%d/stats/(?P<resource>[\-\w]+)', Jetpack_Options::get_option( 'id' ) ),
86            array(
87                'methods'             => WP_REST_Server::READABLE,
88                'callback'            => array( $this, 'get_stats_resource' ),
89                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
90            )
91        );
92
93        // Single post info.
94        register_rest_route(
95            static::$namespace,
96            sprintf( '/sites/%d/posts/(?P<resource_id>[\d]+)', Jetpack_Options::get_option( 'id' ) ),
97            array(
98                'methods'             => WP_REST_Server::READABLE,
99                'callback'            => array( $this, 'get_single_post' ),
100                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
101            )
102        );
103
104        // Single post likes.
105        register_rest_route(
106            static::$namespace,
107            sprintf( '/sites/%d/posts/(?P<resource_id>[\d]+)/likes', Jetpack_Options::get_option( 'id' ) ),
108            array(
109                'methods'             => WP_REST_Server::READABLE,
110                'callback'            => array( $this, 'get_single_post_likes' ),
111                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
112            )
113        );
114
115        // General stats for the site.
116        register_rest_route(
117            static::$namespace,
118            sprintf( '/sites/%d/stats', Jetpack_Options::get_option( 'id' ) ),
119            array(
120                'methods'             => WP_REST_Server::READABLE,
121                'callback'            => array( $this, 'get_site_stats' ),
122                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
123            )
124        );
125
126        // Whether site has never published post / page.
127        register_rest_route(
128            static::$namespace,
129            sprintf( '/sites/%d/site-has-never-published-post', Jetpack_Options::get_option( 'id' ) ),
130            array(
131                'methods'             => WP_REST_Server::READABLE,
132                'callback'            => array( $this, 'site_has_never_published_post' ),
133                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
134            )
135        );
136
137        // List posts.
138        register_rest_route(
139            static::$namespace,
140            sprintf( '/sites/%d/posts', Jetpack_Options::get_option( 'id' ) ),
141            array(
142                'methods'             => WP_REST_Server::READABLE,
143                'callback'            => array( $this, 'get_site_posts' ),
144                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
145            )
146        );
147
148        // Subscribers counts.
149        register_rest_route(
150            static::$namespace,
151            sprintf( '/sites/%d/subscribers/counts', Jetpack_Options::get_option( 'id' ) ),
152            array(
153                'methods'             => WP_REST_Server::READABLE,
154                'callback'            => array( $this, 'get_site_subscribers_counts' ),
155                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
156            )
157        );
158
159        // Stats Plan Usage.
160        register_rest_route(
161            static::$namespace,
162            sprintf( '/sites/%d/jetpack-stats/usage', Jetpack_Options::get_option( 'id' ) ),
163            array(
164                'methods'             => WP_REST_Server::READABLE,
165                'callback'            => array( $this, 'get_site_plan_usage' ),
166                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
167            )
168        );
169
170        // Stats settings.
171        register_rest_route(
172            static::$namespace,
173            sprintf( '/sites/%d/jetpack-stats/settings', Jetpack_Options::get_option( 'id' ) ),
174            array(
175                array(
176                    'methods'             => WP_REST_Server::READABLE,
177                    'callback'            => array( $this, 'get_stats_settings' ),
178                    'permission_callback' => array( $this, 'can_user_manage_stats_settings_callback' ),
179                ),
180                array(
181                    'methods'             => WP_REST_Server::EDITABLE,
182                    'callback'            => array( $this, 'update_stats_settings' ),
183                    'permission_callback' => array( $this, 'can_user_manage_stats_settings_callback' ),
184                    'args'                => array(
185                        'admin_bar'   => array(
186                            'description' => 'Show a chart of the last 48 hours of views in the admin bar',
187                            'type'        => 'boolean',
188                        ),
189                        'roles'       => array(
190                            'description' => 'Roles that can view Stats. `administrator` is always kept.',
191                            'type'        => 'array',
192                            'items'       => array( 'type' => 'string' ),
193                            'minItems'    => 1,
194                        ),
195                        'count_roles' => array(
196                            'description' => 'Roles whose logged-in page views are counted',
197                            'type'        => 'array',
198                            'items'       => array( 'type' => 'string' ),
199                        ),
200                    ),
201                ),
202            )
203        );
204
205        // User feedback endpoint.
206        register_rest_route(
207            static::$namespace,
208            sprintf( '/sites/%d/jetpack-stats/user-feedback', Jetpack_Options::get_option( 'id' ) ),
209            array(
210                'methods'             => WP_REST_Server::CREATABLE,
211                'callback'            => array( $this, 'post_user_feedback' ),
212                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
213            )
214        );
215
216        // WordAds Earnings.
217        register_rest_route(
218            static::$namespace,
219            sprintf( '/sites/%d/wordads/earnings', Jetpack_Options::get_option( 'id' ) ),
220            array(
221                'methods'             => WP_REST_Server::READABLE,
222                'callback'            => array( $this, 'get_wordads_earnings' ),
223                'permission_callback' => array( $this, 'can_user_view_wordads_stats_callback' ),
224            )
225        );
226
227        // WordAds Stats.
228        register_rest_route(
229            static::$namespace,
230            sprintf( '/sites/%d/wordads/stats', Jetpack_Options::get_option( 'id' ) ),
231            array(
232                'methods'             => WP_REST_Server::READABLE,
233                'callback'            => array( $this, 'get_wordads_stats' ),
234                'permission_callback' => array( $this, 'can_user_view_wordads_stats_callback' ),
235            )
236        );
237
238        // Legacy: Update Stats notices.
239        // TODO: remove this in the next release.
240        register_rest_route(
241            static::$namespace,
242            '/stats/notices',
243            array(
244                'methods'             => WP_REST_Server::EDITABLE,
245                'callback'            => array( $this, 'update_notice_status' ),
246                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
247                'args'                => array(
248                    'id'            => array(
249                        'required'    => true,
250                        'type'        => 'string',
251                        'description' => 'ID of the notice',
252                    ),
253                    'status'        => array(
254                        'required'    => true,
255                        'type'        => 'string',
256                        'description' => 'Status of the notice',
257                    ),
258                    'postponed_for' => array(
259                        'type'        => 'number',
260                        'default'     => 0,
261                        'description' => 'Postponed for (in seconds)',
262                        'minimum'     => 0,
263                    ),
264                ),
265            )
266        );
267
268        // Update Stats notices.
269        register_rest_route(
270            static::$namespace,
271            sprintf( '/sites/%d/jetpack-stats-dashboard/notices', Jetpack_Options::get_option( 'id' ) ),
272            array(
273                'methods'             => WP_REST_Server::EDITABLE,
274                'callback'            => array( $this, 'update_notice_status' ),
275                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
276                'args'                => array(
277                    'id'            => array(
278                        'required'    => true,
279                        'type'        => 'string',
280                        'description' => 'ID of the notice',
281                    ),
282                    'status'        => array(
283                        'required'    => true,
284                        'type'        => 'string',
285                        'description' => 'Status of the notice',
286                    ),
287                    'postponed_for' => array(
288                        'type'        => 'number',
289                        // Forwarded to WPCOM as-is, whose schema rejects the null an omitted param would carry.
290                        'default'     => 0,
291                        'description' => 'Postponed for (in seconds)',
292                        'minimum'     => 0,
293                    ),
294                ),
295            )
296        );
297
298        // Get Stats notices.
299        register_rest_route(
300            static::$namespace,
301            sprintf( '/sites/%d/jetpack-stats-dashboard/notices', Jetpack_Options::get_option( 'id' ) ),
302            array(
303                'methods'             => WP_REST_Server::READABLE,
304                'callback'            => array( $this, 'get_notice_status' ),
305                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
306                'args'                => array(
307                    'include_details' => array(
308                        'type'        => 'boolean',
309                        'default'     => false,
310                        'description' => 'Return a detail record per notice instead of a flat boolean map',
311                    ),
312                ),
313            )
314        );
315
316        // Get referrer spam list.
317        register_rest_route(
318            static::$namespace,
319            sprintf( '/sites/%d/stats/referrers/spam', Jetpack_Options::get_option( 'id' ) ),
320            array(
321                'methods'             => WP_REST_Server::READABLE,
322                'callback'            => array( $this, 'get_referrer_spam_list' ),
323                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
324            )
325        );
326
327        // Mark referrer spam.
328        register_rest_route(
329            static::$namespace,
330            sprintf( '/sites/%d/stats/referrers/spam/new', Jetpack_Options::get_option( 'id' ) ),
331            array(
332                'methods'             => WP_REST_Server::EDITABLE,
333                'callback'            => array( $this, 'mark_referrer_spam' ),
334                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
335                'args'                => array(
336                    'domain' => array(
337                        'required'    => true,
338                        'type'        => 'string',
339                        'description' => 'Domain of the referrer',
340                    ),
341                ),
342            )
343        );
344
345        // Unmark referrer spam.
346        register_rest_route(
347            static::$namespace,
348            sprintf( '/sites/%d/stats/referrers/spam/delete', Jetpack_Options::get_option( 'id' ) ),
349            array(
350                'methods'             => WP_REST_Server::EDITABLE,
351                'callback'            => array( $this, 'unmark_referrer_spam' ),
352                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
353                'args'                => array(
354                    'domain' => array(
355                        'required'    => true,
356                        'type'        => 'string',
357                        'description' => 'Domain of the referrer',
358                    ),
359                ),
360            )
361        );
362
363        // Update dashboard modules.
364        register_rest_route(
365            static::$namespace,
366            sprintf( '/sites/%d/jetpack-stats-dashboard/modules', Jetpack_Options::get_option( 'id' ) ),
367            array(
368                'methods'             => WP_REST_Server::EDITABLE,
369                'callback'            => array( $this, 'update_dashboard_modules' ),
370                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
371            )
372        );
373
374        // Get dashboard modules.
375        register_rest_route(
376            static::$namespace,
377            sprintf( '/sites/%d/jetpack-stats-dashboard/modules', Jetpack_Options::get_option( 'id' ) ),
378            array(
379                'methods'             => WP_REST_Server::READABLE,
380                'callback'            => array( $this, 'get_dashboard_modules' ),
381                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
382            )
383        );
384
385        // Update dashboard module settings.
386        register_rest_route(
387            static::$namespace,
388            sprintf( '/sites/%d/jetpack-stats-dashboard/module-settings', Jetpack_Options::get_option( 'id' ) ),
389            array(
390                'methods'             => WP_REST_Server::EDITABLE,
391                'callback'            => array( $this, 'update_dashboard_module_settings' ),
392                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
393            )
394        );
395
396        // Get dashboard module settings.
397        register_rest_route(
398            static::$namespace,
399            sprintf( '/sites/%d/jetpack-stats-dashboard/module-settings', Jetpack_Options::get_option( 'id' ) ),
400            array(
401                'methods'             => WP_REST_Server::READABLE,
402                'callback'            => array( $this, 'get_dashboard_module_settings' ),
403                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
404            )
405        );
406
407        // Get email stats as a list.
408        register_rest_route(
409            static::$namespace,
410            sprintf( '/sites/%d/stats/emails/(?P<resource>[\-\w\d]+)', Jetpack_Options::get_option( 'id' ) ),
411            array(
412                'methods'             => WP_REST_Server::READABLE,
413                'callback'            => array( $this, 'get_email_stats_list' ),
414                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
415            )
416        );
417
418        // Get Email opens stats for a single post.
419        register_rest_route(
420            static::$namespace,
421            sprintf( '/sites/%d/stats/opens/emails/(?P<post_id>[\d]+)/(?P<resource>[\-\w]+)', Jetpack_Options::get_option( 'id' ) ),
422            array(
423                'methods'             => WP_REST_Server::READABLE,
424                'callback'            => array( $this, 'get_email_opens_stats_single' ),
425                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
426            )
427        );
428
429        // Get Email clicks stats for a single post.
430        register_rest_route(
431            static::$namespace,
432            sprintf( '/sites/%d/stats/clicks/emails/(?P<post_id>[\d]+)/(?P<resource>[\-\w]+)', Jetpack_Options::get_option( 'id' ) ),
433            array(
434                'methods'             => WP_REST_Server::READABLE,
435                'callback'            => array( $this, 'get_email_clicks_stats_single' ),
436                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
437            )
438        );
439
440        // Get Email stats time series.
441        register_rest_route(
442            static::$namespace,
443            sprintf( '/sites/%d/stats/(?P<resource>[\-\w]+)/emails/(?P<post_id>[\d]+)', Jetpack_Options::get_option( 'id' ) ),
444            array(
445                'methods'             => WP_REST_Server::READABLE,
446                'callback'            => array( $this, 'get_email_stats_time_series' ),
447                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
448            )
449        );
450
451        // Get UTM stats time series.
452        register_rest_route(
453            static::$namespace,
454            // /stats/utm/utm_campaign,utm_source,utm_medium
455            sprintf( '/sites/%d/stats/utm/(?P<utm_params>[_,\-\w]+)', Jetpack_Options::get_option( 'id' ) ),
456            array(
457                'methods'             => WP_REST_Server::READABLE,
458                'callback'            => array( $this, 'get_utm_stats_time_series' ),
459                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
460            )
461        );
462
463        // Get Devices stats time series.
464        register_rest_route(
465            static::$namespace,
466            // /stats/devices/screensize
467            sprintf( '/sites/%d/stats/devices/(?P<device_property>[\w]+)', Jetpack_Options::get_option( 'id' ) ),
468            array(
469                'methods'             => WP_REST_Server::READABLE,
470                'callback'            => array( $this, 'get_devices_stats_time_series' ),
471                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
472            )
473        );
474
475        // Rerun commercial classificiation.
476        register_rest_route(
477            static::$namespace,
478            sprintf( '/sites/%d/commercial-classification', Jetpack_Options::get_option( 'id' ) ),
479            array(
480                'methods'             => WP_REST_Server::EDITABLE,
481                'callback'            => array( $this, 'run_commercial_classification' ),
482                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
483            )
484        );
485
486        // Purchases endpoint.
487        register_rest_route(
488            static::$namespace,
489            sprintf( '/sites/%d/purchases', Jetpack_Options::get_option( 'id' ) ),
490            array(
491                'methods'             => WP_REST_Server::READABLE,
492                'callback'            => array( $this, 'get_site_purchases' ),
493                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
494            )
495        );
496
497        // Get Location stats.
498        register_rest_route(
499            static::$namespace,
500            sprintf( '/sites/%d/stats/location-views/(?P<geo_mode>country|region|city)', Jetpack_Options::get_option( 'id' ) ),
501            array(
502                'methods'             => WP_REST_Server::READABLE,
503                'callback'            => array( $this, 'get_location_stats' ),
504                'permission_callback' => array( $this, 'can_user_view_general_stats_callback' ),
505            )
506        );
507    }
508
509    /**
510     * Only administrators or users with capability `view_stats` can access the API.
511     *
512     * @return bool|WP_Error True if a blog token was used to sign the request, WP_Error otherwise.
513     */
514    public function can_user_view_general_stats_callback() {
515        if ( current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ) ) {
516            return true;
517        }
518
519        return $this->get_forbidden_error();
520    }
521
522    /**
523     * Only administrators can read or change the Stats settings, because `roles` decides who else can view Stats.
524     *
525     * @return bool|WP_Error
526     */
527    public function can_user_manage_stats_settings_callback() {
528        if ( current_user_can( 'manage_options' ) ) {
529            return true;
530        }
531
532        return $this->get_forbidden_error();
533    }
534
535    /**
536     * Only administrators or users with capability `activate_wordads` can access the API.
537     */
538    public function can_user_view_wordads_stats_callback() {
539        // phpcs:ignore WordPress.WP.Capabilities.Unknown
540        if ( current_user_can( 'manage_options' ) || current_user_can( 'activate_wordads' ) ) {
541            return true;
542        }
543
544        return $this->get_forbidden_error();
545    }
546
547    /**
548     * Stats resource endpoint.
549     *
550     * @param WP_REST_Request $req The request object.
551     * @return array
552     */
553    public function get_stats_resource( $req ) {
554        switch ( $req->get_param( 'resource' ) ) {
555            case 'file-downloads':
556                return $this->wpcom_stats->get_file_downloads( $req->get_params() );
557
558            case 'video-plays':
559                return $this->wpcom_stats->get_video_plays( $req->get_params() );
560
561            case 'clicks':
562                return $this->wpcom_stats->get_clicks( $req->get_params() );
563
564            case 'search-terms':
565                return $this->wpcom_stats->get_search_terms( $req->get_params() );
566
567            case 'top-authors':
568                return $this->wpcom_stats->get_top_authors( $req->get_params() );
569
570            case 'country-views':
571                return $this->wpcom_stats->get_views_by_country( $req->get_params() );
572
573            case 'referrers':
574                return $this->wpcom_stats->get_referrers( $req->get_params() );
575
576            case 'top-posts':
577                return $this->wpcom_stats->get_top_posts( $req->get_params() );
578
579            case 'archives':
580                return $this->wpcom_stats->get_archives( $req->get_params() );
581
582            case 'publicize':
583                return $this->wpcom_stats->get_publicize_followers( $req->get_params() );
584
585            case 'followers':
586                return $this->wpcom_stats->get_followers( $req->get_params() );
587
588            case 'tags':
589                return $this->wpcom_stats->get_tags( $req->get_params() );
590
591            case 'visits':
592                return $this->wpcom_stats->get_visits( $req->get_params() );
593
594            case 'comments':
595                return $this->wpcom_stats->get_top_comments( $req->get_params() );
596
597            case 'comment-followers':
598                return $this->wpcom_stats->get_comment_followers( $req->get_params() );
599
600            case 'streak':
601                return $this->wpcom_stats->get_streak( $req->get_params() );
602
603            case 'insights':
604                return $this->wpcom_stats->get_insights( $req->get_params() );
605
606            case 'highlights':
607                return $this->wpcom_stats->get_highlights( $req->get_params() );
608
609            case 'subscribers':
610                return WPCOM_Client::request_as_blog_cached(
611                    sprintf(
612                        '/sites/%d/stats/subscribers?%s',
613                        Jetpack_Options::get_option( 'id' ),
614                        $this->filter_and_build_query_string(
615                            $req->get_query_params()
616                        )
617                    ),
618                    'v1.1',
619                    array( 'timeout' => 5 )
620                );
621
622            default:
623                return $this->get_forbidden_error();
624        }
625    }
626
627    /**
628     * Return likes of a single post.
629     *
630     * @param WP_REST_Request $req The request object.
631     */
632    public function get_single_post_likes( $req ) {
633        $response = wp_remote_get(
634            sprintf(
635                '%s/rest/v1.2/sites/%d/posts/%d/likes?%s',
636                Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
637                Jetpack_Options::get_option( 'id' ),
638                $req->get_param( 'resource_id' ),
639                $this->filter_and_build_query_string(
640                    $req->get_params(),
641                    array( 'resource_id' )
642                )
643            ),
644            array( 'timeout' => 5 )
645        );
646
647        $response_code = wp_remote_retrieve_response_code( $response );
648        $response_body = json_decode( wp_remote_retrieve_body( $response ), true );
649
650        if ( is_wp_error( $response ) ) {
651            return $response;
652        }
653
654        if ( 200 !== $response_code ) {
655            return new WP_Error(
656                isset( $response_body['error'] ) ? 'remote-error-' . $response_body['error'] : 'remote-error',
657                $response_body['message'] ?? 'unknown remote error',
658                array( 'status' => $response_code )
659            );
660        }
661
662        return $response_body;
663    }
664
665    /**
666     * Site Stats Resource endpoint.
667     *
668     * @param WP_REST_Request $req The request object.
669     * @return array
670     */
671    public function get_single_resource_stats( $req ) {
672        switch ( $req->get_param( 'resource' ) ) {
673            case 'post':
674                return $this->wpcom_stats->get_post_views(
675                    intval( $req->get_param( 'resource_id' ) ),
676                    $req->get_params()
677                );
678
679            case 'video':
680                return $this->wpcom_stats->get_video_details(
681                    intval( $req->get_param( 'resource_id' ) ),
682                    $req->get_params()
683                );
684
685            default:
686                return $this->get_forbidden_error();
687        }
688    }
689
690    /**
691     * Get brief information for a single post.
692     *
693     * @param WP_REST_Request $req The request object.
694     * @return array
695     */
696    public function get_single_post( $req ) {
697        $post = get_post( intval( $req->get_param( 'resource_id' ) ), 'OBJECT', 'display' );
698        if ( is_wp_error( $post ) || empty( $post ) ) {
699            return $post;
700        }
701
702        // The endpoint should be as compatible as possible with `/sites/$site_id/posts/$post_id`.
703        // The reason we are not forwarding the request is that `/sites/$site_id/posts/$post_id` might require user tokens for private posts/sites, which is not possible for users without a WordPress.com account.
704        // 'like_count' is not included in the response because it's available through another endpoint `/sites/$site_id/posts/$post_id/likes`.
705        return array(
706            'ID'             => $post->ID,
707            'site_ID'        => Jetpack_Options::get_option( 'id' ),
708            'title'          => $post->post_title,
709            'URL'            => get_permalink( $post->ID ),
710            'type'           => $post->post_type,
711            'status'         => $post->post_status,
712            'discussion'     => array( 'comment_count' => intval( $post->comment_count ) ),
713            'date'           => $post->post_date,
714            'post_thumbnail' => array( 'URL' => get_the_post_thumbnail_url( $post->ID ) ),
715        );
716    }
717
718    /**
719     * Get site stats.
720     *
721     * @param WP_REST_Request $req The request object.
722     * @return array
723     */
724    public function get_site_stats( $req ) {
725        return $this->wpcom_stats->get_stats( $req->get_params() );
726    }
727
728    /**
729     * List posts for the site.
730     *
731     * @param WP_REST_Request $req The request object.
732     * @return array
733     */
734    public function get_site_posts( $req ) {
735        // Force wpcom response.
736        $params   = array_merge( array( 'force' => 'wpcom' ), $req->get_params() );
737        $response = wp_remote_get(
738            sprintf(
739                '%s/rest/v1.1/sites/%d/posts?%s',
740                Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
741                Jetpack_Options::get_option( 'id' ),
742                $req->get_param( 'resource_id' ),
743                $this->filter_and_build_query_string( $params, array( 'resource_id' ) )
744            ),
745            array( 'timeout' => 5 )
746        );
747
748        $response_code = wp_remote_retrieve_response_code( $response );
749        $response_body = json_decode( wp_remote_retrieve_body( $response ), true );
750
751        if ( is_wp_error( $response ) ) {
752            return $response;
753        }
754
755        if ( 200 !== $response_code ) {
756            return new WP_Error(
757                isset( $response_body['error'] ) ? 'remote-error-' . $response_body['error'] : 'remote-error',
758                $response_body['message'] ?? 'unknown remote error',
759                array( 'status' => $response_code )
760            );
761        }
762
763        return $response_body;
764    }
765
766    /**
767     * Get site subscribers counts.
768     *
769     * @param WP_REST_Request $req The request object.
770     *
771     * @return array
772     */
773    public function get_site_subscribers_counts( $req ) {
774        return WPCOM_Client::request_as_blog_cached(
775            sprintf(
776                '/sites/%d/subscribers/counts?%s',
777                Jetpack_Options::get_option( 'id' ),
778                $this->filter_and_build_query_string(
779                    $req->get_query_params()
780                )
781            ),
782            'v2',
783            array( 'timeout' => 5 ),
784            null,
785            'wpcom'
786        );
787    }
788
789    /**
790     * Get site plan usage.
791     *
792     * @param WP_REST_Request $req The request object.
793     *
794     * @return array
795     */
796    public function get_site_plan_usage( $req ) {
797        return WPCOM_Client::request_as_blog_cached(
798            sprintf(
799                '/sites/%d/jetpack-stats/usage?%s',
800                Jetpack_Options::get_option( 'id' ),
801                $this->filter_and_build_query_string(
802                    $req->get_query_params()
803                )
804            ),
805            'v2',
806            array( 'timeout' => 5 ),
807            null,
808            'wpcom',
809            false
810        );
811    }
812
813    /**
814     * Get the Stats settings and the site's roles.
815     *
816     * @return array
817     */
818    public function get_stats_settings() {
819        return $this->get_stats_settings_response();
820    }
821
822    /**
823     * Save the Stats settings in the request.
824     *
825     * @param WP_REST_Request $req The request object.
826     *
827     * @return array|WP_Error The settings after the save, or why the values were refused.
828     */
829    public function update_stats_settings( $req ) {
830        $params = $req->get_params();
831        $keys   = self::get_stats_settings_keys();
832
833        $stats_values = array_intersect_key( $params, array_flip( $keys ) );
834        if ( empty( $stats_values ) ) {
835            return new WP_Error(
836                'jetpack_stats_missing_setting_field',
837                sprintf(
838                    /* translators: %s: comma-separated list of the settings that can be changed. */
839                    __( 'Provide at least one of: %s.', 'jetpack-stats-admin' ),
840                    implode( ', ', $keys )
841                ),
842                array( 'status' => 400 )
843            );
844        }
845
846        $result = Stats_Settings::update( $stats_values, $keys );
847        if ( is_wp_error( $result ) ) {
848            return $result;
849        }
850
851        return $this->get_stats_settings_response();
852    }
853
854    /**
855     * The Stats settings the Settings screen offers.
856     *
857     * @return string[]
858     */
859    private static function get_stats_settings_keys() {
860        // Nothing reads `do_not_track`, so the screen does not offer it.
861        return array_values( array_diff( Stats_Settings::KEYS, array( 'do_not_track' ) ) );
862    }
863
864    /**
865     * Build the settings response: the current values and the roles the toggles list.
866     *
867     * @return array
868     */
869    private function get_stats_settings_response() {
870        if ( ! function_exists( 'get_editable_roles' ) ) {
871            require_once ABSPATH . 'wp-admin/includes/user.php';
872        }
873
874        $roles = array();
875        foreach ( get_editable_roles() as $slug => $role ) {
876            $roles[] = array(
877                'slug' => $slug,
878                'name' => translate_user_role( $role['name'] ),
879            );
880        }
881
882        return array(
883            'settings' => Stats_Settings::get( self::get_stats_settings_keys() ),
884            'roles'    => $roles,
885        );
886    }
887
888    /**
889     * Post user feedback for Jetpack Stats.
890     *
891     * @param WP_REST_Request $req The request object.
892     *
893     * @return array
894     */
895    public function post_user_feedback( $req ) {
896        $current_user  = wp_get_current_user();
897        $body_from_req = json_decode( $req->get_body(), true );
898        $body_data     = is_array( $body_from_req ) ? $body_from_req : array();
899        $user_email    = $current_user->user_email;
900
901        return WPCOM_Client::request_as_blog_cached(
902            sprintf(
903                '/sites/%d/jetpack-stats/user-feedback?%s',
904                Jetpack_Options::get_option( 'id' ),
905                $this->filter_and_build_query_string(
906                    $req->get_query_params()
907                )
908            ),
909            'v2',
910            array(
911                'timeout' => 5,
912                'method'  => 'POST',
913                'headers' => array( 'Content-Type' => 'application/json' ),
914            ),
915            wp_json_encode(
916                array_merge(
917                    $body_data,
918                    array(
919                        'user_email' => $user_email,
920                    )
921                ),
922                JSON_UNESCAPED_SLASHES
923            ),
924            'wpcom'
925        );
926    }
927
928    /**
929     * Whether site has never published post.
930     *
931     * @param WP_REST_Request $req The request object.
932     * @return array
933     */
934    public function site_has_never_published_post( $req ) {
935        return WPCOM_Client::request_as_blog_cached(
936            sprintf(
937                '/sites/%d/site-has-never-published-post?%s',
938                Jetpack_Options::get_option( 'id' ),
939                $this->filter_and_build_query_string(
940                    $req->get_params()
941                )
942            ),
943            'v2',
944            array( 'timeout' => 5 ),
945            null,
946            'wpcom'
947        );
948    }
949
950    /**
951     * Get detailed WordAds earnings information for the site.
952     *
953     * @param WP_REST_Request $req The request object.
954     * @return array
955     */
956    public function get_wordads_earnings( $req ) {
957        return WPCOM_Client::request_as_blog_cached(
958            sprintf(
959                '/sites/%d/wordads/earnings?%s',
960                Jetpack_Options::get_option( 'id' ),
961                $this->filter_and_build_query_string(
962                    $req->get_params()
963                )
964            ),
965            'v1.1',
966            array( 'timeout' => 5 )
967        );
968    }
969
970    /**
971     * Get WordAds stats for the site.
972     *
973     * @param WP_REST_Request $req The request object.
974     * @return array
975     */
976    public function get_wordads_stats( $req ) {
977        return WPCOM_Client::request_as_blog_cached(
978            sprintf(
979                '/sites/%d/wordads/stats?%s',
980                Jetpack_Options::get_option( 'id' ),
981                $this->filter_and_build_query_string(
982                    $req->get_params()
983                )
984            ),
985            'v1.1',
986            array( 'timeout' => 5 )
987        );
988    }
989
990    /**
991     * Get Email stats as a list.
992     *
993     * @param WP_REST_Request $req The request object.
994     * @return array
995     */
996    public function get_email_stats_list( $req ) {
997        switch ( $req->get_param( 'resource' ) ) {
998            case 'summary':
999                return WPCOM_Client::request_as_blog_cached(
1000                    sprintf(
1001                        '/sites/%d/stats/emails/%s?%s',
1002                        Jetpack_Options::get_option( 'id' ),
1003                        $req->get_param( 'resource' ),
1004                        $this->filter_and_build_query_string(
1005                            $req->get_params()
1006                        )
1007                    ),
1008                    'v1.1',
1009                    array( 'timeout' => 5 )
1010                );
1011            default:
1012                return $this->get_forbidden_error();
1013        }
1014    }
1015
1016    /**
1017     * Get Email opens stats for a single post.
1018     *
1019     * @param WP_REST_Request $req The request object.
1020     * @return array
1021     */
1022    public function get_email_opens_stats_single( $req ) {
1023        switch ( $req->get_param( 'resource' ) ) {
1024            case 'client':
1025            case 'device':
1026            case 'country':
1027            case 'rate':
1028                return WPCOM_Client::request_as_blog_cached(
1029                    sprintf(
1030                        '/sites/%d/stats/opens/emails/%d/%s?%s',
1031                        Jetpack_Options::get_option( 'id' ),
1032                        $req->get_param( 'post_id' ),
1033                        $req->get_param( 'resource' ),
1034                        $this->filter_and_build_query_string(
1035                            $req->get_params()
1036                        )
1037                    ),
1038                    'v1.1',
1039                    array( 'timeout' => 5 )
1040                );
1041            default:
1042                return $this->get_forbidden_error();
1043        }
1044    }
1045
1046    /**
1047     * Get Email clicks stats for a single post.
1048     *
1049     * @param WP_REST_Request $req The request object.
1050     * @return array
1051     */
1052    public function get_email_clicks_stats_single( $req ) {
1053        switch ( $req->get_param( 'resource' ) ) {
1054            case 'client':
1055            case 'device':
1056            case 'country':
1057            case 'rate':
1058            case 'link':
1059            case 'user-content-link':
1060                return WPCOM_Client::request_as_blog_cached(
1061                    sprintf(
1062                        '/sites/%d/stats/clicks/emails/%d/%s?%s',
1063                        Jetpack_Options::get_option( 'id' ),
1064                        $req->get_param( 'post_id' ),
1065                        $req->get_param( 'resource' ),
1066                        $this->filter_and_build_query_string(
1067                            $req->get_params()
1068                        )
1069                    ),
1070                    'v1.1',
1071                    array( 'timeout' => 5 )
1072                );
1073            default:
1074                return $this->get_forbidden_error();
1075        }
1076    }
1077
1078    /**
1079     * Get Email stats time series.
1080     *
1081     * @param WP_REST_Request $req The request object.
1082     * @return array
1083     */
1084    public function get_email_stats_time_series( $req ) {
1085        switch ( $req->get_param( 'resource' ) ) {
1086            case 'opens':
1087            case 'clicks':
1088                return WPCOM_Client::request_as_blog_cached(
1089                    sprintf(
1090                        '/sites/%d/stats/%s/emails/%d?%s',
1091                        Jetpack_Options::get_option( 'id' ),
1092                        $req->get_param( 'resource' ),
1093                        $req->get_param( 'post_id' ),
1094                        $this->filter_and_build_query_string(
1095                            $req->get_params()
1096                        )
1097                    ),
1098                    'v1.1',
1099                    array( 'timeout' => 5 )
1100                );
1101            default:
1102                return $this->get_forbidden_error();
1103        }
1104    }
1105
1106    /**
1107     * Get UTM stats time series.
1108     *
1109     * @param WP_REST_Request $req The request object.
1110     * @return array
1111     */
1112    public function get_utm_stats_time_series( $req ) {
1113        return WPCOM_Client::request_as_blog_cached(
1114            sprintf(
1115                '/sites/%d/stats/utm/%s?%s',
1116                Jetpack_Options::get_option( 'id' ),
1117                $req->get_param( 'utm_params' ),
1118                $this->filter_and_build_query_string(
1119                    $req->get_params()
1120                )
1121            ),
1122            'v1.1',
1123            array( 'timeout' => 10 )
1124        );
1125    }
1126
1127    /**
1128     * Get Devices stats time series.
1129     *
1130     * @param WP_REST_Request $req The request object.
1131     * @return array
1132     */
1133    public function get_devices_stats_time_series( $req ) {
1134        return WPCOM_Client::request_as_blog_cached(
1135            sprintf(
1136                '/sites/%d/stats/devices/%s?%s',
1137                Jetpack_Options::get_option( 'id' ),
1138                $req->get_param( 'device_property' ),
1139                $this->filter_and_build_query_string(
1140                    $req->get_params()
1141                )
1142            ),
1143            'v1.1',
1144            array( 'timeout' => 10 )
1145        );
1146    }
1147
1148    /**
1149     * Get Location stats.
1150     *
1151     * @param WP_REST_Request $req The request object.
1152     * @return array
1153     */
1154    public function get_location_stats( $req ) {
1155        $params   = $req->get_params();
1156        $geo_mode = $params['geo_mode'];
1157        unset( $params['geo_mode'] );
1158
1159        return $this->wpcom_stats->get_views_by_location( $geo_mode, $params );
1160    }
1161
1162    /**
1163     * Dismiss or delay stats notices.
1164     *
1165     * @param WP_REST_Request $req The request object.
1166     * @return array
1167     */
1168    public function update_notice_status( $req ) {
1169        return ( new Notices() )->update_notice( $req->get_param( 'id' ), $req->get_param( 'status' ), $req->get_param( 'postponed_for' ) );
1170    }
1171
1172    /**
1173     * Get stats notices.
1174     *
1175     * @param WP_REST_Request $req The request object.
1176     * @return array
1177     */
1178    public function get_notice_status( $req ) {
1179        return ( new Notices() )->get_notices_to_show( (bool) $req->get_param( 'include_details' ) );
1180    }
1181
1182    /**
1183     * Get the list of spam referrers.
1184     *
1185     * @return array
1186     */
1187    public function get_referrer_spam_list() {
1188        return WPCOM_Client::request_as_blog(
1189            sprintf(
1190                '/sites/%d/stats/referrers/spam',
1191                Jetpack_Options::get_option( 'id' )
1192            ),
1193            'v1.1',
1194            array(
1195                'timeout' => 5,
1196                'method'  => 'GET',
1197            )
1198        );
1199    }
1200
1201    /**
1202     * Mark a referrer as spam.
1203     *
1204     * @param WP_REST_Request $req The request object.
1205     * @return array
1206     */
1207    public function mark_referrer_spam( $req ) {
1208        return WPCOM_Client::request_as_blog(
1209            sprintf(
1210                '/sites/%d/stats/referrers/spam/new?%s',
1211                Jetpack_Options::get_option( 'id' ),
1212                $this->filter_and_build_query_string(
1213                    $req->get_query_params()
1214                )
1215            ),
1216            'v1.1',
1217            array(
1218                'timeout' => 5,
1219                'method'  => 'POST',
1220            )
1221        );
1222    }
1223
1224    /**
1225     * Unmark a referrer as spam.
1226     *
1227     * @param WP_REST_Request $req The request object.
1228     * @return array
1229     */
1230    public function unmark_referrer_spam( $req ) {
1231        return WPCOM_Client::request_as_blog(
1232            sprintf(
1233                '/sites/%d/stats/referrers/spam/delete?%s',
1234                Jetpack_Options::get_option( 'id' ),
1235                $this->filter_and_build_query_string(
1236                    $req->get_query_params()
1237                )
1238            ),
1239            'v1.1',
1240            array(
1241                'timeout' => 5,
1242                'method'  => 'POST',
1243            )
1244        );
1245    }
1246
1247    /**
1248     * Toggle modules on dashboard.
1249     *
1250     * @param WP_REST_Request $req The request object.
1251     * @return array
1252     */
1253    public function update_dashboard_modules( $req ) {
1254        // Clear dashboard modules cache.
1255        delete_transient( static::JETPACK_STATS_DASHBOARD_MODULES_CACHE_KEY );
1256        return WPCOM_Client::request_as_blog(
1257            sprintf(
1258                '/sites/%d/jetpack-stats-dashboard/modules?%s',
1259                Jetpack_Options::get_option( 'id' ),
1260                $this->filter_and_build_query_string(
1261                    $req->get_query_params()
1262                )
1263            ),
1264            'v2',
1265            array(
1266                'timeout' => 5,
1267                'method'  => 'POST',
1268                'headers' => array( 'Content-Type' => 'application/json' ),
1269            ),
1270            $req->get_body(),
1271            'wpcom'
1272        );
1273    }
1274
1275    /**
1276     * Get modules on dashboard.
1277     *
1278     * @param WP_REST_Request $req The request object.
1279     * @return array
1280     */
1281    public function get_dashboard_modules( $req ) {
1282        return WPCOM_Client::request_as_blog_cached(
1283            sprintf(
1284                '/sites/%d/jetpack-stats-dashboard/modules?%s',
1285                Jetpack_Options::get_option( 'id' ),
1286                $this->filter_and_build_query_string(
1287                    $req->get_query_params()
1288                )
1289            ),
1290            'v2',
1291            array(
1292                'timeout' => 5,
1293            ),
1294            null,
1295            'wpcom',
1296            true,
1297            static::JETPACK_STATS_DASHBOARD_MODULES_CACHE_KEY
1298        );
1299    }
1300
1301    /**
1302     * Update module settings on dashboard.
1303     *
1304     * @param WP_REST_Request $req The request object.
1305     * @return array
1306     */
1307    public function update_dashboard_module_settings( $req ) {
1308        // Clear dashboard modules cache.
1309        delete_transient( static::JETPACK_STATS_DASHBOARD_MODULE_SETTINGS_CACHE_KEY );
1310        return WPCOM_Client::request_as_blog(
1311            sprintf(
1312                '/sites/%d/jetpack-stats-dashboard/module-settings?%s',
1313                Jetpack_Options::get_option( 'id' ),
1314                $this->filter_and_build_query_string(
1315                    $req->get_query_params()
1316                )
1317            ),
1318            'v2',
1319            array(
1320                'timeout' => 5,
1321                'method'  => 'POST',
1322                'headers' => array( 'Content-Type' => 'application/json' ),
1323            ),
1324            $req->get_body(),
1325            'wpcom'
1326        );
1327    }
1328
1329    /**
1330     * Get module settings on dashboard.
1331     *
1332     * @param WP_REST_Request $req The request object.
1333     * @return array
1334     */
1335    public function get_dashboard_module_settings( $req ) {
1336        return WPCOM_Client::request_as_blog_cached(
1337            sprintf(
1338                '/sites/%d/jetpack-stats-dashboard/module-settings?%s',
1339                Jetpack_Options::get_option( 'id' ),
1340                $this->filter_and_build_query_string(
1341                    $req->get_query_params()
1342                )
1343            ),
1344            'v2',
1345            array(
1346                'timeout' => 5,
1347            ),
1348            null,
1349            'wpcom',
1350            true,
1351            static::JETPACK_STATS_DASHBOARD_MODULE_SETTINGS_CACHE_KEY
1352        );
1353    }
1354
1355    /**
1356     * Run commercial classification.
1357     *
1358     * @param WP_REST_Request $req The request object.
1359     * @return array
1360     */
1361    public function run_commercial_classification( $req ) {
1362        return WPCOM_Client::request_as_blog(
1363            sprintf(
1364                '/sites/%d/commercial-classification?%s',
1365                Jetpack_Options::get_option( 'id' ),
1366                $this->filter_and_build_query_string(
1367                    $req->get_query_params()
1368                )
1369            ),
1370            'v2',
1371            array(
1372                'timeout' => 5,
1373                'method'  => 'POST',
1374            ),
1375            null,
1376            'wpcom'
1377        );
1378    }
1379
1380    /**
1381     * Get purchases array; I don't see anything sensetive in there, so didn't sentinizie it.
1382     * Plus it is the same case as Jetpack.
1383     *
1384     * @param WP_REST_Request $req The request object.
1385     * @return array
1386     */
1387    public function get_site_purchases( $req ) {
1388        return WPCOM_Client::request_as_blog_cached(
1389            sprintf(
1390                '/upgrades?site=%d&%s',
1391                Jetpack_Options::get_option( 'id' ),
1392                $this->filter_and_build_query_string(
1393                    $req->get_query_params()
1394                )
1395            ),
1396            'v1.2',
1397            array( 'timeout' => 10 ),
1398            null,
1399            'rest',
1400            false
1401        );
1402    }
1403
1404    /**
1405     * Return a WP_Error object with a forbidden error.
1406     */
1407    protected function get_forbidden_error() {
1408        $error_msg = esc_html__(
1409            'You are not allowed to perform this action.',
1410            'jetpack-stats-admin'
1411        );
1412
1413        return new WP_Error( 'rest_forbidden', $error_msg, array( 'status' => rest_authorization_required_code() ) );
1414    }
1415
1416    /**
1417     * Filter and build query string from all the requested params.
1418     *
1419     * @param array $params The params to filter.
1420     * @param array $keys_to_unset The keys to unset from the params array.
1421     * @return string The filtered and built query string.
1422     */
1423    protected function filter_and_build_query_string( $params, $keys_to_unset = array() ) {
1424        if ( isset( $params['rest_route'] ) ) {
1425            unset( $params['rest_route'] );
1426        }
1427        if ( ! empty( $keys_to_unset ) && is_array( $keys_to_unset ) ) {
1428            foreach ( $keys_to_unset as $key ) {
1429                if ( isset( $params[ $key ] ) ) {
1430                    unset( $params[ $key ] );
1431                }
1432            }
1433        }
1434        return http_build_query( $params );
1435    }
1436}