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