Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
54.93% covered (warning)
54.93%
117 / 213
71.43% covered (warning)
71.43%
15 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard
55.45% covered (warning)
55.45%
117 / 211
71.43% covered (warning)
71.43%
15 / 21
390.00
0.00% covered (danger)
0.00%
0 / 1
 load_wp_build
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
4.03
 wp_build_index_path
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 init
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 add_admin_shell_member
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 load_as_admin_shell_guest
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 announce_retired_filter
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 redirect_dashboard_url_cross_variant
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 get_admin_query_page
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 load_admin_scripts
0.00% covered (danger)
0.00%
0 / 73
0.00% covered (danger)
0.00%
0 / 1
56
 is_wp_build_dashboard_page
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_admin_submenu
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
3
 render_dashboard
n/a
0 / 0
n/a
0 / 0
1
 render_wp_build_unavailable
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 has_feedback
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 get_classic_forms_state
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 detect_classic_forms
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 mark_classic_form_detected
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_forms_admin_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_single_response_admin_url
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 get_default_tab
n/a
0 / 0
n/a
0 / 0
3
 get_forms_admin_path_wp_build
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
 is_jetpack_forms_admin_page
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
4.59
 is_notes_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_admin_url
n/a
0 / 0
n/a
0 / 0
3
1<?php
2/**
3 * Jetpack forms dashboard.
4 *
5 * @package automattic/jetpack-forms
6 */
7
8namespace Automattic\Jetpack\Forms\Dashboard;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
12use Automattic\Jetpack\Forms\ContactForm\Contact_Form;
13use Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin;
14use Automattic\Jetpack\Tracking;
15use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
16
17if ( ! defined( 'ABSPATH' ) ) {
18    exit( 0 );
19}
20
21/**
22 * Handles the Jetpack Forms dashboard.
23 */
24class Dashboard {
25    /**
26     * Load wp-build generated files if available.
27     * This is for the new DataViews-based responses list.
28     */
29    public static function load_wp_build() {
30        // Always load for the standalone Forms page.
31        $should_load = self::get_admin_query_page() === self::FORMS_WPBUILD_ADMIN_SLUG;
32
33        /**
34         * Filter whether to load the wp-build asset registrations.
35         * Host applications (e.g., CIAB) can return true to opt in.
36         *
37         * @param bool $should_load Whether build.php should be loaded.
38         */
39        $should_load = apply_filters( 'jetpack_forms_load_wp_build', $should_load );
40
41        if ( ! $should_load ) {
42            return;
43        }
44
45        $wp_build_index = self::wp_build_index_path();
46
47        if ( file_exists( $wp_build_index ) ) {
48            require_once $wp_build_index;
49        }
50
51        // The remaining setup only applies to the standalone Forms page.
52        if ( self::get_admin_query_page() !== self::FORMS_WPBUILD_ADMIN_SLUG ) {
53            return;
54        }
55
56        // Register polyfills for WP < 7.0 (must run before enqueue).
57        WP_Build_Polyfills::register(
58            'jetpack-forms',
59            array_merge(
60                WP_Build_Polyfills::SCRIPT_HANDLES,
61                WP_Build_Polyfills::MODULE_IDS
62            )
63        );
64    }
65
66    /**
67     * Overrides the generated entry point path. Test seam, null in production.
68     *
69     * Private with no setter: tests reach it by reflection, so nothing outside the
70     * package can point the dashboard at another file.
71     *
72     * @var string|null
73     */
74    private static $wp_build_index = null;
75
76    /**
77     * Absolute path to the entry point generated by the WP build script.
78     *
79     * @return string
80     */
81    private static function wp_build_index_path() {
82        return self::$wp_build_index ?? dirname( __DIR__, 2 ) . '/build/build.php';
83    }
84
85    /**
86     * Script handle for the JS file we enqueue in the Feedback admin page.
87     *
88     * @var string
89     * @deprecated 8.2.0 The legacy dashboard bundle was removed.
90     */
91    const SCRIPT_HANDLE = 'jp-forms-dashboard';
92
93    const ADMIN_SLUG = 'jetpack-forms-admin';
94
95    /**
96     * Slug for the wp-admin integrated Responses UI (wp-build page).
97     *
98     * Note: This must be a valid submenu slug (sanitize_key compatible), not a full URL.
99     *
100     * @var string
101     */
102    const FORMS_WPBUILD_ADMIN_SLUG = 'jetpack-forms-responses-wp-admin';
103
104    /**
105     * Cookie holding the top tab the user last chose, written by src/dashboard/last-tab-cookie.ts.
106     */
107    const LAST_TAB_COOKIE = 'jetpack_forms_last_tab';
108
109    /**
110     * Priority for the dashboard menu.
111     * Needs to be high enough for us to be able to unregister the default edit.php menu item.
112     *
113     * @var int
114     */
115    const MENU_PRIORITY = 999;
116
117    /**
118     * Initialize the dashboard.
119     */
120    public function init() {
121        add_action( 'admin_menu', array( $this, 'add_admin_submenu' ), self::MENU_PRIORITY );
122        add_action( 'admin_menu', array( __CLASS__, 'redirect_dashboard_url_cross_variant' ), 1 );
123        add_action( 'admin_notices', array( __CLASS__, 'announce_retired_filter' ) );
124
125        self::load_wp_build();
126
127        add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_scripts' ) );
128        add_filter( 'jetpack_admin_shell_members', array( __CLASS__, 'add_admin_shell_member' ) );
129    }
130
131    /**
132     * Whether Forms was loaded as a guest of another dashboard's admin shell.
133     *
134     * @var bool
135     */
136    private static $is_admin_shell_guest = false;
137
138    /**
139     * Register Forms with the Jetpack admin shell.
140     *
141     * @param array $members Shell members keyed by admin page slug.
142     * @return array
143     */
144    public static function add_admin_shell_member( $members ) {
145        $members[ self::FORMS_WPBUILD_ADMIN_SLUG ] = array(
146            'build_prefix' => 'jetpack_forms',
147            'build_page'   => 'jetpack-forms-responses',
148            'init_modules' => array( '@jetpack-forms/init' ),
149            'default_path' => self::get_forms_admin_path_wp_build( self::get_default_tab(), null ),
150            'title'        => 'Forms',
151            'load'         => array( __CLASS__, 'load_as_admin_shell_guest' ),
152        );
153        return $members;
154    }
155
156    /**
157     * Ready the Forms routes and data on another shell member's page.
158     *
159     * @return void
160     */
161    public static function load_as_admin_shell_guest() {
162        $wp_build_index = self::wp_build_index_path();
163        if ( ! file_exists( $wp_build_index ) ) {
164            return;
165        }
166        require_once $wp_build_index;
167
168        // The generated registration runs on wp_default_scripts, which has fired by admin_menu.
169        if ( function_exists( 'jetpack_forms_register_script_modules' ) ) {
170            jetpack_forms_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Defined in the generated build/modules.php.
171        }
172        self::$is_admin_shell_guest = true;
173    }
174
175    /**
176     * Tell anyone still filtering `jetpack_forms_alpha` that it no longer does anything.
177     *
178     * The filter gated the wp-build dashboard while it was in development. That dashboard
179     * is now the only one, so a `false` return has nothing left to select and is ignored.
180     *
181     * Announced rather than applied: _deprecated_hook() reports the hook without honoring
182     * it, where apply_filters_deprecated() would return a `false` this code can no longer
183     * act on. Guarded by has_filter() so sites that never used it stay silent.
184     *
185     * Hooked to `admin_notices` rather than called from init(). This class loads at
186     * `after_setup_theme` priority -2, so with WP_DEBUG display on the notice would print
187     * â€” and send headers â€” before load_wp_build() and redirect_dashboard_url_cross_variant()
188     * get to redirect, leaving both on "headers already sent" and a blank page.
189     *
190     * That hook also fires only while an admin screen renders, so the notice stays out of
191     * admin-ajax and admin-post responses, which `is_admin()` would have let through. And
192     * it runs late enough that has_filter() sees callbacks registered on `init`, not just
193     * those added at file scope.
194     *
195     * @since 8.1.0
196     */
197    public static function announce_retired_filter() {
198        if ( ! has_filter( 'jetpack_forms_alpha' ) ) {
199            return;
200        }
201
202        // Kept on one line: replace-next-version-tag.sh only recognizes the token in a
203        // single-line deprecation call, and errors the build out otherwise.
204        _deprecated_hook( 'jetpack_forms_alpha', 'jetpack-forms-8.1.0', '', 'The legacy Forms dashboard has been removed, so this filter no longer selects anything.' );
205    }
206
207    /**
208     * Send legacy dashboard URLs to the wp-build dashboard.
209     *
210     * Load-bearing, not a courtesy for stale links: Creative Mail's JITMs and post-install
211     * redirect, and My Jetpack's fallback URL, still emit the legacy slug today. Keep it.
212     */
213    public static function redirect_dashboard_url_cross_variant() {
214        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
215        $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
216
217        if ( $page !== self::ADMIN_SLUG ) {
218            return;
219        }
220
221        // The hash is never sent to the server. "inbox" used as default tab so we end up specifically in the responses
222        // route, where the client-side router will handle the redirect to the correct status in its beforeLoad hook.
223        wp_safe_redirect( self::get_forms_admin_url( 'inbox' ) );
224        exit;
225    }
226
227    /**
228     * Get the current query 'page' parameter.
229     *
230     * @return string
231     */
232    private static function get_admin_query_page() {
233        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
234        return isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
235    }
236
237    /**
238     * Load JavaScript for the dashboard.
239     */
240    public function load_admin_scripts() {
241        if ( ! self::is_jetpack_forms_admin_page() && ! self::$is_admin_shell_guest ) {
242            return;
243        }
244
245        // Attach the shared inline data (connection initial state + REST preload) to
246        // wp-api-fetch, which is always on the page.
247        $inline_handle    = 'wp-api-fetch';
248        $preload_position = 'after';
249
250        // The i18n loader is registered on every admin page by jetpack-assets but
251        // only enqueued when depended on; the esbuild bundles don't pull it in.
252        // Enqueue it so the wp-build dashboard's init module can download its JS
253        // translation catalogs.
254        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
255            wp_enqueue_script( 'wp-jp-i18n-loader' );
256        }
257
258        if ( Contact_Form_Plugin::can_use_analytics() ) {
259            Tracking::register_tracks_functions_scripts( true );
260        }
261
262        // Adds Connection package initial state.
263        Connection_Initial_State::render_script( $inline_handle );
264
265        // Preload Forms endpoints needed in dashboard context.
266        // Pre-fetch the first inbox page so the UI renders instantly on first load.
267        $preload_params = array(
268            'context'       => 'edit',
269            'fields_format' => 'collection',
270            'order'         => 'desc',
271            'orderby'       => 'date',
272            'page'          => 1,
273            'per_page'      => 20,
274            'status'        => 'draft,publish',
275        );
276        \ksort( $preload_params );
277        $initial_responses_path        = \add_query_arg( $preload_params, '/wp/v2/feedback' );
278        $initial_responses_locale_path = \add_query_arg(
279            \array_merge(
280                $preload_params,
281                array( '_locale' => 'user' )
282            ),
283            '/wp/v2/feedback'
284        );
285        $filters_path                  = '/wp/v2/feedback/filters';
286        $filters_locale_path           = \add_query_arg( array( '_locale' => 'user' ), $filters_path );
287        $preload_paths                 = array(
288            '/wp/v2/types?context=view',
289            '/wp/v2/feedback/config',
290            '/wp/v2/feedback/integrations-metadata',
291            '/wp/v2/feedback/counts',
292            $filters_path,
293            $filters_locale_path,
294            $initial_responses_path,
295            $initial_responses_locale_path,
296        );
297
298        // Only preload the Forms list endpoint when centralized form management is enabled.
299        if ( Contact_Form_Plugin::has_editor_feature_flag( 'central-form-management' ) ) {
300            $forms_preload_params = array(
301                'context'               => 'edit',
302                'page'                  => 1,
303                'jetpack_forms_context' => 'dashboard',
304                'order'                 => 'desc',
305                'orderby'               => 'modified',
306                'per_page'              => 20,
307                'status'                => 'publish,draft,pending,future,private',
308            );
309            ksort( $forms_preload_params );
310            $preload_paths[] = add_query_arg( $forms_preload_params, '/wp/v2/jetpack-forms' );
311            $preload_paths[] = add_query_arg(
312                array_merge(
313                    $forms_preload_params,
314                    array( '_locale' => 'user' )
315                ),
316                '/wp/v2/jetpack-forms'
317            );
318            $preload_paths[] = '/wp/v2/jetpack-forms/status-counts';
319            $preload_paths[] = add_query_arg( array( '_locale' => 'user' ), '/wp/v2/jetpack-forms/status-counts' );
320        }
321        $preload_data_raw = array_reduce( $preload_paths, 'rest_preload_api_request', array() );
322
323        // Normalize keys to match what apiFetch will request (without domain).
324        $preload_data = array();
325        foreach ( $preload_data_raw as $key => $value ) {
326            $normalized_key                  = preg_replace( '#^https?://[^/]+/wp-json#', '', $key );
327            $preload_data[ $normalized_key ] = $value;
328        }
329
330        wp_add_inline_script(
331            $inline_handle,
332            sprintf(
333                'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );',
334                wp_json_encode( $preload_data, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP )
335            ),
336            $preload_position
337        );
338    }
339
340    /**
341     * Whether the current request targets the Forms dashboard page.
342     *
343     * @return bool
344     */
345    public static function is_wp_build_dashboard_page() {
346        return self::get_admin_query_page() === self::FORMS_WPBUILD_ADMIN_SLUG;
347    }
348
349    /**
350     * Register the dashboard admin submenu Forms under Jetpack menu.
351     */
352    public function add_admin_submenu() {
353        // Report a missing build here rather than only on the page itself, so a partial
354        // deploy shows up on the first admin request instead of waiting for someone to
355        // open Forms. Keyed on the file and not on the generated callback: load_wp_build()
356        // only requires build.php on the Forms page, so the callback is legitimately
357        // absent on every other admin screen, which runs this method too.
358        if ( ! file_exists( self::wp_build_index_path() ) ) {
359            _doing_it_wrong(
360                __METHOD__,
361                'The Jetpack Forms build output is missing: build/build.php is absent, so the dashboard has nothing to render. The package build did not run for this deploy.',
362                ''
363            );
364        }
365
366        // `jetpack_forms_jetpack_forms_responses_wp_admin_render_page` is the callback generated
367        // by the WP build script, named after the page slug. It only exists once `build/build.php`
368        // is loaded. Without it the page has nothing to render, so show an explanation.
369        $callback = function_exists( 'jetpack_forms_jetpack_forms_responses_wp_admin_render_page' )
370            ? 'jetpack_forms_jetpack_forms_responses_wp_admin_render_page'
371            : array( $this, 'render_wp_build_unavailable' );
372
373        Admin_Menu::add_menu(
374            /** "Jetpack Forms" and "Forms" are product names, do not translate. */
375            'Jetpack Forms',
376            'Forms',
377            'edit_pages',
378            self::FORMS_WPBUILD_ADMIN_SLUG,
379            $callback,
380            null,
381            // The key is not the slug: the page's URL still reads
382            // jetpack-forms-responses-wp-admin, which FORMS-795 tracks separately.
383            array(
384                'product' => 'jetpack-forms',
385                'key'     => 'jetpack-forms',
386            )
387        );
388    }
389
390    /**
391     * Render the legacy dashboard mount point.
392     *
393     * Nothing registers this any more â€” the legacy dashboard was retired and its bundle
394     * is no longer enqueued, so the container it prints stays empty. Kept, and left
395     * printing the same markup, so any caller outside this package behaves as before.
396     *
397     * @deprecated 8.1.0 The legacy dashboard was retired.
398     */
399    public function render_dashboard() {
400        _deprecated_function( __METHOD__, 'jetpack-forms-8.1.0' );
401        ?>
402        <div id="jp-forms-dashboard"></div>
403        <?php
404    }
405
406    /**
407     * Render an error notice when the wp-build dashboard cannot render.
408     *
409     * The wp-build dashboard renders through a callback generated into `build/build.php`.
410     * That file is missing when the package ships without a complete build, and it is
411     * never loaded when a host application filters `jetpack_forms_load_wp_build` to false.
412     * So report the problem instead of rendering a blank page.
413     *
414     * @since 7.25.0
415     */
416    public function render_wp_build_unavailable() {
417        ?>
418        <div class="wrap">
419            <?php /* "Jetpack Forms" is a product name, do not translate. */ ?>
420            <h1>Jetpack Forms</h1>
421            <div class="notice notice-error">
422                <p><?php esc_html_e( 'The Forms dashboard is missing the files it needs to load.', 'jetpack-forms' ); ?></p>
423                <p><?php esc_html_e( 'Reinstalling or updating the plugin usually fixes this. If this site is configured not to load the Forms dashboard, contact your site administrator or host.', 'jetpack-forms' ); ?></p>
424            </div>
425        </div>
426        <?php
427    }
428
429    /**
430     * Returns true if there are any feedback posts on the site.
431     *
432     * @return boolean
433     */
434    public function has_feedback() {
435        $posts = new \WP_Query(
436            array(
437                'post_type'              => 'feedback',
438                'post_status'            => array( 'publish', 'draft', 'spam', 'trash' ),
439                'posts_per_page'         => 1,
440                'fields'                 => 'ids',
441                'no_found_rows'          => true,
442                'update_post_meta_cache' => false,
443                'update_post_term_cache' => false,
444                'suppress_filters'       => true,
445            )
446        );
447        return $posts->have_posts();
448    }
449
450    /**
451     * Option name for storing classic forms state.
452     */
453    const CLASSIC_FORMS_OPTION = 'jetpack_forms_classic_state';
454
455    /**
456     * Classic forms state: site has classic (non-synced) form submissions.
457     */
458    const CLASSIC_FORMS_STATE_CLASSIC = 'classic';
459
460    /**
461     * Classic forms state: no classic form submissions detected.
462     */
463    const CLASSIC_FORMS_STATE_HIDDEN = 'hidden';
464
465    /**
466     * Classic forms state: user dismissed the classic forms notice.
467     */
468    const CLASSIC_FORMS_STATE_DISMISSED = 'dismissed';
469
470    /**
471     * Returns the classic forms state for the current site.
472     *
473     * Returns 'classic' if the site has form submissions (feedback posts) that were not
474     * created by a synced/reusable jetpack_form, 'dismissed' if the user dismissed the
475     * classic forms notice, or 'hidden' otherwise.
476     *
477     * The result is persisted in a WP option so the detection query only runs once per site.
478     * After that, the cached value is returned on every subsequent call. The cache is also
479     * updated eagerly via mark_classic_form_detected() when new classic submissions arrive.
480     *
481     * @since 7.14.0
482     *
483     * @return string 'classic', 'hidden', or 'dismissed'.
484     */
485    public function get_classic_forms_state() {
486        $state = get_option( self::CLASSIC_FORMS_OPTION );
487
488        if ( $state ) {
489            return $state;
490        }
491
492        $state = $this->detect_classic_forms();
493        update_option( self::CLASSIC_FORMS_OPTION, $state, false );
494
495        return $state;
496    }
497
498    /**
499     * Detects whether any feedback posts exist that are not linked to a jetpack_form post,
500     * indicating the site has classic (inline, widget, or template) forms.
501     *
502     * A feedback post is considered "classic" if:
503     * - It has no parent (post_parent = 0), meaning it was created by a form embedded in a
504     *   widget, page template, or other non-post context.
505     * - Its parent exists but is not a jetpack_form post, meaning it was created by a form
506     *   block or shortcode placed directly in a post or page.
507     *
508     * The query uses a LEFT JOIN on the posts table to find feedback posts with no matching
509     * jetpack_form parent. This leverages the primary key index for the join and the
510     * type_status_date index for filtering by post_type, making it efficient even on large
511     * sites. The LIMIT 1 ensures early exit as soon as one classic form is found.
512     *
513     * Note: An alternative approach would be to search post_content for the form block markup
514     * (<!-- wp:jetpack/contact-form) or shortcode ([contact-form]). However, that requires a
515     * full-text scan of the posts table (LIKE '%...%' on a TEXT column) with no usable index,
516     * making it significantly more expensive. The feedback-based approach also better fits the
517     * use case: we only need to surface the "Not seeing all your forms?" prompt when there are
518     * actual submissions that won't appear under any synced form in the dashboard.
519     *
520     * @since 7.14.0
521     *
522     * @return string 'classic' or 'hidden'.
523     */
524    private function detect_classic_forms() {
525        global $wpdb;
526
527        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
528        $result = $wpdb->get_var(
529            $wpdb->prepare(
530                "SELECT 1 FROM {$wpdb->posts} AS f
531                LEFT JOIN {$wpdb->posts} AS p
532                    ON p.ID = f.post_parent AND p.post_type = %s
533                WHERE f.post_type = 'feedback'
534                AND p.ID IS NULL
535                LIMIT 1",
536                Contact_Form::POST_TYPE
537            )
538        );
539
540        return $result ? self::CLASSIC_FORMS_STATE_CLASSIC : self::CLASSIC_FORMS_STATE_HIDDEN;
541    }
542
543    /**
544     * Eagerly marks the site as having classic forms by setting the option to 'classic'.
545     *
546     * Called when a new form submission is saved that does not belong to a synced jetpack_form.
547     * This avoids re-running the detection query â€” once a classic submission is observed, the
548     * state is permanently set without needing to scan the database again.
549     *
550     * If the user has already dismissed the classic forms notice, the state is left as
551     * 'dismissed' so the notice does not reappear.
552     *
553     * @since 7.14.0
554     */
555    public static function mark_classic_form_detected() {
556        $current = get_option( self::CLASSIC_FORMS_OPTION );
557
558        if ( self::CLASSIC_FORMS_STATE_DISMISSED === $current ) {
559            return;
560        }
561
562        update_option( self::CLASSIC_FORMS_OPTION, self::CLASSIC_FORMS_STATE_CLASSIC, false );
563    }
564
565    /**
566     * Returns url of forms admin page.
567     *
568     * @param string|null $tab Tab to open in the forms admin page.
569     * @param int|null    $post_id Post ID of response to open in the forms responses page.
570     *
571     * @return string
572     */
573    public static function get_forms_admin_url( $tab = null, $post_id = null ) {
574        $url  = admin_url( 'admin.php' );
575        $url .= '?page=' . self::FORMS_WPBUILD_ADMIN_SLUG;
576        $url .= '&p=' . rawurlencode( self::get_forms_admin_path_wp_build( $tab, $post_id ) );
577
578        /**
579         * Filters the Forms admin page URL.
580         *
581         * @module contact-form
582         * @since 7.8.0
583         *
584         * @param string      $url The Forms admin page URL.
585         * @param string|null $tab Tab to open in the forms admin page.
586         * @param int|null $post_id Post ID of response to open in the forms responses page.
587         *
588         * @return string The filtered Forms admin page URL.
589         */
590        return apply_filters( 'jetpack_forms_admin_url', $url, $tab, $post_id );
591    }
592
593    /**
594     * Returns the URL of the standalone single response page for a given response.
595     *
596     * The standalone page is a wp-build route (`/response/<id>`). A missing or empty
597     * post ID falls back to the responses list.
598     *
599     * @since 7.25.0
600     *
601     * @param int|null $post_id Post ID of the response to open.
602     *
603     * @return string
604     */
605    public static function get_single_response_admin_url( $post_id = null ) {
606        $post_id = ! empty( $post_id ) ? absint( $post_id ) : null;
607
608        return self::get_forms_admin_url( $post_id ? 'response' : 'inbox', $post_id );
609    }
610
611    /**
612     * The tab the standalone Forms page opens on when the URL names no route.
613     *
614     * @deprecated 8.3.5 The dashboard's root route picks the tab client-side now.
615     *
616     * @return string Tab slug understood by get_forms_admin_url().
617     */
618    public static function get_default_tab() {
619        _deprecated_function( __METHOD__, 'package-8.3.5' );
620
621        if ( ! Contact_Form_Plugin::has_editor_feature_flag( 'central-form-management' ) ) {
622            // The Forms tab is not rendered at all here, so honouring a stored 'forms'
623            // would strand the user on a tab they cannot leave.
624            return 'inbox';
625        }
626
627        $remembered = sanitize_key( wp_unslash( $_COOKIE[ self::LAST_TAB_COOKIE ] ?? '' ) );
628
629        return in_array( $remembered, array( 'forms', 'responses' ), true ) ? $remembered : 'forms';
630    }
631
632    /**
633     * WP-Build path for the forms admin URL.
634     *
635     * @param string|null $tab    Tab to open.
636     * @param int|null    $post_id Post ID of response.
637     * @return string URL path (e.g. '/', '/responses/inbox', '/forms').
638     */
639    private static function get_forms_admin_path_wp_build( $tab, $post_id ) {
640        $post_id      = ! empty( $post_id ) ? absint( $post_id ) : null;
641        $response_ids = ! empty( $post_id ) ? '?responseIds=["' . $post_id . '"]' : '';
642
643        // The standalone single response page, which addresses the response by path
644        // rather than selecting it in a list.
645        if ( $tab === 'response' && ! empty( $post_id ) ) {
646            return '/response/' . $post_id;
647        }
648
649        $path_map = array(
650            'inbox'           => '/responses/inbox',
651            'spam'            => '/responses/spam',
652            'trash'           => '/responses/trash',
653            'forms'           => '/forms',
654            'responses'       => '/responses/inbox',
655            'responses/inbox' => '/responses/inbox',
656        );
657
658        if ( $tab !== null && $tab !== '' && isset( $path_map[ $tab ] ) ) {
659            return $path_map[ $tab ] . $response_ids;
660        }
661
662        if ( ! empty( $post_id ) ) {
663            return '/responses/inbox?responseIds=["' . $post_id . '"]';
664        }
665
666        return '/responses/inbox';
667    }
668
669    /**
670     * Returns true if the current screen is the Jetpack Forms admin page.
671     *
672     * @return boolean
673     */
674    public static function is_jetpack_forms_admin_page() {
675        if ( ! function_exists( 'get_current_screen' ) ) {
676            return false;
677        }
678
679        $screen = get_current_screen();
680
681        if ( ! $screen || ! isset( $screen->id ) ) {
682            return false;
683        }
684
685        return $screen->id === 'jetpack_page_' . self::FORMS_WPBUILD_ADMIN_SLUG;
686    }
687
688    /**
689     * Returns true if form notes feature is enabled.
690     *
691     * @return boolean
692     */
693    public static function is_notes_enabled() {
694        /**
695        * Enable form notes feature in Jetpack Forms .
696        *
697        * @module contact-form
698        * @since 7.3.0
699        *
700        * @param bool $enabled Should the form notes feature be enabled? Defaults to false.
701        */
702        return apply_filters( 'jetpack_forms_notes_enable', false );
703    }
704
705    /**
706     * Get admin URL for given screen ID.
707     *
708     * @deprecated 7.9.0 Use Dashboard::get_forms_admin_url() instead.
709     *
710     * @param string $screen_id Screen ID.
711     * @return string Admin URL.
712     */
713    public static function get_admin_url( $screen_id ) {
714        _deprecated_function( __METHOD__, 'jetpack-7.9.0', 'Dashboard::get_forms_admin_url' );
715
716        if ( 'edit-jetpack_form' === $screen_id ) {
717            return self::get_forms_admin_url( 'forms' );
718        }
719
720        if ( 'edit-feedback' === $screen_id ) {
721            return self::get_forms_admin_url( 'inbox' );
722        }
723
724        return self::get_forms_admin_url();
725    }
726}