Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.70% covered (success)
96.70%
176 / 182
100.00% covered (success)
100.00%
11 / 11
CRAP
n/a
0 / 0
Automattic\Jetpack\PremiumAnalytics\register_dashboard_section
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_registered_dashboard_section
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_available_dashboard_sections
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\configure_dashboard_sections_script_data
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\inject_dashboard_sections_script_data
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
8
Automattic\Jetpack\PremiumAnalytics\check_dashboard_sections_permission
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_available_dashboard_section_for_route
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
Automattic\Jetpack\PremiumAnalytics\get_dashboard_section_schema
100.00% covered (success)
100.00%
86 / 86
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\PremiumAnalytics\get_dashboard_sections_response
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\PremiumAnalytics\get_dashboard_section_default_layout_response
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\PremiumAnalytics\register_dashboard_sections_rest_routes
100.00% covered (success)
100.00%
37 / 37
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Dashboard Sections API: the registry helpers, the section script data, and the REST routes.
4 *
5 * The package's own sections register through this API from default-dashboard-sections.php,
6 * the same way a plugin extending the dashboard does.
7 *
8 * @package automattic/jetpack-premium-analytics
9 */
10
11namespace Automattic\Jetpack\PremiumAnalytics;
12
13require_once __DIR__ . '/dashboard-layout.php';
14require_once __DIR__ . '/dashboard-grammar.php';
15require_once __DIR__ . '/rest-namespace.php';
16require_once __DIR__ . '/class-dashboard-section.php';
17require_once __DIR__ . '/class-dashboard-section-registry.php';
18require_once __DIR__ . '/dashboard-first-visit.php';
19
20/**
21 * Registers a dashboard section.
22 *
23 * @param string $dashboard_name Dashboard identifier.
24 * @param string $id             Section identifier.
25 * @param array  $args           Optional. Section arguments.
26 * @return Dashboard_Section|false The registered section on success, or false on failure.
27 */
28function register_dashboard_section( $dashboard_name, $id, $args = array() ) {
29    return Dashboard_Section_Registry::get_instance()->register( $dashboard_name, $id, $args );
30}
31
32/**
33 * Retrieves a registered dashboard section.
34 *
35 * @param string $dashboard_name Dashboard identifier.
36 * @param string $id             Section identifier.
37 * @return Dashboard_Section|null The registered section, or null when absent.
38 */
39function get_registered_dashboard_section( $dashboard_name, $id ) {
40    return Dashboard_Section_Registry::get_instance()->get_registered( $dashboard_name, $id );
41}
42
43/**
44 * Retrieves available dashboard sections.
45 *
46 * @param string $dashboard_name Dashboard identifier.
47 * @return Dashboard_Section[] Ordered list of available sections.
48 */
49function get_available_dashboard_sections( $dashboard_name ) {
50    return Dashboard_Section_Registry::get_instance()->get_available_sections( $dashboard_name );
51}
52
53/**
54 * Configures the section script data.
55 *
56 * @since 0.6.0
57 *
58 * @return void
59 */
60function configure_dashboard_sections_script_data() {
61    add_filter( 'jetpack_admin_js_script_data', __NAMESPACE__ . '\\inject_dashboard_sections_script_data', 20 );
62}
63
64/**
65 * Injects the available section slugs, those the plan's date limits apply to, those that open
66 * without a connection, and whether the reader may see Stats, into JetpackScriptData.
67 *
68 * The same list travels over REST for the tab bar, but a report route reads no REST before
69 * choosing its redirect, so it reads the slugs from boot data instead.
70 *
71 * @since 0.6.0
72 *
73 * @param array $data The script data passed by the assets package.
74 * @return array
75 */
76function inject_dashboard_sections_script_data( array $data ): array {
77    if ( ! isset( $data['premium_analytics'] ) || ! is_array( $data['premium_analytics'] ) ) {
78        $data['premium_analytics'] = array();
79    }
80
81    // Surfaces outside any section, such as feedback, post to Stats endpoints.
82    $data['premium_analytics']['can_view_stats'] = Capabilities::current_user_can_view_stats();
83
84    // Switching the dashboard off sends the reader to classic Stats, so the client is told where that is.
85    $data['premium_analytics']['classic_stats_url'] = Classic_Stats::page_url();
86
87    // Once classic Stats is retired, Stats v2 stops asking for feedback.
88    $data['premium_analytics']['classic_stats_retired'] = Classic_Stats::is_retired();
89
90    $registry = Dashboard_Section_Registry::get_instance();
91
92    if ( ! empty( $registry->get_all_registered( DASHBOARD_NAME ) ) ) {
93        // One pass over the availability callbacks for all three lists.
94        $sections       = array();
95        $limited        = array();
96        $connectionless = array();
97        foreach ( $registry->get_available_sections( DASHBOARD_NAME ) as $section ) {
98            $sections[] = $section->slug;
99            if ( $section->follows_plan_date_limits ) {
100                $limited[] = $section->slug;
101            }
102            if ( ! $section->requires_connection ) {
103                $connectionless[] = $section->slug;
104            }
105        }
106
107        $data['premium_analytics']['sections']                   = $sections;
108        $data['premium_analytics']['plan_date_limited_sections'] = $limited;
109        // Only when there is one, so a site without leaves its script data as it was.
110        if ( $connectionless ) {
111            $data['premium_analytics']['connectionless_sections'] = $connectionless;
112        }
113    }
114
115    return $data;
116}
117
118/**
119 * Whether the current user can access dashboard section routes.
120 *
121 * @return bool
122 */
123function check_dashboard_sections_permission() {
124    return Capabilities::current_user_can_view_analytics();
125}
126
127/**
128 * Resolves a route section, including availability checks.
129 *
130 * @param string $dashboard_name Dashboard identifier.
131 * @param string $section_id     Section identifier.
132 * @return Dashboard_Section|\WP_Error Registered available section, or error.
133 */
134function get_available_dashboard_section_for_route( $dashboard_name, $section_id ) {
135    $section = get_registered_dashboard_section( $dashboard_name, $section_id );
136
137    if ( ! $section ) {
138        return new \WP_Error(
139            'dashboard_section_not_found',
140            __( 'Dashboard section not found.', 'jetpack-premium-analytics-pkg' ),
141            array( 'status' => 404 )
142        );
143    }
144
145    if ( ! $section->is_available() ) {
146        return new \WP_Error(
147            'dashboard_section_unavailable',
148            __( 'Dashboard section is not available.', 'jetpack-premium-analytics-pkg' ),
149            array( 'status' => 404 )
150        );
151    }
152
153    return $section;
154}
155
156/**
157 * REST schema for one dashboard section, as returned by the sections route.
158 *
159 * Mirrored by the frontend's `sections.ts` and reused by WPCOM for Simple sites (see AGENTS.md).
160 *
161 * @since 0.2.0
162 *
163 * @return array The JSON schema for a dashboard section.
164 */
165function get_dashboard_section_schema() {
166    return array(
167        '$schema'    => 'http://json-schema.org/draft-04/schema#',
168        'title'      => 'jetpack-premium-analytics-dashboard-section',
169        'type'       => 'object',
170        'properties' => array(
171            'id'                      => array(
172                'description' => __( 'Namespaced section identifier.', 'jetpack-premium-analytics-pkg' ),
173                'type'        => 'string',
174                'readonly'    => true,
175            ),
176            'slug'                    => array(
177                'description' => __( 'URL-facing section slug, derived from the identifier.', 'jetpack-premium-analytics-pkg' ),
178                'type'        => 'string',
179                'readonly'    => true,
180            ),
181            'label'                   => array(
182                'description' => __( 'Translated display label, naming the section tab.', 'jetpack-premium-analytics-pkg' ),
183                'type'        => 'string',
184                'readonly'    => true,
185            ),
186            'title'                   => array(
187                'description' => __( 'Translated section heading, distinct from the tab label. Null falls back to the label.', 'jetpack-premium-analytics-pkg' ),
188                'type'        => array( 'string', 'null' ),
189                'readonly'    => true,
190            ),
191            'order'                   => array(
192                'description' => __( 'Sort order, ascending.', 'jetpack-premium-analytics-pkg' ),
193                'type'        => 'integer',
194                'readonly'    => true,
195            ),
196            'date_filter'             => array(
197                'description' => __( 'Which shape the section date filter takes: the rolling date range, or all time plus single years.', 'jetpack-premium-analytics-pkg' ),
198                'type'        => 'string',
199                'enum'        => Dashboard_Section::DATE_FILTERS,
200                'default'     => Dashboard_Section::DATE_FILTER_RANGE,
201                'readonly'    => true,
202            ),
203            'date_filter_options'     => array(
204                'description' => __( 'What the section date filter supports, and where it renders.', 'jetpack-premium-analytics-pkg' ),
205                'type'        => 'object',
206                'properties'  => array(
207                    'with_date_comparison'         => array(
208                        'description' => __( 'Whether the section supports period-over-period comparison at all. When false, no widget in the section receives comparison parameters.', 'jetpack-premium-analytics-pkg' ),
209                        'type'        => 'boolean',
210                        'default'     => true,
211                    ),
212                    'with_header_date_control'     => array(
213                        'description' => __( 'Whether the section header renders the date control. When false, the section widgets host their own.', 'jetpack-premium-analytics-pkg' ),
214                        'type'        => 'boolean',
215                        'default'     => true,
216                    ),
217                    'with_header_interval_control' => array(
218                        'description' => __( 'Whether the section header renders the chart interval control. When false, the section charts host their own.', 'jetpack-premium-analytics-pkg' ),
219                        'type'        => 'boolean',
220                        'default'     => true,
221                    ),
222                ),
223                'readonly'    => true,
224            ),
225            'requires_sync'           => array(
226                'description' => __( 'Whether the section\'s numbers stay incomplete until the analytics initial full sync has finished.', 'jetpack-premium-analytics-pkg' ),
227                'type'        => 'boolean',
228                'default'     => false,
229                'readonly'    => true,
230            ),
231            'notice'                  => array(
232                'description' => __( 'Message shown above the section widgets, or null when there is none.', 'jetpack-premium-analytics-pkg' ),
233                'type'        => array( 'string', 'null' ),
234                'default'     => null,
235                'readonly'    => true,
236            ),
237            'default_layout'          => array(
238                'description' => __( 'Bundled default widget layout.', 'jetpack-premium-analytics-pkg' ),
239                'type'        => 'array',
240                'items'       => array( 'type' => 'object' ),
241                'readonly'    => true,
242            ),
243            'insertable_widget_types' => array(
244                'description' => __( 'Widget types the section inserter offers on top of its default layout.', 'jetpack-premium-analytics-pkg' ),
245                'type'        => 'array',
246                'items'       => array( 'type' => 'string' ),
247                'default'     => array(),
248                'readonly'    => true,
249            ),
250        ),
251    );
252}
253
254/**
255 * REST callback returning available dashboard sections.
256 *
257 * @param \WP_REST_Request $request REST request carrying the dashboard name.
258 * @return \WP_REST_Response
259 */
260function get_dashboard_sections_response( $request ) {
261    // Only a rendering dashboard asks for its sections, so this also counts a visit through the admin shell.
262    if ( DASHBOARD_NAME === $request['name'] ) {
263        store_dashboard_first_visit();
264    }
265
266    $sections = array_map(
267        static function ( Dashboard_Section $section ) {
268            return $section->to_array();
269        },
270        get_available_dashboard_sections( $request['name'] )
271    );
272
273    return rest_ensure_response( $sections );
274}
275
276/**
277 * REST callback returning a section's default layout.
278 *
279 * @param \WP_REST_Request $request REST request carrying dashboard and section identifiers.
280 * @return \WP_REST_Response|\WP_Error
281 */
282function get_dashboard_section_default_layout_response( $request ) {
283    $section = get_available_dashboard_section_for_route( $request['name'], $request['section'] );
284
285    if ( is_wp_error( $section ) ) {
286        return $section;
287    }
288
289    return rest_ensure_response( $section->get_default_layout() );
290}
291
292/**
293 * Registers dashboard section REST routes.
294 *
295 * @return void
296 */
297function register_dashboard_sections_rest_routes() {
298    register_rest_route(
299        DASHBOARD_REST_NAMESPACE,
300        '/dashboards/(?P<name>' . get_dashboard_name_pattern() . ')/sections',
301        array(
302            array(
303                // @phan-suppress-next-line PhanPluginMixedKeyNoKey -- register_rest_route()'s own signature mixes a numerically keyed endpoint list with a route-level `schema` key.
304                'methods'             => \WP_REST_Server::READABLE,
305                'callback'            => __NAMESPACE__ . '\\get_dashboard_sections_response',
306                'permission_callback' => __NAMESPACE__ . '\\check_dashboard_sections_permission',
307                'args'                => array(
308                    'name' => array(
309                        'description' => __( 'Dashboard identifier as produced by the build pipeline.', 'jetpack-premium-analytics-pkg' ),
310                        'type'        => 'string',
311                    ),
312                ),
313            ),
314            'schema' => __NAMESPACE__ . '\\get_dashboard_section_schema',
315        )
316    );
317
318    register_rest_route(
319        DASHBOARD_REST_NAMESPACE,
320        '/dashboards/(?P<name>' . get_dashboard_name_pattern() . ')/sections/(?P<section>' . get_dashboard_section_id_pattern() . ')/default-layout',
321        array(
322            'methods'             => \WP_REST_Server::READABLE,
323            'callback'            => __NAMESPACE__ . '\\get_dashboard_section_default_layout_response',
324            'permission_callback' => __NAMESPACE__ . '\\check_dashboard_sections_permission',
325            'args'                => array(
326                'name'    => array(
327                    'description' => __( 'Dashboard identifier as produced by the build pipeline.', 'jetpack-premium-analytics-pkg' ),
328                    'type'        => 'string',
329                ),
330                'section' => array(
331                    'description' => __( 'Dashboard section identifier.', 'jetpack-premium-analytics-pkg' ),
332                    'type'        => 'string',
333                ),
334            ),
335        )
336    );
337}