Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.53% covered (warning)
85.53%
136 / 159
63.64% covered (warning)
63.64%
14 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
86.62% covered (warning)
86.62%
136 / 157
63.64% covered (warning)
63.64%
14 / 22
59.72
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%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 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
 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
87.10% covered (warning)
87.10%
27 / 31
0.00% covered (danger)
0.00%
0 / 1
5.05
 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\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.3.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        // Simple adds the item itself and reaches WordPress.com directly, so it needs neither: see README.
143        if ( ! ( new Host() )->is_wpcom_simple() ) {
144            // Before Admin_Menu registers its items at 1000.
145            add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 999 );
146            add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
147        }
148
149        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
150        add_action( 'admin_enqueue_scripts', array( Tracks::class, 'enqueue_transport' ) );
151
152        self::register_sections();
153    }
154
155    /**
156     * Register each of SECTIONS, skipping keys already registered so init() can run twice.
157     *
158     * @return void
159     */
160    private static function register_sections() {
161        foreach ( self::SECTIONS as $class ) {
162            $section = new $class();
163            if ( ! isset( self::$sections[ $section->get_key() ] ) ) {
164                self::register_section( $section );
165            }
166        }
167    }
168
169    /**
170     * Add a section to the dashboard.
171     *
172     * @param Dashboard_Section $section The section.
173     * @return void
174     */
175    public static function register_section( Dashboard_Section $section ) {
176        $key = $section->get_key();
177        if ( isset( self::$sections[ $key ] ) ) {
178            /* translators: %s is a dashboard section key. */
179            $message = sprintf( __( 'A Monetize dashboard section with the key "%s" is already registered.', 'jetpack-monetize' ), $key );
180            _doing_it_wrong( __METHOD__, esc_html( $message ), '0.2.0' );
181            return;
182        }
183        self::$sections[ $key ] = $section;
184    }
185
186    /**
187     * Register every section's REST routes.
188     *
189     * @return void
190     */
191    public static function register_rest_routes() {
192        foreach ( self::$sections as $section ) {
193            $section->register_routes();
194        }
195    }
196
197    /**
198     * Whether the current user may see the dashboard and use its REST routes.
199     *
200     * @return bool
201     */
202    public static function can_manage() {
203        return current_user_can( 'manage_options' );
204    }
205
206    /**
207     * Each section's state, keyed by section key.
208     *
209     * @return object[]
210     */
211    public static function get_initial_state() {
212        $state = array();
213        foreach ( self::$sections as $key => $section ) {
214            // An empty array would print as `[]`, and the page reads every section's state as an object.
215            $state[ $key ] = (object) $section->get_state();
216        }
217        return $state;
218    }
219
220    /**
221     * Add the page's data to `JetpackScriptData.monetize` on the dashboard's page: each section's state, and what every tab shares.
222     *
223     * @param array $data Script data.
224     * @return array
225     */
226    public static function add_script_data( $data ) {
227        if ( ! self::is_dashboard_request() ) {
228            return $data;
229        }
230
231        $data['monetize']['sections']   = (object) self::get_initial_state();
232        $data['monetize']['upgradeUrl'] = self::get_upgrade_url();
233        $data['monetize']['tracks']     = Tracks::is_allowed();
234
235        return Tracks::add_identity( $data );
236    }
237
238    /**
239     * Where the page's upgrade links go: Jetpack Creator, unless a host sends them to its own plans.
240     *
241     * A host that sets `url` to an empty string offers no upgrade, and the page hides its links.
242     *
243     * @since 0.2.0
244     *
245     * @return string
246     */
247    public static function get_upgrade_url() {
248        /** This filter is documented in projects/packages/my-jetpack/src/class-main-features.php */
249        $upgrade = apply_filters(
250            'jetpack_feature_upgrade',
251            array(
252                'path'     => '',
253                'name'     => 'Jetpack Creator', // Product name, do not translate.
254                'back_url' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
255            ),
256            self::UPGRADE_SLUG,
257            false
258        );
259
260        if ( is_array( $upgrade ) && array_key_exists( 'url', $upgrade ) && '' === $upgrade['url'] ) {
261            return '';
262        }
263
264        $url = is_array( $upgrade ) ? esc_url_raw( (string) ( $upgrade['url'] ?? '' ) ) : '';
265
266        return $url ? $url : self::get_jetpack_creator_url();
267    }
268
269    /**
270     * Jetpack Creator's checkout, with the arguments Jetpack's other upgrade links carry.
271     *
272     * @return string
273     */
274    private static function get_jetpack_creator_url() {
275        $connection = new Connection_Manager();
276        $blog_id    = Jetpack_Options::get_option( 'id' );
277        $partner    = Partner::init();
278
279        $query = array();
280        if ( ! $connection->is_user_connected() ) {
281            $query['unlinked'] = 1;
282        }
283        // Lets an admin of a site with no connected user buy without a WordPress.com account.
284        if ( $connection->is_site_connection() && current_user_can( 'manage_options' ) ) {
285            $query['purchasetoken'] = self::get_purchase_token();
286        }
287        // Checkout sends the buyer back here instead of to Calypso.
288        $query['redirect_to'] = admin_url( 'admin.php?page=' . self::MENU_SLUG );
289
290        return Redirect::get_url(
291            'jetpack-creator-cta',
292            array(
293                'site'         => $blog_id ? (string) $blog_id : ( new Status() )->get_site_suffix(),
294                'aff'          => $partner->get_partner_code( Partner::AFFILIATE_CODE ),
295                'u'            => (string) get_current_user_id(),
296                'subsidiaryId' => $partner->get_partner_code( Partner::SUBSIDIARY_CODE ),
297                'query'        => http_build_query( $query ),
298                'calypso_env'  => ( new Host() )->get_calypso_env(),
299            )
300        );
301    }
302
303    /**
304     * The site's token for buying without a WordPress.com account, created on first use.
305     *
306     * @return string
307     */
308    private static function get_purchase_token() {
309        $token = Jetpack_Options::get_option( 'purchase_token' );
310        if ( ! $token ) {
311            $token = wp_generate_password( 12, false );
312            Jetpack_Options::update_option( 'purchase_token', $token, true );
313        }
314        return (string) $token;
315    }
316
317    /**
318     * Load wp-build output, only on this page's request.
319     *
320     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
321     *
322     * @return void
323     */
324    public static function maybe_load_wp_build() {
325        if ( self::is_dashboard_request() ) {
326            self::load_wp_build( dirname( __DIR__ ) . '/build/build.php' );
327        }
328    }
329
330    /**
331     * Whether the request is for the dashboard's page.
332     *
333     * @return bool
334     */
335    public static function is_dashboard_request() {
336        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
337        return isset( $_GET['page'] ) && self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
338    }
339
340    /**
341     * The admin URL that opens one of the dashboard's tabs.
342     *
343     * @since 0.2.0
344     *
345     * @param string $tab The tab's `?tab=` value; 'overview' opens the bare page.
346     * @return string
347     */
348    public static function get_tab_url( $tab ) {
349        $path = 'admin.php?page=' . self::MENU_SLUG;
350        if ( 'overview' !== $tab ) {
351            // wp-build's router reads a route's search params from `p`.
352            $path .= '&p=' . rawurlencode( '/?tab=' . $tab );
353        }
354        return admin_url( $path );
355    }
356
357    /**
358     * Load a wp-build index and, if it can render the page, its scripts and polyfills.
359     *
360     * @param string $build_index Path to the generated build.php.
361     * @return bool Whether the build can render the page.
362     */
363    public static function load_wp_build( $build_index ) {
364        if ( ! file_exists( $build_index ) ) {
365            return false;
366        }
367
368        $load_wp_build = static function () use ( $build_index ) {
369            require_once $build_index;
370        };
371
372        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
373        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
374            WP_Build_Screen_Id::load_with_alias(
375                array( __CLASS__, 'alias_screen_id' ),
376                array( __CLASS__, 'restore_screen_id' ),
377                $load_wp_build
378            );
379        } else {
380            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id' ) );
381            $load_wp_build();
382            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id' ) );
383        }
384
385        // A stale or partial build can't render the page, so don't swap core's scripts for it.
386        if ( ! function_exists( self::RENDER_FUNCTION ) ) {
387            return false;
388        }
389
390        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
391
392        // wp-build hooks module registration to wp_default_scripts, which has already fired by
393        // admin_menu — call it directly or the init module never reaches the import map.
394        if ( function_exists( 'jetpack_monetize_register_script_modules' ) ) {
395            jetpack_monetize_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
396        }
397
398        WP_Build_Polyfills::register(
399            'jetpack-monetize',
400            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS ),
401            null,
402            array(
403                array(
404                    'prefix' => 'jetpack_monetize',
405                    'slug'   => self::WP_BUILD_PAGE_ID,
406                ),
407            )
408        );
409
410        return true;
411    }
412
413    /**
414     * Point the screen ID at the wp-build page while its generated enqueue check runs.
415     *
416     * @return void
417     */
418    public static function alias_screen_id() {
419        $screen = get_current_screen();
420        if ( ! $screen ) {
421            return;
422        }
423
424        self::$original_screen_id = $screen->id;
425        $screen->id               = self::WP_BUILD_PAGE_ID;
426    }
427
428    /**
429     * Undo alias_screen_id(), since JITM builds its message path from the screen ID.
430     *
431     * @return void
432     */
433    public static function restore_screen_id() {
434        $screen = get_current_screen();
435        if ( ! $screen || null === self::$original_screen_id ) {
436            return;
437        }
438
439        $screen->id               = self::$original_screen_id;
440        self::$original_screen_id = null;
441    }
442
443    /**
444     * Enqueue the JS translation loader, which the esbuild route bundles don't pull in.
445     *
446     * @return void
447     */
448    public static function enqueue_i18n_loader() {
449        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
450            wp_enqueue_script( 'wp-jp-i18n-loader' );
451        }
452    }
453
454    /**
455     * Add the "Monetize" item to the Jetpack sidebar.
456     *
457     * @return void
458     */
459    public static function add_menu() {
460        Admin_Menu::add_menu(
461            __( 'Monetize', 'jetpack-monetize' ),
462            __( 'Monetize', 'jetpack-monetize' ),
463            'manage_options',
464            self::MENU_SLUG,
465            array( __CLASS__, 'render' ),
466            null,
467            array_merge( array( 'key' => self::MENU_SLUG ), self::$menu_options )
468        );
469    }
470
471    /**
472     * Add the "Monetize" item under the Jetpack menu on the WordPress.com platform, once wpcom-admin-menu.php has built that menu.
473     *
474     * @return void
475     */
476    public static function add_wp_admin_submenu() {
477        global $submenu;
478
479        // Admin_Menu already added it at 1000 where init() queued it, as on WoA.
480        if ( ! empty( $submenu['jetpack'] ) && in_array( self::MENU_SLUG, array_column( $submenu['jetpack'], 2 ), true ) ) {
481            return;
482        }
483
484        add_submenu_page(
485            'jetpack',
486            __( 'Monetize', 'jetpack-monetize' ),
487            __( 'Monetize', 'jetpack-monetize' ),
488            'manage_options',
489            self::MENU_SLUG,
490            array( __CLASS__, 'render' )
491        );
492    }
493
494    /**
495     * Render the wp-build page, or say why it could not be rendered.
496     *
497     * @return void
498     */
499    public static function render() {
500        $render_fn = self::RENDER_FUNCTION;
501        if ( function_exists( $render_fn ) ) {
502            $render_fn();
503            return;
504        }
505
506        printf(
507            '<div class="wrap"><h1>%s</h1><div class="notice notice-error"><p>%s</p></div></div>',
508            esc_html__( 'Monetize', 'jetpack-monetize' ),
509            esc_html__( 'The Monetize dashboard could not be loaded because its assets are missing.', 'jetpack-monetize' )
510        );
511    }
512}