Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.77% covered (warning)
84.77%
128 / 151
63.64% covered (warning)
63.64%
14 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
85.91% covered (warning)
85.91%
128 / 149
63.64% covered (warning)
63.64%
14 / 22
59.57
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%
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
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.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        // 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 = array();
284        if ( ! $connection->is_user_connected() ) {
285            $query['unlinked'] = 1;
286        }
287        // Lets an admin of a site with no connected user buy without a WordPress.com account.
288        if ( $connection->is_site_connection() && current_user_can( 'manage_options' ) ) {
289            $query['purchasetoken'] = self::get_purchase_token();
290        }
291        // Checkout sends the buyer back here instead of to Calypso.
292        $query['redirect_to'] = admin_url( 'admin.php?page=' . self::MENU_SLUG );
293
294        return Redirect::get_url(
295            'jetpack-creator-cta',
296            array(
297                'site'         => $blog_id ? (string) $blog_id : ( new Status() )->get_site_suffix(),
298                'aff'          => $partner->get_partner_code( Partner::AFFILIATE_CODE ),
299                'u'            => (string) get_current_user_id(),
300                'subsidiaryId' => $partner->get_partner_code( Partner::SUBSIDIARY_CODE ),
301                'query'        => http_build_query( $query ),
302                'calypso_env'  => ( new Host() )->get_calypso_env(),
303            )
304        );
305    }
306
307    /**
308     * The site's token for buying without a WordPress.com account, created on first use.
309     *
310     * @return string
311     */
312    private static function get_purchase_token() {
313        $token = Jetpack_Options::get_option( 'purchase_token' );
314        if ( ! $token ) {
315            $token = wp_generate_password( 12, false );
316            Jetpack_Options::update_option( 'purchase_token', $token, true );
317        }
318        return (string) $token;
319    }
320
321    /**
322     * Load wp-build output, only on this page's request.
323     *
324     * Scoped to the page so WP_Build_Polyfills does not replace core scripts everywhere else.
325     *
326     * @return void
327     */
328    public static function maybe_load_wp_build() {
329        if ( self::is_dashboard_request() ) {
330            self::load_wp_build( dirname( __DIR__ ) . '/build/build.php' );
331        }
332    }
333
334    /**
335     * Whether the request is for the dashboard's page.
336     *
337     * @return bool
338     */
339    public static function is_dashboard_request() {
340        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
341        return isset( $_GET['page'] ) && self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
342    }
343
344    /**
345     * The admin URL that opens one of the dashboard's tabs.
346     *
347     * @since 0.2.0
348     *
349     * @param string $tab The tab's `?tab=` value; 'overview' opens the bare page.
350     * @return string
351     */
352    public static function get_tab_url( $tab ) {
353        $path = 'admin.php?page=' . self::MENU_SLUG;
354        if ( 'overview' !== $tab ) {
355            // wp-build's router reads a route's search params from `p`.
356            $path .= '&p=' . rawurlencode( '/?tab=' . $tab );
357        }
358        return admin_url( $path );
359    }
360
361    /**
362     * Load a wp-build index and, if it can render the page, its scripts and polyfills.
363     *
364     * @param string $build_index Path to the generated build.php.
365     * @return bool Whether the build can render the page.
366     */
367    public static function load_wp_build( $build_index ) {
368        if ( ! file_exists( $build_index ) ) {
369            return false;
370        }
371
372        $load_wp_build = static function () use ( $build_index ) {
373            require_once $build_index;
374        };
375
376        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
377        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
378            WP_Build_Screen_Id::load_with_alias(
379                array( __CLASS__, 'alias_screen_id' ),
380                array( __CLASS__, 'restore_screen_id' ),
381                $load_wp_build
382            );
383        } else {
384            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id' ) );
385            $load_wp_build();
386            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id' ) );
387        }
388
389        // A stale or partial build can't render the page, so don't swap core's scripts for it.
390        if ( ! function_exists( self::RENDER_FUNCTION ) ) {
391            return false;
392        }
393
394        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
395
396        // wp-build hooks module registration to wp_default_scripts, which has already fired by
397        // admin_menu — call it directly or the init module never reaches the import map.
398        if ( function_exists( 'jetpack_monetize_register_script_modules' ) ) {
399            jetpack_monetize_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
400        }
401
402        WP_Build_Polyfills::register(
403            'jetpack-monetize',
404            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
405        );
406
407        return true;
408    }
409
410    /**
411     * Point the screen ID at the wp-build page while its generated enqueue check runs.
412     *
413     * @return void
414     */
415    public static function alias_screen_id() {
416        $screen = get_current_screen();
417        if ( ! $screen ) {
418            return;
419        }
420
421        self::$original_screen_id = $screen->id;
422        $screen->id               = self::WP_BUILD_PAGE_ID;
423    }
424
425    /**
426     * Undo alias_screen_id(), since JITM builds its message path from the screen ID.
427     *
428     * @return void
429     */
430    public static function restore_screen_id() {
431        $screen = get_current_screen();
432        if ( ! $screen || null === self::$original_screen_id ) {
433            return;
434        }
435
436        $screen->id               = self::$original_screen_id;
437        self::$original_screen_id = null;
438    }
439
440    /**
441     * Enqueue the JS translation loader, which the esbuild route bundles don't pull in.
442     *
443     * @return void
444     */
445    public static function enqueue_i18n_loader() {
446        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
447            wp_enqueue_script( 'wp-jp-i18n-loader' );
448        }
449    }
450
451    /**
452     * Add the "Monetize" item to the Jetpack sidebar.
453     *
454     * @return void
455     */
456    public static function add_menu() {
457        Admin_Menu::add_menu(
458            __( 'Monetize', 'jetpack-monetize' ),
459            __( 'Monetize', 'jetpack-monetize' ),
460            'manage_options',
461            self::MENU_SLUG,
462            array( __CLASS__, 'render' ),
463            null,
464            array_merge( array( 'key' => self::MENU_SLUG ), self::$menu_options )
465        );
466    }
467
468    /**
469     * Add the "Monetize" item under the Jetpack menu on the WordPress.com platform, once wpcom-admin-menu.php has built that menu.
470     *
471     * @return void
472     */
473    public static function add_wp_admin_submenu() {
474        add_submenu_page(
475            'jetpack',
476            __( 'Monetize', 'jetpack-monetize' ),
477            __( 'Monetize', 'jetpack-monetize' ),
478            'manage_options',
479            self::MENU_SLUG,
480            array( __CLASS__, 'render' )
481        );
482    }
483
484    /**
485     * Render the wp-build page, or say why it could not be rendered.
486     *
487     * @return void
488     */
489    public static function render() {
490        $render_fn = self::RENDER_FUNCTION;
491        if ( function_exists( $render_fn ) ) {
492            $render_fn();
493            return;
494        }
495
496        printf(
497            '<div class="wrap"><h1>%s</h1><div class="notice notice-error"><p>%s</p></div></div>',
498            esc_html__( 'Monetize', 'jetpack-monetize' ),
499            esc_html__( 'The Monetize dashboard could not be loaded because its assets are missing.', 'jetpack-monetize' )
500        );
501    }
502}