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