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