Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
46.28% covered (danger)
46.28%
56 / 121
38.10% covered (danger)
38.10%
8 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
46.28% covered (danger)
46.28%
56 / 121
38.10% covered (danger)
38.10%
8 / 21
454.20
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
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
4.06
 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        );
235        return true;
236    }
237
238    /**
239     * Require the generated build file with the screen ID aliased across its enqueue check.
240     *
241     * @see WP_Build_Screen_Id::load_with_alias()
242     * @param string $build_index Path to the generated `build.php`.
243     * @return void
244     */
245    private static function require_wp_build_with_screen_alias( $build_index ) {
246        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
247        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
248            WP_Build_Screen_Id::load_with_alias(
249                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
250                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
251                function () use ( $build_index ) {
252                    require_once $build_index;
253                }
254            );
255            return;
256        }
257
258        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
259        require_once $build_index;
260        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
261    }
262
263    /**
264     * Path to the generated build entry point. A seam, like the render function below:
265     * tests point it at a stub so this runs without the package being built.
266     *
267     * @return string
268     */
269    protected function wp_build_index() {
270        return dirname( __DIR__, 2 ) . '/build/build.php';
271    }
272
273    /**
274     * Name of the generated render function. A seam: tests override it to render
275     * the dashboard without depending on whether the package happens to be built.
276     *
277     * @return string
278     */
279    protected function wp_build_render_function() {
280        return self::WP_BUILD_RENDER_FN;
281    }
282
283    /**
284     * Whether the current request targets the Search admin page.
285     *
286     * @return bool
287     */
288    protected function is_search_admin_request() {
289        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
290        if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
291            return false;
292        }
293
294        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
295        return 'jetpack-search' === sanitize_text_field( wp_unslash( $_GET['page'] ) );
296    }
297
298    /**
299     * Alias the current screen id to wp-build's expected slug so its
300     * auto-generated enqueue callback fires for our user-facing page.
301     */
302    public static function alias_screen_id_for_wp_build() {
303        $screen = get_current_screen();
304        if ( ! $screen ) {
305            return;
306        }
307
308        self::$wp_build_original_screen_id = $screen->id;
309        $screen->id                        = self::WP_BUILD_PAGE_ID;
310    }
311
312    /**
313     * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
314     */
315    public static function restore_screen_id_after_wp_build() {
316        $screen = get_current_screen();
317        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
318            return;
319        }
320
321        $screen->id                        = self::$wp_build_original_screen_id;
322        self::$wp_build_original_screen_id = null;
323    }
324
325    /**
326     * The page to be added to submenu
327     */
328    public function add_wp_admin_submenu() {
329        // Jetpack of version <= 10.5 would register `jetpack-search` submenu with its built-in search module.
330        $this->remove_search_submenu_if_exists();
331
332        if ( $this->should_add_search_submenu() ) {
333            $page_suffix = Admin_Menu::add_menu(
334                /** "Search" is a product name, do not translate. */
335                'Jetpack Search',
336                'Search',
337                'manage_options',
338                'jetpack-search',
339                array( $this, 'render' ),
340                null,
341                array(
342                    'product' => 'search',
343                    'key'     => 'jetpack-search',
344                )
345            );
346        } else {
347            // always add the page, but hide it from the menu.
348            $page_suffix = add_submenu_page(
349                '',
350                /** "Search" is a product name, do not translate. */
351                'Jetpack Search',
352                'Search',
353                'manage_options',
354                'jetpack-search',
355                array( $this, 'render' )
356            );
357        }
358
359        if ( $page_suffix ) {
360            add_action( 'load-' . $page_suffix, array( $this, 'admin_init' ) );
361        }
362    }
363
364    /**
365     * Render the dashboard page.
366     *
367     * The generated render function is missing where the package was never built.
368     */
369    public function render() {
370        $render_function = $this->wp_build_render_function();
371        if ( function_exists( $render_function ) ) {
372            call_user_func( $render_function );
373        }
374    }
375
376    /**
377     * Test whether we should show Search menu.
378     *
379     * @return boolean Show search sub menu or not.
380     */
381    protected function should_add_search_submenu() {
382        /**
383         * The filter allows to ommit adding a submenu item for Jetpack Search.
384         *
385         * @since 0.11.2
386         *
387         * @param boolean $should_add_search_submenu Default value is true.
388         */
389        return apply_filters( 'jetpack_search_should_add_search_submenu', current_user_can( 'manage_options' ) );
390    }
391
392    /**
393     * Remove `jetpack-search` submenu page
394     */
395    protected function remove_search_submenu_if_exists() {
396        remove_submenu_page( 'jetpack', 'jetpack-search' );
397    }
398
399    /**
400     * Initialize the admin resources.
401     */
402    public function admin_init() {
403        add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_scripts' ) );
404    }
405
406    /**
407     * Enqueue admin scripts.
408     */
409    public function load_admin_scripts() {
410        if ( $this->should_enqueue_tracking_script() ) {
411            // Required for Analytics.
412            Tracking::register_tracks_functions_scripts( true );
413        }
414
415        // wp-build enqueues the app itself; this empty handle exists only to
416        // print the initial state before boot runs on DOMContentLoaded.
417        wp_register_script( self::DATA_SCRIPT_HANDLE, false, array(), Package::VERSION, true );
418        wp_enqueue_script( self::DATA_SCRIPT_HANDLE );
419
420        // The i18n loader is registered on every admin page but only enqueued
421        // when depended on; the esbuild bundle doesn't pull it in.
422        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
423            wp_enqueue_script( 'wp-jp-i18n-loader' );
424        }
425
426        // Add objects to be passed to the initial state of the app.
427        // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
428        wp_add_inline_script(
429            self::DATA_SCRIPT_HANDLE,
430            ( new Initial_State( null, null, $this->is_admin_shell_guest ) )->render(),
431            'before'
432        );
433
434        // Connection initial state.
435        Connection_Initial_State::render_script( self::DATA_SCRIPT_HANDLE );
436    }
437
438    /**
439     * Check if we should enqueue the tracking script.
440     */
441    protected function should_enqueue_tracking_script() {
442        return ! ( new Status() )->is_offline_mode() && $this->connection_manager->is_connected();
443    }
444
445    /**
446     * Deactivate search module if plan doesn't support search.
447     *
448     * @param \WP_Screen $current_screen Creent screen object.
449     */
450    public function check_plan_deactivate_search_module( $current_screen ) {
451        // Only run on Jetpack admin pages.
452        // The first two checks for current screen are cheap to run on every page.
453        if (
454            property_exists( $current_screen, 'base' ) &&
455            strpos( $current_screen->base, 'jetpack_page_' ) !== false &&
456            ( ! $this->plan->supports_search() || $this->plan->must_upgrade() )
457        ) {
458            $this->module_control->deactivate();
459        }
460    }
461}