Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.65% covered (success)
90.65%
504 / 556
70.37% covered (warning)
70.37%
19 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
Forms_Abilities
90.79% covered (success)
90.79%
503 / 554
70.37% covered (warning)
70.37%
19 / 27
76.04
0.00% covered (danger)
0.00%
0 / 1
 init
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 get_category_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_definition
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_abilities
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 spec_list_forms
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_form
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
1
 spec_create_form
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
1
 spec_delete_form
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_responses
100.00% covered (success)
100.00%
72 / 72
100.00% covered (success)
100.00%
1 / 1
1
 spec_update_response
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
1
 spec_bulk_update_responses
100.00% covered (success)
100.00%
37 / 37
100.00% covered (success)
100.00%
1 / 1
1
 spec_get_status_counts
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
1
 can_edit_pages
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 list_forms
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 get_form
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
3
 create_form
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
4
 delete_form
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 get_form_responses
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
 update_form_response
10.53% covered (danger)
10.53%
2 / 19
0.00% covered (danger)
0.00%
0 / 1
31.79
 bulk_update_responses
85.00% covered (warning)
85.00%
34 / 40
0.00% covered (danger)
0.00%
0 / 1
9.27
 get_status_counts
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 dispatch
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 set_params_from_args
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 extract_fields_from_content
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 collect_field_blocks
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
 summarize_field_block
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
5.02
 collect_inner_attrs
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Jetpack Forms Abilities Registration
4 *
5 * Registers Jetpack Forms abilities with the WordPress Abilities API.
6 *
7 * @package automattic/jetpack-forms
8 * @since 1.0.0
9 */
10
11namespace Automattic\Jetpack\Forms\Abilities;
12
13use Automattic\Jetpack\WP_Abilities\Registrar;
14
15if ( ! defined( 'ABSPATH' ) ) {
16    exit( 0 );
17}
18
19/**
20 * Class Forms_Abilities
21 *
22 * Registers Jetpack Forms abilities with the WordPress Abilities API.
23 * Ability callbacks delegate to REST endpoints via rest_do_request()
24 * so they inherit endpoint validation, sanitization, and hooks.
25 */
26class Forms_Abilities extends Registrar {
27
28    const CATEGORY_SLUG = 'jetpack-forms';
29
30    /**
31     * Form post statuses accepted by list-forms.
32     */
33    const FORM_STATUSES = array( 'publish', 'draft', 'trash' );
34
35    /**
36     * Form post statuses accepted by create-form.
37     */
38    const CREATE_FORM_STATUSES = array( 'publish', 'draft' );
39
40    /**
41     * Response post statuses accepted by get-responses / update-response.
42     */
43    const RESPONSE_STATUSES = array( 'publish', 'draft', 'spam', 'trash' );
44
45    /**
46     * Bulk actions accepted by bulk-update-responses.
47     */
48    const BULK_ACTIONS = array( 'mark_as_spam', 'mark_as_not_spam' );
49
50    /**
51     * Default block content used when create-form is called without `content`.
52     */
53    const DEFAULT_FORM_CONTENT = '<!-- wp:jetpack/contact-form --><!-- wp:jetpack/button {"element":"button","text":"Submit","lock":{"remove":true}} /--><!-- /wp:jetpack/contact-form -->';
54
55    /**
56     * Register the category and abilities.
57     *
58     * Forms abilities shipped (see #45998) before the
59     * `jetpack_wp_abilities_enabled` rollout filter existed, so this
60     * deliberately bypasses that gate — backing the `get-responses`,
61     * `update-response`, and `get-status-counts` abilities out behind a
62     * default-off filter would silently break consumers that already
63     * dispatch them. The newer admin abilities ride along for parity:
64     * Forms abilities are uniformly available wherever the package is
65     * loaded.
66     *
67     * @return void
68     */
69    public static function init() {
70        if ( did_action( self::CATEGORIES_INIT_ACTION ) ) {
71            static::register_category();
72        } else {
73            add_action( self::CATEGORIES_INIT_ACTION, array( static::class, 'register_category' ) );
74        }
75
76        if ( did_action( self::ABILITIES_INIT_ACTION ) ) {
77            static::register_abilities();
78        } else {
79            add_action( self::ABILITIES_INIT_ACTION, array( static::class, 'register_abilities' ) );
80        }
81    }
82
83    /**
84     * {@inheritDoc}
85     */
86    public static function get_category_slug(): string {
87        return self::CATEGORY_SLUG;
88    }
89
90    /**
91     * {@inheritDoc}
92     */
93    public static function get_category_definition(): array {
94        return array(
95            // "Jetpack Forms" is a product name and should not be translated.
96            'label'       => 'Jetpack Forms',
97            'description' => __( 'Abilities for managing Jetpack Forms and their responses.', 'jetpack-forms' ),
98        );
99    }
100
101    /**
102     * {@inheritDoc}
103     */
104    public static function get_abilities(): array {
105        return array(
106            'jetpack-forms/list-forms'            => self::spec_list_forms(),
107            'jetpack-forms/get-form'              => self::spec_get_form(),
108            'jetpack-forms/create-form'           => self::spec_create_form(),
109            'jetpack-forms/delete-form'           => self::spec_delete_form(),
110            'jetpack-forms/get-responses'         => self::spec_get_responses(),
111            'jetpack-forms/update-response'       => self::spec_update_response(),
112            'jetpack-forms/bulk-update-responses' => self::spec_bulk_update_responses(),
113            'jetpack-forms/get-status-counts'     => self::spec_get_status_counts(),
114        );
115    }
116
117    /*
118    ---------------------------------------------------------------------
119     * Ability specs
120     * ---------------------------------------------------------------------
121     */
122
123    /**
124     * Spec: jetpack-forms/list-forms.
125     */
126    private static function spec_list_forms(): array {
127        return array(
128            'label'               => __( 'List forms (admin)', 'jetpack-forms' ),
129            'description'         => __( 'List all forms with admin detail including response counts, status, and edit URLs. Supports pagination, search, and status filtering.', 'jetpack-forms' ),
130            'input_schema'        => array(
131                'type'                 => 'object',
132                'default'              => array(),
133                'properties'           => array(
134                    'page'     => array(
135                        'type'        => 'integer',
136                        'description' => __( 'Page number for paginated results.', 'jetpack-forms' ),
137                        'default'     => 1,
138                        'minimum'     => 1,
139                    ),
140                    'per_page' => array(
141                        'type'        => 'integer',
142                        'description' => __( 'Number of forms per page.', 'jetpack-forms' ),
143                        'default'     => 10,
144                        'minimum'     => 1,
145                        'maximum'     => 100,
146                    ),
147                    'search'   => array(
148                        'type'        => 'string',
149                        'description' => __( 'Search forms by title.', 'jetpack-forms' ),
150                    ),
151                    'status'   => array(
152                        'type'        => 'string',
153                        'description' => __( 'Filter by form status.', 'jetpack-forms' ),
154                        'enum'        => self::FORM_STATUSES,
155                    ),
156                ),
157                'additionalProperties' => false,
158            ),
159            'execute_callback'    => array( __CLASS__, 'list_forms' ),
160            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
161            'meta'                => array(
162                'annotations'  => array(
163                    'readonly'    => true,
164                    'destructive' => false,
165                    'idempotent'  => true,
166                ),
167                'public'       => true,
168                'show_in_rest' => true,
169                'mcp'          => array(
170                    'public' => true,
171                    'type'   => 'tool', // default is already "tool", but can be explicit.
172                ),
173            ),
174        );
175    }
176
177    /**
178     * Spec: jetpack-forms/get-form.
179     */
180    private static function spec_get_form(): array {
181        return array(
182            'label'               => __( 'Get form details', 'jetpack-forms' ),
183            'description'         => __( 'Get a single form with its full structure including field definitions, status, and edit URL.', 'jetpack-forms' ),
184            'input_schema'        => array(
185                'type'                 => 'object',
186                'required'             => array( 'id' ),
187                'properties'           => array(
188                    'id' => array(
189                        'type'        => 'integer',
190                        'description' => __( 'The form ID.', 'jetpack-forms' ),
191                    ),
192                ),
193                'additionalProperties' => false,
194            ),
195            'execute_callback'    => array( __CLASS__, 'get_form' ),
196            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
197            'meta'                => array(
198                'annotations'  => array(
199                    'readonly'    => true,
200                    'destructive' => false,
201                    'idempotent'  => true,
202                ),
203                'public'       => true,
204                'show_in_rest' => true,
205                'mcp'          => array(
206                    'public' => true,
207                    'type'   => 'tool', // default is already "tool", but can be explicit.
208                ),
209            ),
210        );
211    }
212
213    /**
214     * Spec: jetpack-forms/create-form.
215     */
216    private static function spec_create_form(): array {
217        return array(
218            'label'               => __( 'Create a form', 'jetpack-forms' ),
219            'description'         => __( 'Create a new form with a title. Optionally provide block content for the form structure. Returns the new form ID and edit URL.', 'jetpack-forms' ),
220            'input_schema'        => array(
221                'type'                 => 'object',
222                'required'             => array( 'title' ),
223                'properties'           => array(
224                    'title'   => array(
225                        'type'        => 'string',
226                        'description' => __( 'The form title/name.', 'jetpack-forms' ),
227                    ),
228                    'content' => array(
229                        'type'        => 'string',
230                        'description' => __( 'Block content for the form structure. If omitted, creates an empty form with a submit button.', 'jetpack-forms' ),
231                    ),
232                    'status'  => array(
233                        'type'        => 'string',
234                        'description' => __( 'Initial form status.', 'jetpack-forms' ),
235                        'enum'        => self::CREATE_FORM_STATUSES,
236                        'default'     => 'publish',
237                    ),
238                ),
239                'additionalProperties' => false,
240            ),
241            'execute_callback'    => array( __CLASS__, 'create_form' ),
242            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
243            'meta'                => array(
244                'annotations'  => array(
245                    'readonly'    => false,
246                    'destructive' => false,
247                    'idempotent'  => false,
248                ),
249                'public'       => true,
250                'show_in_rest' => true,
251                'mcp'          => array(
252                    'public' => true,
253                    'type'   => 'tool', // default is already "tool", but can be explicit.
254                ),
255            ),
256        );
257    }
258
259    /**
260     * Spec: jetpack-forms/delete-form.
261     */
262    private static function spec_delete_form(): array {
263        return array(
264            'label'               => __( 'Delete a form', 'jetpack-forms' ),
265            'description'         => __( 'Move a form to the trash. Does not permanently delete. Trashed forms can be restored.', 'jetpack-forms' ),
266            'input_schema'        => array(
267                'type'                 => 'object',
268                'required'             => array( 'id' ),
269                'properties'           => array(
270                    'id' => array(
271                        'type'        => 'integer',
272                        'description' => __( 'The form ID to delete.', 'jetpack-forms' ),
273                    ),
274                ),
275                'additionalProperties' => false,
276            ),
277            'execute_callback'    => array( __CLASS__, 'delete_form' ),
278            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
279            'meta'                => array(
280                'annotations'  => array(
281                    'readonly'    => false,
282                    'destructive' => true,
283                    'idempotent'  => true,
284                ),
285                'public'       => true,
286                'show_in_rest' => true,
287                'mcp'          => array(
288                    'public' => true,
289                    'type'   => 'tool', // default is already "tool", but can be explicit.
290                ),
291            ),
292        );
293    }
294
295    /**
296     * Spec: jetpack-forms/get-responses.
297     */
298    private static function spec_get_responses(): array {
299        return array(
300            'label'               => __( 'Get form responses', 'jetpack-forms' ),
301            'description'         => __( 'List or search form responses. Returns response data including sender info, form fields, and metadata. Supports filtering by status, date range, read state, and search terms.', 'jetpack-forms' ),
302            'input_schema'        => array(
303                'type'                 => 'object',
304                'default'              => array(),
305                'properties'           => array(
306                    'ids'       => array(
307                        'type'        => 'array',
308                        'description' => __( 'Fetch specific responses by their IDs.', 'jetpack-forms' ),
309                        'items'       => array( 'type' => 'integer' ),
310                    ),
311                    'page'      => array(
312                        'type'        => 'integer',
313                        'description' => __( 'Page number for paginated results.', 'jetpack-forms' ),
314                        'default'     => 1,
315                        'minimum'     => 1,
316                    ),
317                    'per_page'  => array(
318                        'type'        => 'integer',
319                        'description' => __( 'Number of responses to return per page.', 'jetpack-forms' ),
320                        'default'     => 10,
321                        'minimum'     => 1,
322                        'maximum'     => 100,
323                    ),
324                    'parent'    => array(
325                        'type'        => 'array',
326                        'description' => __( 'Filter by the page or post ID where the form is embedded.', 'jetpack-forms' ),
327                        'items'       => array( 'type' => 'integer' ),
328                    ),
329                    'status'    => array(
330                        'type'        => 'string',
331                        'description' => __( 'Filter by response status.', 'jetpack-forms' ),
332                        'enum'        => self::RESPONSE_STATUSES,
333                    ),
334                    'is_unread' => array(
335                        'type'        => 'boolean',
336                        'description' => __( 'Set true for unread only, false for read only.', 'jetpack-forms' ),
337                    ),
338                    'search'    => array(
339                        'type'        => 'string',
340                        'description' => __( 'Search within response content and sender info.', 'jetpack-forms' ),
341                    ),
342                    'before'    => array(
343                        'type'        => 'string',
344                        'description' => __( 'Only responses before this date (ISO8601 format).', 'jetpack-forms' ),
345                        'format'      => 'date-time',
346                    ),
347                    'after'     => array(
348                        'type'        => 'string',
349                        'description' => __( 'Only responses after this date (ISO8601 format).', 'jetpack-forms' ),
350                        'format'      => 'date-time',
351                    ),
352                ),
353                'additionalProperties' => false,
354            ),
355            'execute_callback'    => array( __CLASS__, 'get_form_responses' ),
356            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
357            'meta'                => array(
358                'annotations'  => array(
359                    'readonly'    => true,
360                    'destructive' => false,
361                    'idempotent'  => true,
362                ),
363                'public'       => true,
364                'show_in_rest' => true,
365                'mcp'          => array(
366                    'public' => true,
367                    'type'   => 'tool', // default is already "tool", but can be explicit.
368                ),
369            ),
370        );
371    }
372
373    /**
374     * Spec: jetpack-forms/update-response.
375     */
376    private static function spec_update_response(): array {
377        return array(
378            'label'               => __( 'Update form response', 'jetpack-forms' ),
379            'description'         => __( 'Modify a form response. Use to mark as spam, move to trash, restore from trash, or toggle read/unread state.', 'jetpack-forms' ),
380            'input_schema'        => array(
381                'type'                 => 'object',
382                'required'             => array( 'id' ),
383                'properties'           => array(
384                    'id'        => array(
385                        'type'        => 'integer',
386                        'description' => __( 'The response ID to update.', 'jetpack-forms' ),
387                    ),
388                    'status'    => array(
389                        'type'        => 'string',
390                        'description' => __( 'New status: "publish" (restore), "spam" (mark spam), "trash" (soft delete).', 'jetpack-forms' ),
391                        'enum'        => self::RESPONSE_STATUSES,
392                    ),
393                    'is_unread' => array(
394                        'type'        => 'boolean',
395                        'description' => __( 'Set false to mark as read, true to mark as unread.', 'jetpack-forms' ),
396                    ),
397                ),
398                'additionalProperties' => false,
399            ),
400            'execute_callback'    => array( __CLASS__, 'update_form_response' ),
401            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
402            'meta'                => array(
403                'annotations'  => array(
404                    'readonly'    => false,
405                    'destructive' => false,
406                    'idempotent'  => true,
407                ),
408                'public'       => true,
409                'show_in_rest' => true,
410                'mcp'          => array(
411                    'public' => true,
412                    'type'   => 'tool', // default is already "tool", but can be explicit.
413                ),
414            ),
415        );
416    }
417
418    /**
419     * Spec: jetpack-forms/bulk-update-responses.
420     */
421    private static function spec_bulk_update_responses(): array {
422        return array(
423            'label'               => __( 'Bulk update form responses', 'jetpack-forms' ),
424            'description'         => __( 'Mark multiple responses as spam (or restore from spam) in a single call. Each response is processed individually; the result reports per-id success and any per-id failures so callers can see exactly which responses were updated. Also teaches Akismet from the successful updates.', 'jetpack-forms' ),
425            'input_schema'        => array(
426                'type'                 => 'object',
427                'required'             => array( 'action', 'ids' ),
428                'properties'           => array(
429                    'action' => array(
430                        'type'        => 'string',
431                        'description' => __( 'The bulk action to perform.', 'jetpack-forms' ),
432                        'enum'        => self::BULK_ACTIONS,
433                    ),
434                    'ids'    => array(
435                        'type'        => 'array',
436                        'description' => __( 'Response IDs to update.', 'jetpack-forms' ),
437                        'items'       => array( 'type' => 'integer' ),
438                        'minItems'    => 1,
439                    ),
440                ),
441                'additionalProperties' => false,
442            ),
443            'execute_callback'    => array( __CLASS__, 'bulk_update_responses' ),
444            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
445            'meta'                => array(
446                'annotations'  => array(
447                    'readonly'    => false,
448                    'destructive' => false,
449                    'idempotent'  => true,
450                ),
451                'public'       => true,
452                'show_in_rest' => true,
453                'mcp'          => array(
454                    'public' => true,
455                    'type'   => 'tool', // default is already "tool", but can be explicit.
456                ),
457            ),
458        );
459    }
460
461    /**
462     * Spec: jetpack-forms/get-status-counts.
463     */
464    private static function spec_get_status_counts(): array {
465        return array(
466            'label'               => __( 'Get response status counts', 'jetpack-forms' ),
467            'description'         => __( 'Get a summary of form responses grouped by status. Returns counts for inbox (active), spam, and trash. Useful for dashboard stats or checking if there are new responses.', 'jetpack-forms' ),
468            'input_schema'        => array(
469                'type'                 => 'object',
470                'default'              => array(),
471                'properties'           => array(
472                    'search'    => array(
473                        'type'        => 'string',
474                        'description' => __( 'Only count responses matching this search term.', 'jetpack-forms' ),
475                    ),
476                    'parent'    => array(
477                        'type'        => 'integer',
478                        'description' => __( 'Only count responses from a specific page or post.', 'jetpack-forms' ),
479                    ),
480                    'before'    => array(
481                        'type'        => 'string',
482                        'description' => __( 'Only count responses before this date (ISO8601 format).', 'jetpack-forms' ),
483                        'format'      => 'date-time',
484                    ),
485                    'after'     => array(
486                        'type'        => 'string',
487                        'description' => __( 'Only count responses after this date (ISO8601 format).', 'jetpack-forms' ),
488                        'format'      => 'date-time',
489                    ),
490                    'is_unread' => array(
491                        'type'        => 'boolean',
492                        'description' => __( 'Set true to count only unread, false for only read.', 'jetpack-forms' ),
493                    ),
494                ),
495                'additionalProperties' => false,
496            ),
497            'execute_callback'    => array( __CLASS__, 'get_status_counts' ),
498            'permission_callback' => array( __CLASS__, 'can_edit_pages' ),
499            'meta'                => array(
500                'annotations'  => array(
501                    'readonly'    => true,
502                    'destructive' => false,
503                    'idempotent'  => true,
504                ),
505                'public'       => true,
506                'show_in_rest' => true,
507                'mcp'          => array(
508                    'public' => true,
509                    'type'   => 'tool', // default is already "tool", but can be explicit.
510                ),
511            ),
512        );
513    }
514
515    /*
516    ---------------------------------------------------------------------
517     * Permission callbacks
518     * ---------------------------------------------------------------------
519     */
520
521    /**
522     * Permission callback shared by every Forms ability. The delegated REST
523     * controller re-checks the user's edit permission per-route, so this is
524     * a coarse early-rejection gate, not the authoritative authorization.
525     *
526     * @return bool
527     */
528    public static function can_edit_pages() {
529        return current_user_can( 'edit_pages' );
530    }
531
532    /*
533    ---------------------------------------------------------------------
534     * Execute callbacks
535     * ---------------------------------------------------------------------
536     */
537
538    /**
539     * Execute: list-forms.
540     *
541     * Delegates to GET /wp/v2/jetpack-forms with dashboard context, then
542     * reshapes to a compact format for AI consumption.
543     *
544     * @param array $args Arguments from the ability input.
545     * @return array|\WP_Error
546     */
547    public static function list_forms( $args = array() ) {
548        $args    = is_array( $args ) ? $args : array();
549        $request = new \WP_REST_Request( 'GET', '/wp/v2/jetpack-forms' );
550        $request->set_param( 'jetpack_forms_context', 'dashboard' );
551        self::set_params_from_args( $request, $args, array( 'page', 'per_page', 'search', 'status' ) );
552
553        $data = self::dispatch( $request );
554        if ( is_wp_error( $data ) ) {
555            return $data;
556        }
557
558        if ( ! is_array( $data ) ) {
559            return array();
560        }
561
562        $result = array();
563        foreach ( $data as $form ) {
564            $result[] = array(
565                'id'            => $form['id'],
566                'title'         => $form['title']['rendered'] ?? '',
567                'status'        => $form['status'],
568                'entries_count' => $form['entries_count'] ?? 0,
569                'edit_url'      => $form['edit_url'] ?? '',
570                'date'          => $form['date'],
571                'modified'      => $form['modified'],
572            );
573        }
574
575        return $result;
576    }
577
578    /**
579     * Execute: get-form.
580     *
581     * Delegates to GET /wp/v2/jetpack-forms/{id} with `context=edit` so the
582     * raw block content comes back in the response — no second `get_post()`
583     * fetch needed.
584     *
585     * @param array $args Arguments from the ability input.
586     * @return array|\WP_Error
587     */
588    public static function get_form( $args ) {
589        if ( ! isset( $args['id'] ) ) {
590            return new \WP_Error( 'missing_id', __( 'Form ID is required.', 'jetpack-forms' ) );
591        }
592
593        $request = new \WP_REST_Request( 'GET', '/wp/v2/jetpack-forms/' . absint( $args['id'] ) );
594        $request->set_param( 'context', 'edit' );
595
596        $data = self::dispatch( $request );
597        if ( is_wp_error( $data ) ) {
598            return $data;
599        }
600
601        $raw_content = $data['content']['raw'] ?? '';
602
603        return array(
604            'id'       => $data['id'],
605            'title'    => $data['title']['raw'] ?? $data['title']['rendered'] ?? '',
606            'status'   => $data['status'],
607            'fields'   => self::extract_fields_from_content( $raw_content ),
608            'date'     => $data['date'],
609            'modified' => $data['modified'],
610            'edit_url' => $data['link'] ?? get_edit_post_link( $data['id'], 'raw' ),
611        );
612    }
613
614    /**
615     * Execute: create-form.
616     *
617     * @param array $args Arguments from the ability input.
618     * @return array|\WP_Error
619     */
620    public static function create_form( $args ) {
621        if ( empty( $args['title'] ) ) {
622            return new \WP_Error( 'missing_title', __( 'Form title is required.', 'jetpack-forms' ) );
623        }
624
625        $content = $args['content'] ?? '';
626        if ( '' === $content ) {
627            $content = self::DEFAULT_FORM_CONTENT;
628        }
629
630        $request = new \WP_REST_Request( 'POST', '/wp/v2/jetpack-forms' );
631        $request->set_body_params(
632            array(
633                'title'   => $args['title'],
634                'content' => $content,
635                'status'  => $args['status'] ?? 'publish',
636            )
637        );
638
639        $data = self::dispatch( $request );
640        if ( is_wp_error( $data ) ) {
641            return $data;
642        }
643
644        return array(
645            'id'       => $data['id'],
646            'title'    => $data['title']['raw'] ?? $data['title']['rendered'] ?? '',
647            'status'   => $data['status'],
648            'edit_url' => get_edit_post_link( $data['id'], 'raw' ),
649        );
650    }
651
652    /**
653     * Execute: delete-form.
654     *
655     * @param array $args Arguments from the ability input.
656     * @return array|\WP_Error
657     */
658    public static function delete_form( $args ) {
659        if ( ! isset( $args['id'] ) ) {
660            return new \WP_Error( 'missing_id', __( 'Form ID is required.', 'jetpack-forms' ) );
661        }
662
663        $request = new \WP_REST_Request( 'DELETE', '/wp/v2/jetpack-forms/' . absint( $args['id'] ) );
664
665        $data = self::dispatch( $request );
666        if ( is_wp_error( $data ) ) {
667            return $data;
668        }
669
670        return array(
671            'id'      => $data['id'] ?? absint( $args['id'] ),
672            'deleted' => true,
673            'status'  => $data['status'] ?? 'trash',
674        );
675    }
676
677    /**
678     * Execute: get-responses.
679     *
680     * @param array $args Arguments from the ability input.
681     * @return array|\WP_Error
682     */
683    public static function get_form_responses( $args = array() ) {
684        $args    = is_array( $args ) ? $args : array();
685        $request = new \WP_REST_Request( 'GET', '/wp/v2/feedback' );
686        self::set_params_from_args( $request, $args, array( 'page', 'per_page', 'parent', 'status', 'is_unread', 'search', 'before', 'after' ) );
687
688        if ( isset( $args['ids'] ) && is_array( $args['ids'] ) ) {
689            $request->set_param( 'include', $args['ids'] );
690        }
691
692        return self::dispatch( $request );
693    }
694
695    /**
696     * Execute: update-response.
697     *
698     * @param array $args Arguments from the ability input.
699     * @return array|\WP_Error
700     */
701    public static function update_form_response( $args ) {
702        if ( ! isset( $args['id'] ) ) {
703            return new \WP_Error( 'missing_id', __( 'Response ID is required.', 'jetpack-forms' ) );
704        }
705
706        $id     = absint( $args['id'] );
707        $result = array();
708
709        if ( isset( $args['status'] ) ) {
710            $request = new \WP_REST_Request( 'POST', '/wp/v2/feedback/' . $id );
711            $request->set_body_params( array( 'status' => $args['status'] ) );
712            $data = self::dispatch( $request );
713            if ( is_wp_error( $data ) ) {
714                return $data;
715            }
716            $result = $data;
717        }
718
719        if ( isset( $args['is_unread'] ) ) {
720            $request = new \WP_REST_Request( 'POST', '/wp/v2/feedback/' . $id . '/read' );
721            $request->set_body_params( array( 'is_unread' => $args['is_unread'] ) );
722            $data = self::dispatch( $request );
723            if ( is_wp_error( $data ) ) {
724                return $data;
725            }
726            $result = array_merge( $result, $data );
727        }
728
729        return $result;
730    }
731
732    /**
733     * Execute: bulk-update-responses.
734     *
735     * The `/wp/v2/feedback/bulk_actions` REST endpoint only teaches Akismet —
736     * it does not change post status. The dashboard handles bulk spam/not-spam
737     * by issuing per-id status updates first, then calling bulk_actions to
738     * teach Akismet from the successful flips. We mirror that here so callers
739     * get a faithful per-id confirmation: each id either lands in `succeeded`
740     * or in `failed` with the underlying error code/message.
741     *
742     * @param array $args Arguments from the ability input.
743     * @return array|\WP_Error
744     */
745    public static function bulk_update_responses( $args ) {
746        if ( empty( $args['action'] ) || empty( $args['ids'] ) || ! is_array( $args['ids'] ) ) {
747            return new \WP_Error( 'missing_params', __( 'Action and IDs are required.', 'jetpack-forms' ) );
748        }
749
750        $action        = $args['action'];
751        $target_status = 'mark_as_spam' === $action ? 'spam' : 'publish';
752        $ids           = array_values( array_unique( array_map( 'absint', $args['ids'] ) ) );
753
754        $succeeded = array();
755        $failed    = array();
756        foreach ( $ids as $id ) {
757            if ( $id <= 0 ) {
758                $failed[] = array(
759                    'id'      => $id,
760                    'code'    => 'invalid_id',
761                    'message' => __( 'Response IDs must be positive integers.', 'jetpack-forms' ),
762                );
763                continue;
764            }
765            $request = new \WP_REST_Request( 'POST', '/wp/v2/feedback/' . $id );
766            $request->set_body_params( array( 'status' => $target_status ) );
767            $data = self::dispatch( $request );
768            if ( is_wp_error( $data ) ) {
769                $failed[] = array(
770                    'id'      => $id,
771                    'code'    => $data->get_error_code(),
772                    'message' => $data->get_error_message(),
773                );
774                continue;
775            }
776            $succeeded[] = $id;
777        }
778
779        // Teach Akismet from the responses whose status actually flipped.
780        // Akismet learning is best-effort and independent of the status update,
781        // so a failure here doesn't roll back the per-id changes above.
782        if ( ! empty( $succeeded ) ) {
783            $teach = new \WP_REST_Request( 'POST', '/wp/v2/feedback/bulk_actions' );
784            $teach->set_body_params(
785                array(
786                    'action'   => $action,
787                    'post_ids' => $succeeded,
788                )
789            );
790            self::dispatch( $teach );
791        }
792
793        return array(
794            'action'    => $action,
795            'succeeded' => $succeeded,
796            'failed'    => $failed,
797        );
798    }
799
800    /**
801     * Execute: get-status-counts.
802     *
803     * @param array $args Arguments from the ability input.
804     * @return array|\WP_Error
805     */
806    public static function get_status_counts( $args = array() ) {
807        $args    = is_array( $args ) ? $args : array();
808        $request = new \WP_REST_Request( 'GET', '/wp/v2/feedback/counts' );
809        self::set_params_from_args( $request, $args, array( 'search', 'parent', 'before', 'after', 'is_unread' ) );
810
811        return self::dispatch( $request );
812    }
813
814    /*
815    ---------------------------------------------------------------------
816     * Helpers
817     * ---------------------------------------------------------------------
818     */
819
820    /**
821     * Dispatch an internal REST request and unwrap the response.
822     *
823     * @param \WP_REST_Request $request The REST request to dispatch.
824     * @return array|\WP_Error Response data array, or WP_Error on failure.
825     */
826    private static function dispatch( $request ) {
827        $response = rest_do_request( $request );
828        if ( $response->is_error() ) {
829            return $response->as_error();
830        }
831        return $response->get_data();
832    }
833
834    /**
835     * Copy a whitelisted subset of `$args` onto a REST request as parameters.
836     *
837     * @param \WP_REST_Request $request Target request.
838     * @param array            $args    Caller-supplied arguments.
839     * @param array            $keys    Allowed keys to forward.
840     */
841    private static function set_params_from_args( \WP_REST_Request $request, array $args, array $keys ): void {
842        foreach ( $keys as $key ) {
843            if ( isset( $args[ $key ] ) ) {
844                $request->set_param( $key, $args[ $key ] );
845            }
846        }
847    }
848
849    /**
850     * Extract field definitions from raw block content.
851     *
852     * Walks `jetpack/field-*` blocks and projects each into a compact
853     * `{ label, type, required, options?, placeholder?, help_text? }` shape. Modern
854     * field blocks store the label/placeholder in `jetpack/label` and
855     * `jetpack/input` sub-blocks; legacy fixtures keep them inline as
856     * top-level attrs. Both layouts are supported.
857     *
858     * @param string $raw_content Raw block content (typically `content.raw` from REST).
859     * @return array
860     */
861    private static function extract_fields_from_content( string $raw_content ): array {
862        if ( '' === $raw_content ) {
863            return array();
864        }
865        $fields = array();
866        self::collect_field_blocks( parse_blocks( $raw_content ), $fields );
867        return $fields;
868    }
869
870    /**
871     * Recursively walk parsed blocks and append field definitions to `$fields`.
872     *
873     * Field blocks are not recursed into — their inner blocks are layout
874     * sub-blocks (`jetpack/label`, `jetpack/input`), not nested fields.
875     * Non-field containers (columns, groups, the contact-form block itself)
876     * are recursed so fields nested inside them still get picked up.
877     *
878     * @param array $blocks Parsed blocks.
879     * @param array $fields Reference to the fields array being built.
880     */
881    private static function collect_field_blocks( array $blocks, array &$fields ): void {
882        foreach ( $blocks as $block ) {
883            $name = $block['blockName'] ?? '';
884
885            if ( strpos( $name, 'jetpack/field-' ) === 0 ) {
886                $summary = self::summarize_field_block( $block );
887                if ( null !== $summary ) {
888                    $fields[] = $summary;
889                }
890                continue;
891            }
892
893            if ( ! empty( $block['innerBlocks'] ) ) {
894                self::collect_field_blocks( $block['innerBlocks'], $fields );
895            }
896        }
897    }
898
899    /**
900     * Project a single `jetpack/field-*` block into the compact field shape.
901     *
902     * @param array $block Parsed block array.
903     * @return array|null Field summary, or null if the block has no usable label.
904     */
905    private static function summarize_field_block( array $block ): ?array {
906        $attrs       = $block['attrs'] ?? array();
907        $inner_attrs = self::collect_inner_attrs( $block['innerBlocks'] ?? array() );
908        $label_attrs = $inner_attrs['jetpack/label'] ?? array();
909        $input_attrs = $inner_attrs['jetpack/input'] ?? array();
910
911        $label = (string) ( $label_attrs['label'] ?? $attrs['label'] ?? '' );
912        if ( '' === $label ) {
913            return null;
914        }
915
916        $field = array(
917            'label'    => $label,
918            'type'     => str_replace( 'jetpack/field-', '', (string) ( $block['blockName'] ?? '' ) ),
919            'required' => ! empty( $attrs['required'] ),
920        );
921
922        if ( ! empty( $attrs['options'] ) ) {
923            $field['options'] = $attrs['options'];
924        }
925
926        $placeholder = $input_attrs['placeholder'] ?? $attrs['placeholder'] ?? '';
927        if ( '' !== $placeholder ) {
928            $field['placeholder'] = $placeholder;
929        }
930
931        $help_text = trim( (string) ( $attrs['helpText'] ?? '' ) );
932        if ( '' !== $help_text ) {
933            $field['help_text'] = $help_text;
934        }
935
936        return $field;
937    }
938
939    /**
940     * Build a `block_name => attrs` lookup from the field's direct children.
941     *
942     * @param array $inner_blocks Direct children of a field block.
943     * @return array
944     */
945    private static function collect_inner_attrs( array $inner_blocks ): array {
946        $out = array();
947        foreach ( $inner_blocks as $child ) {
948            $name = $child['blockName'] ?? '';
949            if ( '' !== $name && ! isset( $out[ $name ] ) ) {
950                $out[ $name ] = $child['attrs'] ?? array();
951            }
952        }
953        return $out;
954    }
955}