Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
49.22% covered (danger)
49.22%
63 / 128
38.10% covered (danger)
38.10%
8 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
49.22% covered (danger)
49.22%
63 / 128
38.10% covered (danger)
38.10%
8 / 21
391.60
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 init_hooks
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 add_admin_shell_member
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 load_as_admin_shell_guest
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_admin_shell_guest_request
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 maybe_load_wp_build
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 load_wp_build
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
4.02
 require_wp_build_with_screen_alias
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
2.06
 wp_build_index
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 wp_build_render_function
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_search_admin_request
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 alias_screen_id_for_wp_build
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 restore_screen_id_after_wp_build
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 add_wp_admin_submenu
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
12
 render
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 should_add_search_submenu
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 remove_search_submenu_if_exists
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 admin_init
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 load_admin_scripts
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 should_enqueue_tracking_script
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 check_plan_deactivate_search_module
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2/**
3 * A class that adds a search dashboard to wp-admin.
4 *
5 * @package automattic/jetpack
6 */
7
8namespace Automattic\Jetpack\Search;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Admin_UI\Admin_Shell;
12use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
13use Automattic\Jetpack\Connection\Manager as Connection_Manager;
14use Automattic\Jetpack\Status;
15use Automattic\Jetpack\Status\Host;
16use Automattic\Jetpack\Tracking;
17use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
18use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
19/**
20 * Responsible for adding a search dashboard to wp-admin.
21 *
22 * @package Automattic\Jetpack\Search
23 */
24class Dashboard {
25    /**
26     * Slug emitted by `@wordpress/build` (`wpPlugin.pages[0].id`). Must differ from the
27     * `jetpack-search` menu slug: the generated page.php takes over, and exits, any request
28     * whose `page` matches this id.
29     */
30    const WP_BUILD_PAGE_ID = 'jetpack-search-dashboard';
31
32    /**
33     * Render function generated by `@wordpress/build` into
34     * `build/pages/jetpack-search-dashboard/page-wp-admin.php`. Naming convention:
35     * `{wpPlugin.name}_{page-with-underscores}_wp_admin_render_page`.
36     */
37    const WP_BUILD_RENDER_FN = 'jetpack_search_jetpack_search_dashboard_wp_admin_render_page';
38
39    /**
40     * Classic script handle with no source, registered only so the dashboard has
41     * something to hang {@see Initial_State} and the connection initial state on.
42     */
43    const DATA_SCRIPT_HANDLE = 'jetpack-search-dashboard-data';
44
45    /**
46     * Whether the class has been initialized
47     *
48     * @var boolean
49     */
50    private static $initialized = false;
51
52    /**
53     * The screen ID {@see self::alias_screen_id_for_wp_build()} replaced, until it is restored.
54     *
55     * @var string|null
56     */
57    private static $wp_build_original_screen_id = null;
58
59    /**
60     * Plan instance
61     *
62     * @var \Automattic\Jetpack\Search\Plan
63     */
64    protected $plan;
65
66    /**
67     * Connection manager instance
68     *
69     * @var \Automattic\Jetpack\Connection\Manager
70     */
71    protected $connection_manager;
72
73    /**
74     * Module_Control instance
75     *
76     * @var \Automattic\Jetpack\Search\Module_Control
77     */
78    protected $module_control;
79
80    /**
81     * Priority for the dashboard menu
82     * For Jetpack sites: Akismet uses 4, so we use 1 to ensure both menus are added when only they exist.
83     * For Simple sites: the value is overriden in a child class with value 100000 to wait for all menus to be registered.
84     *
85     * @var int
86     */
87    protected $search_menu_priority = 1;
88
89    /**
90     * Whether the admin shell's hover request is readying Search behind another dashboard, where nothing may be saved.
91     *
92     * @var bool
93     */
94    private $is_admin_shell_guest = false;
95
96    /**
97     * Contructor
98     *
99     * @param \Automattic\Jetpack\Search\Plan           $plan - Plan instance.
100     * @param \Automattic\Jetpack\Connection\Manager    $connection_manager - Connection Manager instance.
101     * @param \Automattic\Jetpack\Search\Module_Control $module_control - Module_Control instance.
102     */
103    public function __construct( $plan = null, $connection_manager = null, $module_control = null ) {
104        $this->plan               = $plan ? $plan : new Plan();
105        $this->connection_manager = $connection_manager ? $connection_manager : new Connection_Manager( Package::SLUG );
106        $this->module_control     = $module_control ? $module_control : new Module_Control( $this->plan );
107        $this->plan->init_hooks();
108    }
109
110    /**
111     * Initialise hooks.
112     *
113     * We use the `config` package to initialize the search package, which ensures the package is
114     * only initialized once. However earlier versions of Jetpack would still forcely initialize the
115     * dashboard. As a result, there would be two `Search` submenus if we don't ensure the dashboard
116     * is initialized only once. So we use `$initialized` to ensure the class is only initialized once.
117     *
118     * Ref: https://github.com/Automattic/jetpack/pull/21888/files#diff-aae7d66951585fc55053a4d53b68552a41864d2c69aee900574ef4404b7ad5f7L42
119     */
120    public function init_hooks() {
121        if ( ! self::$initialized ) {
122            self::$initialized = true;
123            // Any priority works: render() reads the loaded build after admin_menu, and the
124            // wpcom subclass overrides this to 100000.
125            add_action( 'admin_menu', array( $this, 'maybe_load_wp_build' ), $this->search_menu_priority );
126            add_action( 'admin_menu', array( $this, 'add_wp_admin_submenu' ), $this->search_menu_priority );
127            // Check if the site plan changed and deactivate module accordingly.
128            add_action( 'current_screen', array( $this, 'check_plan_deactivate_search_module' ) );
129            if ( class_exists( Admin_Shell::class ) ) {
130                add_filter( 'jetpack_admin_shell_members', array( $this, 'add_admin_shell_member' ) );
131            }
132        }
133    }
134
135    /**
136     * Register Search with the admin shell, which switches between Jetpack dashboards without a page load.
137     *
138     * The page is registered for every admin, with or without a menu entry, so links to it switch in place.
139     *
140     * @since 8.4.3
141     *
142     * @param array $members Shell members keyed by admin page slug.
143     * @return array
144     */
145    public function add_admin_shell_member( $members ) {
146        if ( ( new Host() )->is_wpcom_simple() || ! file_exists( $this->wp_build_index() ) ) {
147            return $members;
148        }
149
150        $members['jetpack-search'] = array(
151            'build_prefix' => 'jetpack_search',
152            'build_page'   => self::WP_BUILD_PAGE_ID,
153            'init_modules' => array( '@jetpack-search/init' ),
154            // "Search" is a product name, do not translate.
155            'title'        => 'Search',
156            'header'       => array(
157                'title'    => 'Search',
158                'subtitle' => __( 'Help your visitors find exactly what they are looking for.', 'jetpack-search-pkg' ),
159            ),
160            'capability'   => 'manage_options',
161            'handles'      => array( self::DATA_SCRIPT_HANDLE, 'jetpack-script-data', 'jp-tracks-functions', 'wp-jp-i18n-loader' ),
162            'load'         => array( $this, 'load_as_admin_shell_guest' ),
163        );
164        return $members;
165    }
166
167    /**
168     * Ready the Search routes and page data while another dashboard's page is open, without the screen ID alias.
169     *
170     * @since 8.4.3
171     *
172     * @return void
173     */
174    public function load_as_admin_shell_guest() {
175        // The shell also runs this on other dashboards' pages, to ready Search for a switch.
176        $this->is_admin_shell_guest = self::is_admin_shell_guest_request();
177        if ( $this->load_wp_build( false ) ) {
178            $this->admin_init();
179        }
180    }
181
182    /**
183     * Whether this is the admin shell's hover request, which readies Search behind another dashboard.
184     *
185     * @return bool
186     */
187    private static function is_admin_shell_guest_request() {
188        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Compared only; the shell checks the nonce.
189        return wp_doing_ajax() && isset( $_GET['action'] ) && Admin_Shell::GUEST_ACTION === wp_unslash( $_GET['action'] );
190    }
191
192    /**
193     * Load the wp-build dashboard bundle for this request.
194     *
195     * A no-op unless this is the Search page and `build/build.php` exists.
196     */
197    public function maybe_load_wp_build() {
198        if ( ! $this->is_search_admin_request() ) {
199            return;
200        }
201
202        $this->load_wp_build();
203    }
204
205    /**
206     * Load the wp-build bundle and its polyfills.
207     *
208     * @since 8.4.3
209     *
210     * @param bool $alias Whether to alias the screen ID. Pass false to ready the routes on another page, which must not boot it.
211     * @return bool Whether the build exists.
212     */
213    private function load_wp_build( $alias = true ) {
214        $build_index = $this->wp_build_index();
215        if ( ! file_exists( $build_index ) ) {
216            return false;
217        }
218
219        if ( $alias ) {
220            self::require_wp_build_with_screen_alias( $build_index );
221        } else {
222            require_once $build_index;
223        }
224
225        // wp-build hooks module registration to wp_default_scripts, which has already
226        // fired by admin_menu â€” call it directly or the init module never registers.
227        if ( function_exists( 'jetpack_search_register_script_modules' ) ) {
228            jetpack_search_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- guarded by function_exists(); defined in the generated build/modules.php, which Phan excludes.
229        }
230
231        WP_Build_Polyfills::register(
232            'jetpack-search',
233            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS ),
234            null,
235            array(
236                array(
237                    'prefix' => 'jetpack_search',
238                    'slug'   => self::WP_BUILD_PAGE_ID,
239                ),
240            )
241        );
242        return true;
243    }
244
245    /**
246     * Require the generated build file with the screen ID aliased across its enqueue check.
247     *
248     * @see WP_Build_Screen_Id::load_with_alias()
249     * @param string $build_index Path to the generated `build.php`.
250     * @return void
251     */
252    private static function require_wp_build_with_screen_alias( $build_index ) {
253        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
254        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
255            WP_Build_Screen_Id::load_with_alias(
256                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
257                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
258                function () use ( $build_index ) {
259                    require_once $build_index;
260                }
261            );
262            return;
263        }
264
265        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
266        require_once $build_index;
267        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
268    }
269
270    /**
271     * Path to the generated build entry point. A seam, like the render function below:
272     * tests point it at a stub so this runs without the package being built.
273     *
274     * @return string
275     */
276    protected function wp_build_index() {
277        return dirname( __DIR__, 2 ) . '/build/build.php';
278    }
279
280    /**
281     * Name of the generated render function. A seam: tests override it to render
282     * the dashboard without depending on whether the package happens to be built.
283     *
284     * @return string
285     */
286    protected function wp_build_render_function() {
287        return self::WP_BUILD_RENDER_FN;
288    }
289
290    /**
291     * Whether the current request targets the Search admin page.
292     *
293     * @return bool
294     */
295    protected function is_search_admin_request() {
296        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
297        if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
298            return false;
299        }
300
301        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
302        return 'jetpack-search' === sanitize_text_field( wp_unslash( $_GET['page'] ) );
303    }
304
305    /**
306     * Alias the current screen id to wp-build's expected slug so its
307     * auto-generated enqueue callback fires for our user-facing page.
308     */
309    public static function alias_screen_id_for_wp_build() {
310        $screen = get_current_screen();
311        if ( ! $screen ) {
312            return;
313        }
314
315        self::$wp_build_original_screen_id = $screen->id;
316        $screen->id                        = self::WP_BUILD_PAGE_ID;
317    }
318
319    /**
320     * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
321     */
322    public static function restore_screen_id_after_wp_build() {
323        $screen = get_current_screen();
324        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
325            return;
326        }
327
328        $screen->id                        = self::$wp_build_original_screen_id;
329        self::$wp_build_original_screen_id = null;
330    }
331
332    /**
333     * The page to be added to submenu
334     */
335    public function add_wp_admin_submenu() {
336        // Jetpack of version <= 10.5 would register `jetpack-search` submenu with its built-in search module.
337        $this->remove_search_submenu_if_exists();
338
339        if ( $this->should_add_search_submenu() ) {
340            $page_suffix = Admin_Menu::add_menu(
341                /** "Search" is a product name, do not translate. */
342                'Jetpack Search',
343                'Search',
344                'manage_options',
345                'jetpack-search',
346                array( $this, 'render' ),
347                null,
348                array(
349                    'product' => 'search',
350                    'key'     => 'jetpack-search',
351                )
352            );
353        } else {
354            // always add the page, but hide it from the menu.
355            $page_suffix = add_submenu_page(
356                '',
357                /** "Search" is a product name, do not translate. */
358                'Jetpack Search',
359                'Search',
360                'manage_options',
361                'jetpack-search',
362                array( $this, 'render' )
363            );
364        }
365
366        if ( $page_suffix ) {
367            add_action( 'load-' . $page_suffix, array( $this, 'admin_init' ) );
368        }
369    }
370
371    /**
372     * Render the dashboard page.
373     *
374     * The generated render function is missing where the package was never built.
375     */
376    public function render() {
377        $render_function = $this->wp_build_render_function();
378        if ( function_exists( $render_function ) ) {
379            call_user_func( $render_function );
380        }
381    }
382
383    /**
384     * Test whether we should show Search menu.
385     *
386     * @return boolean Show search sub menu or not.
387     */
388    protected function should_add_search_submenu() {
389        /**
390         * The filter allows to ommit adding a submenu item for Jetpack Search.
391         *
392         * @since 0.11.2
393         *
394         * @param boolean $should_add_search_submenu Default value is true.
395         */
396        return apply_filters( 'jetpack_search_should_add_search_submenu', current_user_can( 'manage_options' ) );
397    }
398
399    /**
400     * Remove `jetpack-search` submenu page
401     */
402    protected function remove_search_submenu_if_exists() {
403        remove_submenu_page( 'jetpack', 'jetpack-search' );
404    }
405
406    /**
407     * Initialize the admin resources.
408     */
409    public function admin_init() {
410        add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_scripts' ) );
411    }
412
413    /**
414     * Enqueue admin scripts.
415     */
416    public function load_admin_scripts() {
417        if ( $this->should_enqueue_tracking_script() ) {
418            // Required for Analytics.
419            Tracking::register_tracks_functions_scripts( true );
420        }
421
422        // wp-build enqueues the app itself; this empty handle exists only to
423        // print the initial state before boot runs on DOMContentLoaded.
424        wp_register_script( self::DATA_SCRIPT_HANDLE, false, array(), Package::VERSION, true );
425        wp_enqueue_script( self::DATA_SCRIPT_HANDLE );
426
427        // The i18n loader is registered on every admin page but only enqueued
428        // when depended on; the esbuild bundle doesn't pull it in.
429        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
430            wp_enqueue_script( 'wp-jp-i18n-loader' );
431        }
432
433        // Add objects to be passed to the initial state of the app.
434        // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
435        wp_add_inline_script(
436            self::DATA_SCRIPT_HANDLE,
437            ( new Initial_State( null, null, $this->is_admin_shell_guest ) )->render(),
438            'before'
439        );
440
441        // Connection initial state.
442        Connection_Initial_State::render_script( self::DATA_SCRIPT_HANDLE );
443    }
444
445    /**
446     * Check if we should enqueue the tracking script.
447     */
448    protected function should_enqueue_tracking_script() {
449        return ! ( new Status() )->is_offline_mode() && $this->connection_manager->is_connected();
450    }
451
452    /**
453     * Deactivate search module if plan doesn't support search.
454     *
455     * @param \WP_Screen $current_screen Creent screen object.
456     */
457    public function check_plan_deactivate_search_module( $current_screen ) {
458        // Only run on Jetpack admin pages.
459        // The first two checks for current screen are cheap to run on every page.
460        if (
461            property_exists( $current_screen, 'base' ) &&
462            strpos( $current_screen->base, 'jetpack_page_' ) !== false &&
463            ( ! $this->plan->supports_search() || $this->plan->must_upgrade() )
464        ) {
465            $this->module_control->deactivate();
466        }
467    }
468}