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