Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
38.38% covered (danger)
38.38%
38 / 99
12.50% covered (danger)
12.50%
2 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Social_Admin_Page
38.38% covered (danger)
38.38%
38 / 99
12.50% covered (danger)
12.50%
2 / 16
434.23
0.00% covered (danger)
0.00%
0 / 1
 init
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 add_admin_shell_member
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 load_as_admin_shell_guest
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 is_admin_shell_guest
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 should_add_menu
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
30
 maybe_load_wp_build
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
3.58
 add_menu
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 admin_init
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 render
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_admin_scripts
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
4.59
 load_wp_build
23.08% covered (danger)
23.08%
3 / 13
0.00% covered (danger)
0.00%
0 / 1
7.10
 load_wp_build_with_screen_alias
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
2.06
 alias_screen_id_for_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 restore_screen_id_after_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 is_social_admin_request
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
1<?php
2/**
3 * Social Admin Page class.
4 *
5 * @package automattic/jetpack-publicize
6 */
7
8namespace Automattic\Jetpack\Publicize;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
12use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13use Automattic\Jetpack\Current_Plan;
14use Automattic\Jetpack\Publicize\Publicize_Utils as Utils;
15use Automattic\Jetpack\Status\Host;
16
17/**
18 * The class to handle the Social Admin Page.
19 */
20class Social_Admin_Page {
21
22    /**
23     * Nonce action used when refreshing plan data.
24     */
25    public const REFRESH_PLAN_NONCE_ACTION = 'jetpack_social_refresh_plan_data';
26
27    /**
28     * The instance of the class.
29     *
30     * @var Social_Admin_Page
31     */
32    private static $instance;
33
34    /**
35     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
36     *
37     * @var string|null
38     */
39    private static $wp_build_original_screen_id = null;
40
41    /**
42     * Whether Social was loaded as a guest of another dashboard's admin shell.
43     *
44     * @var bool
45     */
46    private static $is_admin_shell_guest = false;
47
48    /**
49     * Initialize the class.
50     *
51     * @return Social_Admin_Page
52     */
53    public static function init() {
54        if ( ! isset( self::$instance ) ) {
55            self::$instance = new self();
56        }
57
58        return self::$instance;
59    }
60
61    /**
62     * The constructor.
63     */
64    private function __construct() {
65        // Load the wp-build dashboard at admin_menu priority 1 so its render
66        // function is defined before `add_menu` (priority 10) registers the page.
67        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
68        add_action( 'admin_menu', array( $this, 'add_menu' ) );
69        add_filter( 'jetpack_admin_shell_members', array( $this, 'add_admin_shell_member' ) );
70    }
71
72    /**
73     * Register Social with the Jetpack admin shell.
74     *
75     * @param array $members Shell members keyed by admin page slug.
76     * @return array
77     */
78    public function add_admin_shell_member( $members ) {
79        if ( ! self::should_add_menu() || ! current_user_can( 'publish_posts' ) ) {
80            return $members;
81        }
82        $members['jetpack-social'] = array(
83            'build_prefix' => 'jetpack_social',
84            'build_page'   => 'jetpack-social-dashboard',
85            'init_modules' => array( '@jetpack-social/init' ),
86            'title'        => 'Social',
87            'load'         => array( $this, 'load_as_admin_shell_guest' ),
88        );
89        return $members;
90    }
91
92    /**
93     * Ready the Social route and data on another shell member's page.
94     *
95     * Skips the screen ID alias, which would boot a second app, and wp_enqueue_media(), which is too heavy to run eagerly.
96     *
97     * @return void
98     */
99    public function load_as_admin_shell_guest() {
100        self::load_wp_build();
101        if ( function_exists( 'jetpack_social_register_script_modules' ) ) {
102            jetpack_social_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Defined in the generated build/modules.php.
103        }
104        self::$is_admin_shell_guest = true;
105        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ), 20 );
106    }
107
108    /**
109     * Whether Social was loaded as a guest of another dashboard's admin shell.
110     *
111     * @return bool
112     */
113    public static function is_admin_shell_guest() {
114        return self::$is_admin_shell_guest;
115    }
116
117    /**
118     * Whether the Social page should be registered for the current user and site.
119     *
120     * @return bool
121     */
122    private static function should_add_menu() {
123        // If this isn't an admin (or someone with the capability to change the module status )
124        // and Publicize is inactive, then don't render the admin page.
125        if ( ! current_user_can( 'manage_options' ) && ! Utils::is_publicize_active() ) {
126            return false;
127        }
128
129        // We don't need Jetpack connection on WP.com.
130        $needs_site_connection = ! ( new Host() )->is_wpcom_platform() && ! ( new Connection_Manager() )->is_connected();
131
132        // If the Jetpack Social plugin is not active, hide the menu if the site is not connected.
133        return defined( 'JETPACK_SOCIAL_PLUGIN_DIR' ) || ! $needs_site_connection;
134    }
135
136    /**
137     * Load the wp-build dashboard on the Social admin request.
138     *
139     * Hooked to `admin_menu` priority 1 so the wp-build render function and
140     * enqueue hook are in place before `add_menu()` runs at the default priority.
141     *
142     * @return void
143     */
144    public static function maybe_load_wp_build() {
145        if ( ! self::is_social_admin_request() ) {
146            return;
147        }
148
149        self::load_wp_build_with_screen_alias();
150
151        // wp-build registers standalone modules (e.g. the init module) on
152        // wp_default_scripts, which has already fired by admin_menu. Register them
153        // directly so the init module makes it into the import map.
154        if ( function_exists( 'jetpack_social_register_script_modules' ) ) {
155            jetpack_social_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
156        }
157    }
158
159    /**
160     * Add the admin menu.
161     */
162    public function add_menu() {
163
164        // Remove the old Social menu item, if it exists.
165        Admin_Menu::remove_menu( 'jetpack-social' );
166
167        if ( ! self::should_add_menu() ) {
168            return;
169        }
170
171        $page_suffix = Admin_Menu::add_menu(
172            /** "Jetpack Social" is a product name, do not translate. */
173            'Jetpack Social',
174            'Social',
175            'publish_posts',
176            'jetpack-social',
177            array( $this, 'render' ),
178            null,
179            array(
180                'product' => 'social',
181                'key'     => 'jetpack-social',
182            )
183        );
184
185        add_action( 'load-' . $page_suffix, array( $this, 'admin_init' ) );
186    }
187
188    /**
189     * Initialize the admin resources.
190     */
191    public function admin_init() {
192        // Refresh data if coming from purchase to ensure it is up to date
193        // without making API calls on every admin page load.
194        if ( isset( $_GET['refresh_plan_data'] ) ) {
195            check_admin_referer( self::REFRESH_PLAN_NONCE_ACTION );
196            if ( apply_filters( 'jetpack_social_should_refresh_plan_data', true ) ) {
197                Current_Plan::refresh_from_wpcom();
198            }
199        }
200
201        /**
202         * Use priority 20 to ensure that we can dequeue the old Social assets.
203         */
204        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ), 20 );
205
206        // Initialize the media library for the social image generator.
207        wp_enqueue_media();
208    }
209
210    /**
211     * Render the admin page by delegating to the wp-build dashboard.
212     *
213     * `maybe_load_wp_build()` defines the render function before this fires;
214     * render nothing on an unbuilt dev checkout rather than fatal.
215     */
216    public function render() {
217        if ( function_exists( 'jetpack_social_jetpack_social_dashboard_wp_admin_render_page' ) ) {
218            // Generated by wp-build (build/pages/jetpack-social-dashboard/page-wp-admin.php), so phan can't see it.
219            // @phan-suppress-next-line PhanUndeclaredFunction
220            jetpack_social_jetpack_social_dashboard_wp_admin_render_page();
221        }
222    }
223
224    /**
225     * Enqueue admin scripts and styles.
226     */
227    public function enqueue_admin_scripts() {
228        /*
229         * wp-build owns its own enqueue pipeline. The chassis reads connection
230         * state via `useConnection()`, which has no REST resolver, so hydrate it
231         * inline onto the prerequisites script that loads before the chassis module.
232         */
233        if ( wp_script_is( 'jetpack-social-dashboard-wp-admin-prerequisites', 'registered' ) ) {
234            Connection_Initial_State::render_script( 'jetpack-social-dashboard-wp-admin-prerequisites' );
235        } elseif ( self::$is_admin_shell_guest ) {
236            // As a guest, the prerequisites handle belongs to the host app, so use the always-present wp-api-fetch.
237            Connection_Initial_State::render_script( 'wp-api-fetch' );
238        }
239
240        // The i18n loader is registered on every admin page by jetpack-assets but
241        // only enqueued when depended on; the esbuild bundles don't pull it in.
242        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
243            wp_enqueue_script( 'wp-jp-i18n-loader' );
244        }
245    }
246
247    /**
248     * Load the wp-build entry file and register its polyfills.
249     *
250     * Only called on `?page=jetpack-social` admin requests. Keeps wp-build off
251     * every other request.
252     *
253     * @return void
254     */
255    private static function load_wp_build() {
256        $build_index = dirname( __DIR__ ) . '/build/build.php';
257
258        if ( ! file_exists( $build_index ) ) {
259            return;
260        }
261
262        require_once $build_index;
263
264        // The wp-build dashboard (unlike the Social bundles) uses the full polyfill set:
265        // the @wordpress/boot|route|a11y modules, wp-notices, wp-views, etc.
266        if ( ! class_exists( '\Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills' ) ) {
267            return;
268        }
269
270        \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::register(
271            'jetpack-social',
272            array_merge(
273                \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::SCRIPT_HANDLES,
274                \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::MODULE_IDS
275            )
276        );
277    }
278
279    /**
280     * Load wp-build with the screen ID aliased across its generated enqueue check.
281     *
282     * @see WP_Build_Screen_Id::load_with_alias()
283     * @return void
284     */
285    private static function load_wp_build_with_screen_alias() {
286        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
287        if ( method_exists( \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
288            \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id::load_with_alias(
289                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
290                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
291                function () {
292                    self::load_wp_build();
293                }
294            );
295            return;
296        }
297
298        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
299        self::load_wp_build();
300        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
301    }
302
303    /**
304     * Alias the current screen ID to satisfy wp-build's auto-generated enqueue check.
305     *
306     * The wp-build `<page>-wp-admin` enqueue callback fires only when the screen ID
307     * matches the wp-build page slug (`jetpack-social-dashboard`). Our wp-admin menu
308     * slug stays `jetpack-social`, so we mutate the screen object in place to make
309     * the check pass without changing the user-facing URL.
310     *
311     * Hooked only when we're on the Social admin page, so this never affects any
312     * other request.
313     *
314     * @since 0.87.1 Takes no argument; hooked on `admin_enqueue_scripts`.
315     *
316     * @return void
317     */
318    public static function alias_screen_id_for_wp_build() {
319        $screen = get_current_screen();
320        if ( ! $screen ) {
321            return;
322        }
323
324        self::$wp_build_original_screen_id = $screen->id;
325        $screen->id                        = 'jetpack-social-dashboard';
326    }
327
328    /**
329     * Undo alias_screen_id_for_wp_build(), so code after the generated check sees the real screen ID.
330     *
331     * @since 0.87.1
332     *
333     * @return void
334     */
335    public static function restore_screen_id_after_wp_build() {
336        $screen = get_current_screen();
337        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
338            return;
339        }
340
341        $screen->id                        = self::$wp_build_original_screen_id;
342        self::$wp_build_original_screen_id = null;
343    }
344
345    /**
346     * Returns true when the current request targets the Social admin page.
347     *
348     * Used to scope wp-build loading to the one page that needs it. The
349     * `$_GET['page']` value is populated by wp-admin/admin.php before any of
350     * our hooks fire, so this check is reliable from the constructor onwards.
351     *
352     * @return bool
353     */
354    private static function is_social_admin_request() {
355        if ( ! is_admin() || ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
356            return false;
357        }
358
359        return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === 'jetpack-social'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
360    }
361}