diff --git a/projects/packages/forms/changelog/add-forms-export-responses-ability b/projects/packages/forms/changelog/add-forms-export-responses-ability new file mode 100644 index 000000000000..0fded745df49 --- /dev/null +++ b/projects/packages/forms/changelog/add-forms-export-responses-ability @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Abilities: Add jetpack-forms/export-responses, which returns a 15-minute link that downloads responses as CSV. diff --git a/projects/packages/forms/src/abilities/class-forms-abilities.php b/projects/packages/forms/src/abilities/class-forms-abilities.php index b7f649724895..11154eae04d1 100644 --- a/projects/packages/forms/src/abilities/class-forms-abilities.php +++ b/projects/packages/forms/src/abilities/class-forms-abilities.php @@ -10,6 +10,8 @@ namespace Automattic\Jetpack\Forms\Abilities; +use Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin; +use Automattic\Jetpack\Forms\ContactForm\Response_Export_Link; use Automattic\Jetpack\WP_Abilities\Registrar; if ( ! defined( 'ABSPATH' ) ) { @@ -47,6 +49,16 @@ class Forms_Abilities extends Registrar { */ const BULK_ACTIONS = array( 'mark_as_spam', 'mark_as_not_spam' ); + /** + * Folders accepted by export-responses. + */ + const EXPORT_STATUSES = array( 'inbox', 'spam', 'trash' ); + + /** + * Most forms export-responses lists by name. + */ + const EXPORT_MAX_FORMS = 50; + /** * Default block content used when create-form is called without `content`. */ @@ -111,6 +123,7 @@ public static function get_abilities(): array { 'jetpack-forms/update-response' => self::spec_update_response(), 'jetpack-forms/bulk-update-responses' => self::spec_bulk_update_responses(), 'jetpack-forms/get-status-counts' => self::spec_get_status_counts(), + 'jetpack-forms/export-responses' => self::spec_export_responses(), ); } @@ -512,6 +525,100 @@ private static function spec_get_status_counts(): array { ); } + /** + * Spec: jetpack-forms/export-responses. + */ + private static function spec_export_responses(): array { + return array( + 'label' => __( 'Export form responses', 'jetpack-forms' ), + 'description' => __( 'Export form responses as a CSV file, with the same columns as the Export button in Jetpack Forms. Returns how many responses match, the forms they came from, and a download link for the user to open. The link works for 15 minutes and only in the signed-in browser of the user who asked, so it is useless to anyone else. Leaves out spam, trash and form preview test responses unless asked. Returns count 0 and no link when nothing matches.', 'jetpack-forms' ), + 'input_schema' => array( + 'type' => 'object', + 'default' => array(), + 'properties' => array( + 'form_id' => array( + 'type' => 'integer', + 'description' => __( 'Only export responses to this form, by its ID. For older forms saved inside a post or page, use that post or page ID. Leave out to export every form.', 'jetpack-forms' ), + 'minimum' => 1, + ), + 'status' => array( + 'type' => 'string', + 'description' => __( 'Which folder to export: inbox (the default), spam or trash.', 'jetpack-forms' ), + 'enum' => self::EXPORT_STATUSES, + 'default' => 'inbox', + ), + 'search' => array( + 'type' => 'string', + 'description' => __( 'Only export responses matching this search term.', 'jetpack-forms' ), + ), + 'after' => array( + 'type' => 'string', + 'description' => __( 'Only export responses received after this date (ISO8601 format).', 'jetpack-forms' ), + 'format' => 'date-time', + ), + 'before' => array( + 'type' => 'string', + 'description' => __( 'Only export responses received before this date (ISO8601 format).', 'jetpack-forms' ), + 'format' => 'date-time', + ), + 'include_test_responses' => array( + 'type' => 'boolean', + 'description' => __( 'Set true to include test responses sent from the form preview.', 'jetpack-forms' ), + 'default' => false, + ), + ), + 'additionalProperties' => false, + ), + 'output_schema' => array( + 'type' => 'object', + 'properties' => array( + 'count' => array( + 'type' => 'integer', + 'description' => __( 'Number of matching responses.', 'jetpack-forms' ), + ), + 'forms' => array( + 'type' => 'array', + 'description' => __( 'Forms the responses came from, up to 50.', 'jetpack-forms' ), + 'items' => array( + 'type' => 'object', + 'properties' => array( + 'id' => array( 'type' => 'integer' ), + 'title' => array( 'type' => 'string' ), + ), + ), + ), + 'forms_total' => array( + 'type' => 'integer', + 'description' => __( 'Number of forms the responses came from, including any left out of forms.', 'jetpack-forms' ), + ), + 'download_url' => array( + 'type' => array( 'string', 'null' ), + 'description' => __( 'Link that downloads the CSV file. Null when no response matches.', 'jetpack-forms' ), + ), + 'expires_at' => array( + 'type' => array( 'string', 'null' ), + 'description' => __( 'When the link stops working, in UTC (ISO8601 format).', 'jetpack-forms' ), + ), + ), + ), + 'execute_callback' => array( __CLASS__, 'export_responses' ), + 'permission_callback' => array( __CLASS__, 'can_export' ), + 'meta' => array( + 'annotations' => array( + 'readonly' => true, + 'destructive' => false, + 'idempotent' => true, + ), + 'public' => true, + 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + 'type' => 'tool', + ), + ), + ); + } + /* --------------------------------------------------------------------- * Permission callbacks @@ -529,6 +636,16 @@ public static function can_edit_pages() { return current_user_can( 'edit_pages' ); } + /** + * Permission callback for export-responses. Matches the Export button in + * Jetpack Forms, since an export holds the personal data in every response. + * + * @return bool + */ + public static function can_export() { + return current_user_can( 'export' ); + } + /* --------------------------------------------------------------------- * Execute callbacks @@ -811,6 +928,74 @@ public static function get_status_counts( $args = array() ) { return self::dispatch( $request ); } + /** + * Execute: export-responses. + * + * @param array $args Arguments from the ability input. + * @return array|\WP_Error + */ + public static function export_responses( $args = array() ) { + $args = is_array( $args ) ? $args : array(); + $filters = array( + 'status' => isset( $args['status'] ) && 'inbox' !== $args['status'] ? (string) $args['status'] : '', + 'search' => isset( $args['search'] ) ? (string) $args['search'] : '', + ); + if ( ! empty( $args['form_id'] ) ) { + $filters['form'] = (int) $args['form_id']; + } + + // Read dates as the export query does: in site time unless they name a timezone. + $times = array(); + foreach ( array( 'after', 'before' ) as $bound ) { + if ( ! isset( $args[ $bound ] ) || '' === $args[ $bound ] ) { + continue; + } + $date = date_create( (string) $args[ $bound ], wp_timezone() ); + if ( false === $date ) { + return new \WP_Error( + 'jetpack_forms_invalid_date', + /* translators: %s: name of the date input, "after" or "before". */ + sprintf( __( 'Could not read the "%s" date. Use ISO8601 format, for example 2026-10-01T00:00:00Z.', 'jetpack-forms' ), $bound ), + array( 'status' => 400 ) + ); + } + $filters[ $bound ] = (string) $args[ $bound ]; + $times[ $bound ] = $date->getTimestamp(); + } + + if ( isset( $times['after'] ) && isset( $times['before'] ) && $times['after'] >= $times['before'] ) { + return new \WP_Error( + 'jetpack_forms_invalid_date_range', + __( 'The "after" date must come before the "before" date.', 'jetpack-forms' ), + array( 'status' => 400 ) + ); + } + + $include_test_responses = ! empty( $args['include_test_responses'] ); + if ( ! $include_test_responses ) { + $filters['exclude_test_responses'] = true; + } + $summary = Contact_Form_Plugin::init()->get_export_summary( $filters, self::EXPORT_MAX_FORMS ); + + $forms = array(); + foreach ( $summary['form_ids'] as $form_id ) { + $forms[] = array( + 'id' => $form_id, + 'title' => (string) get_post_field( 'post_title', $form_id, 'raw' ), + ); + } + + $link = $summary['count'] > 0 ? Response_Export_Link::create( $filters, $include_test_responses, get_current_user_id() ) : null; + + return array( + 'count' => $summary['count'], + 'forms' => $forms, + 'forms_total' => $summary['forms_total'], + 'download_url' => $link ? $link['url'] : null, + 'expires_at' => $link ? gmdate( 'Y-m-d\\TH:i:s\\Z', $link['expires_at'] ) : null, + ); + } + /* --------------------------------------------------------------------- * Helpers diff --git a/projects/packages/forms/src/contact-form/class-contact-form-plugin.php b/projects/packages/forms/src/contact-form/class-contact-form-plugin.php index 9fcc49328851..24321442deee 100644 --- a/projects/packages/forms/src/contact-form/class-contact-form-plugin.php +++ b/projects/packages/forms/src/contact-form/class-contact-form-plugin.php @@ -234,6 +234,7 @@ protected function __construct() { add_action( 'wp_ajax_feedback_export', array( $this, 'download_feedback_as_csv' ) ); add_action( 'wp_ajax_create_new_form', array( $this, 'create_new_form' ) ); add_action( 'wp_ajax_grunion_export_to_gdrive', array( $this, 'export_to_gdrive' ) ); + Response_Export_Link::init(); } add_action( 'admin_menu', array( $this, 'admin_menu' ) ); // Priority 1000: after Dashboard::add_admin_submenu() (999) registers the Forms submenu, @@ -3373,19 +3374,37 @@ private function get_export_feedback_ids_from_post() { * @type string $before Only responses before this date; any format strtotime() accepts. * @type int[] $selected Only these response IDs. * @type int $source Only responses from this source post ID. + * @type bool $exclude_test_responses Leave out responses flagged as form preview tests. * } * * @return int[] */ public function get_export_feedback_ids( $filters = array() ) { + return array_map( 'intval', $this->query_export_feedback( $filters )['posts'] ); + } + + /** + * Runs the export's response query. + * + * @param array $filters See get_export_feedback_ids(). + * @param array $overrides WP_Query arguments that replace the export's own. + * + * @return array{posts: array, found: int} The query's result, and how many rows match when the query counts them. + */ + private function query_export_feedback( $filters, $overrides = array() ) { $args = array( - 'posts_per_page' => -1, - 'post_type' => Feedback::POST_TYPE, - 'post_status' => array( 'publish', 'draft' ), - 'order' => 'ASC', - 'fields' => 'ids', - 'suppress_filters' => false, - 'date_query' => array(), + 'posts_per_page' => -1, + 'post_type' => Feedback::POST_TYPE, + 'post_status' => array( 'publish', 'draft' ), + 'orderby' => 'date', + 'order' => 'ASC', + 'fields' => 'ids', + 'suppress_filters' => false, + 'ignore_sticky_posts' => true, + 'no_found_rows' => true, + // An export's ID list can be too large for one object cache entry. + 'cache_results' => false, + 'date_query' => array(), ); if ( ! empty( $filters['form'] ) ) { @@ -3400,18 +3419,30 @@ public function get_export_feedback_ids( $filters = array() ) { $args['s'] = $filters['search']; } - // date_query expects date strings/arrays, not timestamps. + // date_query compares with post_date, which is in site time; a date with no timezone already is. foreach ( array( 'after', 'before' ) as $bound ) { - $time = ! empty( $filters[ $bound ] ) ? strtotime( $filters[ $bound ] ) : false; - if ( $time ) { - $args['date_query'][ $bound ] = gmdate( 'Y-m-d H:i:s', $time ); + $date = ! empty( $filters[ $bound ] ) ? date_create( $filters[ $bound ], wp_timezone() ) : false; + if ( $date ) { + $args['date_query'][ $bound ] = $date->setTimezone( wp_timezone() )->format( 'Y-m-d H:i:s' ); } } - if ( ! empty( $filters['selected'] ) ) { - $args['include'] = array_filter( array_map( 'intval', (array) $filters['selected'] ) ); + $selected = ! empty( $filters['selected'] ) ? array_filter( array_map( 'intval', (array) $filters['selected'] ) ) : array(); + if ( $selected ) { + $args['post__in'] = $selected; + } + + if ( ! empty( $filters['exclude_test_responses'] ) ) { + $args['meta_query'] = array( + array( + 'key' => Feedback::IS_TEST_META_KEY, + 'compare' => 'NOT EXISTS', + ), + ); } + $args = array_merge( $args, $overrides ); + $source_id = ! empty( $filters['source'] ) ? absint( $filters['source'] ) : 0; $join_cb = null; $where_cb = null; @@ -3437,8 +3468,9 @@ public function get_export_feedback_ids( $filters = array() ) { add_filter( 'posts_where', $where_cb, 10, 2 ); } + $query = new \WP_Query(); try { - $feedbacks = get_posts( $args ); + $feedbacks = $query->query( $args ); } finally { if ( is_callable( $join_cb ) ) { remove_filter( 'posts_join', $join_cb, 10 ); @@ -3448,7 +3480,10 @@ public function get_export_feedback_ids( $filters = array() ) { } } - return array_map( 'intval', $feedbacks ); + return array( + 'posts' => $feedbacks, + 'found' => (int) $query->found_posts, + ); } /** @@ -3462,26 +3497,37 @@ public function download_feedback_as_csv() { return; } - $export = $this->prepare_export( $request['ids'], $request['include_test_responses'] ); + $form_id = ! empty( $post_data['post'] ) && $post_data['post'] !== 'all' ? (int) $post_data['post'] : 0; + if ( $this->stream_export_csv( $request['ids'], $request['include_test_responses'], $form_id ) ) { + exit( 0 ); + } + } + + /** + * Sends responses to the browser as a CSV file download. + * + * Does no permission checks; callers must. + * + * @since $$next-version$$ + * + * @param int[] $feedback_ids Feedback IDs to export. + * @param bool $include_test_responses Whether to include responses submitted from form preview. + * @param int $form_id The post the form lives on, used to name the file. 0 for all forms. + * + * @return int Number of responses sent. Sends nothing when no response qualifies. + */ + public function stream_export_csv( $feedback_ids, $include_test_responses, $form_id = 0 ) { + $export = $this->prepare_export( $feedback_ids, $include_test_responses ); $rows = $this->get_prepared_export_rows( $export ); if ( ! $rows->valid() ) { - return; + return 0; } - // Check if we want to download all the feedbacks or just a certain contact form - if ( ! empty( $post_data['post'] ) && $post_data['post'] !== 'all' ) { - $filename = sprintf( - '%s - %s.csv', - Util::get_export_filename( get_the_title( (int) $post_data['post'] ) ), - gmdate( 'Y-m-d H:i' ) - ); - } else { - $filename = sprintf( - '%s - %s.csv', - Util::get_export_filename(), - gmdate( 'Y-m-d H:i' ) - ); - } + $filename = sprintf( + '%s - %s.csv', + $form_id ? Util::get_export_filename( get_the_title( $form_id ) ) : Util::get_export_filename(), + gmdate( 'Y-m-d H:i' ) + ); // Forces the download of the CSV instead of echoing header( 'Content-Disposition: attachment; filename=' . $filename ); @@ -3492,11 +3538,74 @@ public function download_feedback_as_csv() { header( 'X-Jetpack-Forms-Export-Count: ' . count( $export['ids'] ) ); $output = fopen( 'php://output', 'w' ); - $this->write_export_csv( $output, $rows ); + $count = $this->write_export_csv( $output, $rows ); fclose( $output ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose $this->record_tracks_event( 'forms_export_responses', array( 'format' => 'csv' ) ); - exit( 0 ); + return $count; + } + + /** + * Counts the responses an export covers and lists the forms they came from. + * + * Does no permission checks; callers must. + * + * @since $$next-version$$ + * + * @param array $filters See get_export_feedback_ids(). + * @param int $max_forms Most form IDs to return. + * + * @return array{count: int, form_ids: int[], forms_total: int} Form IDs are the posts the forms live on. + */ + public function get_export_summary( $filters = array(), $max_forms = 50 ) { + $count = $this->query_export_feedback( + $filters, + array( + 'posts_per_page' => 1, + 'no_found_rows' => false, + 'orderby' => 'none', + ) + )['found']; + if ( 0 === $count ) { + return array( + 'count' => 0, + 'form_ids' => array(), + 'forms_total' => 0, + ); + } + + $group_by_form = static function ( $groupby, $query ) { + global $wpdb; + return Feedback::POST_TYPE === $query->get( 'post_type' ) ? "{$wpdb->posts}.post_parent" : $groupby; + }; + // Strict SQL modes refuse a selected column that is neither grouped nor aggregated. + $one_row_per_form = static function ( $fields, $query ) { + global $wpdb; + return Feedback::POST_TYPE === $query->get( 'post_type' ) ? "MIN({$wpdb->posts}.ID) AS ID, {$wpdb->posts}.post_parent" : $fields; + }; + add_filter( 'posts_groupby', $group_by_form, 10, 2 ); + add_filter( 'posts_fields', $one_row_per_form, 10, 2 ); + try { + $forms = $this->query_export_feedback( + $filters, + array( + 'fields' => 'id=>parent', + 'posts_per_page' => (int) $max_forms, + 'no_found_rows' => false, + 'post_parent__not_in' => array( 0 ), + 'orderby' => 'parent', + ) + ); + } finally { + remove_filter( 'posts_groupby', $group_by_form, 10 ); + remove_filter( 'posts_fields', $one_row_per_form, 10 ); + } + + return array( + 'count' => $count, + 'form_ids' => array_values( array_unique( array_map( 'intval', $forms['posts'] ) ) ), + 'forms_total' => $forms['found'], + ); } /** diff --git a/projects/packages/forms/src/contact-form/class-response-export-link.php b/projects/packages/forms/src/contact-form/class-response-export-link.php new file mode 100644 index 000000000000..067c27db5568 --- /dev/null +++ b/projects/packages/forms/src/contact-form/class-response-export-link.php @@ -0,0 +1,187 @@ + (int) $user_id, + 'filters' => $filters, + 'include_test_responses' => (bool) $include_test_responses, + 'expires_at' => $expires_at, + ), + self::RECORD_LIFETIME + ); + + return array( + 'url' => self::get_url( $token ), + 'expires_at' => $expires_at, + ); + } + + /** + * Returns the export a link describes, when the user may download it. + * + * @param string $token Token from the link. + * @param int $user_id The user opening the link. + * + * @return array{filters: array, include_test_responses: bool}|WP_Error + */ + public static function resolve( $token, $user_id ) { + $token = is_string( $token ) ? $token : ''; + $record = 1 === preg_match( '/^[A-Za-z0-9]{32}$/', $token ) ? get_transient( self::get_transient_key( $token ) ) : false; + + // One error for every refusal, so a link reveals nothing about who made it. + if ( + ! is_array( $record ) + || ! $user_id + || (int) $record['user_id'] !== (int) $user_id + || ! user_can( (int) $user_id, 'export' ) + ) { + return new WP_Error( + 'jetpack_forms_export_link_invalid', + __( 'This export link does not work for your account. Ask for a new export.', 'jetpack-forms' ), + array( 'status' => 403 ) + ); + } + + if ( time() > (int) $record['expires_at'] ) { + return new WP_Error( + 'jetpack_forms_export_link_expired', + __( 'This export link has expired. Ask for a new export.', 'jetpack-forms' ), + array( 'status' => 410 ) + ); + } + + return array( + 'filters' => (array) $record['filters'], + 'include_test_responses' => (bool) $record['include_test_responses'], + ); + } + + /** + * Sends the CSV file for the link in the request. + * + * @return never + */ + public static function handle_download() { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The token is the secret and is bound to the user. + $token = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : ''; + $export = self::resolve( $token, get_current_user_id() ); + if ( is_wp_error( $export ) ) { + wp_die( esc_html( $export->get_error_message() ), '', array( 'response' => (int) $export->get_error_data()['status'] ) ); + } + + nocache_headers(); + header( 'Referrer-Policy: no-referrer' ); + + $plugin = Contact_Form_Plugin::init(); + $form_id = (int) ( $export['filters']['form'] ?? 0 ); + $ids = $plugin->get_export_feedback_ids( $export['filters'] ); + if ( ! $plugin->stream_export_csv( $ids, $export['include_test_responses'], $form_id ) ) { + wp_die( esc_html__( 'No responses match this export any more.', 'jetpack-forms' ), '', array( 'response' => 404 ) ); + } + exit( 0 ); + } + + /** + * Sends a signed-out visitor to log in, then back to the link. + * + * @return never + */ + public static function redirect_to_login() { + auth_redirect(); + exit( 0 ); + } + + /** + * Returns the download URL for a token. + * + * @param string $token Link token. + * @return string + */ + private static function get_url( $token ) { + return add_query_arg( + array( + 'action' => self::ACTION, + 'token' => rawurlencode( $token ), + ), + admin_url( 'admin-post.php' ) + ); + } + + /** + * Returns the transient key for a token. + * + * @param string $token Link token. + * @return string + */ + private static function get_transient_key( $token ) { + return self::TRANSIENT_PREFIX . hash( 'sha256', $token ); + } +} diff --git a/projects/packages/forms/tests/php/abilities/Forms_Abilities_Test.php b/projects/packages/forms/tests/php/abilities/Forms_Abilities_Test.php index a97f19774e6b..a48e13e33b6b 100644 --- a/projects/packages/forms/tests/php/abilities/Forms_Abilities_Test.php +++ b/projects/packages/forms/tests/php/abilities/Forms_Abilities_Test.php @@ -11,8 +11,13 @@ use Automattic\Jetpack\Forms\ContactForm\Contact_Form; use Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin; +use Automattic\Jetpack\Forms\ContactForm\Response_Export_Link; +use Automattic\Jetpack\Forms\ContactForm\Utility; +use PHPUnit\Framework\Attributes\DataProvider; use WorDBless\BaseTestCase; +require_once __DIR__ . '/../contact-form/class-utility.php'; + /** * Unit tests for Forms Abilities registration and execution. * @@ -200,6 +205,7 @@ function ( $ability ) { 'jetpack-forms/update-response', 'jetpack-forms/bulk-update-responses', 'jetpack-forms/get-status-counts', + 'jetpack-forms/export-responses', ); foreach ( $expected_abilities as $ability_name ) { @@ -639,6 +645,364 @@ public function test_bulk_update_responses_dedupes_repeated_ids() { $this->assertSame( array( $id ), $result['succeeded'], 'Duplicate IDs in input should collapse to one succeeded entry.' ); } + /** + * Creates a legacy response to the form on the given post. + * + * @param int $form_id Post the form lives on. + * @param string $status Response status. + * @return int Response ID. + */ + private static function make_response( int $form_id, string $status = 'publish' ): int { + global $post; + $post = get_post( $form_id ); + $id = (int) Utility::create_legacy_feedback( array(), 'Comment', 'Author', 'author@example.com', 'http://example.com', '127.0.0.1', 'Subject', $status ); + $post = null; + return $id; + } + + /** + * Answers the export's response queries for the given IDs, since the test + * database cannot run post queries, and records each query it was asked. + * + * @param int[] $ids Response IDs that match the export. + * @return \ArrayObject Receives the query vars of each export query. + */ + private function answer_export_query( array $ids ): \ArrayObject { + $queries = new \ArrayObject(); + $forms = array_values( array_unique( array_filter( array_map( 'wp_get_post_parent_id', $ids ) ) ) ); + add_filter( + 'posts_pre_query', + static function ( $posts, $query ) use ( $ids, $forms, $queries ) { + if ( 'feedback' !== $query->get( 'post_type' ) ) { + return $posts; + } + $queries->append( $query->query_vars ); + if ( 'id=>parent' !== $query->get( 'fields' ) ) { + return $ids; + } + return array_map( + static function ( $form ) { + return (object) array( + 'ID' => $form, + 'post_parent' => $form, + ); + }, + array_slice( $forms, 0, $query->get( 'posts_per_page' ) ) + ); + }, + 10, + 2 + ); + add_filter( + 'found_posts', + static function ( $found, $query ) use ( $ids, $forms ) { + if ( 'feedback' !== $query->get( 'post_type' ) ) { + return $found; + } + return 'id=>parent' === $query->get( 'fields' ) ? count( $forms ) : count( $ids ); + }, + 10, + 2 + ); + return $queries; + } + + /** + * @dataProvider provide_export_roles + * + * @param string $role Role of the user asking. + * @param bool $allowed Whether the export may run. + */ + #[DataProvider( 'provide_export_roles' )] + public function test_export_responses_runs_only_for_users_who_can_export( $role, $allowed ) { + if ( ! function_exists( 'wp_get_ability' ) ) { + $this->markTestSkipped( 'Abilities API functions not available' ); + } + $this->simulate_doing_wp_abilities_categories_init_action(); + Forms_Abilities::register_category(); + $this->simulate_doing_wp_abilities_init_action(); + Forms_Abilities::register_abilities(); + wp_set_current_user( + wp_insert_user( + array( + 'user_login' => "export_$role", + 'user_pass' => '123', + 'role' => $role, + ) + ) + ); + + $this->assertSame( $allowed, true === wp_get_ability( 'jetpack-forms/export-responses' )->check_permissions() ); + } + + /** + * Roles and whether each may export, since an export holds every response's personal data. + */ + public static function provide_export_roles() { + return array( + 'administrator' => array( 'administrator', true ), + 'editor' => array( 'editor', false ), + 'subscriber' => array( 'subscriber', false ), + ); + } + + public function test_export_responses_returns_count_forms_and_a_link_for_the_current_user() { + wp_set_current_user( self::$user_id ); + $contact = (int) wp_insert_post( array( 'post_title' => 'Contact' ) ); + $survey = (int) wp_insert_post( array( 'post_title' => 'Survey' ) ); + $this->answer_export_query( array( self::make_response( $contact ), self::make_response( $contact ), self::make_response( $survey ) ) ); + + $result = Forms_Abilities::export_responses( array() ); + + $this->assertSame( 3, $result['count'] ); + $this->assertSame( + array( + array( + 'id' => $contact, + 'title' => 'Contact', + ), + array( + 'id' => $survey, + 'title' => 'Survey', + ), + ), + $result['forms'] + ); + $this->assertSame( 2, $result['forms_total'] ); + $this->assertEqualsWithDelta( time() + Response_Export_Link::LIFETIME, strtotime( $result['expires_at'] ), 5 ); + + $query = array(); + wp_parse_str( (string) wp_parse_url( $result['download_url'], PHP_URL_QUERY ), $query ); + $this->assertIsArray( Response_Export_Link::resolve( $query['token'], self::$user_id ) ); + } + + public function test_export_responses_lists_at_most_fifty_forms_but_counts_them_all() { + wp_set_current_user( self::$user_id ); + $responses = array( self::make_response( 0 ) ); + for ( $i = 0; $i <= Forms_Abilities::EXPORT_MAX_FORMS; $i++ ) { + $responses[] = self::make_response( (int) wp_insert_post( array( 'post_title' => "Form $i" ) ) ); + } + $queries = $this->answer_export_query( $responses ); + + $result = Forms_Abilities::export_responses( array() ); + + $this->assertSame( Forms_Abilities::EXPORT_MAX_FORMS + 2, $result['count'] ); + $this->assertCount( Forms_Abilities::EXPORT_MAX_FORMS, $result['forms'] ); + $this->assertSame( Forms_Abilities::EXPORT_MAX_FORMS + 1, $result['forms_total'], 'A response with no form must not count as a form.' ); + $this->assertNotContains( -1, array_column( $queries->getArrayCopy(), 'posts_per_page' ), 'The summary must not load every response.' ); + } + + public function test_export_responses_link_repeats_the_requested_filters() { + wp_set_current_user( self::$user_id ); + $contact = (int) wp_insert_post( array( 'post_title' => 'Contact' ) ); + $this->answer_export_query( array( self::make_response( $contact ) ) ); + + $result = Forms_Abilities::export_responses( + array( + 'form_id' => $contact, + 'status' => 'spam', + 'search' => 'invoice', + 'after' => '2026-10-01T00:00:00Z', + 'before' => '2026-11-01T00:00:00Z', + 'include_test_responses' => true, + ) + ); + + $query = array(); + wp_parse_str( (string) wp_parse_url( $result['download_url'], PHP_URL_QUERY ), $query ); + $this->assertSame( + array( + 'filters' => array( + 'status' => 'spam', + 'search' => 'invoice', + 'form' => $contact, + 'after' => '2026-10-01T00:00:00Z', + 'before' => '2026-11-01T00:00:00Z', + ), + 'include_test_responses' => true, + ), + Response_Export_Link::resolve( $query['token'], self::$user_id ) + ); + } + + public function test_export_responses_queries_one_form_and_date_range() { + wp_set_current_user( self::$user_id ); + $queries = $this->answer_export_query( array() ); + + Forms_Abilities::export_responses( + array( + 'form_id' => 12, + 'after' => '2026-10-01T00:00:00Z', + 'before' => '2026-11-01T00:00:00Z', + ) + ); + + $this->assertSame( 12, $queries[0]['post_parent'] ); + $this->assertSame( + array( + 'after' => '2026-10-01 00:00:00', + 'before' => '2026-11-01 00:00:00', + ), + $queries[0]['date_query'] + ); + } + + public function test_export_responses_reads_dates_with_a_timezone_in_site_time() { + wp_set_current_user( self::$user_id ); + update_option( 'timezone_string', 'Asia/Tokyo' ); + $queries = $this->answer_export_query( array() ); + + Forms_Abilities::export_responses( + array( + 'after' => '2026-10-01T00:00:00Z', + 'before' => '2026-11-01T09:00:00+09:00', + ) + ); + + $this->assertSame( + array( + 'after' => '2026-10-01 09:00:00', + 'before' => '2026-11-01 09:00:00', + ), + $queries[0]['date_query'] + ); + } + + public function test_export_responses_accepts_a_range_that_is_in_order_in_site_time() { + wp_set_current_user( self::$user_id ); + update_option( 'timezone_string', 'Asia/Tokyo' ); + $this->answer_export_query( array() ); + + $result = Forms_Abilities::export_responses( + array( + 'after' => '2026-10-01T05:00:00', + 'before' => '2026-10-01T00:00:00Z', + ) + ); + + $this->assertIsArray( $result ); + } + + public function test_export_with_a_search_term_stays_oldest_first() { + $queries = $this->answer_export_query( array() ); + + Contact_Form_Plugin::init()->get_export_feedback_ids( array( 'search' => 'invoice' ) ); + + $this->assertSame( 'date', $queries[0]['orderby'], 'WP_Query sorts a search by relevance unless told otherwise.' ); + $this->assertSame( 'ASC', $queries[0]['order'] ); + } + + /** + * @dataProvider provide_test_response_inputs + * + * @param array $input Ability input. + * @param bool $excluded Whether the count and the file leave test responses out. + */ + #[DataProvider( 'provide_test_response_inputs' )] + public function test_export_responses_counts_test_responses_only_when_the_file_has_them( $input, $excluded ) { + wp_set_current_user( self::$user_id ); + $queries = $this->answer_export_query( array( self::make_response( 0 ) ) ); + + $result = Forms_Abilities::export_responses( $input ); + + $query = array(); + wp_parse_str( (string) wp_parse_url( $result['download_url'], PHP_URL_QUERY ), $query ); + $link = Response_Export_Link::resolve( $query['token'], self::$user_id ); + $this->assertSame( $excluded, ! empty( $queries[0]['meta_query'] ) ); + $this->assertSame( $excluded, ! empty( $link['filters']['exclude_test_responses'] ) ); + } + + /** + * Inputs and whether each leaves out form preview test responses. + */ + public static function provide_test_response_inputs() { + return array( + 'default' => array( array(), true ), + 'excluded' => array( array( 'include_test_responses' => false ), true ), + 'included' => array( array( 'include_test_responses' => true ), false ), + ); + } + + /** + * @dataProvider provide_export_statuses + * + * @param array $input Ability input. + * @param string|array $post_status Expected query post status. + */ + #[DataProvider( 'provide_export_statuses' )] + public function test_export_responses_queries_the_requested_folder( $input, $post_status ) { + wp_set_current_user( self::$user_id ); + $queries = $this->answer_export_query( array() ); + + Forms_Abilities::export_responses( $input ); + + $this->assertEqualsCanonicalizing( $post_status, $queries[0]['post_status'] ); + } + + /** + * Folders and the post status each one queries. + */ + public static function provide_export_statuses() { + return array( + 'no status' => array( array(), array( 'publish', 'draft' ) ), + 'inbox' => array( array( 'status' => 'inbox' ), array( 'publish', 'draft' ) ), + 'spam' => array( array( 'status' => 'spam' ), 'spam' ), + 'trash' => array( array( 'status' => 'trash' ), 'trash' ), + ); + } + + public function test_export_responses_with_no_matches_returns_no_link() { + wp_set_current_user( self::$user_id ); + $this->answer_export_query( array() ); + + $result = Forms_Abilities::export_responses( array() ); + + $this->assertSame( 0, $result['count'] ); + $this->assertSame( array(), $result['forms'] ); + $this->assertNull( $result['download_url'] ); + $this->assertNull( $result['expires_at'] ); + } + + /** + * @dataProvider provide_bad_dates + * + * @param array $input Ability input. + * @param string $code Expected error code. + */ + #[DataProvider( 'provide_bad_dates' )] + public function test_export_responses_rejects_bad_dates( $input, $code ) { + wp_set_current_user( self::$user_id ); + + $result = Forms_Abilities::export_responses( $input ); + + $this->assertInstanceOf( \WP_Error::class, $result ); + $this->assertSame( $code, $result->get_error_code() ); + } + + /** + * Date inputs the ability must refuse. + */ + public static function provide_bad_dates() { + return array( + 'unreadable after' => array( array( 'after' => 'last month-ish' ), 'jetpack_forms_invalid_date' ), + 'unreadable before' => array( array( 'before' => 'soonish' ), 'jetpack_forms_invalid_date' ), + 'range ends earlier' => array( + array( + 'after' => '2026-11-01T00:00:00Z', + 'before' => '2026-10-01T00:00:00Z', + ), + 'jetpack_forms_invalid_date_range', + ), + 'empty range' => array( + array( + 'after' => '2026-11-01T00:00:00Z', + 'before' => '2026-11-01T00:00:00Z', + ), + 'jetpack_forms_invalid_date_range', + ), + ); + } + public function test_every_ability_opts_into_mcp_as_public_tool(): void { foreach ( Forms_Abilities::get_abilities() as $slug => $spec ) { $this->assertArrayHasKey( 'public', $spec['meta'], "{$slug} must declare meta.public." ); diff --git a/projects/packages/forms/tests/php/contact-form/Contact_Form_Plugin_Test.php b/projects/packages/forms/tests/php/contact-form/Contact_Form_Plugin_Test.php index 4aa8f0ea0b12..b9720c0f7ec2 100644 --- a/projects/packages/forms/tests/php/contact-form/Contact_Form_Plugin_Test.php +++ b/projects/packages/forms/tests/php/contact-form/Contact_Form_Plugin_Test.php @@ -15,6 +15,8 @@ use Closure; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; use WorDBless\BaseTestCase; use WP_Block; use WP_Block_Type_Registry; @@ -1043,6 +1045,49 @@ public function test_write_export_csv_escapes_formulas_in_responses() { Utility::destroy_post_context( $current_post ); } + /** + * Runs isolated because it sends headers, which older PHPUnit refuses after printing output. + * + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + #[RunInSeparateProcess] + #[PreserveGlobalState( false )] + public function test_stream_export_csv_writes_every_response_and_returns_the_count() { + $current_post = Utility::create_post_context(); + $post_ids = array( + Utility::create_legacy_feedback( array( '1_Name' => 'First' ) ), + Utility::create_legacy_feedback( array( '1_Name' => 'Second' ) ), + ); + + ob_start(); + $count = Contact_Form_Plugin::init()->stream_export_csv( $post_ids, false ); + $csv = ob_get_clean(); + + $lines = array_map( + static function ( $line ) { + return str_getcsv( $line, ',', '"', '' ); + }, + array_filter( explode( "\n", $csv ) ) + ); + $header = array_shift( $lines ); + $column = array_search( 'Name', $header, true ); + + $this->assertSame( 2, $count ); + $this->assertSame( array( 'First', 'Second' ), array_column( $lines, $column ) ); + + Utility::destroy_post_context( $current_post ); + } + + public function test_stream_export_csv_sends_nothing_when_no_response_qualifies() { + ob_start(); + $count = Contact_Form_Plugin::init()->stream_export_csv( array(), false ); + $csv = ob_get_clean(); + + $this->assertSame( 0, $count ); + $this->assertSame( '', $csv ); + } + public function test_get_export_feedback_data_includes_fields_first_seen_in_a_later_batch() { $current_post = Utility::create_post_context(); diff --git a/projects/packages/forms/tests/php/contact-form/Response_Export_Link_Test.php b/projects/packages/forms/tests/php/contact-form/Response_Export_Link_Test.php new file mode 100644 index 000000000000..988c3ccb63c2 --- /dev/null +++ b/projects/packages/forms/tests/php/contact-form/Response_Export_Link_Test.php @@ -0,0 +1,255 @@ +admin_id = wp_insert_user( + array( + 'user_login' => 'export_admin', + 'user_pass' => 'pass', + 'role' => 'administrator', + ) + ); + $this->other_admin_id = wp_insert_user( + array( + 'user_login' => 'other_admin', + 'user_pass' => 'pass', + 'role' => 'administrator', + ) + ); + } + + /** + * Returns the token query arg of a download URL. + * + * @param string $url Download URL. + * @return string + */ + private static function get_token( $url ) { + $query = array(); + wp_parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $query ); + return (string) ( $query['token'] ?? '' ); + } + + public function test_create_returns_admin_post_url_that_expires_in_fifteen_minutes() { + $before = time(); + $link = Response_Export_Link::create( array( 'form' => 12 ), false, $this->admin_id ); + + $this->assertStringStartsWith( admin_url( 'admin-post.php' ), $link['url'] ); + $this->assertStringContainsString( 'action=' . Response_Export_Link::ACTION, $link['url'] ); + $this->assertMatchesRegularExpression( '/^[A-Za-z0-9]{32}$/', self::get_token( $link['url'] ) ); + $this->assertGreaterThanOrEqual( $before + 15 * MINUTE_IN_SECONDS, $link['expires_at'] ); + $this->assertLessThanOrEqual( time() + 15 * MINUTE_IN_SECONDS, $link['expires_at'] ); + } + + public function test_resolve_returns_the_export_for_the_user_who_asked() { + $filters = array( + 'form' => 12, + 'status' => 'spam', + 'after' => '2026-10-01T00:00:00', + ); + $link = Response_Export_Link::create( $filters, true, $this->admin_id ); + + $export = Response_Export_Link::resolve( self::get_token( $link['url'] ), $this->admin_id ); + + $this->assertSame( + array( + 'filters' => $filters, + 'include_test_responses' => true, + ), + $export + ); + } + + public function test_resolve_refuses_another_user() { + $link = Response_Export_Link::create( array(), false, $this->admin_id ); + + $export = Response_Export_Link::resolve( self::get_token( $link['url'] ), $this->other_admin_id ); + + $this->assertInstanceOf( WP_Error::class, $export ); + $this->assertSame( 'jetpack_forms_export_link_invalid', $export->get_error_code() ); + } + + public function test_resolve_refuses_a_user_who_can_no_longer_export() { + $link = Response_Export_Link::create( array(), false, $this->admin_id ); + ( new \WP_User( $this->admin_id ) )->set_role( 'editor' ); + + $export = Response_Export_Link::resolve( self::get_token( $link['url'] ), $this->admin_id ); + + $this->assertInstanceOf( WP_Error::class, $export ); + $this->assertSame( 'jetpack_forms_export_link_invalid', $export->get_error_code() ); + } + + /** + * @dataProvider provide_bad_tokens + * + * @param mixed $token Token from the request. + */ + #[DataProvider( 'provide_bad_tokens' )] + public function test_resolve_refuses_an_unknown_or_malformed_token( $token ) { + Response_Export_Link::create( array(), false, $this->admin_id ); + + $export = Response_Export_Link::resolve( $token, $this->admin_id ); + + $this->assertInstanceOf( WP_Error::class, $export ); + $this->assertSame( 'jetpack_forms_export_link_invalid', $export->get_error_code() ); + } + + /** + * Tokens that match no link. + */ + public static function provide_bad_tokens() { + return array( + 'empty' => array( '' ), + 'wrong format' => array( 'not-a-token' ), + 'unknown' => array( str_repeat( 'a', 32 ) ), + 'too long' => array( str_repeat( 'a', 200 ) ), + 'not a string' => array( array( 'token' ) ), + 'null' => array( null ), + ); + } + + public function test_resolve_says_a_link_expired_after_fifteen_minutes() { + $link = Response_Export_Link::create( array(), false, $this->admin_id ); + $key = Response_Export_Link::TRANSIENT_PREFIX . hash( 'sha256', self::get_token( $link['url'] ) ); + $this->assertGreaterThan( $link['expires_at'], (int) get_option( '_transient_timeout_' . $key ), 'The record must outlive the link, or an expired link reads as invalid.' ); + + set_transient( $key, array_merge( get_transient( $key ), array( 'expires_at' => time() - 1 ) ), HOUR_IN_SECONDS ); + $export = Response_Export_Link::resolve( self::get_token( $link['url'] ), $this->admin_id ); + + $this->assertInstanceOf( WP_Error::class, $export ); + $this->assertSame( 'jetpack_forms_export_link_expired', $export->get_error_code() ); + } + + /** + * Runs isolated because it sends headers, which older PHPUnit refuses after printing output. + * + * @runInSeparateProcess + * @preserveGlobalState disabled + * @dataProvider provide_refused_downloads + * + * @param bool $real_token Whether the request carries the link's own token. + * @param string $opener Who opens the link: owner, other or demoted. + * @param int $status Expected HTTP status. + */ + #[DataProvider( 'provide_refused_downloads' )] + #[RunInSeparateProcess] + #[PreserveGlobalState( false )] + public function test_handle_download_refuses_without_sending_the_file( $real_token, $opener, $status ) { + $link = Response_Export_Link::create( array(), false, $this->admin_id ); + $_GET['token'] = $real_token ? self::get_token( $link['url'] ) : str_repeat( 'a', 32 ); + wp_set_current_user( 'other' === $opener ? $this->other_admin_id : $this->admin_id ); + if ( 'demoted' === $opener ) { + ( new \WP_User( $this->admin_id ) )->set_role( 'editor' ); + } + add_filter( + 'posts_pre_query', + static function ( $posts, $query ) { + return Feedback::POST_TYPE === $query->get( 'post_type' ) ? array() : $posts; + }, + 10, + 2 + ); + add_filter( + 'wp_die_ajax_handler', + static function () { + /** @return never */ + return static function ( $message, $title, $args ) { + throw new \RuntimeException( (string) $args['response'] ); + }; + } + ); + + $this->expectException( \RuntimeException::class ); + $this->expectExceptionMessage( (string) $status ); + $this->expectOutputString( '' ); + try { + Response_Export_Link::handle_download(); + } finally { + unset( $_GET['token'] ); + } + } + + /** + * Runs isolated because it sends headers. + * + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + #[RunInSeparateProcess] + #[PreserveGlobalState( false )] + public function test_redirect_to_login_returns_to_the_link_even_when_login_is_on_another_host() { + $link = Response_Export_Link::create( array(), false, $this->admin_id ); + $_SERVER['HTTP_HOST'] = (string) wp_parse_url( $link['url'], PHP_URL_HOST ); + $_SERVER['REQUEST_URI'] = (string) wp_parse_url( $link['url'], PHP_URL_PATH ) . '?' . wp_parse_url( $link['url'], PHP_URL_QUERY ); + add_filter( + 'login_url', + static function ( $login_url, $redirect ) { + return add_query_arg( 'redirect_to', rawurlencode( $redirect ), 'https://sso.example.org/login' ); + }, + 10, + 2 + ); + add_filter( + 'wp_redirect', + /** @return never */ + static function ( $location ) { + throw new \RuntimeException( $location ); + } + ); + + $this->expectException( \RuntimeException::class ); + $this->expectExceptionMessage( 'https://sso.example.org/login?redirect_to=' . rawurlencode( set_url_scheme( $link['url'] ) ) ); + Response_Export_Link::redirect_to_login(); + } + + /** + * Requests the download handler must refuse, with the status it sends. + */ + public static function provide_refused_downloads() { + return array( + 'unknown token' => array( false, 'owner', 403 ), + 'another user' => array( true, 'other', 403 ), + 'user who lost export' => array( true, 'demoted', 403 ), + 'nothing matches now' => array( true, 'owner', 404 ), + ); + } +} diff --git a/projects/plugins/jetpack/changelog/add-forms-export-responses-ability b/projects/plugins/jetpack/changelog/add-forms-export-responses-ability new file mode 100644 index 000000000000..d2ff229f59b5 --- /dev/null +++ b/projects/plugins/jetpack/changelog/add-forms-export-responses-ability @@ -0,0 +1,4 @@ +Significance: minor +Type: enhancement + +Forms: Let AI agents export form responses as a CSV download link.