Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.13% covered (warning)
87.13%
149 / 171
60.00% covered (warning)
60.00%
9 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Wpcom_Products
87.13% covered (warning)
87.13%
149 / 171
60.00% covered (warning)
60.00%
9 / 15
58.98
0.00% covered (danger)
0.00%
0 / 1
 get_products_from_wpcom
88.00% covered (warning)
88.00%
44 / 50
0.00% covered (danger)
0.00%
0 / 1
9.14
 build_check_hash
53.85% covered (warning)
53.85%
7 / 13
0.00% covered (danger)
0.00%
0 / 1
9.54
 update_cache
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 is_cache_old
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 get_products_from_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_products
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
 get_product
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_product_pricing
85.00% covered (warning)
85.00%
17 / 20
0.00% covered (danger)
0.00%
0 / 1
3.03
 populate_with_discount
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
4.01
 get_site_current_purchases
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
6
 get_site_current_plan
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 reset_request_failures
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reset_purchases_cache
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 set_request_failure
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_request_failure
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Fetches and store the list of Jetpack products available in WPCOM
4 *
5 * @package automattic/my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Current_Plan;
13use Automattic\Jetpack\Status\Visitor;
14use Jetpack_Options;
15use WP_Error;
16/**
17 * Stores the list of products available for purchase in WPCOM
18 */
19class Wpcom_Products {
20
21    /**
22     * The meta name used to store the cache date
23     *
24     * @var string
25     */
26    const CACHE_DATE_META_NAME = 'my-jetpack-cache-date';
27
28    /**
29     * The meta name used to store the cache
30     *
31     * @var string
32     */
33    const CACHE_META_NAME = 'my-jetpack-cache';
34
35    const CACHE_CHECK_HASH_NAME = 'my-jetpack-wpcom-product-check-hash';
36
37    const MY_JETPACK_PURCHASES_TRANSIENT_KEY = 'my-jetpack-purchases';
38
39    /**
40     * How long, in seconds, a purchases lookup is reused before WPCOM is asked again
41     *
42     * @var int
43     */
44    const MY_JETPACK_PURCHASES_CACHE_DURATION = 5;
45
46    /**
47     * How long, in seconds, a failed WPCOM request answers later callers before it is retried
48     *
49     * @var int
50     */
51    const WPCOM_REQUEST_FAILURE_CACHE_DURATION = 5;
52
53    /**
54     * The request label the site purchases lookup records its failures under
55     *
56     * @var string
57     */
58    const PURCHASES_REQUEST_LABEL = 'get_site_current_purchases';
59
60    /**
61     * Store the data on failed WPCOM requests, each with the time it stops answering.
62     *
63     * @var array
64     */
65    private static $wpcom_request_failures = array();
66
67    /**
68     * A successful purchases lookup, kept so one WPCOM request serves a whole render
69     * even when the transient write does not retain (e.g. an object cache evicting under load)
70     *
71     * @var mixed
72     */
73    private static $site_purchases = null;
74
75    /**
76     * Unix time at which the memo above stops being used
77     *
78     * @var int
79     */
80    private static $site_purchases_expires = 0;
81
82    /**
83     * Fetches the list of products from WPCOM
84     *
85     * @return Object|WP_Error
86     */
87    private static function get_products_from_wpcom() {
88        $connection = new Connection_Manager();
89        $blog_id    = \Jetpack_Options::get_option( 'id' );
90        $ip         = ( new Visitor() )->get_ip( true );
91        $headers    = array(
92            'X-Forwarded-For' => $ip,
93        );
94
95        if ( $blog_id ) {
96            $request_label   = 'get_products_from_wpcom_blog_' . $blog_id;
97            $request_failure = static::get_request_failure( $request_label );
98            if ( null !== $request_failure ) {
99                return $request_failure;
100            }
101
102            // If has a blog id, use connected endpoint.
103            $endpoint = sprintf( '/sites/%d/products/?_locale=%s&type=jetpack', $blog_id, get_user_locale() );
104
105            // If available in the user data, set the user's currency as one of the params
106            if ( $connection->is_user_connected() ) {
107                $user_details = $connection->get_connected_user_data();
108                if ( ! empty( $user_details['user_currency'] ) && $user_details['user_currency'] !== 'USD' ) {
109                    $endpoint .= sprintf( '&currency=%s', $user_details['user_currency'] );
110                }
111            }
112
113            $wpcom_request = Client::wpcom_json_api_request_as_blog(
114                $endpoint,
115                '1.1',
116                array(
117                    'method'  => 'GET',
118                    'headers' => $headers,
119                )
120            );
121        } else {
122            $request_label   = 'get_products_from_wpcom';
123            $request_failure = static::get_request_failure( $request_label );
124            if ( null !== $request_failure ) {
125                return $request_failure;
126            }
127
128            $endpoint = 'https://public-api.wordpress.com/rest/v1.1/products?locale=' . get_user_locale() . '&type=jetpack';
129
130            $wpcom_request = wp_remote_get(
131                esc_url_raw( $endpoint ),
132                array(
133                    'headers' => $headers,
134                )
135            );
136        }
137
138        $response_code = wp_remote_retrieve_response_code( $wpcom_request );
139
140        if ( 200 === $response_code ) {
141            $products = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
142            if ( is_object( $products ) ) {
143                return $products;
144            }
145            $error = new WP_Error( 'invalid_wpcom_products', __( 'Unable to read the products list from WordPress.com', 'jetpack-my-jetpack' ) );
146            static::set_request_failure( $request_label, $error );
147            return $error;
148        } else {
149            $error = new WP_Error(
150                'failed_to_fetch_wpcom_products',
151                esc_html__( 'Unable to fetch the products list from WordPress.com', 'jetpack-my-jetpack' ),
152                array( 'status' => $response_code )
153            );
154            static::set_request_failure( $request_label, $error );
155            return $error;
156        }
157    }
158
159    /**
160     * Super unintelligent hash string that can help us reset the cache after connection changes
161     * This is important because the currency can change after a user connects depending on what is set in their profile
162     *
163     * @return string
164     */
165    private static function build_check_hash() {
166        static $has_user_data_fetch_error = false;
167
168        $hash_string = 'check_hash_' . Jetpack_Options::get_option( 'id' ) . '_' . get_user_locale();
169        $connection  = new Connection_Manager();
170
171        if ( $connection->is_connected() ) {
172            $hash_string .= 'site_connected_';
173        }
174
175        if ( $connection->is_user_connected() ) {
176            $hash_string .= 'user_connected';
177            // Add the user's currency
178            $user_details = $has_user_data_fetch_error ? false : $connection->get_connected_user_data();
179
180            if ( $user_details === false ) {
181                $has_user_data_fetch_error = true;
182            } elseif ( ! empty( $user_details['user_currency'] ) ) {
183                $hash_string .= '_' . $user_details['user_currency'];
184            }
185        }
186
187        return md5( $hash_string );
188    }
189
190    /**
191     * Update the cache with new information retrieved from WPCOM
192     *
193     * We store one cache for each user, as the information is internationalized based on user preferences
194     * Also, the currency is based on the user IP address
195     *
196     * @param Object $products_list The products list as received from WPCOM.
197     * @return bool
198     */
199    private static function update_cache( $products_list ) {
200        update_user_meta( get_current_user_id(), self::CACHE_DATE_META_NAME, time() );
201        update_user_meta( get_current_user_id(), self::CACHE_CHECK_HASH_NAME, self::build_check_hash() );
202        return update_user_meta( get_current_user_id(), self::CACHE_META_NAME, $products_list );
203    }
204
205    /**
206     * Checks if the cache is old, meaning we need to fetch new data from WPCOM
207     */
208    private static function is_cache_old() {
209        if ( empty( self::get_products_from_cache() ) ) {
210            return true;
211        }
212
213        // This allows the cache to reset after the site or user connects/ disconnects
214        $check_hash = get_user_meta( get_current_user_id(), self::CACHE_CHECK_HASH_NAME, true );
215        if ( $check_hash !== self::build_check_hash() ) {
216            return true;
217        }
218
219        $cache_date = get_user_meta( get_current_user_id(), self::CACHE_DATE_META_NAME, true );
220        return time() - (int) $cache_date > 5 * MINUTE_IN_SECONDS;
221    }
222
223    /**
224     * Gets the product list from the user cache
225     */
226    private static function get_products_from_cache() {
227        return get_user_meta( get_current_user_id(), self::CACHE_META_NAME, true );
228    }
229
230    /**
231     * Gets the product list
232     *
233     * Attempts to retrieve the products list from the user cache if cache is not too old.
234     * If cache is old, it will attempt to fetch information from WPCOM. If it fails, we return what we have in cache, if anything, otherwise we return an error.
235     *
236     * @param bool $skip_cache If true it will ignore the cache and attempt to fetch fresh information from WPCOM.
237     *
238     * @return Object|WP_Error
239     */
240    public static function get_products( $skip_cache = false ) {
241        // This is only available for logged in users.
242        if ( ! get_current_user_id() ) {
243            return null;
244        }
245        if ( ! self::is_cache_old() && ! $skip_cache ) {
246            return self::get_products_from_cache();
247        }
248
249        $products = self::get_products_from_wpcom();
250        if ( is_wp_error( $products ) ) {
251            // Let's see if we have it cached.
252            $cached = self::get_products_from_cache();
253            if ( is_object( $cached ) ) {
254                // Pro requires confirmed availability; existing offers retain their cached behavior.
255                $cached = clone $cached;
256                foreach ( $cached as $slug => $product ) {
257                    if ( str_starts_with( $slug, 'jetpack_pro_' ) && is_object( $product ) ) {
258                        $cached->$slug            = clone $product;
259                        $cached->$slug->available = false;
260                    }
261                }
262                return $cached;
263            } else {
264                return $products;
265            }
266        }
267
268        self::update_cache( $products );
269        return $products;
270    }
271
272    /**
273     * Get one product
274     *
275     * @param string $product_slug The product slug.
276     * @param bool   $renew_cache A flag to force the cache to be renewed.
277     *
278     * @return ?Object The product details if found
279     */
280    public static function get_product( $product_slug, $renew_cache = false ) {
281        $products = self::get_products( $renew_cache );
282        if ( ! empty( $products->$product_slug ) ) {
283            return $products->$product_slug;
284        }
285    }
286
287    /**
288     * Get only the product currency code and price in an array
289     *
290     * @param string $product_slug The product slug.
291     *
292     * @return array An array with currency_code and full_price. Empty array if product not found.
293     */
294    public static function get_product_pricing( $product_slug ) {
295        $product = self::get_product( $product_slug );
296        if ( empty( $product ) ) {
297            return array();
298        }
299
300        $cost                  = $product->cost;
301        $discount_price        = $cost;
302        $is_introductory_offer = false;
303        $introductory_offer    = null;
304
305        // Get/compute the discounted price.
306        if ( isset( $product->introductory_offer->cost_per_interval ) ) {
307            $discount_price        = $product->introductory_offer->cost_per_interval;
308            $is_introductory_offer = true;
309            $introductory_offer    = $product->introductory_offer;
310        }
311
312        $pricing = array(
313            'currency_code'         => $product->currency_code,
314            'full_price'            => $cost,
315            'discount_price'        => $discount_price,
316            'is_introductory_offer' => $is_introductory_offer,
317            'introductory_offer'    => $introductory_offer,
318            'product_term'          => $product->product_term,
319        );
320
321        return self::populate_with_discount( $product, $pricing, $discount_price );
322    }
323
324    /**
325     * Populate the pricing array with the discount information.
326     *
327     * @param object $product - The product object.
328     * @param array  $pricing - The pricing array.
329     * @param float  $price   - The price to be discounted.
330     * @return array The pricing array with the discount information.
331     */
332    public static function populate_with_discount( $product, $pricing, $price ) {
333        // Check whether the product has a coupon.
334        if ( ! isset( $product->sale_coupon ) ) {
335            return $pricing;
336        }
337
338        // Check whether it is still valid.
339        $coupon            = $product->sale_coupon;
340        $coupon_start_date = strtotime( $coupon->start_date );
341        $coupon_expires    = strtotime( $coupon->expires );
342        if ( $coupon_start_date > time() || $coupon_expires < time() ) {
343            return $pricing;
344        }
345
346        $coupon_discount = intval( $coupon->discount );
347
348        // Populate response with coupon discount.
349        $pricing['coupon_discount'] = $coupon_discount;
350
351        // Apply coupon discount to the price.
352        $pricing['discount_price'] = $price * ( 100 - $coupon_discount ) / 100;
353
354        return $pricing;
355    }
356
357    /**
358     * Gets the site purchases from WPCOM.
359     *
360     * @return Object|WP_Error
361     */
362    public static function get_site_current_purchases() {
363        // Read the cache first, so a memo can never outrank a warm lookup.
364        $stored_purchases = get_transient( self::MY_JETPACK_PURCHASES_TRANSIENT_KEY );
365        if ( $stored_purchases !== false ) {
366            return $stored_purchases;
367        }
368
369        /*
370         * Checked after the transient so it can never outrank a warm cache, but kept so a
371         * dashboard render still makes a single WPCOM request when the transient write is dropped.
372         */
373        if ( self::$site_purchases !== null && time() < self::$site_purchases_expires ) {
374            return self::$site_purchases;
375        }
376
377        $request_failure = static::get_request_failure( self::PURCHASES_REQUEST_LABEL );
378        if ( null !== $request_failure ) {
379            return $request_failure;
380        }
381
382        $site_id = Jetpack_Options::get_option( 'id' );
383
384        $response = Client::wpcom_json_api_request_as_blog(
385            sprintf( '/upgrades?site=%d', $site_id ),
386            '1.2',
387            array(
388                'method' => 'GET',
389            )
390        );
391        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
392            $error = new WP_Error( 'purchases_state_fetch_failed' );
393            static::set_request_failure( self::PURCHASES_REQUEST_LABEL, $error );
394            return $error;
395        }
396
397        $body      = wp_remote_retrieve_body( $response );
398        $purchases = json_decode( $body );
399        // Set short transient to help with repeated lookups on the same page load
400        set_transient( self::MY_JETPACK_PURCHASES_TRANSIENT_KEY, $purchases, self::MY_JETPACK_PURCHASES_CACHE_DURATION );
401
402        self::$site_purchases         = $purchases;
403        self::$site_purchases_expires = time() + self::MY_JETPACK_PURCHASES_CACHE_DURATION;
404
405        return $purchases;
406    }
407
408    /**
409     * Gets the site's currently active "plan" (bundle).
410     *
411     * @param bool $reload  Whether to refresh data from wpcom or not.
412     * @return array
413     */
414    public static function get_site_current_plan( $reload = false ) {
415        static $reloaded_already = false;
416
417        if ( $reload && ! $reloaded_already ) {
418            Current_Plan::refresh_from_wpcom();
419            $reloaded_already = true;
420        }
421
422        return Current_Plan::get();
423    }
424
425    /**
426     * Reset the request failures to retry the API requests.
427     *
428     * @return void
429     */
430    public static function reset_request_failures() {
431        static::$wpcom_request_failures = array();
432    }
433
434    /**
435     * Forget the cached site purchases â€” the in-process memo, the memoized failure, and the
436     * transient â€” so the next call asks WPCOM again.
437     *
438     * @return void
439     */
440    public static function reset_purchases_cache() {
441        self::$site_purchases         = null;
442        self::$site_purchases_expires = 0;
443        unset( static::$wpcom_request_failures[ self::PURCHASES_REQUEST_LABEL ] );
444        delete_transient( self::MY_JETPACK_PURCHASES_TRANSIENT_KEY );
445    }
446
447    /**
448     * Record the request failure to prevent repeated requests.
449     *
450     * @param string   $request_label The request label.
451     * @param WP_Error $error The error.
452     *
453     * @return void
454     */
455    private static function set_request_failure( $request_label, WP_Error $error ) {
456        static::$wpcom_request_failures[ $request_label ] = array(
457            'error'   => $error,
458            'expires' => time() + self::WPCOM_REQUEST_FAILURE_CACHE_DURATION,
459        );
460    }
461
462    /**
463     * Get the pre-saved request failure if exists.
464     *
465     * @param string $request_label The request label.
466     *
467     * @return null|WP_Error
468     */
469    private static function get_request_failure( $request_label ) {
470        if ( ! isset( static::$wpcom_request_failures[ $request_label ] ) ) {
471            return null;
472        }
473
474        // Expire rather than answer for the life of the process, which can outlast the outage.
475        if ( time() >= static::$wpcom_request_failures[ $request_label ]['expires'] ) {
476            unset( static::$wpcom_request_failures[ $request_label ] );
477            return null;
478        }
479
480        return static::$wpcom_request_failures[ $request_label ]['error'];
481    }
482}