Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.49% covered (warning)
78.49%
135 / 172
79.55% covered (warning)
79.55%
35 / 44
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_Stats
78.49% covered (warning)
78.49%
135 / 172
79.55% covered (warning)
79.55%
35 / 44
146.31
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
 get_stats
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_stats_summary
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_top_posts
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 get_archives
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_video_details
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_referrers
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_clicks
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_tags
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_top_authors
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_top_comments
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_video_plays
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_file_downloads
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_post_views
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 get_views_by_country
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_views_by_location
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_followers
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_comment_followers
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_publicize_followers
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_search_terms
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_total_post_views
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 get_visits
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_streak
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_highlights
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_insights
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_utm_views
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_device_views
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_author_views
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_email_summary
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_email_breakdown
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_subscriber_history
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_subscriber_counts
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_subscribers
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_stats_usage
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_wordads_stats
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_wordads_earnings
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 build_endpoint
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 fetch_stats
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
7
 fetch_post_stats
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
72
 refresh_post_stats_cache
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 should_bypass_cache
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
6
 fetch_remote_stats
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
12
 fetch_stats_on_wpcom_simple
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 convert_stats_array_to_object
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * Stats WPCOM_Stats
4 *
5 * @package automattic/jetpack-stats
6 */
7
8namespace Automattic\Jetpack\Stats;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Status\Host;
12use Jetpack_Options;
13use WP_Error;
14
15/**
16 * Stats WPCOM_Stats class.
17 *
18 * Responsible for fetching Stats related data from WPCOM.
19 *
20 * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
21 *
22 * @since 0.1.0
23 */
24class WPCOM_Stats {
25    /**
26     * Transient prefix for storing Stats results from the REST API.
27     *
28     * @var string
29     */
30    const STATS_CACHE_TRANSIENT_PREFIX = 'jetpack_restapi_stats_cache_';
31
32    /**
33     * Time, in minutes, to cache stats results from the REST API.
34     *
35     * @var int
36     */
37    const STATS_CACHE_EXPIRATION_IN_MINUTES = 5;
38
39    /**
40     * Stats REST API version.
41     *
42     * @var string
43     */
44    const STATS_REST_API_VERSION = '1.1';
45
46    /**
47     * The stats resource to fetch results for.
48     *
49     * @var string
50     */
51    protected $resource;
52
53    /**
54     * If the site is on WPCOM Simple.
55     *
56     * @var bool
57     */
58    protected $is_wpcom_simple;
59
60    /**
61     * The constructor.
62     */
63    public function __construct() {
64        $this->is_wpcom_simple = ( new Host() )->is_wpcom_simple();
65    }
66
67    /**
68     * Get site's stats.
69     *
70     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
71     * @param array $args Optional query parameters.
72     * @return array| WP_Error
73     */
74    public function get_stats( $args = array() ) {
75        $this->resource = '';
76
77        return $this->fetch_stats( $args );
78    }
79
80    /**
81     * Get site's summarized views, visitors, likes and comments.
82     *
83     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/summary/
84     * @param array $args Optional query parameters.
85     * @return array|WP_Error
86     */
87    public function get_stats_summary( $args = array() ) {
88        $this->resource = 'summary';
89
90        return $this->fetch_stats( $args );
91    }
92
93    /**
94     * Get site's top posts and pages by views.
95     *
96     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/top-posts/
97     * @param array $args Optional query parameters.
98     * @param bool  $override_cache Optional override cache.
99     * @return array|WP_Error
100     */
101    public function get_top_posts( $args = array(), $override_cache = false ) {
102        $this->resource = 'top-posts';
103
104        // Needed for the Top Posts block, so users can preview changes instantly.
105        if ( $override_cache ) {
106            return $this->fetch_remote_stats( $this->build_endpoint(), $args );
107        }
108
109        return $this->fetch_stats( $args );
110    }
111
112    /**
113     * Get site's archive pages by views.
114     *
115     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/archives/
116     * @param array $args Optional query parameters.
117     * @return array|WP_Error
118     */
119    public function get_archives( $args = array() ) {
120        $this->resource = 'archives';
121
122        return $this->fetch_stats( $args );
123    }
124
125    /**
126     * Get the details of a single video.
127     *
128     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/video/%24post_id/
129     * @param int   $post_id The video's ID.
130     * @param array $args    Optional query parameters: `statType`, `period`, `num`, `date`.
131     * @return array|WP_Error
132     */
133    public function get_video_details( $post_id, $args = array() ) {
134        $this->resource = sprintf( 'video/%d', $post_id );
135
136        return $this->fetch_stats( $args );
137    }
138
139    /**
140     * Get site's referrers.
141     *
142     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/referrers/
143     * @param array $args Optional query parameters.
144     * @return array|WP_Error
145     */
146    public function get_referrers( $args = array() ) {
147        $this->resource = 'referrers';
148
149        return $this->fetch_stats( $args );
150    }
151
152    /**
153     * Get site's outbound clicks.
154     *
155     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/clicks/
156     * @param array $args Optional query parameters.
157     * @return array|WP_Error
158     */
159    public function get_clicks( $args = array() ) {
160        $this->resource = 'clicks';
161
162        return $this->fetch_stats( $args );
163    }
164
165    /**
166     * Get site's views by tags and categories.
167     *
168     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/tags/
169     * @param array $args Optional query parameters.
170     * @return array|WP_Error
171     */
172    public function get_tags( $args = array() ) {
173        $this->resource = 'tags';
174
175        return $this->fetch_stats( $args );
176    }
177
178    /**
179     * Get site's top authors.
180     *
181     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/top-authors/
182     * @param array $args Optional query parameters.
183     * @return array|WP_Error
184     */
185    public function get_top_authors( $args = array() ) {
186        $this->resource = 'top-authors';
187
188        return $this->fetch_stats( $args );
189    }
190
191    /**
192     * Get site's top comment authors and most-commented posts.
193     *
194     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/comments/
195     * @param array $args Optional query parameters.
196     * @return array|WP_Error
197     */
198    public function get_top_comments( $args = array() ) {
199        $this->resource = 'comments';
200
201        return $this->fetch_stats( $args );
202    }
203
204    /**
205     * Get site's video plays.
206     *
207     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/video-plays/
208     * @param array $args Optional query parameters.
209     * @return array|WP_Error
210     */
211    public function get_video_plays( $args = array() ) {
212        $this->resource = 'video-plays';
213
214        return $this->fetch_stats( $args );
215    }
216
217    /**
218     * Get site's file downloads.
219     *
220     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/file-downloads/
221     * @param array $args Optional query parameters.
222     * @return array|WP_Error
223     */
224    public function get_file_downloads( $args = array() ) {
225        $this->resource = 'file-downloads';
226
227        return $this->fetch_stats( $args );
228    }
229
230    /**
231     * Get a post's views.
232     *
233     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/post/%24post_id/
234     * @param int   $post_id        The post's ID.
235     * @param array $args           Optional query parameters.
236     * @param bool  $cache_in_meta  Optional should cache in post meta.
237     * @return array|WP_Error
238     */
239    public function get_post_views( $post_id, $args = array(), $cache_in_meta = false ) {
240        $this->resource = sprintf( 'post/%d', $post_id );
241
242        if ( $cache_in_meta ) {
243            return $this->fetch_post_stats( $args, $post_id );
244        }
245
246        return $this->fetch_stats( $args );
247    }
248
249    /**
250     * Get site's views by country.
251     *
252     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/country-views/
253     * @param array $args Optional query parameters.
254     * @return array|WP_Error
255     */
256    public function get_views_by_country( $args = array() ) {
257
258        $this->resource = 'country-views';
259
260        return $this->fetch_stats( $args );
261    }
262
263    /**
264     * Get site's views by location.
265     *
266     * @param string $geo_mode The type of location to fetch views for (country, region, city).
267     * @param array  $args     Optional query parameters.
268     * @return array|WP_Error
269     */
270    public function get_views_by_location( $geo_mode, $args = array() ) {
271        $this->resource = sprintf( 'location-views/%s', $geo_mode );
272
273        return $this->fetch_stats( $args );
274    }
275
276    /**
277     * Get site's followers.
278     *
279     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/followers/
280     * @param array $args Optional query parameters.
281     * @return array|WP_Error
282     */
283    public function get_followers( $args = array() ) {
284
285        $this->resource = 'followers';
286
287        return $this->fetch_stats( $args );
288    }
289
290    /**
291     * Get site's comment followers.
292     *
293     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/comment-followers/
294     * @param array $args Optional query parameters.
295     * @return array|WP_Error
296     */
297    public function get_comment_followers( $args = array() ) {
298
299        $this->resource = 'comment-followers';
300
301        return $this->fetch_stats( $args );
302    }
303
304    /**
305     * Get site's publicize follower counts.
306     *
307     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/publicize/
308     * @param array $args Optional query parameters.
309     * @return array|WP_Error
310     */
311    public function get_publicize_followers( $args = array() ) {
312
313        $this->resource = 'publicize';
314
315        return $this->fetch_stats( $args );
316    }
317
318    /**
319     * Get search terms used to find the site.
320     *
321     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/search-terms/
322     * @param array $args Optional query parameters.
323     * @return array|WP_Error
324     */
325    public function get_search_terms( $args = array() ) {
326
327        $this->resource = 'search-terms';
328
329        return $this->fetch_stats( $args );
330    }
331
332    /**
333     * Get the total number of views for each post.
334     *
335     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/views/posts/
336     * @param array $args Optional query parameters.
337     * @return array|WP_Error
338     */
339    public function get_total_post_views( $args = array() ) {
340        if ( $this->is_wpcom_simple ) {
341            $post_ids         = isset( $args['post_ids'] ) ? array_map( 'absint', explode( ',', $args['post_ids'] ) ) : array();
342            $escaped_post_ids = implode( ',', $post_ids );
343
344            $number_of_days = isset( $args['num'] ) ? absint( $args['num'] ) : 1;
345            // It's the same function used in WPCOM simple.
346            // @phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
347            $end_date = $args['end'] ?? date( 'Y-m-d' );
348
349            $stats = $this->fetch_stats_on_wpcom_simple( $end_date, $number_of_days, $escaped_post_ids );
350
351            $post_views = $stats['-'] ?? array();
352
353            $posts = array_map(
354                function ( $post_id ) use ( $post_views ) {
355                    return array(
356                        'ID'    => $post_id,
357                        'views' => $post_views[ $post_id ] ?? 0,
358                    );
359                },
360                $post_ids
361            );
362
363            return array( 'posts' => $posts );
364        }
365
366        $this->resource = 'views/posts';
367
368        return $this->fetch_stats( $args );
369    }
370
371    /**
372     * Get the number of visits for the site.
373     *
374     * @param array $args Optional query parameters.
375     * @return array|WP_Error
376     */
377    public function get_visits( $args = array() ) {
378
379        $this->resource = 'visits';
380
381        return $this->fetch_stats( $args );
382    }
383
384    /**
385     * Get streaks for the site.
386     *
387     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/streak/
388     *
389     * @param array $args Optional query parameters.
390     * @return array|WP_Error
391     */
392    public function get_streak( $args = array() ) {
393
394        $this->resource = 'streak';
395
396        return $this->fetch_stats( $args );
397    }
398
399    /**
400     * Get the highlights for the site.
401     *
402     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/highlights/
403     *
404     * @param array $args Optional query parameters.
405     * @return array|WP_Error
406     */
407    public function get_highlights( $args = array() ) {
408
409        $this->resource = 'highlights';
410
411        return $this->fetch_stats( $args );
412    }
413
414    /**
415     * Get the number of visits for the site.
416     *
417     * @param array $args Optional query parameters.
418     * @return array|WP_Error
419     */
420    public function get_insights( $args = array() ) {
421
422        $this->resource = 'insights';
423
424        return $this->fetch_stats( $args );
425    }
426
427    /**
428     * Get the site's views by UTM parameter value.
429     *
430     * @param string $utm_param UTM parameter, or a comma-separated combination WordPress.com groups by, e.g. `utm_source,utm_medium`.
431     * @param array  $args      Optional query parameters: `days`, `date`, `max`, `post_id`.
432     * @return array|WP_Error
433     */
434    public function get_utm_views( $utm_param, $args = array() ) {
435        $this->resource = sprintf( 'utm/%s', $utm_param );
436
437        return $this->fetch_stats( $args );
438    }
439
440    /**
441     * Get the site's views by device property.
442     *
443     * @param string $property One of `browser`, `platform` or `screensize`.
444     * @param array  $args     Optional query parameters: `days`, `date`, `max`.
445     * @return array|WP_Error
446     */
447    public function get_device_views( $property, $args = array() ) {
448        $this->resource = sprintf( 'devices/%s', $property );
449
450        return $this->fetch_stats( $args );
451    }
452
453    /**
454     * Get one author's views, likes and comments.
455     *
456     * @param int   $author_id The author's user ID, as `stats/top-authors` reports it.
457     * @param array $args      Optional query parameters: `period`, `date`, `num`.
458     * @return array|WP_Error
459     */
460    public function get_author_views( $author_id, $args = array() ) {
461        $this->resource = sprintf( 'author/%d', $author_id );
462
463        return $this->fetch_stats( $args );
464    }
465
466    /**
467     * Get the opens and clicks of the posts the site sent as emails.
468     *
469     * @param array $args Optional query parameters: `quantity`, `sort_field`, `sort_order`, `start_date`, `end_date`.
470     * @return array|WP_Error
471     */
472    public function get_email_summary( $args = array() ) {
473        $this->resource = 'emails/summary';
474
475        return $this->fetch_stats( $args );
476    }
477
478    /**
479     * Get one breakdown of the opens or clicks of a post the site sent as an email, over all time.
480     *
481     * @param int    $post_id The post the site emailed.
482     * @param string $stat    `opens` or `clicks`.
483     * @param string $field   `rate`, `client`, `country` or `device`; for clicks also `link` or `user-content-link`.
484     * @return array|WP_Error
485     */
486    public function get_email_breakdown( $post_id, $stat, $field ) {
487        $this->resource = sprintf( '%s/emails/%d/%s', $stat, $post_id, $field );
488
489        return $this->fetch_stats();
490    }
491
492    /**
493     * Get the site's subscriber count over time.
494     *
495     * @param array $args Optional query parameters: `unit`, `quantity`, `date`.
496     * @return array|WP_Error
497     */
498    public function get_subscriber_history( $args = array() ) {
499        $this->resource = 'subscribers';
500
501        return $this->fetch_stats( $args );
502    }
503
504    /**
505     * Get the site's current subscriber counts by kind.
506     *
507     * @return array|WP_Error
508     */
509    public function get_subscriber_counts() {
510        $this->resource = '/subscribers/counts';
511
512        return $this->fetch_stats( array(), '2', 'wpcom' );
513    }
514
515    /**
516     * Get a page of the site's subscribers.
517     *
518     * @param array $args Optional query parameters: `page`, `per_page`, `search`, `sort`, `sort_order`, `filter`.
519     * @return array|WP_Error
520     */
521    public function get_subscribers( $args = array() ) {
522        $this->resource = '/subscribers';
523
524        return $this->fetch_stats( $args, '2', 'wpcom' );
525    }
526
527    /**
528     * Get the site's Stats plan usage: views counted this billing month and the plan's limit.
529     *
530     * @return array|WP_Error
531     */
532    public function get_stats_usage() {
533        $this->resource = '/jetpack-stats/usage';
534
535        return $this->fetch_stats( array(), '2', 'wpcom' );
536    }
537
538    /**
539     * Get the site's ad impressions and revenue over time.
540     *
541     * @param array $args Optional query parameters: `unit`, `quantity`, `date`.
542     * @return array|WP_Error
543     */
544    public function get_wordads_stats( $args = array() ) {
545        $this->resource = '/wordads/stats';
546
547        return $this->fetch_stats( $args );
548    }
549
550    /**
551     * Get the site's ad earnings by month, and the amounts paid and owed.
552     *
553     * @return array|WP_Error
554     */
555    public function get_wordads_earnings() {
556        $this->resource = '/wordads/earnings';
557
558        return $this->fetch_stats();
559    }
560
561    /**
562     * Build WPCOM REST API endpoint.
563     *
564     * A resource starting with `/` is a path under the site; any other is a path under its Stats.
565     *
566     * @return string
567     */
568    protected function build_endpoint() {
569        if ( str_starts_with( $this->resource, '/' ) ) {
570            return sprintf( '/sites/%d%s', Jetpack_Options::get_option( 'id' ), $this->resource );
571        }
572
573        $resource = ltrim( $this->resource, '/' );
574
575        return sprintf( '/sites/%d/stats/%s', Jetpack_Options::get_option( 'id' ), $resource );
576    }
577
578    /**
579     * Fetches stats data from WPCOM or local Cache. Caches locally for 5 minutes.
580     *
581     * @param array  $args          Optional query parameters.
582     * @param string $api_version   WordPress.com API version.
583     * @param string $base_api_path WordPress.com API base path: `rest` for v1.x, `wpcom` for v2.
584     *
585     * @return array|WP_Error
586     */
587    protected function fetch_stats( $args = array(), $api_version = self::STATS_REST_API_VERSION, $base_api_path = 'rest' ) {
588        $endpoint       = $this->build_endpoint();
589        $cache_key      = md5( implode( '|', array( $endpoint, $api_version, wp_json_encode( $args, JSON_UNESCAPED_SLASHES ) ) ) );
590        $transient_name = self::STATS_CACHE_TRANSIENT_PREFIX . $cache_key;
591        $stats_cache    = $this->should_bypass_cache() ? false : get_transient( $transient_name );
592
593        if ( $stats_cache ) {
594            $time = key( $stats_cache );
595            $data = $stats_cache[ $time ]; // WP_Error or string (JSON encoded object).
596
597            if ( is_wp_error( $data ) ) {
598                return $data;
599            }
600
601            return array_merge( array( 'cached_at' => $time ), (array) json_decode( $data, true ) );
602        }
603
604        $wpcom_stats = $this->fetch_remote_stats( $endpoint, $args, $api_version, $base_api_path );
605
606        /*
607         * Connection failures stop being true as soon as the site reconnects. Do not cache
608         * them: otherwise the next request keeps returning the old failure after recovery.
609         *
610         * `no_possible_tokens` is what the connection package reports for a missing blog token
611         * since it started naming the reason; `missing_token` is what older versions still return.
612         */
613        if ( is_wp_error( $wpcom_stats ) && in_array( $wpcom_stats->get_error_code(), array( 'missing_token', 'no_possible_tokens', 'site_not_connected' ), true ) ) {
614            return $wpcom_stats;
615        }
616
617        // To reduce size in storage: store with time as key, store JSON encoded data.
618        $cached_value = is_wp_error( $wpcom_stats ) ? $wpcom_stats : wp_json_encode( $wpcom_stats, JSON_UNESCAPED_SLASHES );
619
620        /**
621         * Filters the expiration time for the stats cache.
622         *
623         * @module stats
624         *
625         * @since 0.10.0
626         *
627         * @param int $expiration The expiration time in minutes.
628         */
629        $expiration = apply_filters(
630            'jetpack_fetch_stats_cache_expiration',
631            self::STATS_CACHE_EXPIRATION_IN_MINUTES * MINUTE_IN_SECONDS
632        );
633        set_transient( $transient_name, array( time() => $cached_value ), $expiration );
634
635        return $wpcom_stats;
636    }
637
638    /**
639     * Fetches stats data from WPCOM or local Cache. Caches locally for 5 minutes.
640     *
641     * Unlike the above function, this caches data in the post meta table. As such,
642     * it prevents wp_options from blowing up when retrieving views for large numbers
643     * of posts at the same time.
644     *
645     * This function returns valid arrays and WP_Error objects from cache if within the expiration period.
646     * If the cached entry is malformed or invalid, a refresh is triggered regardless of cache time.
647     * This self-healing behavior reduces API calls when remote fetch fails, but ensures data validity.
648     *
649     * @param array $args Query parameters.
650     * @param int   $post_id Post ID to acquire stats for.
651     *
652     * @return array|WP_Error
653     */
654    protected function fetch_post_stats( $args, $post_id ) {
655        $endpoint    = $this->build_endpoint();
656        $meta_name   = '_' . self::STATS_CACHE_TRANSIENT_PREFIX;
657        $stats_cache = get_post_meta( $post_id, $meta_name, false );
658
659        if ( $stats_cache ) {
660            $data = reset( $stats_cache );
661
662            // Check if we have a valid cache structure with a time key.
663            if ( is_array( $data ) && ! empty( $data ) ) {
664                $time = key( $data );
665
666                // If we have a numeric time, check if cache is still valid.
667                if ( is_numeric( $time ) ) {
668                    /** This filter is already documented in projects/packages/stats/src/class-wpcom-stats.php */
669                    $expiration = apply_filters(
670                        'jetpack_fetch_stats_cache_expiration',
671                        self::STATS_CACHE_EXPIRATION_IN_MINUTES * MINUTE_IN_SECONDS
672                    );
673
674                    // If within cache period, return cached data after type validation.
675                    if ( ( time() - $time ) < $expiration ) {
676                        $cached_value = $data[ $time ];
677
678                        // If it's an array or WP_Error, handle appropriately.
679                        if ( is_wp_error( $cached_value ) ) {
680                            return $cached_value;
681                        }
682                        if ( is_array( $cached_value ) ) {
683                            return array_merge( array( 'cached_at' => $time ), $cached_value );
684                        }
685
686                        // For any other unexpected type, treat as malformed cache.
687                        // Fall through to refresh.
688                    }
689                }
690            }
691        }
692
693        // Cache doesn't exist, is expired, or is malformed - refresh it.
694        return $this->refresh_post_stats_cache( $endpoint, $args, $post_id, $meta_name );
695    }
696
697    /**
698     * Force fetch stats from WPCOM, and always update cache.
699     *
700     * This function will cache the result regardless of whether the fetch succeeds
701     * or fails. This ensures that failed requests are also cached, reducing the
702     * frequency of API calls when the remote service is experiencing issues.
703     *
704     * @param string $endpoint The stats endpoint.
705     * @param array  $args The query arguments.
706     * @param int    $post_id The post ID.
707     * @param string $meta_name The meta name.
708     *
709     * @return array|WP_Error
710     */
711    protected function refresh_post_stats_cache( $endpoint, $args, $post_id, $meta_name ) {
712        $wpcom_stats = $this->fetch_remote_stats( $endpoint, $args );
713
714        // Always cache the result, even if it's an error or empty.
715        update_post_meta( $post_id, $meta_name, array( time() => $wpcom_stats ) );
716
717        return $wpcom_stats;
718    }
719
720    /**
721     * Whether the caller has asked for an answer newer than the cached one.
722     *
723     * A site that has just connected, or just bought a plan, carries answers from before it did
724     * -- including failures, which are cached like any other answer. Both markers are the ones
725     * `Stats_Admin\WPCOM_Client` already honours, so a page load clears every layer or none.
726     *
727     * The dashboard asks for its data over REST, and those requests carry none of the page's
728     * query, so the marker has to be read from the page that sent them as well.
729     *
730     * Limited to users who can view stats: `fetch_stats()` also serves public widgets and
731     * blocks, and those must not skip the cache because a visitor supplied a query arg or a
732     * Referer that happens to contain one of the markers.
733     *
734     * @return bool
735     */
736    protected function should_bypass_cache() {
737        if ( ! current_user_can( 'view_stats' ) ) {
738            return false;
739        }
740
741        foreach ( array( 'force_refresh', 'statsPurchaseSuccess' ) as $marker ) {
742            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
743            if ( isset( $_GET[ $marker ] ) ) {
744                return true;
745            }
746
747            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
748            if ( isset( $_SERVER['HTTP_REFERER'] ) && false !== strpos( (string) $_SERVER['HTTP_REFERER'], $marker ) ) {
749                return true;
750            }
751        }
752
753        return false;
754    }
755
756    /**
757     * Fetches stats data from WPCOM.
758     *
759     * @link https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
760     * @param string $endpoint      The stats endpoint.
761     * @param array  $args          The query arguments.
762     * @param string $api_version   WordPress.com API version.
763     * @param string $base_api_path WordPress.com API base path: `rest` for v1.x, `wpcom` for v2.
764     * @return array|WP_Error
765     */
766    protected function fetch_remote_stats( $endpoint, $args, $api_version = self::STATS_REST_API_VERSION, $base_api_path = 'rest' ) {
767        if ( is_array( $args ) && ! empty( $args ) ) {
768            $endpoint .= '?' . http_build_query( $args );
769        }
770        $response      = Client::wpcom_json_api_request_as_blog( $endpoint, $api_version, array( 'timeout' => 20 ), null, $base_api_path );
771        $response_code = wp_remote_retrieve_response_code( $response );
772        $response_body = wp_remote_retrieve_body( $response );
773        $data          = json_decode( $response_body, true );
774        $error_code    = is_wp_error( $response ) ? $response->get_error_code() : ( $data['error'] ?? $data['code'] ?? null );
775
776        // Traffic endpoints must expose the same connection errors as the Stats admin API client.
777        if ( in_array( $error_code, array( 'missing_token', 'no_possible_tokens', 'malformed_token', 'invalid_token', 'unknown_token', 'signature_mismatch' ), true ) ) {
778            return new WP_Error(
779                'site_not_connected',
780                __( 'This site is not connected to WordPress.com.', 'jetpack-stats-pkg' ),
781                array( 'status' => 400 )
782            );
783        }
784
785        if ( is_wp_error( $response ) || 200 !== $response_code || empty( $response_body ) ) {
786            if ( is_wp_error( $response ) ) {
787                return $response;
788            }
789            // WordPress.com says why it refused, e.g. that the site's plan does not include a report.
790            $message = is_array( $data ) && is_string( $data['message'] ?? null ) && '' !== $data['message'] ? $data['message'] : 'Failed to fetch Stats from WPCOM';
791            return new WP_Error( 'stats_error', $message, array( 'status' => $response_code ) );
792        }
793
794        return $data;
795    }
796
797    /**
798     * Fetch the stats when executed in WPCOM Simple.
799     *
800     * @param string $end_date         The end date.
801     * @param int    $number_of_days   The number of days.
802     * @param string $escaped_post_ids The escaped post ids.
803     *
804     * @return array
805     */
806    protected function fetch_stats_on_wpcom_simple( $end_date, $number_of_days, $escaped_post_ids ) {
807        return stats_get_daily_history( false, get_current_blog_id(), 'postviews', 'post_id', $end_date, $number_of_days, " AND post_id IN ($escaped_post_ids)", 0, true );
808    }
809
810    /**
811     * Convert stats array to object after sanity checking the array is valid.
812     *
813     * @since 0.11.0
814     *
815     * @param  array $stats_array The stats array.
816     * @return WP_Error|object|null
817     */
818    public function convert_stats_array_to_object( $stats_array ) {
819
820        if ( is_wp_error( $stats_array ) ) {
821            return $stats_array;
822        }
823        $encoded_array = wp_json_encode( $stats_array, JSON_UNESCAPED_SLASHES );
824        if ( ! $encoded_array ) {
825            return new WP_Error( 'stats_encoding_error', 'Failed to encode stats array' );
826        }
827        return json_decode( $encoded_array );
828    }
829}