Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
37.97% covered (danger)
37.97%
30 / 79
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Subscriber_Data
38.96% covered (danger)
38.96%
30 / 77
0.00% covered (danger)
0.00%
0 / 3
296.89
0.00% covered (danger)
0.00%
0 / 1
 get_count
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 get_counts
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
13
 get_stats
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
342
1<?php
2/**
3 * Shared subscriber counts and statistics.
4 *
5 * @package jetpack
6 */
7
8use Automattic\Jetpack\Connection\Client;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14/**
15 * Fetches subscriber data for subscription consumers.
16 */
17class Jetpack_Subscriber_Data {
18    /**
19     * Transient key for counts, separate from the old cache's hour-long failures.
20     */
21    const COUNTS_CACHE_KEY = 'jetpack_subscriber_counts';
22
23    /**
24     * Get the combined subscriber and social follower count.
25     *
26     * @param bool $refresh Whether to refresh a successful cached count.
27     * @return int
28     */
29    public static function get_count( $refresh = false ) {
30        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
31            return wpcom_reach_total_for_blog();
32        }
33
34        $subs_count = self::get_counts( $refresh );
35        $counts     = $subs_count['value'];
36        return (int) ( $counts['total_subscribers'] ?? 0 ) + (int) ( $counts['social_followers'] ?? 0 );
37    }
38
39    /**
40     * Preserve the public count envelope and the native WordPress.com cache.
41     *
42     * @param bool $refresh Whether to refresh successful cached counts.
43     * @return array
44     */
45    public static function get_counts( $refresh = false ) {
46        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
47            return array( 'value' => wpcom_fetch_subs_counts( true ) );
48        }
49
50        $subs_count = get_transient( self::COUNTS_CACHE_KEY );
51        if ( false === $subs_count || ( $refresh && 'success' === $subs_count['status'] ) ) {
52            $xml = new Jetpack_IXR_Client();
53            $xml->query( 'jetpack.fetchSubscriberCounts' );
54            $is_error = $xml->isError();
55            $value    = $is_error ? null : $xml->getResponse();
56
57            if ( ! is_array( $value ) || ! isset( $value['total_subscribers'] ) || ! isset( $value['social_followers'] ) ) {
58                $subs_count = array(
59                    'status'  => 'failed',
60                    'code'    => $is_error ? $xml->getErrorCode() : 'invalid_response',
61                    'message' => $is_error ? $xml->getErrorMessage() : '',
62                    'value'   => array(
63                        'total_subscribers' => 0,
64                        'email_subscribers' => 0,
65                        'social_followers'  => 0,
66                        'paid_subscribers'  => 0,
67                    ),
68                );
69            } else {
70                $subs_count = array(
71                    'status' => 'success',
72                    'value'  => $value,
73                );
74            }
75            $ttl = 'failed' === $subs_count['status'] ? 5 * MINUTE_IN_SECONDS : HOUR_IN_SECONDS;
76            set_transient( self::COUNTS_CACHE_KEY, $subs_count, $ttl );
77        }
78        return $subs_count;
79    }
80
81    /**
82     * Share counts and chart history between dashboard and ability requests.
83     *
84     * @return array|WP_Error
85     */
86    public static function get_stats() {
87        // WordPress.com answers in-process from its own cache, which it clears when subscribers change.
88        $use_cache = ! ( defined( 'IS_WPCOM' ) && IS_WPCOM );
89        $cache_key = 'jetpack_newsletter_subscriber_stats_data';
90        $cached    = $use_cache ? get_transient( $cache_key ) : false;
91        if ( is_array( $cached ) ) {
92            return isset( $cached['error'] )
93                ? new WP_Error( 'jetpack_newsletter_subscriber_stats_unavailable', $cached['error'] )
94                : $cached;
95        }
96
97        if ( ! class_exists( 'Jetpack' ) || ! Jetpack::is_connection_ready() ) {
98            return new WP_Error(
99                'jetpack_newsletter_not_connected',
100                __( 'Subscriber stats are only available on Jetpack-connected sites. Connect Jetpack and retry.', 'jetpack' )
101            );
102        }
103
104        $site_id = (int) Jetpack_Options::get_option( 'id' );
105        if ( $site_id <= 0 ) {
106            return new WP_Error(
107                'jetpack_newsletter_not_connected',
108                __( 'No Jetpack site ID is registered. Connect Jetpack and retry.', 'jetpack' )
109            );
110        }
111
112        $response = Client::wpcom_json_api_request_as_blog(
113            sprintf( '/sites/%d/subscribers/stats', $site_id ),
114            '2',
115            array(),
116            null,
117            'wpcom'
118        );
119
120        $error = null;
121        $body  = null;
122        if ( is_wp_error( $response ) ) {
123            $error = $response->get_error_message();
124        } else {
125            $body = json_decode( wp_remote_retrieve_body( $response ), true );
126            if ( 200 !== (int) wp_remote_retrieve_response_code( $response )
127                || ! is_array( $body ) || ! isset( $body['counts'] ) || ! is_array( $body['counts'] )
128                || ( isset( $body['aggregate'] ) && ! is_array( $body['aggregate'] ) )
129            ) {
130                $error = __( 'WordPress.com did not return subscriber stats. Retry shortly.', 'jetpack' );
131            }
132        }
133
134        if ( null !== $error ) {
135            if ( $use_cache ) {
136                set_transient( $cache_key, array( 'error' => $error ), 5 * MINUTE_IN_SECONDS );
137            }
138            return new WP_Error( 'jetpack_newsletter_subscriber_stats_unavailable', $error );
139        }
140
141        $stats = array(
142            'counts'    => $body['counts'],
143            'aggregate' => $body['aggregate'] ?? array(),
144        );
145        if ( $use_cache ) {
146            set_transient( $cache_key, $stats, HOUR_IN_SECONDS );
147        }
148        return $stats;
149    }
150}