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