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