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