Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
130 / 143
66.67% covered (warning)
66.67%
14 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initial_State
90.91% covered (success)
90.91%
130 / 143
66.67% covered (warning)
66.67%
14 / 21
51.88
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 render
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_initial_state
100.00% covered (success)
100.00%
44 / 44
100.00% covered (success)
100.00%
1 / 1
3
 get_wp_api_root
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_reader_chat_guidelines_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_reader_chat_brand
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_reader_chat_brand_palette
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_ai_agent_access_guidelines_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_guidelines_url
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 is_ai_agent_access_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_block_template_overlay_config
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 get_product_overlay_template_config
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 get_search_template_config
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_product_search_template_config
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 build_singleton_template_config
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 is_private_site
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 current_user_data
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
3
 get_post_types_with_labels
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 get_purchase_token
28.57% covered (danger)
28.57%
2 / 7
0.00% covered (danger)
0.00%
0 / 1
6.28
 generate_purchase_token
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 current_user_can_purchase
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
1<?php
2/**
3 * The React initial state.
4 *
5 * @package automattic/jetpack-search
6 */
7
8namespace Automattic\Jetpack\Search;
9
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\Status;
12use Jetpack_Options;
13
14/**
15 * The React initial state.
16 */
17class Initial_State {
18
19    /**
20     * Connection Manager
21     *
22     * @var Connection_Manager
23     */
24    protected $connection_manager;
25
26    /**
27     * Search Module Control
28     *
29     * @var Module_Control
30     */
31    protected $module_control;
32
33    /**
34     * Constructor
35     *
36     * @param Connection_Manager $connection_manager - Connection mananger instance.
37     * @param Module_Control     $module_control - Module control instance.
38     */
39    public function __construct( $connection_manager = null, $module_control = null ) {
40        $this->connection_manager = $connection_manager ? $connection_manager : new Connection_Manager( Package::SLUG );
41        $this->module_control     = $module_control ? $module_control : new Module_Control();
42    }
43
44    /**
45     * Render JS for the initial state
46     *
47     * @return string - JS string.
48     */
49    public function render() {
50        return 'var JETPACK_SEARCH_DASHBOARD_INITIAL_STATE=' . wp_json_encode( $this->get_initial_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';';
51    }
52
53    /**
54     * Get the initial state data.
55     *
56     * @return array
57     */
58    public function get_initial_state() {
59        return array(
60            'siteData'        => array(
61                'WP_API_root'                => esc_url_raw( rest_url() ),
62                'wpcomOriginApiUrl'          => $this->get_wp_api_root(),
63                'WP_API_nonce'               => wp_create_nonce( 'wp_rest' ),
64                'registrationNonce'          => wp_create_nonce( 'jetpack-registration-nonce' ),
65                'purchaseToken'              => $this->get_purchase_token(),
66                /**
67                 * Whether promotions are visible or not.
68                 *
69                 * @param bool $are_promotions_active Status of promotions visibility. True by default.
70                 */
71                'showPromotions'             => apply_filters( 'jetpack_show_promotions', true ),
72                'adminUrl'                   => esc_url( admin_url() ),
73                'readerChatGuidelinesUrl'    => $this->get_reader_chat_guidelines_url(),
74                'readerChatBrand'            => $this->get_reader_chat_brand(),
75                'readerChatBrandPalette'     => $this->get_reader_chat_brand_palette(),
76                'aiAgentAccessAvailable'     => $this->is_ai_agent_access_available(),
77                'aiAgentAccessGuidelinesUrl' => $this->get_ai_agent_access_guidelines_url(),
78                'blogId'                     => Jetpack_Options::get_option( 'id', 0 ),
79                'version'                    => Package::VERSION,
80                'calypsoSlug'                => ( new Status() )->get_site_suffix(),
81                'title'                      => get_bloginfo( 'name' ),
82                'postTypes'                  => $this->get_post_types_with_labels(),
83                'isWpcom'                    => Helper::is_wpcom(),
84                // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
85                'isPlanJustUpgraded'         => isset( $_GET['just_upgraded'] ) && wp_unslash( $_GET['just_upgraded'] ),
86                /**
87                 * Whether the Jetpack Search 3.0 Interactivity API blocks are enabled.
88                 * Mirrors the `jetpack_search_blocks_enabled` server-side filter so the
89                 * dashboard React app can gate the new feature-selection UI on the
90                 * same flag the back end uses to register the blocks themselves.
91                 */
92                'searchBlocksEnabled'        => (bool) apply_filters( 'jetpack_search_blocks_enabled', true ),
93                /**
94                 * Whether the experimental blocks-powered Overlay search experience
95                 * is available in the Experience Selector. Mirrors the
96                 * `jetpack_search_overlay_block_template_enabled` server-side filter
97                 * so the dashboard React app can gate the new card on the same flag
98                 * the back end uses to enable the runtime swap. Defaults to true so
99                 * the Beta card ships to every site; operators that pin the filter
100                 * to false fall back to the original four-card selector.
101                 */
102                'blockOverlayEnabled'        => (bool) apply_filters( 'jetpack_search_overlay_block_template_enabled', true ),
103                /**
104                 * Editor affordances for the experimental blocks-powered overlay.
105                 * Surfaces in the new Overlay search card so admins can edit the
106                 * rendered template via the standard block editor on `post.php` â€”
107                 * works on both block and classic themes. URLs are null for any
108                 * visitor without `manage_options`; the action handlers also
109                 * enforce that capability server-side.
110                 */
111                'blockTemplateOverlay'       => $this->get_block_template_overlay_config(),
112                /**
113                 * Same as `blockTemplateOverlay` but for the WooCommerce product
114                 * variant of the overlay â€” the Overlay card surfaces a second
115                 * "Edit the product Search overlay" entry on Woo stores so the
116                 * product-search overlay template is customizable too.
117                 */
118                'productOverlayTemplate'     => $this->get_product_overlay_template_config(),
119                /**
120                 * Editor affordances for the classic-theme search-template
121                 * singleton CPT. The Embedded card surfaces these on
122                 * classic themes (which can't reach the Site Editor) so
123                 * admins still get an "Edit search template" entry â€” same
124                 * shape and same React link as `blockTemplateOverlay`.
125                 */
126                'searchTemplate'             => $this->get_search_template_config(),
127                /**
128                 * Same as `searchTemplate` but for the WooCommerce product
129                 * search shim â€” the `WooCommerceProductSearchControl`
130                 * surfaces this on classic themes so the "Edit the product
131                 * search template" link routes to `post.php` on the hidden
132                 * CPT instead of a useless Site Editor URL.
133                 */
134                'productSearchTemplate'      => $this->get_product_search_template_config(),
135                // Gates the WooCommerce Product Search control to stores.
136                'isWooCommerceActive'        => Search_Blocks::woocommerce_blocks_enabled(),
137                /**
138                 * Active theme stylesheet â€” used by the experience-selector to deep-link
139                 * the "Edit search template" action to the right Site Editor entry
140                 * (`?p=/wp_template/<stylesheet>//jetpack-search`).
141                 */
142                'activeThemeStylesheet'      => get_stylesheet(),
143                /**
144                 * Whether the active theme is a block theme. Embedded itself
145                 * works on every theme â€” block themes through the FSE
146                 * `search_template_hierarchy` route, classic themes through
147                 * the singleton-CPT shim â€” but the Embedded card's
148                 * customization affordances diverge: block themes get the
149                 * Site-Editor entry points ("Edit search template" / "Insert
150                 * pattern"), classic themes get the block-editor-on-a-hidden-
151                 * CPT path via `searchTemplate`. This flag is the dashboard's
152                 * branch selector for which to render.
153                 */
154                'themeSupportsBlocks'        => wp_is_block_theme(),
155            ),
156            'userData'        => array(
157                'currentUser' => $this->current_user_data(),
158            ),
159            'jetpackSettings' => array(
160                'search'                 => $this->module_control->is_active(),
161                'instant_search_enabled' => $this->module_control->is_instant_search_enabled(),
162                'experience'             => $this->module_control->get_experience(),
163            ),
164            'features'        => array_map(
165                'sanitize_text_field',
166                // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
167                isset( $_GET['features'] ) ? explode( ',', wp_unslash( $_GET['features'] ) ) : array()
168            ),
169        );
170    }
171
172    /**
173     * Get API root.
174     *
175     * It return first party API root for WPCOM simple sites.
176     */
177    protected function get_wp_api_root() {
178        if ( ! Helper::is_wpcom() ) {
179            return esc_url_raw( rest_url() );
180        }
181        // First party API prefix for WPCOM.
182        return esc_url_raw( site_url( '/wp-json/wpcom-origin/' ) );
183    }
184
185    /**
186     * Get the Reader Chat guidelines admin page URL when it is registered.
187     *
188     * The guidelines page is controlled outside Jetpack. Returning an empty
189     * URL lets the dashboard hide the link when that experiment is unavailable.
190     *
191     * @return string Guidelines admin URL, or an empty string when unavailable.
192     */
193    protected function get_reader_chat_guidelines_url() {
194        return $this->get_guidelines_url();
195    }
196
197    /**
198     * Get the resolved Reader Chat brand defaults for the settings UI.
199     *
200     * The Reader Chat implementation lives in the Jetpack plugin, while this
201     * package also runs independently. Return an empty value when that optional
202     * integration is unavailable.
203     *
204     * @return array Resolved Reader Chat brand defaults.
205     */
206    protected function get_reader_chat_brand() {
207        $class = '\Automattic\Jetpack\Extensions\AiAssistantPlugin\Jetpack_Reader_Chat';
208
209        return is_callable( array( $class, 'get_brand' ) ) ? $class::get_brand() : array();
210    }
211
212    /**
213     * Get theme palette entries available to the Reader Chat accent control.
214     *
215     * @return array Reader Chat theme palette.
216     */
217    protected function get_reader_chat_brand_palette() {
218        $class = '\Automattic\Jetpack\Extensions\AiAssistantPlugin\Jetpack_Reader_Chat';
219
220        return is_callable( array( $class, 'get_brand_palette' ) ) ? $class::get_brand_palette() : array();
221    }
222
223    /**
224     * Get the AI Agent Access guidelines admin page URL when it is registered.
225     *
226     * The guidelines page is controlled outside Jetpack. Returning an empty
227     * URL lets the dashboard hide the link when that page is unavailable.
228     *
229     * @return string Guidelines admin URL, or an empty string when unavailable.
230     */
231    protected function get_ai_agent_access_guidelines_url() {
232        return $this->get_guidelines_url();
233    }
234
235    /**
236     * Get the Guidelines admin page URL when it is registered.
237     *
238     * @return string Guidelines admin URL, or an empty string when unavailable.
239     */
240    protected function get_guidelines_url() {
241        if ( ! function_exists( 'menu_page_url' ) ) {
242            return '';
243        }
244
245        return esc_url_raw( menu_page_url( 'guidelines-wp-admin', false ) );
246    }
247
248    /**
249     * Check whether the AI Agent Access toggle should be available.
250     *
251     * Private sites are not eligible because external AI agents cannot read
252     * their public content.
253     *
254     * @return bool
255     */
256    protected function is_ai_agent_access_available() {
257        return ! $this->is_private_site();
258    }
259
260    /**
261     * Build the block-template overlay editor config exposed to the dashboard.
262     *
263     * `enabled` mirrors `Search_Blocks::is_block_template_overlay_enabled()`
264     * â€” true only when the user is currently *on* the blocks Overlay arm.
265     * The editor URLs, by contrast, are gated on the operator filter alone
266     * so admins can edit the template from the Beta card even before
267     * activating it (otherwise the React store, computed at page load
268     * before any switch, would carry a null `editorUrl` and the link would
269     * become a no-op once the card flipped to Active without a refresh).
270     *
271     * @return array{enabled: bool, editorUrl: string|null, postType: string|null, isCustomized: bool}
272     */
273    protected function get_block_template_overlay_config(): array {
274        return $this->build_singleton_template_config(
275            Search_Blocks::is_block_template_overlay_enabled(),
276            Search_Blocks::is_block_template_overlay_filter_on() && current_user_can( 'manage_options' ),
277            Overlay_Template::class
278        );
279    }
280
281    /**
282     * Build the product-overlay editor config exposed to the dashboard.
283     * Counterpart of `get_block_template_overlay_config()` for the WooCommerce
284     * product variant. `enabled` adds the override-on + WC check on top of the
285     * overlay-arm gate â€” it signals the product overlay's front-end render path
286     * is actually wired. `$can_edit` mirrors the init gate: the editable CPT
287     * only registers on Woo stores with the overlay filter on (see
288     * `Search_Blocks::init()`), so exposing the editor URL off Woo would produce
289     * a link that silently does nothing.
290     *
291     * @return array{enabled: bool, editorUrl: string|null, postType: string|null, isCustomized: bool}
292     */
293    protected function get_product_overlay_template_config(): array {
294        $wc_enabled = Search_Blocks::woocommerce_blocks_enabled();
295        return $this->build_singleton_template_config(
296            Search_Blocks::is_block_template_overlay_enabled()
297                && $wc_enabled
298                && Search_Blocks::woocommerce_search_template_override_enabled(),
299            Search_Blocks::is_block_template_overlay_filter_on()
300                && $wc_enabled
301                && current_user_can( 'manage_options' ),
302            Product_Overlay_Template::class
303        );
304    }
305
306    /**
307     * Build the classic-theme search-template editor config exposed to the
308     * dashboard. Counterpart of `get_block_template_overlay_config()` â€”
309     * same `{enabled, editorUrl, postType, isCustomized}` shape and the
310     * same "expose URLs before activation" rule: admins can edit the
311     * template from the Embedded card on any classic theme, even before
312     * actually switching to Embedded.
313     *
314     * @return array{enabled: bool, editorUrl: string|null, postType: string|null, isCustomized: bool}
315     */
316    protected function get_search_template_config(): array {
317        $is_classic = ! wp_is_block_theme();
318        return $this->build_singleton_template_config(
319            $is_classic && Module_Control::EXPERIENCE_EMBEDDED === $this->module_control->get_experience(),
320            $is_classic && current_user_can( 'manage_options' ),
321            Search_Template::class
322        );
323    }
324
325    /**
326     * Build the classic-theme product-search-template editor config exposed
327     * to the dashboard. Counterpart of `get_search_template_config()` for the
328     * WooCommerce product shim â€” same `{enabled, editorUrl, postType, isCustomized}`
329     * shape. `enabled` adds the override-on check on top of the classic +
330     * server-rendered-experience gate â€” it signals "the front-end render path
331     * is actually wired", distinct from "the override toggle is on" in
332     * `jetpackSettings.override_woocommerce_search_template`. `$can_edit`
333     * mirrors the init gate: `Product_Search_Template::init()` (in
334     * `Search_Blocks::init()`) registers `maybe_handle_editor_request` on
335     * classic Embedded **and** classic Inline (both route the product shim),
336     * so the editor URL surfaces for both â€” but not on a block theme, where
337     * the Site Editor link is used instead.
338     *
339     * @return array{enabled: bool, editorUrl: string|null, postType: string|null, isCustomized: bool}
340     */
341    protected function get_product_search_template_config(): array {
342        $experience = $this->module_control->get_experience();
343        $is_classic = ! wp_is_block_theme();
344        // Embedded and Inline both route the classic product shim, so both
345        // expose the CPT editor.
346        $is_classic_product_override = $is_classic
347            && in_array(
348                $experience,
349                array( Module_Control::EXPERIENCE_EMBEDDED, Module_Control::EXPERIENCE_INLINE ),
350                true
351            );
352        return $this->build_singleton_template_config(
353            $is_classic_product_override && Search_Blocks::woocommerce_search_template_override_enabled(),
354            $is_classic_product_override && current_user_can( 'manage_options' ),
355            Product_Search_Template::class
356        );
357    }
358
359    /**
360     * Shared assembly for a {@see Singleton_Template_Cpt}-backed editor
361     * config block. Both `blockTemplateOverlay` and `searchTemplate` ship
362     * the same `{enabled, editorUrl, postType, isCustomized}` shape to
363     * the React dashboard. The `$enabled` and `$can_edit` flags are
364     * intentionally separate: the card lights up as "active" on
365     * `$enabled`, but the URLs / `postType` surface as soon as `$can_edit`
366     * is true so admins can pre-customize the template before activating
367     * the experience â€” without forcing a page reload after the switch.
368     *
369     * `postType` (rather than a pre-built REST path) is what the dashboard
370     * needs: the React "Restore default" handler builds the
371     * `${wpcomOriginApiUrl}jetpack/v4/search/templates/<post_type>` URL
372     * itself, which is how the request reaches the right route on wpcom
373     * Simple sites (the local /wp-json/ surface there doesn't expose
374     * Jetpack routes). The handler re-checks `manage_options` server-side,
375     * so omitting the URLs / postType here just keeps the wire payload
376     * tight for non-admins.
377     *
378     * @param bool   $enabled   Whether the CPT-backed route is currently live on the site.
379     * @param bool   $can_edit  Whether to expose the editor URL + postType (operator-level gate + capability).
380     * @param string $cpt_class Concrete `Singleton_Template_Cpt` subclass to query.
381     * @return array{enabled: bool, editorUrl: string|null, postType: string|null, isCustomized: bool}
382     */
383    protected function build_singleton_template_config( bool $enabled, bool $can_edit, string $cpt_class ): array {
384        return array(
385            'enabled'      => $enabled,
386            'editorUrl'    => $can_edit ? $cpt_class::get_editor_url() : null,
387            'postType'     => $can_edit ? $cpt_class::POST_TYPE : null,
388            'isCustomized' => $can_edit && $cpt_class::is_customized(),
389        );
390    }
391
392    /**
393     * Check whether the current site is private.
394     *
395     * @return bool
396     */
397    protected function is_private_site() {
398        if ( function_exists( 'is_private_blog' ) ) {
399            return (bool) \is_private_blog();
400        }
401
402        return -1 === (int) get_option( 'blog_public', 1 );
403    }
404
405    /**
406     * Gather data about the current user.
407     *
408     * @return array
409     */
410    protected function current_user_data() {
411        $current_user      = wp_get_current_user();
412        $is_user_connected = $this->connection_manager->is_user_connected( $current_user->ID );
413        $is_master_user    = $is_user_connected && (int) $current_user->ID && (int) Jetpack_Options::get_option( 'master_user' ) === (int) $current_user->ID;
414        $dotcom_data       = $this->connection_manager->get_connected_user_data();
415
416        $current_user_data = array(
417            'isConnected' => $is_user_connected,
418            'isMaster'    => $is_master_user,
419            'username'    => $current_user->user_login,
420            'id'          => $current_user->ID,
421            'wpcomUser'   => $dotcom_data,
422            'permissions' => array(
423                'manage_options' => current_user_can( 'manage_options' ),
424            ),
425        );
426
427        return $current_user_data;
428    }
429
430    /**
431     * Gets the post type labels for all of the site's post types (including custom post types)
432     *
433     * @return array
434     */
435    protected function get_post_types_with_labels() {
436
437        $args = array(
438            'public' => true,
439        );
440
441        $post_types_with_labels = array();
442
443        $post_types = get_post_types( $args, 'objects' );
444
445        // We don't need all the additional post_type data, just the slug & label
446        foreach ( $post_types as $post_type ) {
447            $post_type_with_label = array(
448                'slug'  => $post_type->name,
449                'label' => $post_type->label,
450            );
451
452            $post_types_with_labels[ $post_type->name ] = $post_type_with_label;
453        }
454        return $post_types_with_labels;
455    }
456
457    /**
458     * Gets a purchase token that is used for Jetpack logged out visitor checkout.
459     * The purchase token should be appended to all CTA url's that lead to checkout.
460     *
461     * @return string|boolean
462     */
463    protected function get_purchase_token() {
464        if ( ! $this->current_user_can_purchase() ) {
465            return false;
466        }
467
468        $purchase_token = Jetpack_Options::get_option( 'purchase_token', false );
469
470        if ( $purchase_token ) {
471            return $purchase_token;
472        }
473        // If the purchase token is not saved in the options table yet, then add it.
474        Jetpack_Options::update_option( 'purchase_token', $this->generate_purchase_token(), true );
475        return Jetpack_Options::get_option( 'purchase_token', false );
476    }
477
478    /**
479     * Generates a purchase token that is used for Jetpack logged out visitor checkout.
480     *
481     * @return string
482     */
483    protected function generate_purchase_token() {
484        return wp_generate_password( 12, false );
485    }
486
487    /**
488     * Determine if the current user is allowed to make Jetpack purchases without
489     * a WordPress.com account
490     *
491     * @return boolean True if the user can make purchases, false if not
492     */
493    public function current_user_can_purchase() {
494        // The site must be site-connected to Jetpack (no users connected).
495        if ( ! $this->connection_manager->is_site_connection() ) {
496            return false;
497        }
498
499        // Make sure only administrators can make purchases.
500        if ( ! current_user_can( 'manage_options' ) ) {
501            return false;
502        }
503
504        return true;
505    }
506}