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