Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.50% covered (warning)
87.50%
336 / 384
56.00% covered (warning)
56.00%
14 / 25
CRAP
0.00% covered (danger)
0.00%
0 / 1
REST_Controller
87.70% covered (warning)
87.70%
335 / 382
56.00% covered (warning)
56.00%
14 / 25
148.27
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 register
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 register_rest_routes
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 register_common_rest_routes
100.00% covered (success)
100.00%
60 / 60
100.00% covered (success)
100.00%
1 / 1
1
 register_jetpack_only_rest_routes
100.00% covered (success)
100.00%
52 / 52
100.00% covered (success)
100.00%
1 / 1
1
 register_wpcom_only_rest_routes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 require_admin_privilege_callback
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 require_valid_blog_token_callback
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_forbidden_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_search_plan
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 update_settings
74.55% covered (warning)
74.55%
41 / 55
0.00% covered (danger)
0.00%
0 / 1
37.15
 validate_search_settings
98.18% covered (success)
98.18%
54 / 55
0.00% covered (danger)
0.00%
0 / 1
41
 get_settings
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 is_reader_chat_setting_registered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_stats
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_search_results
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 activate_plan
92.50% covered (success)
92.50%
37 / 40
0.00% covered (danger)
0.00%
0 / 1
13.07
 activate_free_plan
42.86% covered (danger)
42.86%
6 / 14
0.00% covered (danger)
0.00%
0 / 1
6.99
 deactivate_plan
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 get_local_stats
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 reset_singleton_template
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
4
 resolve_singleton_template_class
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 product_pricing
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 make_proper_response
45.45% covered (danger)
45.45%
5 / 11
0.00% covered (danger)
0.00%
0 / 1
6.60
 get_blog_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * The Search Rest Controller class.
