Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.77% covered (warning)
87.77%
165 / 188
70.37% covered (warning)
70.37%
19 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
88.71% covered (warning)
88.71%
165 / 186
70.37% covered (warning)
70.37%
19 / 27
68.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%
11 / 11
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_pro_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_payment_plans_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 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.4.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_filter( 'jetpack_newsletter_payment_plans_url', array( __CLASS__, 'get_payment_plans_url' ) );
162        add_action( 'admin_enqueue_scripts', array( Tracks::class, 'enqueue_transport' ) );
163
164        self::register_sections();
165    }
166
167    /**
168     * Register each of SECTIONS, skipping keys already registered so init() can run twice.
169     *
170     * @return void
171     */
172    private static function register_sections() {
173        foreach ( self::SECTIONS as $class ) {
174            $section = new $class();
175            if ( ! isset( self::$sections[ $section->get_key() ] ) ) {
176                self::register_section( $section );
177            }
178        }
179    }
180
181    /**
182     * Add a section to the dashboard.
183     *
184     * @param Dashboard_Section $section The section.
185     * @return void
186     */
187    public static function register_section( Dashboard_Section $section ) {
188        $key = $section->get_key();
189        if ( isset( self::$sections[ $key ] ) ) {
190            /* translators: %s is a dashboard section key. */
191            $message = sprintf( __( 'A Monetize dashboard section with the key "%s" is already registered.', 'jetpack-monetize' ), $key );
192            _doing_it_wrong( __METHOD__, esc_html( $message ), '0.2.0' );
193            return;
194        }
195        self::$sections[ $key ] = $section;
196    }
197
198    /**
199     * Register every section's REST routes.
200     *
201     * @return void
202     */
203    public static function register_rest_routes() {
204        foreach ( self::$sections as $section ) {
205            $section->register_routes();
206        }
207    }
208
209    /**
210     * Whether the current user may see the dashboard and use its REST routes.
211     *
212     * @return bool
213     */
214    public static function can_manage() {
215        return current_user_can( 'manage_options' );
216    }
217
218    /**
219     * Each section's state, keyed by section key.
220     *
221     * @return object[]
222     */
223    public static function get_initial_state() {
224        $state = array();
225        foreach ( self::$sections as $key => $section ) {
226            // An empty array would print as `[]`, and the page reads every section's state as an object.
227            $state[ $key ] = (object) $section->get_state();
228        }
229        return $state;
230    }
231
232    /**
233     * Add the page's data to `JetpackScriptData.monetize` on the dashboard's page: each section's state, and what every tab shares.
234     *
235     * @param array $data Script data.
236     * @return array
237     */
238    public static function add_script_data( $data ) {
239        if ( ! self::renders_dashboard() ) {
240            return $data;
241        }
242
243        $data['monetize']['sections']   = (object) self::get_initial_state();
244        $data['monetize']['upgradeUrl'] = self::get_upgrade_url();
245        $data['monetize']['tracks']     = Tracks::is_allowed();
246
247        return Tracks::add_identity( $data );
248    }
249
250    /**
251     * Where the page's upgrade links go: Jetpack Pro, unless a host sends them to its own plans.
252     *
253     * A host that sets `url` to an empty string offers no upgrade, and the page hides its links.
254     *
255     * @since 0.2.0
256     *
257     * @return string
258     */
259    public static function get_upgrade_url() {
260        /** This filter is documented in projects/packages/my-jetpack/src/class-main-features.php */
261        $upgrade = apply_filters(
262            'jetpack_feature_upgrade',
263            array(
264                'path'     => '',
265                'name'     => 'Jetpack Pro', // Product name, do not translate.
266                'back_url' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
267            ),
268            self::UPGRADE_SLUG,
269            false
270        );
271
272        if ( is_array( $upgrade ) && array_key_exists( 'url', $upgrade ) && '' === $upgrade['url'] ) {
273            return '';
274        }
275
276        $url = is_array( $upgrade ) ? esc_url_raw( (string) ( $upgrade['url'] ?? '' ) ) : '';
277
278        return $url ? $url : self::get_jetpack_pro_url();
279    }
280
281    /**
282     * Jetpack Pro's checkout, with the arguments Jetpack's other upgrade links carry.
283     *
284     * @return string
285     */
286    private static function get_jetpack_pro_url() {
287        $connection = new Connection_Manager();
288        $blog_id    = Jetpack_Options::get_option( 'id' );
289        $partner    = Partner::init();
290
291        $query = array();
292        if ( ! $connection->is_user_connected() ) {
293            $query['unlinked'] = 1;
294        }
295        // Lets an admin of a site with no connected user buy without a WordPress.com account.
296        if ( $connection->is_site_connection() && current_user_can( 'manage_options' ) ) {
297            $query['purchasetoken'] = self::get_purchase_token();
298        }
299        // Checkout sends the buyer back here instead of to Calypso.
300        $query['redirect_to'] = admin_url( 'admin.php?page=' . self::MENU_SLUG );
301
302        return Redirect::get_url(
303            'jetpack-monetize-pro-cta',
304            array(
305                'site'         => $blog_id ? (string) $blog_id : ( new Status() )->get_site_suffix(),
306                'aff'          => $partner->get_partner_code( Partner::AFFILIATE_CODE ),
307                'u'            => (string) get_current_user_id(),
308                'subsidiaryId' => $partner->get_partner_code( Partner::SUBSIDIARY_CODE ),
309                'query'        => http_build_query( $query ),
310                'calypso_env'  => ( new Host() )->get_calypso_env(),
311            )
312        );
313    }
314
315    /**
316     * The site's token for buying without a WordPress.com account, created on first use.
317     *
318     * @return string
319     */
320    private static function get_purchase_token() {
321        $token = Jetpack_Options::get_option( 'purchase_token' );
322        if ( ! $token ) {
323            $token = wp_generate_password( 12, false );
324            Jetpack_Options::update_option( 'purchase_token', $token, true );
325        }
326        return (string) $token;
327    }
328
329    /**
330     * Load wp-build output, only on this page's request.
331     *
332     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
333     *
334     * @return void
335     */
336    public static function maybe_load_wp_build() {
337        if ( self::is_dashboard_request() ) {
338            self::load_wp_build( self::build_index() );
339        }
340    }
341
342    /**
343     * Path to the generated wp-build index.
344     *
345     * @return string
346     */
347    private static function build_index() {
348        return self::$wp_build_index ?? dirname( __DIR__ ) . '/build/build.php';
349    }
350
351    /**
352     * Whether the request is for the dashboard's page.
353     *
354     * @return bool
355     */
356    public static function is_dashboard_request() {
357        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
358        return isset( $_GET['page'] ) && self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
359    }
360
361    /**
362     * Whether the request prints the dashboard's page data: its own page, or the admin shell loading it into another dashboard's page.
363     *
364     * @since 0.4.0
365     *
366     * @return bool
367     */
368    public static function renders_dashboard() {
369        if ( self::is_dashboard_request() ) {
370            return true;
371        }
372        // An older admin-ui under the jetpack-autoloader may predate requested_guest().
373        return method_exists( Admin_Shell::class, 'requested_guest' )
374            && self::MENU_SLUG === Admin_Shell::requested_guest();
375    }
376
377    /**
378     * Send Newsletter's paid plan buttons to the Payments tab.
379     *
380     * @since $$next-version$$
381     *
382     * @return string
383     */
384    public static function get_payment_plans_url() {
385        return self::get_tab_url( 'payments' );
386    }
387
388    /**
389     * The admin URL that opens one of the dashboard's tabs.
390     *
391     * @since 0.2.0
392     *
393     * @param string $tab The tab's `?tab=` value; 'overview' opens the bare page.
394     * @return string
395     */
396    public static function get_tab_url( $tab ) {
397        $path = 'admin.php?page=' . self::MENU_SLUG;
398        if ( 'overview' !== $tab ) {
399            // wp-build's router reads a route's search params from `p`.
400            $path .= '&p=' . rawurlencode( '/?tab=' . $tab );
401        }
402        return admin_url( $path );
403    }
404
405    /**
406     * Load a wp-build index and, if it can render the page, its scripts and polyfills.
407     *
408     * @param string $build_index Path to the generated build.php.
409     * @param bool   $alias       Whether to alias the screen ID, which only the dashboard's own page needs.
410     * @return bool Whether the build can render the page.
411     */
412    public static function load_wp_build( $build_index, $alias = true ) {
413        if ( ! file_exists( $build_index ) ) {
414            return false;
415        }
416
417        $load_wp_build = static function () use ( $build_index ) {
418            require_once $build_index;
419        };
420
421        if ( ! $alias ) {
422            $load_wp_build();
423        } elseif ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
424            WP_Build_Screen_Id::load_with_alias(
425                array( __CLASS__, 'alias_screen_id' ),
426                array( __CLASS__, 'restore_screen_id' ),
427                $load_wp_build
428            );
429        } else {
430            // An older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
431            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id' ) );
432            $load_wp_build();
433            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id' ) );
434        }
435
436        // A stale or partial build can't render the page, so don't swap core's scripts for it.
437        if ( ! function_exists( self::RENDER_FUNCTION ) ) {
438            return false;
439        }
440
441        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
442
443        // wp-build hooks module registration to wp_default_scripts, which has already fired by
444        // admin_menu â€” call it directly or the init module never reaches the import map.
445        if ( function_exists( 'jetpack_monetize_register_script_modules' ) ) {
446            jetpack_monetize_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
447        }
448
449        WP_Build_Polyfills::register(
450            'jetpack-monetize',
451            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS ),
452            null,
453            array(
454                array(
455                    'prefix' => 'jetpack_monetize',
456                    'slug'   => self::WP_BUILD_PAGE_ID,
457                ),
458            )
459        );
460
461        return true;
462    }
463
464    /**
465     * Register Monetize with the admin shell, which switches between Jetpack dashboards without a page load.
466     *
467     * @since 0.4.0
468     *
469     * @param array $members Shell members keyed by admin page slug.
470     * @return array
471     */
472    public static function add_admin_shell_member( $members ) {
473        if ( ! file_exists( self::build_index() ) ) {
474            return $members;
475        }
476
477        $title                      = __( 'Monetize', 'jetpack-monetize' );
478        $members[ self::MENU_SLUG ] = array(
479            'build_prefix' => 'jetpack_monetize',
480            'build_page'   => self::WP_BUILD_PAGE_ID,
481            'init_modules' => array( '@jetpack-monetize/init' ),
482            'title'        => $title,
483            'header'       => array(
484                'title'    => $title,
485                'subtitle' => '',
486            ),
487            'capability'   => 'manage_options',
488            // The connection initial state is an inline script on wp-api-fetch.
489            'handles'      => array( 'jetpack-script-data', 'wp-api-fetch', 'jp-tracks', 'wp-jp-i18n-loader' ),
490            'load'         => array( __CLASS__, 'load_as_admin_shell_guest' ),
491        );
492        return $members;
493    }
494
495    /**
496     * Ready the Monetize routes and page data while another dashboard's page is open, without the screen ID alias.
497     *
498     * @since 0.4.0
499     *
500     * @return void
501     */
502    public static function load_as_admin_shell_guest() {
503        self::load_wp_build( self::build_index(), false );
504    }
505
506    /**
507     * Point the screen ID at the wp-build page while its generated enqueue check runs.
508     *
509     * @return void
510     */
511    public static function alias_screen_id() {
512        $screen = get_current_screen();
513        if ( ! $screen ) {
514            return;
515        }
516
517        self::$original_screen_id = $screen->id;
518        $screen->id               = self::WP_BUILD_PAGE_ID;
519    }
520
521    /**
522     * Undo alias_screen_id(), since JITM builds its message path from the screen ID.
523     *
524     * @return void
525     */
526    public static function restore_screen_id() {
527        $screen = get_current_screen();
528        if ( ! $screen || null === self::$original_screen_id ) {
529            return;
530        }
531
532        $screen->id               = self::$original_screen_id;
533        self::$original_screen_id = null;
534    }
535
536    /**
537     * Enqueue the JS translation loader, which the esbuild route bundles don't pull in.
538     *
539     * @return void
540     */
541    public static function enqueue_i18n_loader() {
542        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
543            wp_enqueue_script( 'wp-jp-i18n-loader' );
544        }
545    }
546
547    /**
548     * Add the "Monetize" item to the Jetpack sidebar.
549     *
550     * @return void
551     */
552    public static function add_menu() {
553        Admin_Menu::add_menu(
554            __( 'Monetize', 'jetpack-monetize' ),
555            __( 'Monetize', 'jetpack-monetize' ),
556            'manage_options',
557            self::MENU_SLUG,
558            array( __CLASS__, 'render' ),
559            null,
560            array_merge( array( 'key' => self::MENU_SLUG ), self::$menu_options )
561        );
562    }
563
564    /**
565     * Add the "Monetize" item under the Jetpack menu on the WordPress.com platform, once wpcom-admin-menu.php has built that menu.
566     *
567     * @return void
568     */
569    public static function add_wp_admin_submenu() {
570        global $submenu;
571
572        // Admin_Menu already added it at 1000 where init() queued it, as on WoA.
573        if ( ! empty( $submenu['jetpack'] ) && in_array( self::MENU_SLUG, array_column( $submenu['jetpack'], 2 ), true ) ) {
574            return;
575        }
576
577        add_submenu_page(
578            'jetpack',
579            __( 'Monetize', 'jetpack-monetize' ),
580            __( 'Monetize', 'jetpack-monetize' ),
581            'manage_options',
582            self::MENU_SLUG,
583            array( __CLASS__, 'render' )
584        );
585    }
586
587    /**
588     * Render the wp-build page, or say why it could not be rendered.
589     *
590     * @return void
591     */
592    public static function render() {
593        $render_fn = self::RENDER_FUNCTION;
594        if ( function_exists( $render_fn ) ) {
595            $render_fn();
596            return;
597        }
598
599        printf(
600            '<div class="wrap"><h1>%s</h1><div class="notice notice-error"><p>%s</p></div></div>',
601            esc_html__( 'Monetize', 'jetpack-monetize' ),
602            esc_html__( 'The Monetize dashboard could not be loaded because its assets are missing.', 'jetpack-monetize' )
603        );
604    }
605}