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