Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.46% covered (warning)
84.46%
125 / 148
63.64% covered (warning)
63.64%
14 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
85.62% covered (warning)
85.62%
125 / 146
63.64% covered (warning)
63.64%
14 / 22
60.05
0.00% covered (danger)
0.00%
0 / 1
 register_feature_flag
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 is_enabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 init
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 register_sections
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 register_section
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 register_rest_routes
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 can_manage
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_initial_state
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 add_script_data
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 get_upgrade_url
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
6
 get_jetpack_creator_url
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 get_purchase_token
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 maybe_load_wp_build
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 is_dashboard_request
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_tab_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 load_wp_build
83.33% covered (warning)
83.33%
20 / 24
0.00% covered (danger)
0.00%
0 / 1
5.12
 alias_screen_id
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 restore_screen_id
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 enqueue_i18n_loader
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 add_menu
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 add_wp_admin_submenu
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 render
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
2.04
1<?php
2/**
3 * Monetize dashboard: a wp-build page in the Jetpack sidebar.
4 *
5 * @package automattic/jetpack-monetize
6 */
7
8namespace Automattic\Jetpack\Monetize;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Feature_Flags\Feature_Flags;
13use Automattic\Jetpack\Partner;
14use Automattic\Jetpack\Redirect;
15use Automattic\Jetpack\Status;
16use Automattic\Jetpack\Status\Host;
17use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
18use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
19use Jetpack_Options;
20
21if ( ! defined( 'ABSPATH' ) ) {
22    exit( 0 );
23}
24
25/**
26 * Registers the Monetize sidebar item and renders its wp-build route.
27 */
28class Dashboard {
29
30    /**
31     * Package version, bumped at release through composer.json `version-constants`.
32     *
33     * @var string
34     */
35    const PACKAGE_VERSION = '0.2.0';
36
37    /**
38     * Feature flag that makes the dashboard available while it is built.
39     *
40     * @var string
41     */
42    const FEATURE_FLAG = 'jetpack-monetize-dashboard';
43
44    /**
45     * Sidebar menu slug.
46     *
47     * @var string
48     */
49    const MENU_SLUG = 'jetpack-monetize';
50
51    /**
52     * The wp-build route's page id. It must not be the menu slug: the generated
53     * standalone page.php intercepts `admin_init` for its own id and exits.
54     *
55     * @var string
56     */
57    const WP_BUILD_PAGE_ID = 'jetpack-monetize-dashboard';
58
59    /**
60     * Name of the wp-build render function generated for WP_BUILD_PAGE_ID.
61     *
62     * @var string
63     */
64    const RENDER_FUNCTION = 'jetpack_monetize_jetpack_monetize_dashboard_wp_admin_render_page';
65
66    /**
67     * The slug the `jetpack_feature_upgrade` filter sees for this page's upgrade links.
68     *
69     * @var string
70     */
71    const UPGRADE_SLUG = 'monetize-dashboard';
72
73    /**
74     * The dashboard's sections.
75     *
76     * @var string[]
77     */
78    const SECTIONS = array(
79        Sections\Overview::class,
80        Sections\Payments::class,
81        Sections\Subscribers::class,
82        Sections\Ads::class,
83    );
84
85    /**
86     * Extra Admin_Menu item options, such as the module that owns the item.
87     *
88     * @var array
89     */
90    private static $menu_options = array();
91
92    /**
93     * The screen ID alias_screen_id() replaced, until it is restored.
94     *
95     * @var string|null
96     */
97    private static $original_screen_id = null;
98
99    /**
100     * Registered sections, keyed by section key.
101     *
102     * @var Dashboard_Section[]
103     */
104    private static $sections = array();
105
106    /**
107     * Register the flag. Hosts call this before they decide whether to load the dashboard.
108     *
109     * @return void
110     */
111    public static function register_feature_flag() {
112        Feature_Flags::register(
113            self::FEATURE_FLAG,
114            array(
115                'default'     => false,
116                'description' => 'Make the Monetize dashboard available while it is built.',
117                'owner'       => 'jetpack',
118            )
119        );
120    }
121
122    /**
123     * Whether the dashboard's feature flag is on.
124     *
125     * @return bool
126     */
127    public static function is_enabled() {
128        return Feature_Flags::is_enabled( self::FEATURE_FLAG );
129    }
130
131    /**
132     * Wire the hooks.
133     *
134     * @param array $menu_options Admin_Menu item options merged over the defaults, e.g. `module`.
135     * @return void
136     */
137    public static function init( array $menu_options = array() ) {
138        self::$menu_options = $menu_options;
139
140        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
141
142        // A wpcom host adds the item itself: see README.
143        if ( ! ( new Host() )->is_wpcom_platform() ) {
144            // Before Admin_Menu registers its items at 1000.
145            add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 999 );
146        }
147
148        // Simple reaches WordPress.com directly, so it needs none of the forwarding routes.
149        if ( ! ( new Host() )->is_wpcom_simple() ) {
150            add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
151        }
152
153        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
154        add_action( 'admin_enqueue_scripts', array( Tracks::class, 'enqueue_transport' ) );
155
156        self::register_sections();
157    }
158
159    /**
160     * Register each of SECTIONS, skipping keys already registered so init() can run twice.
161     *
162     * @return void
163     */
164    private static function register_sections() {
165        foreach ( self::SECTIONS as $class ) {
166            $section = new $class();
167            if ( ! isset( self::$sections[ $section->get_key() ] ) ) {
168                self::register_section( $section );
169            }
170        }
171    }
172
173    /**
174     * Add a section to the dashboard.
175     *
176     * @param Dashboard_Section $section The section.
177     * @return void
178     */
179    public static function register_section( Dashboard_Section $section ) {
180        $key = $section->get_key();
181        if ( isset( self::$sections[ $key ] ) ) {
182            /* translators: %s is a dashboard section key. */
183            $message = sprintf( __( 'A Monetize dashboard section with the key "%s" is already registered.', 'jetpack-monetize' ), $key );
184            _doing_it_wrong( __METHOD__, esc_html( $message ), '0.2.0' );
185            return;
186        }
187        self::$sections[ $key ] = $section;
188    }
189
190    /**
191     * Register every section's REST routes.
192     *
193     * @return void
194     */
195    public static function register_rest_routes() {
196        foreach ( self::$sections as $section ) {
197            $section->register_routes();
198        }
199    }
200
201    /**
202     * Whether the current user may see the dashboard and use its REST routes.
203     *
204     * @return bool
205     */
206    public static function can_manage() {
207        return current_user_can( 'manage_options' );
208    }
209
210    /**
211     * Each section's state, keyed by section key.
212     *
213     * @return object[]
214     */
215    public static function get_initial_state() {
216        $state = array();
217        foreach ( self::$sections as $key => $section ) {
218            // An empty array would print as `[]`, and the page reads every section's state as an object.
219            $state[ $key ] = (object) $section->get_state();
220        }
221        return $state;
222    }
223
224    /**
225     * Add the page's data to `JetpackScriptData.monetize` on the dashboard's page: each section's state, and what every tab shares.
226     *
227     * @param array $data Script data.
228     * @return array
229     */
230    public static function add_script_data( $data ) {
231        if ( ! self::is_dashboard_request() ) {
232            return $data;
233        }
234
235        $data['monetize']['sections']   = (object) self::get_initial_state();
236        $data['monetize']['upgradeUrl'] = self::get_upgrade_url();
237        $data['monetize']['tracks']     = Tracks::is_allowed();
238
239        return Tracks::add_identity( $data );
240    }
241
242    /**
243     * Where the page's upgrade links go: Jetpack Creator, unless a host sends them to its own plans.
244     *
245     * A host that sets `url` to an empty string offers no upgrade, and the page hides its links.
246     *
247     * @since 0.2.0
248     *
249     * @return string
250     */
251    public static function get_upgrade_url() {
252        /** This filter is documented in projects/packages/my-jetpack/src/class-main-features.php */
253        $upgrade = apply_filters(
254            'jetpack_feature_upgrade',
255            array(
256                'path'     => '',
257                'name'     => 'Jetpack Creator', // Product name, do not translate.
258                'back_url' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
259            ),
260            self::UPGRADE_SLUG,
261            false
262        );
263
264        if ( is_array( $upgrade ) && array_key_exists( 'url', $upgrade ) && '' === $upgrade['url'] ) {
265            return '';
266        }
267
268        $url = is_array( $upgrade ) ? esc_url_raw( (string) ( $upgrade['url'] ?? '' ) ) : '';
269
270        return $url ? $url : self::get_jetpack_creator_url();
271    }
272
273    /**
274     * Jetpack Creator's checkout, with the arguments Jetpack's other upgrade links carry.
275     *
276     * @return string
277     */
278    private static function get_jetpack_creator_url() {
279        $connection = new Connection_Manager();
280        $blog_id    = Jetpack_Options::get_option( 'id' );
281        $partner    = Partner::init();
282
283        $query = $connection->is_user_connected() ? '' : 'unlinked=1&';
284        // Lets an admin of a site with no connected user buy without a WordPress.com account.
285        if ( $connection->is_site_connection() && current_user_can( 'manage_options' ) ) {
286            $query .= 'purchasetoken=' . self::get_purchase_token();
287        }
288
289        return Redirect::get_url(
290            'jetpack-creator-cta',
291            array(
292                'site'         => $blog_id ? (string) $blog_id : ( new Status() )->get_site_suffix(),
293                'aff'          => $partner->get_partner_code( Partner::AFFILIATE_CODE ),
294                'u'            => (string) get_current_user_id(),
295                'subsidiaryId' => $partner->get_partner_code( Partner::SUBSIDIARY_CODE ),
296                'query'        => $query,
297                'calypso_env'  => ( new Host() )->get_calypso_env(),
298            )
299        );
300    }
301
302    /**
303     * The site's token for buying without a WordPress.com account, created on first use.
304     *
305     * @return string
306     */
307    private static function get_purchase_token() {
308        $token = Jetpack_Options::get_option( 'purchase_token' );
309        if ( ! $token ) {
310            $token = wp_generate_password( 12, false );
311            Jetpack_Options::update_option( 'purchase_token', $token, true );
312        }
313        return (string) $token;
314    }
315
316    /**
317     * Load wp-build output, only on this page's request.
318     *
319     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
320     *
321     * @return void
322     */
323    public static function maybe_load_wp_build() {
324        if ( self::is_dashboard_request() ) {
325            self::load_wp_build( dirname( __DIR__ ) . '/build/build.php' );
326        }
327    }
328
329    /**
330     * Whether the request is for the dashboard's page.
331     *
332     * @return bool
333     */
334    public static function is_dashboard_request() {
335        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
336        return isset( $_GET['page'] ) && self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
337    }
338
339    /**
340     * The admin URL that opens one of the dashboard's tabs.
341     *
342     * @since 0.2.0
343     *
344     * @param string $tab The tab's `?tab=` value; 'overview' opens the bare page.
345     * @return string
346     */
347    public static function get_tab_url( $tab ) {
348        $path = 'admin.php?page=' . self::MENU_SLUG;
349        if ( 'overview' !== $tab ) {
350            // wp-build's router reads a route's search params from `p`.
351            $path .= '&p=' . rawurlencode( '/?tab=' . $tab );
352        }
353        return admin_url( $path );
354    }
355
356    /**
357     * Load a wp-build index and, if it can render the page, its scripts and polyfills.
358     *
359     * @param string $build_index Path to the generated build.php.
360     * @return bool Whether the build can render the page.
361     */
362    public static function load_wp_build( $build_index ) {
363        if ( ! file_exists( $build_index ) ) {
364            return false;
365        }
366
367        $load_wp_build = static function () use ( $build_index ) {
368            require_once $build_index;
369        };
370
371        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
372        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
373            WP_Build_Screen_Id::load_with_alias(
374                array( __CLASS__, 'alias_screen_id' ),
375                array( __CLASS__, 'restore_screen_id' ),
376                $load_wp_build
377            );
378        } else {
379            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id' ) );
380            $load_wp_build();
381            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id' ) );
382        }
383
384        // A stale or partial build can't render the page, so don't swap core's scripts for it.
385        if ( ! function_exists( self::RENDER_FUNCTION ) ) {
386            return false;
387        }
388
389        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
390
391        // wp-build hooks module registration to wp_default_scripts, which has already fired by
392        // admin_menu — call it directly or the init module never reaches the import map.
393        if ( function_exists( 'jetpack_monetize_register_script_modules' ) ) {
394            jetpack_monetize_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
395        }
396
397        WP_Build_Polyfills::register(
398            'jetpack-monetize',
399            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
400        );
401
402        return true;
403    }
404
405    /**
406     * Point the screen ID at the wp-build page while its generated enqueue check runs.
407     *
408     * @return void
409     */
410    public static function alias_screen_id() {
411        $screen = get_current_screen();
412        if ( ! $screen ) {
413            return;
414        }
415
416        self::$original_screen_id = $screen->id;
417        $screen->id               = self::WP_BUILD_PAGE_ID;
418    }
419
420    /**
421     * Undo alias_screen_id(), since JITM builds its message path from the screen ID.
422     *
423     * @return void
424     */
425    public static function restore_screen_id() {
426        $screen = get_current_screen();
427        if ( ! $screen || null === self::$original_screen_id ) {
428            return;
429        }
430
431        $screen->id               = self::$original_screen_id;
432        self::$original_screen_id = null;
433    }
434
435    /**
436     * Enqueue the JS translation loader, which the esbuild route bundles don't pull in.
437     *
438     * @return void
439     */
440    public static function enqueue_i18n_loader() {
441        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
442            wp_enqueue_script( 'wp-jp-i18n-loader' );
443        }
444    }
445
446    /**
447     * Add the "Monetize" item to the Jetpack sidebar.
448     *
449     * @return void
450     */
451    public static function add_menu() {
452        Admin_Menu::add_menu(
453            __( 'Monetize', 'jetpack-monetize' ),
454            __( 'Monetize', 'jetpack-monetize' ),
455            'manage_options',
456            self::MENU_SLUG,
457            array( __CLASS__, 'render' ),
458            null,
459            array_merge( array( 'key' => self::MENU_SLUG ), self::$menu_options )
460        );
461    }
462
463    /**
464     * Add the "Monetize" item under the Jetpack menu on the WordPress.com platform, once wpcom-admin-menu.php has built that menu.
465     *
466     * @return void
467     */
468    public static function add_wp_admin_submenu() {
469        add_submenu_page(
470            'jetpack',
471            __( 'Monetize', 'jetpack-monetize' ),
472            __( 'Monetize', 'jetpack-monetize' ),
473            'manage_options',
474            self::MENU_SLUG,
475            array( __CLASS__, 'render' )
476        );
477    }
478
479    /**
480     * Render the wp-build page, or say why it could not be rendered.
481     *
482     * @return void
483     */
484    public static function render() {
485        $render_fn = self::RENDER_FUNCTION;
486        if ( function_exists( $render_fn ) ) {
487            $render_fn();
488            return;
489        }
490
491        printf(
492            '<div class="wrap"><h1>%s</h1><div class="notice notice-error"><p>%s</p></div></div>',
493            esc_html__( 'Monetize', 'jetpack-monetize' ),
494            esc_html__( 'The Monetize dashboard could not be loaded because its assets are missing.', 'jetpack-monetize' )
495        );
496    }
497}