4 * Registers the REST routes for Search.
5 *
6 * @package automattic/jetpack-search
7 */
8
9namespace Automattic\Jetpack\Search;
10
11use Automattic\Jetpack\Connection\Client;
12use Automattic\Jetpack\Connection\Rest_Authentication;
13use Automattic\Jetpack\My_Jetpack\Products\Search as Search_Product;
14use Automattic\Jetpack\My_Jetpack\Products\Search_Stats as Search_Product_Stats;
15use Automattic\Jetpack\Status;
16use Jetpack_Options;
17use WP_Error;
18use WP_REST_Request;
19use WP_REST_Response;
20use WP_REST_Server;
21
22if ( ! defined( 'ABSPATH' ) ) {
23    exit( 0 );
24}
25
26/**
27 * Registers the REST routes for Search.
28 */
29class REST_Controller {
30    /**
31     * Namespace for the REST API.
32     *
33     * This is overriden with value `wpcom-orgin/jetpack/v4` for WPCOM.
34     *
35     * @var string
36     */
37    public static $namespace = 'jetpack/v4';
38    /**
39     * Whether it's run on WPCOM.
40     *
41     * @var bool
42     */
43    protected $is_wpcom;
44
45    /**
46     * Module Control object.
47     *
48     * @var Module_Control
49     */
50    protected $search_module;
51
52    /**
53     * Plan object.
54     *
55     * @var Plan
56     */
57    public $plan;
58
59    /**
60     * Constructor
61     *
62     * @param bool                $is_wpcom - Whether it's run on WPCOM.
63     * @param Module_Control|null $module_control - Module_Control object if any.
64     * @param Plan|null           $plan - Plan object if any.
65     */
66    public function __construct( $is_wpcom = false, $module_control = null, $plan = null ) {
67        $this->is_wpcom      = $is_wpcom;
68        $this->search_module = $module_control === null ? new Module_Control() : $module_control;
69        $this->plan          = $plan === null ? new Plan() : $plan;
70    }
71
72    /**
73     * Registers the REST routes on the `rest_api_init` hook.
74     *
75     * Instantiated here, rather than eagerly, so the controller class only loads
76     * on requests that reach `rest_api_init`. Static so the callback can be
77     * unregistered.
78     *
79     * @access public
80     */
81    public static function register() {
82        ( new self() )->register_rest_routes();
83    }
84
85    /**
86     * Registers the REST routes for Search.
87     *
88     * @access public
89     * @static
90     */
91    public function register_rest_routes() {
92        $this->register_common_rest_routes();
93        if ( ! Helper::is_wpcom() ) {
94            $this->register_jetpack_only_rest_routes();
95        } else {
96            $this->register_wpcom_only_rest_routes();
97        }
98    }
99
100    /**
101     * Routes both existing in Jetpack and WPCOM simple sites.
102     */
103    protected function register_common_rest_routes() {
104        register_rest_route(
105            static::$namespace,
106            '/search/plan',
107            array(
108                'methods'             => WP_REST_Server::READABLE,
109                'callback'            => array( $this, 'get_search_plan' ),
110                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
111            )
112        );
113        register_rest_route(
114            static::$namespace,
115            '/search/settings',
116            array(
117                'methods'             => WP_REST_Server::EDITABLE,
118                'callback'            => array( $this, 'update_settings' ),
119                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
120            )
121        );
122        register_rest_route(
123            static::$namespace,
124            '/search/settings',
125            array(
126                'methods'             => WP_REST_Server::READABLE,
127                'callback'            => array( $this, 'get_settings' ),
128                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
129            )
130        );
131        register_rest_route(
132            static::$namespace,
133            '/search/stats',
134            array(
135                'methods'             => WP_REST_Server::READABLE,
136                'callback'            => array( $this, 'get_stats' ),
137                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
138            )
139        );
140        register_rest_route(
141            static::$namespace,
142            '/search/pricing',
143            array(
144                'methods'             => WP_REST_Server::READABLE,
145                'callback'            => array( $this, 'product_pricing' ),
146                'permission_callback' => 'is_user_logged_in',
147            )
148        );
149        // "Restore default" for the singleton-template CPTs. Lives on
150        // jetpack/v4 (not /wp/v2/<rest_base>) so wpcom-origin can proxy it
151        // on Simple sites — the Jetpack-registered CPT controller isn't on
152        // the wpcom REST surface. The allowed `<post_type>` slugs are
153        // enforced inside the handler (single source of truth) rather than
154        // duplicated into a route-level validate_callback.
155        register_rest_route(
156            static::$namespace,
157            '/search/templates/(?P<post_type>[a-z0-9_-]+)',
158            array(
159                'methods'             => WP_REST_Server::DELETABLE,
160                'callback'            => array( $this, 'reset_singleton_template' ),
161                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
162                'args'                => array(
163                    'post_type' => array(
164                        'required'          => true,
165                        'sanitize_callback' => 'sanitize_key',
166                    ),
167                ),
168            )
169        );
170    }
171
172    /**
173     * Routes only existing in Jetpack.
174     */
175    protected function register_jetpack_only_rest_routes() {
176        register_rest_route(
177            static::$namespace,
178            '/search/plan/activate',
179            array(
180                'methods'             => WP_REST_Server::EDITABLE,
181                'callback'            => array( $this, 'activate_plan' ),
182                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
183            )
184        );
185        register_rest_route(
186            static::$namespace,
187            '/search/plan/activate-free',
188            array(
189                'methods'             => WP_REST_Server::EDITABLE,
190                'callback'            => array( $this, 'activate_free_plan' ),
191                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
192                'args'                => array(
193                    'source' => array(
194                        'type'              => 'string',
195                        'required'          => false,
196                        'sanitize_callback' => 'sanitize_key',
197                    ),
198                ),
199            )
200        );
201        register_rest_route(
202            static::$namespace,
203            '/search/plan/deactivate',
204            array(
205                'methods'             => WP_REST_Server::EDITABLE,
206                'callback'            => array( $this, 'deactivate_plan' ),
207                'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
208            )
209        );
210        register_rest_route(
211            static::$namespace,
212            '/search',
213            array(
214                'methods'             => WP_REST_Server::READABLE,
215                'callback'            => array( $this, 'get_search_results' ),
216                'permission_callback' => 'is_user_logged_in',
217            )
218        );
219        register_rest_route(
220            static::$namespace,
221            '/search/local-stats',
222            array(
223                'methods'             => WP_REST_Server::READABLE,
224                'callback'            => array( $this, 'get_local_stats' ),
225                'permission_callback' => array( $this, 'require_valid_blog_token_callback' ),
226            )
227        );
228    }
229
230    /**
231     * Routes only existing in WPCOM.
232     *
233     * We currently don't have any.
234     */
235    protected function register_wpcom_only_rest_routes() {
236        return true;
237    }
238
239    /**
240     * Only administrators can access the API.
241     *
242     * @return bool|WP_Error True if a blog token was used to sign the request, WP_Error otherwise.
243     */
244    public function require_admin_privilege_callback() {
245        if ( current_user_can( 'manage_options' ) ) {
246            return true;
247        }
248
249        return $this->get_forbidden_error();
250    }
251
252    /**
253     * The corresponding endpoints can only be accessible from WPCOM.
254     *
255     * @access public
256     * @static
257     *
258     * @return bool|WP_Error True if a blog token was used to sign the request, WP_Error otherwise.
259     */
260    public function require_valid_blog_token_callback() {
261        if ( Rest_Authentication::is_signed_with_blog_token() ) {
262            return true;
263        }
264
265        return $this->get_forbidden_error();
266    }
267
268    /**
269     * Return a WP_Error object with a forbidden error.
270     */
271    protected function get_forbidden_error() {
272        $error_msg = esc_html__(
273            'You are not allowed to perform this action.',
274            'jetpack-search-pkg'
275        );
276
277        return new WP_Error( 'rest_forbidden', $error_msg, array( 'status' => rest_authorization_required_code() ) );
278    }
279
280    /**
281     * Return the stored plan offline, or refresh it from WPCOM online.
282     *
283     * GET `jetpack/v4/search/plan`
284     */
285    public function get_search_plan() {
286        if ( ( new Status() )->is_offline_mode() ) {
287            $plan_info = ( new Plan() )->get_plan_info();
288            return false === $plan_info
289                ? new WP_Error( 'site_offline', 'Site is in offline mode.', array( 'status' => 503 ) )
290                : $plan_info;
291        }
292        $response = ( new Plan() )->get_plan_info_from_wpcom();
293        return $this->make_proper_response( $response );
294    }
295
296    /**
297     * POST `jetpack/v4/search/settings`
298     *
299     * @param WP_REST_Request $request - REST request.
300     */
301    public function update_settings( $request ) {
302        $request_body = $request->get_json_params();
303        if ( ! is_array( $request_body ) ) {
304            $request_body = array();
305        }
306
307        $module_active                 = isset( $request_body['module_active'] ) ? (bool) $request_body['module_active'] : null;
308        $instant_search_enabled        = isset( $request_body['instant_search_enabled'] ) ? (bool) $request_body['instant_search_enabled'] : null;
309        $swap_classic_to_inline_search = isset( $request_body['swap_classic_to_inline_search'] ) ? (bool) $request_body['swap_classic_to_inline_search'] : null;
310        $experience                    = isset( $request_body['experience'] ) && is_string( $request_body['experience'] )
311            ? sanitize_text_field( $request_body['experience'] )
312            : null;
313        $reader_chat                   = array_key_exists( 'reader_chat', $request_body ) ? (bool) $request_body['reader_chat'] : null;
314        // rest_sanitize_boolean(), not (bool): this value now drives the paid-plan
315        // gate below, and a plain (bool) cast reads a JSON `"false"` string as true.
316        $ai_answers_enabled = isset( $request_body['ai_answers_enabled'] ) ? rest_sanitize_boolean( $request_body['ai_answers_enabled'] ) : null;
317
318        $search_suggestions_enabled = isset( $request_body['search_suggestions_enabled'] ) ? (bool) $request_body['search_suggestions_enabled'] : null;
319
320        $override_woocommerce_search_template = isset( $request_body['override_woocommerce_search_template'] ) ? (bool) $request_body['override_woocommerce_search_template'] : null;
321
322        $error = $this->validate_search_settings( $module_active, $instant_search_enabled, $swap_classic_to_inline_search, $experience, $reader_chat, $ai_answers_enabled, $search_suggestions_enabled, $override_woocommerce_search_template );
323
324        if ( is_wp_error( $error ) ) {
325            return $error;
326        }
327
328        // If an experience value was provided, delegate to Module_Control::update_experience(),
329        // which encapsulates the storage shape (off → module deactivate, inline → delete option,
330        // embedded/overlay → write affirmative value) and keeps the legacy booleans in lockstep.
331        if ( $experience !== null ) {
332            $result = $this->search_module->update_experience( $experience );
333            if ( is_wp_error( $result ) ) {
334                return $result;
335            }
336            return rest_ensure_response( $this->get_settings() );
337        }
338
339        // Enabling instant search should enable the module too.
340        if ( true === $instant_search_enabled && true !== $module_active ) {
341            $module_active = true;
342        }
343
344        $errors = array();
345        if ( $module_active !== null ) {
346            $module_active_updated = $this->search_module->update_status( $module_active );
347            if ( is_wp_error( $module_active_updated ) ) {
348                $errors['module_active'] = $module_active_updated;
349            }
350        }
351
352        if ( $instant_search_enabled !== null ) {
353            $instant_search_enabled_updated = $this->search_module->update_instant_search_status( $instant_search_enabled );
354            if ( is_wp_error( $instant_search_enabled_updated ) ) {
355                $errors['instant_search_enabled'] = $instant_search_enabled_updated;
356            }
357        }
358
359        if ( $swap_classic_to_inline_search !== null ) {
360            $this->search_module->update_swap_classic_to_inline_search( $swap_classic_to_inline_search );
361        }
362
363        if ( $reader_chat !== null ) {
364            update_option( 'reader_chat', $reader_chat );
365        }
366
367        if ( $ai_answers_enabled !== null ) {
368            update_option( 'jetpack_search_ai_answers_enabled', $ai_answers_enabled );
369        }
370        if ( $search_suggestions_enabled !== null ) {
371            update_option( 'jetpack_search_suggestions_enabled', $search_suggestions_enabled );
372        }
373        if ( $override_woocommerce_search_template !== null ) {
374            update_option( 'jetpack_search_override_woocommerce_search_template', $override_woocommerce_search_template );
375        }
376
377        if ( ! empty( $errors ) ) {
378            return new WP_Error(
379                'some_updated',
380                sprintf(
381                    /* translators: %s are the setting name that not updated. */
382                    __( 'Some settings ( %s ) not updated.', 'jetpack-search-pkg' ),
383                    implode(
384                        ',',
385                        array_keys( $errors )
386                    )
387                ),
388                array( 'status' => 400 )
389            );
390        }
391
392        return rest_ensure_response( $this->get_settings() );
393    }
394
395    /**
396     * Validate $module_active and $instant_search_enabled. Returns an WP_Error instance if invalid.
397     *
398     * @param boolean     $module_active - Module status.
399     * @param boolean     $instant_search_enabled - Instant Search status.
400     * @param boolean     $swap_classic_to_inline_search - New inline search status.
401     * @param string|null $experience - Experience value.
402     * @param bool|null   $reader_chat - Reader Chat status.
403     * @param bool|null   $ai_answers_enabled - Whether Jetpack Search AI answers is enabled.
404     * @param bool|null   $search_suggestions_enabled - New search suggestions status.
405     * @param bool|null   $override_woocommerce_search_template - New WooCommerce search-template override status.
406     */
407    protected function validate_search_settings( $module_active, $instant_search_enabled, $swap_classic_to_inline_search, $experience = null, $reader_chat = null, $ai_answers_enabled = null, $search_suggestions_enabled = null, $override_woocommerce_search_template = null ) {
408        if ( $reader_chat !== null && ! $this->is_reader_chat_setting_registered() ) {
409            return new WP_Error(
410                'rest_invalid_arguments',
411                esc_html__( 'The arguments passed in are invalid.', 'jetpack-search-pkg' ),
412                array( 'status' => 400 )
413            );
414        }
415
416        // AI Answers cannot be turned on while the site-wide Jetpack AI switch is
417        // off. Turning it off stays allowed, so a saved choice can still be cleared.
418        if ( true === $ai_answers_enabled && ! AI_Answers::is_master_enabled() ) {
419            return new WP_Error(
420                'rest_invalid_arguments',
421                esc_html__( 'AI Answers cannot be enabled while Jetpack AI is turned off for this site.', 'jetpack-search-pkg' ),
422                array( 'status' => 400 )
423            );
424        }
425
426        // AI Answers runs inside Instant Search, so enabling it requires Instant
427        // Search on — either already, or turned on by this same request.
428        if ( true === $ai_answers_enabled && true !== $instant_search_enabled && ! $this->search_module->is_instant_search_enabled() ) {
429            return new WP_Error(
430                'rest_invalid_arguments',
431                esc_html__( 'AI Answers cannot be enabled while Instant Search is off.', 'jetpack-search-pkg' ),
432                array( 'status' => 400 )
433            );
434        }
435
436        // `experience` is the canonical source of truth and writes the legacy booleans in lockstep.
437        // Reject requests that mix it with any other settings field so callers don't silently
438        // lose those fields — the `experience` branch in update_settings() early-returns and
439        // would otherwise drop them.
440        if ( $experience !== null ) {
441            if ( $module_active !== null || $instant_search_enabled !== null || $swap_classic_to_inline_search !== null || $reader_chat !== null || $ai_answers_enabled !== null || $search_suggestions_enabled !== null || $override_woocommerce_search_template !== null ) {
442                return new WP_Error(
443                    'rest_invalid_arguments',
444                    esc_html__( 'The `experience` field cannot be combined with `module_active`, `instant_search_enabled`, `swap_classic_to_inline_search`, `reader_chat`, `ai_answers_enabled`, `search_suggestions_enabled`, or `override_woocommerce_search_template`.', 'jetpack-search-pkg' ),
445                    array( 'status' => 400 )
446                );
447            }
448            return true;
449        }
450
451        if ( true === $reader_chat && ( ! $this->plan->supports_search() || $this->plan->is_free_plan() ) ) {
452            return new WP_Error(
453                'rest_forbidden',
454                esc_html__( 'Site Chat requires a paid Jetpack Search plan.', 'jetpack-search-pkg' ),
455                array( 'status' => 403 )
456            );
457        }
458
459        // AI Answers requires a paid Search plan; reject the write outright.
460        if ( true === $ai_answers_enabled && ! Search_Blocks::supports_paid_search() ) {
461            return new WP_Error(
462                'rest_forbidden',
463                esc_html__( 'AI Answers requires a paid Jetpack Search plan.', 'jetpack-search-pkg' ),
464                array( 'status' => 403 )
465            );
466        }
467
468        if (
469            $module_active === null &&
470            $instant_search_enabled === null &&
471            ( $swap_classic_to_inline_search !== null || $reader_chat !== null )
472        ) {
473            // Allow updating auxiliary settings without updating/validating the module settings.
474            return true;
475        }
476        if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $ai_answers_enabled !== null ) {
477            // allow updating 'ai_answers_enabled' without updating/validating other settings.
478            return true;
479        }
480        if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $search_suggestions_enabled !== null ) {
481            // allow updating 'search_suggestions_enabled' without updating/validating other settings.
482            return true;
483        }
484        if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $override_woocommerce_search_template !== null ) {
485            // allow updating 'override_woocommerce_search_template' without updating/validating other settings.
486            return true;
487        }
488        if ( ( true === $instant_search_enabled && false === $module_active ) || ( $module_active === null && $instant_search_enabled === null ) ) {
489            return new WP_Error(
490                'rest_invalid_arguments',
491                esc_html__( 'The arguments passed in are invalid.', 'jetpack-search-pkg' ),
492                array( 'status' => 400 )
493            );
494        }
495        return true;
496    }
497
498        /**
499         *     GET `jetpack/v4/search/settings`
500         */
501    public function get_settings() {
502        $settings = array(
503            'module_active'                        => $this->search_module->is_active(),
504            'instant_search_enabled'               => $this->search_module->is_instant_search_enabled(),
505            'swap_classic_to_inline_search'        => $this->search_module->is_swap_classic_to_inline_search(),
506            'experience'                           => $this->search_module->get_experience(),
507            'ai_answers_enabled'                   => AI_Answers::is_enabled(),
508            'ai_answers_saved'                     => AI_Answers::is_saved_on(),
509            'ai_master_enabled'                    => AI_Answers::is_master_enabled(),
510            'search_suggestions_enabled'           => (bool) get_option( 'jetpack_search_suggestions_enabled', false ),
511            'override_woocommerce_search_template' => Search_Blocks::woocommerce_search_template_override_enabled(),
512        );
513
514        if ( $this->is_reader_chat_setting_registered() ) {
515            $settings['reader_chat'] = (bool) get_option( 'reader_chat', false );
516        }
517
518        return rest_ensure_response( $settings );
519    }
520
521    /**
522     * Check whether Reader Chat is available through REST settings in this request.
523     *
524     * Reader Chat registers `reader_chat` only for proxied rollout contexts, so the
525     * Search dashboard should expose the toggle only when that setting exists.
526     *
527     * @return bool True when reader_chat is registered.
528     */
529    protected function is_reader_chat_setting_registered() {
530        return array_key_exists( 'reader_chat', get_registered_settings() );
531    }
532
533    /**
534     * Proxy the request to WPCOM and return the response.
535     *
536     * GET `jetpack/v4/search/stats`
537     */
538    public function get_stats() {
539        $response = ( new Stats() )->get_stats_from_wpcom();
540        return $this->make_proper_response( $response );
541    }
542
543    /**
544     * Search Endpoint for private sites.
545     *
546     * GET `jetpack/v4/search`
547     *
548     * @param WP_REST_Request $request - REST request.
549     */
550    public function get_search_results( $request ) {
551        $blog_id  = $this->get_blog_id();
552        $path     = sprintf( '/sites/%d/search', absint( $blog_id ) );
553        $path     = add_query_arg(
554            $request->get_query_params(),
555            sprintf( '/sites/%d/search', absint( $blog_id ) )
556        );
557        $response = Client::wpcom_json_api_request_as_blog( $path, '1.3', array(), null, 'rest' );
558        return rest_ensure_response( $this->make_proper_response( $response ) );
559    }
560
561    /**
562     * Activate plan: activate the search module, instant search and do initial configuration.
563     * Typically called from WPCOM.
564     *
565     * POST `jetpack/v4/search/plan/activate`
566     *
567     * @param WP_REST_Request $request - REST request.
568     */
569    public function activate_plan( $request ) {
570        $default_options = array(
571            'search_plan_info'      => null,
572            'enable_search'         => true,
573            'enable_instant_search' => true,
574            'search_experience'     => null,
575            'auto_config_search'    => true,
576        );
577        $payload         = $request->get_json_params();
578        $payload         = wp_parse_args( $payload, $default_options );
579
580        // Update plan data, plan info is in the request body.
581        // We do this to avoid another call to WPCOM and reduce latency.
582        if ( $payload['search_plan_info'] === null || ! $this->plan->set_plan_options( $payload['search_plan_info'] ) ) {
583            $this->plan->get_plan_info_from_wpcom();
584        }
585
586        // Enable search module by default, unless `enable_search` is explicitly set to boolean `false`.
587        if ( false !== $payload['enable_search'] ) {
588            $ret = $this->search_module->activate();
589            if ( is_wp_error( $ret ) ) {
590                return $ret;
591            }
592        }
593
594        if ( $payload['search_experience'] !== null ) {
595            // Canonical path. Restrict to activate-able experiences — `off`
596            // belongs on `/plan/deactivate`, and a non-string payload would
597            // blow up `update_experience(string $experience)`.
598            $valid_experiences = array(
599                Module_Control::EXPERIENCE_OVERLAY,
600                Module_Control::EXPERIENCE_INLINE,
601                Module_Control::EXPERIENCE_EMBEDDED,
602            );
603            if ( ! is_string( $payload['search_experience'] )
604                || ! in_array( $payload['search_experience'], $valid_experiences, true )
605            ) {
606                return new WP_Error(
607                    'invalid_experience',
608                    __( 'Invalid experience value.', 'jetpack-search-pkg' ),
609                    array( 'status' => 400 )
610                );
611            }
612            $ret = $this->search_module->update_experience( sanitize_text_field( $payload['search_experience'] ) );
613            if ( is_wp_error( $ret ) ) {
614                return $ret;
615            }
616        }
617
618        if ( $payload['search_experience'] === null && false !== $payload['enable_instant_search'] ) {
619            // Legacy path: old WPCOM callers send `enable_instant_search`
620            // instead of `search_experience`. Gated on the canonical value
621            // being absent so it doesn't overwrite a non-overlay experience
622            // the caller just set.
623            // Error handling intentionally skipped — this is the legacy fallback.
624            $ret = $this->search_module->enable_instant_search();
625        }
626
627        // `auto_config_search` wires up Overlay sidebar widgets — only meaningful
628        // when Overlay is the resulting experience. For Inline / Embedded, the
629        // caller would otherwise get widget side effects they didn't ask for.
630        if ( false !== $payload['auto_config_search'] && $this->search_module->is_instant_search_enabled() ) {
631            Instant_Search::instance( $this->get_blog_id() )->auto_config_search();
632        }
633
634        return rest_ensure_response(
635            array(
636                'code' => 'success',
637            )
638        );
639    }
640
641    /**
642     * Grant the free Search product to this site instead of sending the user to a $0 checkout.
643     *
644     * POST `jetpack/v4/search/plan/activate-free`
645     *
646     * @since 8.3.0
647     *
648     * @param WP_REST_Request $request - REST request.
649     * @return WP_REST_Response|WP_Error Errors carry `checkout_fallback`, which the dashboard
650     *                                   branches on to decide whether to fall back to checkout.
651     */
652    public function activate_free_plan( $request ) {
653        /*
654         * Another plugin can load an older My Jetpack before this package's copy registers, and
655         * that copy has no such method. Degrade to the checkout the dashboard still has.
656         */
657        if ( ! method_exists( Search_Product::class, 'activate_free_product' ) ) {
658            return new WP_Error(
659                'jetpack_search_free_activation_unavailable',
660                __( 'Jetpack Search Free could not be activated for this site.', 'jetpack-search-pkg' ),
661                array(
662                    'status'            => 501,
663                    'checkout_fallback' => true,
664                )
665            );
666        }
667
668        $source = $request->get_param( 'source' );
669        $result = Search_Product::activate_free_product( $source ? $source : 'search-dashboard' );
670        if ( is_wp_error( $result ) ) {
671            return $result;
672        }
673
674        return rest_ensure_response( $result );
675    }
676
677    /**
678     * Deactivate plan: turn off search module and instant search.
679     * If the plan is still valid then the function would simply deactivate the search module.
680     * Typically called from WPCOM.
681     *
682     * POST `jetpack/v4/search/plan/deactivate`
683     */
684    public function deactivate_plan() {
685        // Instant Search would be disabled along with search module.
686        $this->search_module->deactivate();
687        return rest_ensure_response(
688            array(
689                'code' => 'success',
690            )
691        );
692    }
693
694    /**
695     * Return post type breakdown for the site.
696     */
697    public function get_local_stats() {
698        return array(
699            'post_count'          => Search_Product_Stats::estimate_count(),
700            'post_type_breakdown' => Search_Product_Stats::get_post_type_breakdown(),
701        );
702    }
703
704    /**
705     * Force-delete the {@see Singleton_Template_Cpt} customization for the
706     * requested post type, backing the dashboard's "Restore default" link.
707     * `before_delete_post` in the base class clears the option pointer +
708     * per-request cache so the next render falls back to the bundled template.
709     *
710     * DELETE `jetpack/v4/search/templates/<post_type>`
711     *
712     * @param WP_REST_Request $request - REST request.
713     * @return WP_REST_Response|WP_Error
714     */
715    public function reset_singleton_template( $request ) {
716        $cpt_class = $this->resolve_singleton_template_class( $request['post_type'] );
717        if ( ! $cpt_class ) {
718            return new WP_Error(
719                'jetpack_search_template_unknown',
720                __( 'Unknown search template.', 'jetpack-search-pkg' ),
721                array( 'status' => 404 )
722            );
723        }
724        if ( ! $cpt_class::is_customized() ) {
725            return new WP_Error(
726                'jetpack_search_template_not_customized',
727                __( 'No customization to restore.', 'jetpack-search-pkg' ),
728                array( 'status' => 404 )
729            );
730        }
731        $post_id = $cpt_class::get_post_id();
732        if ( ! wp_delete_post( $post_id, true ) ) {
733            return new WP_Error(
734                'jetpack_search_template_reset_failed',
735                __( 'Failed to restore the default template.', 'jetpack-search-pkg' ),
736                array( 'status' => 500 )
737            );
738        }
739        return rest_ensure_response( array( 'deleted' => true ) );
740    }
741
742    /**
743     * Map a CPT slug to its concrete `Singleton_Template_Cpt` subclass.
744     * Returns null when the slug isn't one of the registered singleton-template
745     * CPTs — the route only sanitizes the slug (via `sanitize_key`), so this
746     * lookup is the primary "is this a known CPT?" filter, not a backup check.
747     *
748     * @param string $post_type Post type slug from the request.
749     * @return class-string<Singleton_Template_Cpt>|null
750     */
751    protected function resolve_singleton_template_class( $post_type ) {
752        $map = array(
753            Overlay_Template::POST_TYPE         => Overlay_Template::class,
754            Product_Overlay_Template::POST_TYPE => Product_Overlay_Template::class,
755            Search_Template::POST_TYPE          => Search_Template::class,
756            Product_Search_Template::POST_TYPE  => Product_Search_Template::class,
757        );
758        return $map[ $post_type ] ?? null;
759    }
760
761    /**
762     * Pricing for record count of the site
763     */
764    public function product_pricing() {
765        $tier_pricing = Search_Product::get_pricing_for_ui();
766        // we can force the plugin to use the new pricing by appending `new_pricing_202208=1` to URL.
767        if ( Helper::is_forced_new_pricing_202208() ) {
768            $tier_pricing['pricing_version'] = Plan::JETPACK_SEARCH_NEW_PRICING_VERSION;
769        }
770        return rest_ensure_response( $tier_pricing );
771    }
772
773    /**
774     * Forward remote response to client with error handling.
775     *
776     * @param array|WP_Error $response - Response from WPCOM.
777     */
778    protected function make_proper_response( $response ) {
779        if ( is_wp_error( $response ) ) {
780            return $response;
781        }
782
783        $body        = json_decode( wp_remote_retrieve_body( $response ), true );
784        $status_code = wp_remote_retrieve_response_code( $response );
785
786        if ( 200 === $status_code ) {
787            return $body;
788        }
789
790        return new WP_Error(
791            isset( $body['error'] ) ? 'remote-error-' . $body['error'] : 'remote-error',
792            $body['message'] ?? 'unknown remote error',
793            array( 'status' => $status_code )
794        );
795    }
796
797    /**
798     * Get blog id
799     */
800    protected function get_blog_id() {
801        return $this->is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
802    }
803}