Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.95% covered (warning)
78.95%
75 / 95
57.89% covered (warning)
57.89%
11 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Search
79.57% covered (warning)
79.57%
74 / 93
57.89% covered (warning)
57.89%
11 / 19
50.31
0.00% covered (danger)
0.00%
0 / 1
 get_name
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_title
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_description
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_long_description
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_features
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 get_pricing_for_ui
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
3
 get_post_checkout_url
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_wpcom_product_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_wpcom_free_product_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_new_pricing_202208
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
4.05
 get_status
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_pricing_from_wpcom
89.29% covered (warning)
89.29%
25 / 28
0.00% covered (danger)
0.00%
0 / 1
8.08
 has_trial_support
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_paid_plan_product_slugs
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 has_free_plan_for_product
37.50% covered (danger)
37.50%
3 / 8
0.00% covered (danger)
0.00%
0 / 1
14.79
 do_product_specific_activation
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 get_post_activation_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_manage_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_upgradable_by_bundle
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Search product
4 *
5 * @package my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack\Products;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Constants;
13use Automattic\Jetpack\My_Jetpack\Hybrid_Product;
14use Automattic\Jetpack\My_Jetpack\Wpcom_Products;
15use Automattic\Jetpack\Search\Module_Control as Search_Module_Control;
16use WP_Error;
17
18if ( ! defined( 'ABSPATH' ) ) {
19    exit( 0 );
20}
21
22/**
23 * Class responsible for handling the Search product
24 */
25class Search extends Hybrid_Product {
26    /**
27     * Fallback starting price (USD, billed yearly) for the entry record tier, used when
28     * the WPCOM pricing fetch fails so the dashboard still shows a price, not "$0".
29     *
30     * @var float
31     */
32    const FALLBACK_STARTING_PRICE_USD = 100;
33
34    /**
35     * Search "new pricing" version identifier (introduced 202208).
36     *
37     * Intentionally duplicated from Automattic\Jetpack\Search\Plan::JETPACK_SEARCH_NEW_PRICING_VERSION
38     * rather than referencing that class. My Jetpack is bundled into standalone plugins (e.g. Jetpack
39     * Boost) that do NOT ship the jetpack-search package, so referencing Search\Plan here fatals with
40     * "Class not found" the moment this product builds its pricing data (introduced by PR #48892).
41     *
42     * @var string
43     */
44    const SEARCH_NEW_PRICING_VERSION = '202208';
45
46    /**
47     * The product slug
48     *
49     * @var string
50     */
51    public static $slug = 'search';
52
53    /**
54     * The Jetpack module name
55     *
56     * @var string
57     */
58    public static $module_name = 'search';
59
60    /**
61     * The slug of the plugin associated with this product.
62     *
63     * @var string
64     */
65    public static $plugin_slug = 'jetpack-search';
66
67    /**
68     * The category of the product
69     *
70     * @var string
71     */
72    public static $category = 'performance';
73
74    /**
75     * Search has a standalone plugin
76     *
77     * @var bool
78     */
79    public static $has_standalone_plugin = true;
80
81    /**
82     * Whether this product has a free offering
83     *
84     * @var bool
85     */
86    public static $has_free_offering = true;
87
88    /**
89     * Whether this product requires a plan to work at all
90     *
91     * @var bool
92     */
93    public static $requires_plan = true;
94
95    /**
96     * The filename (id) of the plugin associated with this product.
97     *
98     * @var string
99     */
100    public static $plugin_filename = array(
101        'jetpack-search/jetpack-search.php',
102        'search/jetpack-search.php',
103        'jetpack-search-dev/jetpack-search.php',
104    );
105
106    /**
107     * Search only requires site connection
108     *
109     * @var boolean
110     */
111    public static $requires_user_connection = true;
112
113    /**
114     * The feature slug that identifies the paid plan
115     *
116     * @var string
117     */
118    public static $feature_identifying_paid_plan = 'search';
119
120    /**
121     * Get the product name
122     *
123     * @return string
124     */
125    public static function get_name() {
126        return 'Search';
127    }
128
129    /**
130     * Get the product title
131     *
132     * @return string
133     */
134    public static function get_title() {
135        return 'Jetpack Search';
136    }
137
138    /**
139     * Get the internationalized product description
140     *
141     * @return string
142     */
143    public static function get_description() {
144        return __( 'Instantly deliver the most relevant results to your visitors.', 'jetpack-my-jetpack' );
145    }
146
147    /**
148     * Get the internationalized product long description
149     *
150     * @return string
151     */
152    public static function get_long_description() {
153        return __( 'Help your site visitors find answers instantly so they keep reading and buying. Great for sites with a lot of content.', 'jetpack-my-jetpack' );
154    }
155
156    /**
157     * Get the internationalized features list
158     *
159     * @return array Boost features list
160     */
161    public static function get_features() {
162        return array(
163            __( 'Instant search and indexing', 'jetpack-my-jetpack' ),
164            __( 'Powerful filtering', 'jetpack-my-jetpack' ),
165            __( 'Supports 38 languages', 'jetpack-my-jetpack' ),
166            __( 'Spelling correction', 'jetpack-my-jetpack' ),
167        );
168    }
169
170    /**
171     * Get the product princing details
172     *
173     * @return array Pricing details
174     */
175    public static function get_pricing_for_ui() {
176        // Basic pricing info.
177        $pricing = array_merge(
178            array(
179                'available'               => true,
180                'trial_available'         => static::has_trial_support(),
181                'wpcom_product_slug'      => static::get_wpcom_product_slug(),
182                'wpcom_free_product_slug' => static::get_wpcom_free_product_slug(),
183            ),
184            Wpcom_Products::get_product_pricing( static::get_wpcom_product_slug() )
185        );
186
187        $record_count   = intval( Search_Stats::estimate_count() );
188        $search_pricing = static::get_pricing_from_wpcom( $record_count );
189
190        if ( is_wp_error( $search_pricing ) ) {
191            // Default to the current pricing experience when the WPCOM fetch fails so the
192            // dashboard degrades to the production default, not the legacy single-card view.
193            $pricing['pricing_version'] = self::SEARCH_NEW_PRICING_VERSION;
194
195            // If the generic product pricing was also unavailable, fall back to a USD
196            // starting price so the pricing grid renders a price instead of "$0".
197            if ( empty( $pricing['full_price'] ) ) {
198                $pricing['currency_code']  = 'USD';
199                $pricing['full_price']     = self::FALLBACK_STARTING_PRICE_USD;
200                $pricing['discount_price'] = self::FALLBACK_STARTING_PRICE_USD;
201            }
202
203            return $pricing;
204        }
205
206        $pricing['estimated_record_count'] = $record_count;
207
208        return array_merge( $pricing, $search_pricing );
209    }
210
211    /**
212     * Get the URL the user is taken after purchasing the product through the checkout
213     *
214     * @return ?string
215     */
216    public static function get_post_checkout_url() {
217        return self::get_manage_url();
218    }
219
220    /**
221     * Get the WPCOM product slug used to make the purchase
222     *
223     * @return ?string
224     */
225    public static function get_wpcom_product_slug() {
226        return 'jetpack_search';
227    }
228
229    /**
230     * Get the WPCOM free product slug
231     *
232     * @return ?string
233     */
234    public static function get_wpcom_free_product_slug() {
235        return 'jetpack_search_free';
236    }
237
238    /**
239     * Returns true if the new_pricing_202208 is set to not empty in URL for testing purpose, or it's active.
240     */
241    public static function is_new_pricing_202208() {
242        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
243        if ( isset( $_GET['new_pricing_202208'] ) && $_GET['new_pricing_202208'] ) {
244            return true;
245        }
246
247        $record_count   = intval( Search_Stats::estimate_count() );
248        $search_pricing = static::get_pricing_from_wpcom( $record_count );
249        if ( is_wp_error( $search_pricing ) ) {
250            // Default to the current pricing experience when the WPCOM fetch fails.
251            return true;
252        }
253
254        return self::SEARCH_NEW_PRICING_VERSION === $search_pricing['pricing_version'];
255    }
256
257    /**
258     * Override status to `needs_activation` when status is `needs_plan`.
259     */
260    public static function get_status() {
261        $status = parent::get_status();
262        return $status;
263    }
264
265    /**
266     * Use centralized Search pricing API.
267     *
268     * The function is also used by the search package, as a result it could be called before site connection - i.e. blog token might not be available.
269     *
270     * @param int $record_count Record count to estimate pricing.
271     *
272     * @return array|WP_Error
273     */
274    public static function get_pricing_from_wpcom( $record_count ) {
275        static $pricings = array();
276        $connection      = new Connection_Manager();
277        $blog_id         = \Jetpack_Options::get_option( 'id' );
278
279        if ( isset( $pricings[ $record_count ] ) ) {
280            return $pricings[ $record_count ];
281        }
282
283        // If the site is connected, request pricing with the blog token
284        if ( $blog_id ) {
285            $endpoint = sprintf( '/jetpack-search/pricing?record_count=%1$d&locale=%2$s', $record_count, get_user_locale() );
286
287            // If available in the user data, set the user's currency as one of the params
288            if ( $connection->is_user_connected() ) {
289                $user_details = $connection->get_connected_user_data();
290                if ( ! empty( $user_details['user_currency'] ) && $user_details['user_currency'] !== 'USD' ) {
291                    $endpoint .= sprintf( '&currency=%s', $user_details['user_currency'] );
292                }
293            }
294
295            $response = Client::wpcom_json_api_request_as_blog(
296                $endpoint,
297                '2',
298                array( 'timeout' => 5 ),
299                null,
300                'wpcom'
301            );
302        } else {
303            $response = wp_remote_get(
304                sprintf( Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ) . '/wpcom/v2/jetpack-search/pricing?record_count=%1$d&locale=%2$s', $record_count, get_user_locale() ),
305                array( 'timeout' => 5 )
306            );
307        }
308
309        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
310            // Cache the failure too: get_pricing_for_ui() reaches this twice per request
311            // (once via has_trial_support(), once directly), and each miss is a 5s timeout.
312            $pricings[ $record_count ] = new WP_Error( 'search_pricing_fetch_failed' );
313            return $pricings[ $record_count ];
314        }
315
316        $body                      = wp_remote_retrieve_body( $response );
317        $pricings[ $record_count ] = json_decode( $body, true );
318        return $pricings[ $record_count ];
319    }
320
321    /**
322     * Checks whether the product supports trial or not
323     *
324     * Returns true if it supports. Return false otherwise.
325     *
326     * Free products will always return false.
327     *
328     * @return boolean
329     */
330    public static function has_trial_support() {
331        return static::is_new_pricing_202208();
332    }
333
334    /**
335     * Get the product-slugs of the paid plans for this product (not including bundles)
336     *
337     * @return array
338     */
339    public static function get_paid_plan_product_slugs() {
340        return array(
341            'jetpack_search',
342            'jetpack_search_monthly',
343            'jetpack_search_bi_yearly',
344        );
345    }
346
347    /**
348     * Checks if the site purchases contain a free search plan
349     *
350     * @return bool
351     */
352    public static function has_free_plan_for_product() {
353        $purchases_data = Wpcom_Products::get_site_current_purchases();
354        if ( is_wp_error( $purchases_data ) ) {
355            return false;
356        }
357        if ( is_array( $purchases_data ) && ! empty( $purchases_data ) ) {
358            foreach ( $purchases_data as $purchase ) {
359                if ( str_contains( $purchase->product_slug, 'jetpack_search_free' ) ) {
360                    return true;
361                }
362            }
363        }
364        return false;
365    }
366
367    /**
368     * Activates the product. Try to enable instant search after the Search module was enabled.
369     *
370     * @param bool|WP_Error $product_activation Is the result of the top level activation actions. You probably won't do anything if it is an WP_Error.
371     * @return bool|WP_Error
372     */
373    public static function do_product_specific_activation( $product_activation ) {
374        $product_activation = parent::do_product_specific_activation( $product_activation );
375        if ( is_wp_error( $product_activation ) ) {
376            return $product_activation;
377        }
378
379        if ( class_exists( 'Automattic\Jetpack\Search\Module_Control' ) ) {
380            ( new Search_Module_Control() )->enable_instant_search();
381        }
382
383        // we don't want to change the success of the activation if we fail to activate instant search. That's not mandatory.
384        return $product_activation;
385    }
386
387    /**
388     * Get the URL the user is taken after activating the product
389     *
390     * @return ?string
391     */
392    public static function get_post_activation_url() {
393        return ''; // stay in My Jetpack page or continue the purchase flow if needed.
394    }
395
396    /**
397     * Get the URL where the user manages the product
398     *
399     * @return ?string
400     */
401    public static function get_manage_url() {
402        return admin_url( 'admin.php?page=jetpack-search' );
403    }
404
405    /**
406     * Return product bundles list
407     * that supports the product.
408     *
409     * @return boolean|array Products bundle list.
410     */
411    public static function is_upgradable_by_bundle() {
412        return array( 'complete' );
413    }
414}