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