PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.2
Jetpack – WP Security, Backup, Speed, & Growth v16.2
16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 All 506 releases
jetpack / jetpack_vendor / automattic / jetpack-search / src / class-rest-controller.php

class-rest-controller.php in Jetpack – WP Security, Backup, Speed, & Growth 16.2, at jetpack_vendor/automattic/jetpack-search/src/class-rest-controller.php

737 lines 25.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * The Search Rest Controller class.
4 * Registers the REST routes for Search.
5 *
6 * @package automattic/jetpack-search
7 */
8
9 namespace Automattic\Jetpack\Search;
10
11 use Automattic\Jetpack\Connection\Client;
12 use Automattic\Jetpack\Connection\Rest_Authentication;
13 use Automattic\Jetpack\My_Jetpack\Products\Search as Search_Product;
14 use Automattic\Jetpack\My_Jetpack\Products\Search_Stats as Search_Product_Stats;
15 use Jetpack_Options;
16 use WP_Error;
17 use WP_REST_Request;
18 use WP_REST_Response;
19 use WP_REST_Server;
20
21 if ( ! defined( 'ABSPATH' ) ) {
22 exit( 0 );
23 }
24
25 /**
26 * Registers the REST routes for Search.
27 */
28 class 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 // AI Answers requires a paid Search plan; reject the write outright.
429 if ( true === $ai_answers_enabled && ! Search_Blocks::supports_paid_search() ) {
430 return new WP_Error(
431 'rest_forbidden',
432 esc_html__( 'AI Answers requires a paid Jetpack Search plan.', 'jetpack-search-pkg' ),
433 array( 'status' => 403 )
434 );
435 }
436
437 if (
438 $module_active === null &&
439 $instant_search_enabled === null &&
440 ( $swap_classic_to_inline_search !== null || $reader_chat !== null )
441 ) {
442 // Allow updating auxiliary settings without updating/validating the module settings.
443 return true;
444 }
445 if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $ai_answers_enabled !== null ) {
446 // allow updating 'ai_answers_enabled' without updating/validating other settings.
447 return true;
448 }
449 if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $search_suggestions_enabled !== null ) {
450 // allow updating 'search_suggestions_enabled' without updating/validating other settings.
451 return true;
452 }
453 if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $override_woocommerce_search_template !== null ) {
454 // allow updating 'override_woocommerce_search_template' without updating/validating other settings.
455 return true;
456 }
457 if ( ( true === $instant_search_enabled && false === $module_active ) || ( $module_active === null && $instant_search_enabled === null ) ) {
458 return new WP_Error(
459 'rest_invalid_arguments',
460 esc_html__( 'The arguments passed in are invalid.', 'jetpack-search-pkg' ),
461 array( 'status' => 400 )
462 );
463 }
464 return true;
465 }
466
467 /**
468 * GET `jetpack/v4/search/settings`
469 */
470 public function get_settings() {
471 $settings = array(
472 'module_active' => $this->search_module->is_active(),
473 'instant_search_enabled' => $this->search_module->is_instant_search_enabled(),
474 'swap_classic_to_inline_search' => $this->search_module->is_swap_classic_to_inline_search(),
475 'experience' => $this->search_module->get_experience(),
476 'ai_answers_enabled' => AI_Answers::is_enabled(),
477 'ai_answers_saved' => AI_Answers::is_saved_on(),
478 'ai_master_enabled' => AI_Answers::is_master_enabled(),
479 'search_suggestions_enabled' => (bool) get_option( 'jetpack_search_suggestions_enabled', false ),
480 'override_woocommerce_search_template' => Search_Blocks::woocommerce_search_template_override_enabled(),
481 );
482
483 if ( $this->is_reader_chat_setting_registered() ) {
484 $settings['reader_chat'] = (bool) get_option( 'reader_chat', false );
485 }
486
487 return rest_ensure_response( $settings );
488 }
489
490 /**
491 * Check whether Reader Chat is available through REST settings in this request.
492 *
493 * Reader Chat registers `reader_chat` only for proxied rollout contexts, so the
494 * Search dashboard should expose the toggle only when that setting exists.
495 *
496 * @return bool True when reader_chat is registered.
497 */
498 protected function is_reader_chat_setting_registered() {
499 return array_key_exists( 'reader_chat', get_registered_settings() );
500 }
501
502 /**
503 * Proxy the request to WPCOM and return the response.
504 *
505 * GET `jetpack/v4/search/stats`
506 */
507 public function get_stats() {
508 $response = ( new Stats() )->get_stats_from_wpcom();
509 return $this->make_proper_response( $response );
510 }
511
512 /**
513 * Search Endpoint for private sites.
514 *
515 * GET `jetpack/v4/search`
516 *
517 * @param WP_REST_Request $request - REST request.
518 */
519 public function get_search_results( $request ) {
520 $blog_id = $this->get_blog_id();
521 $path = sprintf( '/sites/%d/search', absint( $blog_id ) );
522 $path = add_query_arg(
523 $request->get_query_params(),
524 sprintf( '/sites/%d/search', absint( $blog_id ) )
525 );
526 $response = Client::wpcom_json_api_request_as_blog( $path, '1.3', array(), null, 'rest' );
527 return rest_ensure_response( $this->make_proper_response( $response ) );
528 }
529
530 /**
531 * Activate plan: activate the search module, instant search and do initial configuration.
532 * Typically called from WPCOM.
533 *
534 * POST `jetpack/v4/search/plan/activate`
535 *
536 * @param WP_REST_Request $request - REST request.
537 */
538 public function activate_plan( $request ) {
539 $default_options = array(
540 'search_plan_info' => null,
541 'enable_search' => true,
542 'enable_instant_search' => true,
543 'search_experience' => null,
544 'auto_config_search' => true,
545 );
546 $payload = $request->get_json_params();
547 $payload = wp_parse_args( $payload, $default_options );
548
549 // Update plan data, plan info is in the request body.
550 // We do this to avoid another call to WPCOM and reduce latency.
551 if ( $payload['search_plan_info'] === null || ! $this->plan->set_plan_options( $payload['search_plan_info'] ) ) {
552 $this->plan->get_plan_info_from_wpcom();
553 }
554
555 // Enable search module by default, unless `enable_search` is explicitly set to boolean `false`.
556 if ( false !== $payload['enable_search'] ) {
557 $ret = $this->search_module->activate();
558 if ( is_wp_error( $ret ) ) {
559 return $ret;
560 }
561 }
562
563 if ( $payload['search_experience'] !== null ) {
564 // Canonical path. Restrict to activate-able experiences — `off`
565 // belongs on `/plan/deactivate`, and a non-string payload would
566 // blow up `update_experience(string $experience)`.
567 $valid_experiences = array(
568 Module_Control::EXPERIENCE_OVERLAY,
569 Module_Control::EXPERIENCE_INLINE,
570 Module_Control::EXPERIENCE_EMBEDDED,
571 );
572 if ( ! is_string( $payload['search_experience'] )
573 || ! in_array( $payload['search_experience'], $valid_experiences, true )
574 ) {
575 return new WP_Error(
576 'invalid_experience',
577 __( 'Invalid experience value.', 'jetpack-search-pkg' ),
578 array( 'status' => 400 )
579 );
580 }
581 $ret = $this->search_module->update_experience( sanitize_text_field( $payload['search_experience'] ) );
582 if ( is_wp_error( $ret ) ) {
583 return $ret;
584 }
585 }
586
587 if ( $payload['search_experience'] === null && false !== $payload['enable_instant_search'] ) {
588 // Legacy path: old WPCOM callers send `enable_instant_search`
589 // instead of `search_experience`. Gated on the canonical value
590 // being absent so it doesn't overwrite a non-overlay experience
591 // the caller just set.
592 // Error handling intentionally skipped — this is the legacy fallback.
593 $ret = $this->search_module->enable_instant_search();
594 }
595
596 // `auto_config_search` wires up Overlay sidebar widgets — only meaningful
597 // when Overlay is the resulting experience. For Inline / Embedded, the
598 // caller would otherwise get widget side effects they didn't ask for.
599 if ( false !== $payload['auto_config_search'] && $this->search_module->is_instant_search_enabled() ) {
600 Instant_Search::instance( $this->get_blog_id() )->auto_config_search();
601 }
602
603 return rest_ensure_response(
604 array(
605 'code' => 'success',
606 )
607 );
608 }
609
610 /**
611 * Deactivate plan: turn off search module and instant search.
612 * If the plan is still valid then the function would simply deactivate the search module.
613 * Typically called from WPCOM.
614 *
615 * POST `jetpack/v4/search/plan/deactivate`
616 */
617 public function deactivate_plan() {
618 // Instant Search would be disabled along with search module.
619 $this->search_module->deactivate();
620 return rest_ensure_response(
621 array(
622 'code' => 'success',
623 )
624 );
625 }
626
627 /**
628 * Return post type breakdown for the site.
629 */
630 public function get_local_stats() {
631 return array(
632 'post_count' => Search_Product_Stats::estimate_count(),
633 'post_type_breakdown' => Search_Product_Stats::get_post_type_breakdown(),
634 );
635 }
636
637 /**
638 * Force-delete the {@see Singleton_Template_Cpt} customization for the
639 * requested post type, backing the dashboard's "Restore default" link.
640 * `before_delete_post` in the base class clears the option pointer +
641 * per-request cache so the next render falls back to the bundled template.
642 *
643 * DELETE `jetpack/v4/search/templates/<post_type>`
644 *
645 * @param WP_REST_Request $request - REST request.
646 * @return WP_REST_Response|WP_Error
647 */
648 public function reset_singleton_template( $request ) {
649 $cpt_class = $this->resolve_singleton_template_class( $request['post_type'] );
650 if ( ! $cpt_class ) {
651 return new WP_Error(
652 'jetpack_search_template_unknown',
653 __( 'Unknown search template.', 'jetpack-search-pkg' ),
654 array( 'status' => 404 )
655 );
656 }
657 if ( ! $cpt_class::is_customized() ) {
658 return new WP_Error(
659 'jetpack_search_template_not_customized',
660 __( 'No customization to restore.', 'jetpack-search-pkg' ),
661 array( 'status' => 404 )
662 );
663 }
664 $post_id = $cpt_class::get_post_id();
665 if ( ! wp_delete_post( $post_id, true ) ) {
666 return new WP_Error(
667 'jetpack_search_template_reset_failed',
668 __( 'Failed to restore the default template.', 'jetpack-search-pkg' ),
669 array( 'status' => 500 )
670 );
671 }
672 return rest_ensure_response( array( 'deleted' => true ) );
673 }
674
675 /**
676 * Map a CPT slug to its concrete `Singleton_Template_Cpt` subclass.
677 * Returns null when the slug isn't one of the registered singleton-template
678 * CPTs — the route only sanitizes the slug (via `sanitize_key`), so this
679 * lookup is the primary "is this a known CPT?" filter, not a backup check.
680 *
681 * @param string $post_type Post type slug from the request.
682 * @return class-string<Singleton_Template_Cpt>|null
683 */
684 protected function resolve_singleton_template_class( $post_type ) {
685 $map = array(
686 Overlay_Template::POST_TYPE => Overlay_Template::class,
687 Product_Overlay_Template::POST_TYPE => Product_Overlay_Template::class,
688 Search_Template::POST_TYPE => Search_Template::class,
689 Product_Search_Template::POST_TYPE => Product_Search_Template::class,
690 );
691 return $map[ $post_type ] ?? null;
692 }
693
694 /**
695 * Pricing for record count of the site
696 */
697 public function product_pricing() {
698 $tier_pricing = Search_Product::get_pricing_for_ui();
699 // we can force the plugin to use the new pricing by appending `new_pricing_202208=1` to URL.
700 if ( Helper::is_forced_new_pricing_202208() ) {
701 $tier_pricing['pricing_version'] = Plan::JETPACK_SEARCH_NEW_PRICING_VERSION;
702 }
703 return rest_ensure_response( $tier_pricing );
704 }
705
706 /**
707 * Forward remote response to client with error handling.
708 *
709 * @param array|WP_Error $response - Response from WPCOM.
710 */
711 protected function make_proper_response( $response ) {
712 if ( is_wp_error( $response ) ) {
713 return $response;
714 }
715
716 $body = json_decode( wp_remote_retrieve_body( $response ), true );
717 $status_code = wp_remote_retrieve_response_code( $response );
718
719 if ( 200 === $status_code ) {
720 return $body;
721 }
722
723 return new WP_Error(
724 isset( $body['error'] ) ? 'remote-error-' . $body['error'] : 'remote-error',
725 $body['message'] ?? 'unknown remote error',
726 array( 'status' => $status_code )
727 );
728 }
729
730 /**
731 * Get blog id
732 */
733 protected function get_blog_id() {
734 return $this->is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
735 }
736 }
737