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