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