';
foreach ( $fields as $field_name => $field_data ) {
- $value = isset( $field_data['value'] ) ? $field_data['value'] : '';
+ $raw = isset( $field_data['value'] ) ? $field_data['value'] : '';
$type = isset( $field_data['type'] ) ? $field_data['type'] : 'text';
+ $text = self::display_value( $raw, (string) $type );
+ $label = isset( $field_data['label'] ) && '' !== $field_data['label'] ? (string) $field_data['label'] : '';
// Format value based on type.
- if ( 'email' === $type ) {
- $value = '' . esc_html( $value ) . '';
- } elseif ( 'url' === $type ) {
- $value = '' . esc_html( $value ) . '';
+ if ( 'email' === $type && is_string( $raw ) ) {
+ $value = '' . esc_html( $raw ) . '';
+ } elseif ( 'url' === $type && is_string( $raw ) ) {
+ $value = '' . esc_html( $raw ) . '';
} elseif ( 'textarea' === $type ) {
- $value = '' . esc_html( $value ) . '
';
+ $value = '' . esc_html( $text ) . '
';
} else {
- $value = esc_html( $value );
+ $value = esc_html( $text );
}
+ $name_cell = '' !== $label
+ ? '' . esc_html( $label ) . '
' . esc_html( $field_name ) . ''
+ : '' . esc_html( $field_name ) . '';
+
echo '';
- echo '| ' . esc_html( $field_name ) . ' | ';
+ echo '' . $name_cell . ' | '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped above.
echo '' . $value . ' | '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo '' . esc_html( $type ) . ' | ';
echo '
';
@@ -151,6 +157,39 @@ public function render_submission_details( $post ) {
echo '';
}
+ /**
+ * Flatten a stored field value to display text.
+ *
+ * Checkbox groups and multi-selects store arrays; only scalar members are kept.
+ *
+ * @param mixed $value Stored value.
+ * @return string Text.
+ */
+ public static function format_field_value( $value ): string {
+ if ( is_array( $value ) ) {
+ return implode( ', ', array_map( 'strval', array_filter( $value, 'is_scalar' ) ) );
+ }
+
+ return is_scalar( $value ) ? (string) $value : '';
+ }
+
+ /**
+ * A stored value as a site owner should read it.
+ *
+ * A ticked single checkbox stores its value attribute, "1" unless the
+ * author set one; show that default as "Yes". Webhook payloads keep the
+ * stored value.
+ *
+ * @param mixed $value Stored value.
+ * @param string $type Field type.
+ * @return string Text.
+ */
+ public static function display_value( $value, string $type ): string {
+ $text = self::format_field_value( $value );
+
+ return 'checkbox' === $type && '1' === $text ? __( 'Yes', 'airo-wp' ) : $text;
+ }
+
/**
* Render submission meta information.
*
diff --git a/includes/Blocks/Common/Forms/FormSubmissionsExport.php b/includes/Blocks/Common/Forms/FormSubmissionsExport.php
new file mode 100644
index 0000000..ac8c954
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormSubmissionsExport.php
@@ -0,0 +1,287 @@
+ isset( $source['airowp_form'] ) && is_string( $source['airowp_form'] ) ? sanitize_text_field( wp_unslash( $source['airowp_form'] ) ) : '',
+ 'from' => self::valid_date( isset( $source['airowp_from'] ) ? $source['airowp_from'] : '' ),
+ 'to' => self::valid_date( isset( $source['airowp_to'] ) ? $source['airowp_to'] : '' ),
+ );
+ }
+
+ /**
+ * WP_Query arguments for the filters.
+ *
+ * Dates are inclusive whole days in the site's timezone (post_date is local).
+ * An optional `until` (local Y-m-d H:i:s) caps the newest submission.
+ *
+ * @param array $args Filter args from request_args().
+ * @return array Query args.
+ */
+ public static function query_args( array $args ): array {
+ $query = array();
+
+ if ( ! empty( $args['form_id'] ) ) {
+ $query['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Admin-only filter.
+ array(
+ 'key' => '_dsg_form_id',
+ 'value' => $args['form_id'],
+ ),
+ );
+ }
+
+ $date = array( 'inclusive' => true );
+ if ( ! empty( $args['from'] ) ) {
+ $date['after'] = self::date_parts( $args['from'] );
+ }
+ if ( ! empty( $args['to'] ) ) {
+ // Array form so WP_Date_Query fills the time with 23:59:59 for an inclusive "before".
+ $date['before'] = self::date_parts( $args['to'] );
+ }
+ $clauses = count( $date ) > 1 ? array( $date ) : array();
+ if ( ! empty( $args['until'] ) ) {
+ $clauses[] = array(
+ 'before' => $args['until'],
+ 'inclusive' => true,
+ );
+ }
+ if ( $clauses ) {
+ $query['date_query'] = $clauses;
+ }
+
+ return $query;
+ }
+
+ /**
+ * Neutralise spreadsheet formula injection. A plain negative number is
+ * left alone: a spreadsheet reads it as the number it is.
+ *
+ * @param mixed $value Cell value.
+ * @return string Safe cell.
+ */
+ public static function escape_cell( $value ): string {
+ $value = (string) $value;
+
+ if ( '' === $value || ! in_array( $value[0], self::FORMULA_PREFIXES, true ) || preg_match( '/^-\d+(\.\d+)?\z/', $value ) ) {
+ return $value;
+ }
+
+ return "'" . $value;
+ }
+
+ /**
+ * Write the CSV for the given filters to the response output.
+ *
+ * Two passes over the matching IDs, in batches: the first collects every
+ * field name (so the header is complete), the second writes rows. Memory
+ * stays flat however many submissions there are. Both passes stop at the
+ * export's start time, so a submission arriving mid-export can't add a
+ * row whose fields have no column.
+ *
+ * The handle needs no fclose(): it closes, flushing, when it goes out of
+ * scope at return.
+ *
+ * @param array $args Filter args from request_args().
+ */
+ public function write_csv( array $args ): void {
+ $args['until'] = wp_date( 'Y-m-d H:i:s', time() - 1 );
+ $handle = fopen( 'php://output', 'w' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Streaming to the response.
+ if ( false === $handle ) {
+ return;
+ }
+ echo "\xEF\xBB\xBF"; // UTF-8 BOM so spreadsheets detect the encoding.
+
+ $names = array();
+ $labels = array();
+ $this->each_submission(
+ $args,
+ function ( $id ) use ( &$names, &$labels ) {
+ foreach ( $this->stored_fields( $id ) as $name => $data ) {
+ $names[ $name ] = true;
+ if ( is_array( $data ) && isset( $data['label'] ) && '' !== $data['label'] ) {
+ $labels[ $name ] = (string) $data['label'];
+ }
+ }
+ }
+ );
+
+ $columns = FormSubmissions_Export_Columns::build( array_keys( $names ), $labels, $args );
+ $this->put_row( $handle, array_values( $columns ) );
+
+ $keys = array_keys( $columns );
+ $this->each_submission(
+ $args,
+ function ( $id ) use ( $handle, $keys ) {
+ $fields = $this->stored_fields( $id );
+ $row = array();
+ foreach ( $keys as $key ) {
+ $row[] = FormSubmissions_Export_Columns::value( $key, $id, $fields );
+ }
+ $this->put_row( $handle, $row );
+ }
+ );
+ }
+
+ /**
+ * Stream the CSV download when the Export button was used.
+ */
+ public function maybe_export(): void {
+ // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Presence checks only; nonce verified below.
+ $post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : '';
+ if ( self::POST_TYPE !== $post_type || empty( $_GET['airowp_export'] ) ) {
+ return;
+ }
+ // phpcs:enable
+
+ check_admin_referer( self::NONCE_ACTION, self::NONCE_NAME );
+ if ( ! current_user_can( 'manage_options' ) ) {
+ wp_die( esc_html__( 'Sorry, you are not allowed to export submissions.', 'airo-wp' ), '', array( 'response' => 403 ) );
+ }
+
+ $args = self::request_args( $_GET );
+ $filename = 'submissions-' . ( '' !== $args['form_id'] ? sanitize_file_name( $args['form_id'] ) : 'all' ) . '-' . wp_date( 'Y-m-d' ) . '.csv';
+
+ // No set_time_limit(): Plugin Check forbids it, and core's export_wp()
+ // streams without it. Batching keeps CPU time (what max_execution_time
+ // counts on most hosts) low; the wait is mostly DB and output I/O.
+ // Where the limit counts wall-clock time (Windows), a very large
+ // export can still be cut off, leaving a silently truncated file.
+ wp_raise_memory_limit( 'admin' );
+
+ nocache_headers();
+ header( 'Content-Type: text/csv; charset=utf-8' );
+ header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
+
+ $this->write_csv( $args );
+ exit;
+ }
+
+ /**
+ * Call $callback for each matching submission ID, oldest first, in batches.
+ *
+ * @param array $args Filter args.
+ * @param callable $callback Receives an int ID.
+ */
+ private function each_submission( array $args, callable $callback ): void {
+ $paged = 1;
+ $found = 0;
+ do {
+ // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts -- Admin-only export; bounded batches.
+ $ids = get_posts(
+ array_merge(
+ self::query_args( $args ),
+ array(
+ 'post_type' => self::POST_TYPE,
+ 'post_status' => 'any',
+ 'fields' => 'ids',
+ 'posts_per_page' => self::BATCH,
+ 'paged' => $paged,
+ 'orderby' => array(
+ 'date' => 'ASC',
+ 'ID' => 'ASC',
+ ),
+ 'no_found_rows' => true,
+ )
+ )
+ );
+
+ update_meta_cache( 'post', $ids );
+ _prime_post_caches( $ids, false, false ); // One query for the post rows instead of one per cell lookup.
+ foreach ( $ids as $id ) {
+ $callback( (int) $id );
+ wp_cache_delete( (int) $id, 'post_meta' );
+ wp_cache_delete( (int) $id, 'posts' );
+ }
+ ++$paged;
+ $found = count( $ids );
+ } while ( self::BATCH === $found );
+ }
+
+ /**
+ * Stored field map for a submission.
+ *
+ * @param int $id Submission ID.
+ * @return array Fields.
+ */
+ private function stored_fields( int $id ): array {
+ $fields = get_post_meta( $id, '_dsg_form_fields', true );
+ return is_array( $fields ) ? $fields : array();
+ }
+
+ /**
+ * Write one escaped row.
+ *
+ * @param resource $handle Stream.
+ * @param array $cells Cells.
+ */
+ private function put_row( $handle, array $cells ): void {
+ fputcsv( $handle, array_map( array( __CLASS__, 'escape_cell' ), $cells ), ',', '"', '' ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fputcsv -- Streaming to the response.
+ }
+
+ /**
+ * A Y-m-d string, or '' when invalid.
+ *
+ * @param mixed $value Raw value.
+ * @return string Date.
+ */
+ private static function valid_date( $value ): string {
+ $value = is_string( $value ) ? sanitize_text_field( wp_unslash( $value ) ) : '';
+ $date = \DateTime::createFromFormat( '!Y-m-d', $value );
+
+ return ( $date && $date->format( 'Y-m-d' ) === $value ) ? $value : '';
+ }
+
+ /**
+ * Split Y-m-d into WP_Date_Query parts.
+ *
+ * @param string $ymd Date.
+ * @return array{year: int, month: int, day: int}
+ */
+ private static function date_parts( string $ymd ): array {
+ list( $year, $month, $day ) = array_map( 'intval', explode( '-', $ymd ) );
+
+ return array(
+ 'year' => $year,
+ 'month' => $month,
+ 'day' => $day,
+ );
+ }
+}
diff --git a/includes/Blocks/Common/Forms/FormSubmissionsExportColumns.php b/includes/Blocks/Common/Forms/FormSubmissionsExportColumns.php
new file mode 100644
index 0000000..8059e46
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormSubmissionsExportColumns.php
@@ -0,0 +1,114 @@
+ header. Fields are keyed "field:{name}".
+ *
+ * A field header that appears more than once in the row (two fields with
+ * the same label, a label matching a built-in column, an unlabeled field
+ * named like another label) gets " (field_name)" appended.
+ *
+ * @param string[] $names Field names in first-seen order.
+ * @param array $labels Latest label per field.
+ * @param array $args Filter args.
+ * @return array Columns.
+ */
+ public static function build( array $names, array $labels, array $args ): array {
+ $leading = array(
+ 'id' => __( 'Submission ID', 'airo-wp' ),
+ 'date' => __( 'Date', 'airo-wp' ),
+ 'form_id' => __( 'Form ID', 'airo-wp' ),
+ 'source_url' => __( 'Source URL', 'airo-wp' ),
+ );
+ $trailing = array(
+ 'email_status' => __( 'Email status', 'airo-wp' ),
+ 'webhook_status' => __( 'Webhook status', 'airo-wp' ),
+ );
+
+ $headers = array();
+ foreach ( $names as $name ) {
+ $headers[ $name ] = isset( $labels[ $name ] ) ? $labels[ $name ] : (string) $name;
+ }
+ $counts = array_count_values( array_merge( array_values( $leading ), array_values( $trailing ), array_map( 'strval', $headers ) ) );
+
+ $fields = array();
+ foreach ( $headers as $name => $header ) {
+ $header = (string) $header;
+ $fields[ 'field:' . $name ] = $counts[ $header ] > 1 ? sprintf( '%s (%s)', $header, $name ) : $header;
+ }
+
+ return (array) apply_filters( 'airowp_form_export_columns', array_merge( $leading, $fields, $trailing ), $args );
+ }
+
+ /**
+ * One cell's final value, after the `airowp_form_export_cell` filter.
+ *
+ * @param string $key Column key.
+ * @param int $id Submission ID.
+ * @param array $fields Stored fields.
+ * @return string Value.
+ */
+ public static function value( string $key, int $id, array $fields ): string {
+ return (string) apply_filters( 'airowp_form_export_cell', self::cell( $key, $id, $fields ), $key, $id );
+ }
+
+ /**
+ * One cell's raw value.
+ *
+ * @param string $key Column key.
+ * @param int $id Submission ID.
+ * @param array $fields Stored fields.
+ * @return string Value.
+ */
+ private static function cell( string $key, int $id, array $fields ): string {
+ if ( 0 === strpos( $key, 'field:' ) ) {
+ $name = substr( $key, 6 );
+ if ( ! isset( $fields[ $name ]['value'] ) ) {
+ return '';
+ }
+ $type = isset( $fields[ $name ]['type'] ) && is_string( $fields[ $name ]['type'] ) ? $fields[ $name ]['type'] : 'text';
+ return FormSubmissions::display_value( $fields[ $name ]['value'], $type );
+ }
+
+ switch ( $key ) {
+ case 'id':
+ return (string) $id;
+ case 'date':
+ return (string) get_post_field( 'post_date', $id );
+ case 'form_id':
+ return (string) get_post_meta( $id, '_dsg_form_id', true );
+ case 'source_url':
+ return (string) get_post_meta( $id, '_dsg_submission_referer', true );
+ case 'email_status':
+ $sent = get_post_meta( $id, '_dsg_email_sent', true );
+ if ( '' === $sent ) {
+ return '';
+ }
+ // Same words as the submissions list: 'no' means wp_mail() failed.
+ return 'yes' === $sent ? __( 'Sent', 'airo-wp' ) : __( 'Failed', 'airo-wp' );
+ case 'webhook_status':
+ return Form_Webhook_Status::label( $id );
+ case 'ip':
+ return (string) get_post_meta( $id, '_dsg_submission_ip', true );
+ case 'user_agent':
+ return (string) get_post_meta( $id, '_dsg_submission_user_agent', true );
+ default:
+ return '';
+ }
+ }
+}
diff --git a/includes/Blocks/Common/Forms/FormSubmissionsListFilters.php b/includes/Blocks/Common/Forms/FormSubmissionsListFilters.php
new file mode 100644
index 0000000..3cb26f5
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormSubmissionsListFilters.php
@@ -0,0 +1,155 @@
+' . esc_html__( 'Filter by form', 'airo-wp' ) . '';
+ echo '';
+
+ printf(
+ ' ',
+ esc_html__( 'From date', 'airo-wp' ),
+ esc_attr( $current['from'] ),
+ esc_html__( 'To date', 'airo-wp' ),
+ esc_attr( $current['to'] )
+ );
+
+ wp_nonce_field( FormSubmissions_Export::NONCE_ACTION, FormSubmissions_Export::NONCE_NAME, false );
+ echo '';
+ }
+
+ /**
+ * "Contact (b4ae2351) — 4" when the form's page is known, else "b4ae2351 — 4".
+ *
+ * Form IDs alone are opaque, and two pages can hold forms with the same
+ * title, so the ID stays in the label.
+ *
+ * @param object $form Row from forms().
+ * @return string Option label.
+ */
+ private static function option_label( $form ): string {
+ if ( '' !== $form->page_title ) {
+ return sprintf(
+ /* translators: 1: page title, 2: form ID, 3: number of submissions. */
+ __( '%1$s (%2$s) — %3$d', 'airo-wp' ),
+ $form->page_title,
+ $form->form_id,
+ (int) $form->total
+ );
+ }
+ return sprintf(
+ /* translators: 1: form ID, 2: number of submissions. */
+ __( '%1$s — %2$d', 'airo-wp' ),
+ $form->form_id,
+ (int) $form->total
+ );
+ }
+
+ /**
+ * Title of the page a submission came from, or '' when it can't be found.
+ *
+ * @param int $submission_id Submission post ID.
+ * @return string Page title.
+ */
+ private static function source_page_title( int $submission_id ): string {
+ $referer = get_post_meta( $submission_id, '_dsg_submission_referer', true );
+ // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.url_to_postid_url_to_postid -- Not a VIP site; admin-only, once per form, cached with the list in forms().
+ $page_id = is_string( $referer ) && '' !== $referer ? url_to_postid( $referer ) : 0;
+ return $page_id ? wp_strip_all_tags( get_the_title( $page_id ) ) : '';
+ }
+
+ /**
+ * Form IDs with their submission counts and the title of the page the
+ * latest submission came from. Cached until any post or post meta changes
+ * (core bumps the `posts` last-changed stamp for both).
+ *
+ * @return object[] Rows with form_id, total and page_title.
+ */
+ private static function forms(): array {
+ global $wpdb;
+
+ // v2: rows gained latest_id and page_title. Rows an older release
+ // cached under the unversioned key lack them.
+ $key = 'airowp_submission_forms:v2:' . wp_cache_get_last_changed( 'posts' );
+ $forms = wp_cache_get( $key, 'airo-wp' );
+ if ( is_array( $forms ) ) {
+ return $forms;
+ }
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $forms = (array) $wpdb->get_results(
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $wpdb->prepare(
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ "SELECT pm.meta_value AS form_id, COUNT(*) AS total, MAX(p.ID) AS latest_id FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = %s AND p.post_type = %s GROUP BY pm.meta_value ORDER BY pm.meta_value",
+ '_dsg_form_id',
+ FormSubmissions_Export::POST_TYPE
+ )
+ );
+ foreach ( $forms as $form ) {
+ $form->page_title = self::source_page_title( (int) $form->latest_id );
+ }
+ wp_cache_set( $key, $forms, 'airo-wp' );
+
+ return $forms;
+ }
+
+ /**
+ * Apply the filters to the submissions list.
+ *
+ * @param \WP_Query $query Query.
+ */
+ public function filter_list( \WP_Query $query ): void {
+ if ( ! is_admin() || ! $query->is_main_query() || FormSubmissions_Export::POST_TYPE !== $query->get( 'post_type' ) ) {
+ return;
+ }
+ foreach ( FormSubmissions_Export::query_args( FormSubmissions_Export::request_args( $_GET ) ) as $key => $value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only list filter.
+ $query->set( $key, $value );
+ }
+ }
+}
diff --git a/includes/Blocks/Common/Forms/FormWebhookRecovery.php b/includes/Blocks/Common/Forms/FormWebhookRecovery.php
new file mode 100644
index 0000000..6a9905b
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormWebhookRecovery.php
@@ -0,0 +1,74 @@
+ 'dsgo_form_submission',
+ 'post_status' => 'any',
+ 'fields' => 'ids',
+ 'posts_per_page' => self::SWEEP_LIMIT,
+ 'orderby' => 'date',
+ 'order' => 'ASC',
+ 'no_found_rows' => true,
+ 'meta_key' => '_dsg_webhook_status', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Bounded daily sweep.
+ 'meta_value' => 'pending', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Bounded daily sweep.
+ 'date_query' => array(
+ array(
+ 'column' => 'post_date_gmt',
+ 'before' => gmdate( 'Y-m-d H:i:s', time() - self::IN_FLIGHT_SECONDS ), // UTC, matching the column.
+ ),
+ ),
+ )
+ );
+
+ update_meta_cache( 'post', $ids );
+ $scheduled = 0;
+ foreach ( $ids as $id ) {
+ $args = array( (int) $id );
+ if ( (int) get_post_meta( (int) $id, '_dsg_webhook_last_attempt', true ) > time() - self::IN_FLIGHT_SECONDS || false !== wp_next_scheduled( Form_Webhooks::RETRY_HOOK, $args ) ) {
+ continue;
+ }
+ if ( wp_schedule_single_event( time() + $scheduled * self::SWEEP_SPACING, Form_Webhooks::RETRY_HOOK, $args ) ) {
+ ++$scheduled;
+ }
+ }
+
+ return $scheduled;
+ }
+}
diff --git a/includes/Blocks/Common/Forms/FormWebhookRequest.php b/includes/Blocks/Common/Forms/FormWebhookRequest.php
new file mode 100644
index 0000000..bd72f5e
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormWebhookRequest.php
@@ -0,0 +1,274 @@
+, signed: bool}
+ */
+ public static function build( int $submission_id ): array {
+ $body = (string) wp_json_encode( self::build_payload( $submission_id ) );
+ $timestamp = time();
+ $secret = self::get_secret();
+ $headers = array(
+ 'Content-Type' => 'application/json',
+ 'User-Agent' => 'airo-wp/' . AIRO_WP_VERSION . '; ' . home_url( '/' ),
+ 'X-DSGo-Event' => 'form.submitted',
+ 'X-DSGo-Delivery' => (string) get_post_meta( $submission_id, '_dsg_webhook_delivery_id', true ),
+ 'X-DSGo-Timestamp' => (string) $timestamp,
+ );
+ if ( '' !== $secret ) {
+ $headers['X-DSGo-Signature'] = 'sha256=' . hash_hmac( 'sha256', $timestamp . '.' . $body, $secret );
+ }
+
+ return array(
+ 'body' => $body,
+ 'headers' => $headers,
+ 'signed' => '' !== $secret,
+ );
+ }
+
+ /**
+ * Build the JSON payload from the stored submission.
+ *
+ * @param int $submission_id Submission post ID.
+ * @return array Payload.
+ */
+ public static function build_payload( int $submission_id ): array {
+ $form_id = (string) get_post_meta( $submission_id, '_dsg_form_id', true );
+ $stored = get_post_meta( $submission_id, '_dsg_form_fields', true );
+ $fields = array();
+ $labels = array();
+
+ foreach ( is_array( $stored ) ? $stored : array() as $name => $data ) {
+ if ( ! is_array( $data ) ) {
+ continue;
+ }
+ $fields[ $name ] = isset( $data['value'] ) ? $data['value'] : '';
+ $labels[ $name ] = isset( $data['label'] ) && '' !== $data['label'] ? (string) $data['label'] : (string) $name;
+ }
+
+ $payload = array(
+ 'version' => self::VERSION,
+ 'event' => 'form.submitted',
+ 'form_id' => $form_id,
+ 'submission_id' => $submission_id,
+ 'submitted_at' => (string) get_post_time( 'c', true, $submission_id ),
+ 'source_url' => (string) get_post_meta( $submission_id, '_dsg_submission_referer', true ),
+ 'fields' => (object) $fields,
+ 'labels' => (object) $labels,
+ );
+
+ /**
+ * Filters the webhook payload before it is encoded and signed.
+ *
+ * Receivers rely on `version`, `event` and `submission_id`; keep them.
+ * A non-array return is ignored.
+ *
+ * @since 2.10.0
+ *
+ * @param array $payload Payload.
+ * @param int $submission_id Submission post ID.
+ * @param string $form_id Form ID.
+ */
+ $filtered = apply_filters( 'airowp_form_webhook_payload', $payload, $submission_id, $form_id );
+
+ return is_array( $filtered ) ? $filtered : $payload; // @phpstan-ignore ternary.elseUnreachable (a third-party filter can return anything)
+ }
+
+ /**
+ * Validate the stored URL and run it through the allowlist filter.
+ *
+ * @param string $url Stored URL.
+ * @param string $form_id Form ID.
+ * @param int $submission_id Submission post ID.
+ * @return string URL, or '' when not allowed.
+ */
+ public static function allowed_url( string $url, string $form_id, int $submission_id ): string {
+ if ( ! self::is_safe_url( $url ) ) {
+ return '';
+ }
+
+ /**
+ * Filters the receiver URL for one attempt; return '' to block it. The
+ * result is validated again, so it can't point at a private address.
+ *
+ * @since 2.10.0
+ *
+ * @param string $url Stored URL.
+ * @param string $form_id Form ID.
+ * @param int $submission_id Submission post ID.
+ */
+ $url = apply_filters( 'airowp_form_webhook_url', $url, $form_id, $submission_id );
+
+ return ( is_string( $url ) && self::is_safe_url( $url ) ) ? $url : '';
+ }
+
+ /**
+ * Whether core's URL check rejects link-local and CGNAT hosts itself.
+ *
+ * WordPress 7.1 added the check and backported it to 6.7.6, 6.8.7, 6.9.6
+ * and 7.0.3, so the version number can't tell. Core is asked directly, with
+ * `http_request_host_is_external` held closed so a site's own allowlist
+ * can't hide the answer. An IP literal needs no DNS lookup.
+ *
+ * @internal
+ *
+ * @return bool
+ */
+ public static function core_rejects_reserved_hosts(): bool {
+ $closed = static function () {
+ return false;
+ };
+ add_filter( 'http_request_host_is_external', $closed, PHP_INT_MAX );
+ $rejects = false === wp_http_validate_url( 'http://100.64.0.1/' );
+ remove_filter( 'http_request_host_is_external', $closed, PHP_INT_MAX );
+
+ return $rejects;
+ }
+
+ /**
+ * Core's URL check, plus the link-local (cloud metadata) and CGNAT ranges
+ * on WordPress versions whose check lets them through. Where core rejects
+ * them itself, `http_request_host_is_external` decides, and this adds
+ * nothing.
+ *
+ * @param string $url URL.
+ * @return bool
+ */
+ private static function is_safe_url( string $url ): bool {
+ if ( '' === $url || ! wp_http_validate_url( $url ) ) {
+ return false;
+ }
+
+ if ( self::core_rejects_reserved_hosts() ) {
+ return true;
+ }
+
+ $host = trim( (string) wp_parse_url( $url, PHP_URL_HOST ), '.' );
+ $home = (string) wp_parse_url( home_url(), PHP_URL_HOST );
+ if ( '' === $host || strtolower( $host ) === strtolower( $home ) ) {
+ return true;
+ }
+
+ $ip = filter_var( $host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ? $host : gethostbyname( $host );
+ if ( ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
+ return true; // Unresolvable; core already decided.
+ }
+
+ $parts = array_map( 'intval', explode( '.', $ip ) );
+ // 169.254.0.0/16 is link-local (cloud metadata); 100.64.0.0/10 is CGNAT.
+ $reserved = ( 169 === $parts[0] && 254 === $parts[1] )
+ || ( 100 === $parts[0] && 64 <= $parts[1] && 127 >= $parts[1] );
+ if ( ! $reserved ) {
+ return true;
+ }
+
+ /**
+ * Filters whether a webhook may be sent to a link-local or CGNAT host,
+ * on WordPress versions whose own URL check doesn't reject these ranges
+ * (before 6.7.6, 6.8.7, 6.9.6, 7.0.3 and 7.1). Elsewhere core rejects
+ * them itself, `http_request_host_is_external` decides, and this filter
+ * is not consulted.
+ *
+ * @since 2.11.0
+ *
+ * @param bool $allow Whether to allow the host. Default false.
+ * @param string $host Host name of the receiver URL.
+ * @param string $url Receiver URL.
+ */
+ return (bool) apply_filters( 'airowp_form_webhook_allow_reserved_host', false, $host, $url );
+ }
+
+ /**
+ * POST a built request. Redirects are not followed: a redirect target was
+ * never validated, so a 3xx is reported as the response.
+ *
+ * @param string $url Validated receiver URL.
+ * @param array $request Result of build().
+ * @return array{code: int, error: string} HTTP code (0 without a response) and error message ('' on 2xx).
+ */
+ public static function send( string $url, array $request ): array {
+ /**
+ * Filters the webhook request timeout in seconds, clamped to 1–30.
+ *
+ * @since 2.10.0
+ *
+ * @param int $timeout Timeout. Default 5.
+ */
+ $timeout = max( 1, min( 30, (int) apply_filters( 'airowp_form_webhook_timeout', 5 ) ) );
+
+ $response = wp_safe_remote_post(
+ $url,
+ array(
+ 'timeout' => $timeout,
+ 'redirection' => 0,
+ 'headers' => $request['headers'],
+ 'body' => $request['body'],
+ )
+ );
+
+ if ( is_wp_error( $response ) ) {
+ return array(
+ 'code' => 0,
+ 'error' => $response->get_error_message(),
+ );
+ }
+
+ $code = (int) wp_remote_retrieve_response_code( $response );
+
+ return array(
+ 'code' => $code,
+ /* translators: %d: HTTP status code */
+ 'error' => ( $code >= 200 && $code < 300 ) ? '' : sprintf( __( 'The receiver responded with HTTP %d.', 'airo-wp' ), $code ),
+ );
+ }
+
+ /**
+ * Whether another attempt could succeed. No response, 408, 425, 429 and
+ * 5xx are transient; a redirect or any other 4xx will repeat until the
+ * receiver or URL is fixed, so it fails at once (Resend retries it).
+ *
+ * @param int $code HTTP code, 0 when there was no response.
+ * @return bool
+ */
+ public static function is_retryable( int $code ): bool {
+ return 0 === $code || $code >= 500 || in_array( $code, array( 408, 425, 429 ), true );
+ }
+
+ /**
+ * The site-wide signing secret.
+ *
+ * @return string Secret, or '' when none is configured.
+ */
+ public static function get_secret(): string {
+ if ( ! class_exists( '\airo-wp\Admin\Settings' ) ) {
+ return '';
+ }
+ $settings = \airo - wp\Admin\Settings::get_settings();
+ $secret = isset( $settings['integrations']['form_webhook_secret'] ) ? $settings['integrations']['form_webhook_secret'] : '';
+
+ return is_string( $secret ) ? trim( $secret ) : '';
+ }
+}
diff --git a/includes/Blocks/Common/Forms/FormWebhookStatus.php b/includes/Blocks/Common/Forms/FormWebhookStatus.php
new file mode 100644
index 0000000..bd652b0
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormWebhookStatus.php
@@ -0,0 +1,68 @@
+ Form_Webhooks::RESEND_ACTION,
+ 'submission' => $submission_id,
+ ),
+ admin_url( 'admin-post.php' )
+ ),
+ Form_Webhooks::RESEND_ACTION . '_' . $submission_id
+ );
+ }
+}
diff --git a/includes/Blocks/Common/Forms/FormWebhooks.php b/includes/Blocks/Common/Forms/FormWebhooks.php
new file mode 100644
index 0000000..b67bd9c
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormWebhooks.php
@@ -0,0 +1,298 @@
+queue[] = $submission_id;
+ if ( ! has_action( 'shutdown', array( $this, 'deliver_queued' ) ) ) {
+ add_action( 'shutdown', array( $this, 'deliver_queued' ), PHP_INT_MAX );
+ }
+ }
+
+ /**
+ * Make the first attempt for queued submissions, after the response is sent.
+ * Deferred to `shutdown` so a slow receiver never delays the visitor. The
+ * status stays `pending` until then; if PHP dies first, Form_Webhook_Recovery
+ * recovers it. Only PHP-FPM and LiteSpeed can flush the response early;
+ * elsewhere the attempt is handed to WP-Cron instead. After the flush,
+ * output from later shutdown callbacks no longer reaches the visitor.
+ */
+ public function deliver_queued(): void {
+ if ( empty( $this->queue ) ) {
+ return;
+ }
+
+ $queued = $this->queue;
+ $this->queue = array(); // Cleared first so a re-entrant call can't double-send.
+
+ /**
+ * Filters whether the first attempt is sent at shutdown, after the
+ * response is flushed. When false it is handed to WP-Cron.
+ *
+ * @since 2.10.0
+ *
+ * @param bool $after_response Default: whether the server can flush early.
+ */
+ if ( ! apply_filters( 'airowp_form_webhook_send_after_response', function_exists( 'fastcgi_finish_request' ) || function_exists( 'litespeed_finish_request' ) ) ) {
+ $this->hand_off_to_cron( $queued );
+ return;
+ }
+
+ ignore_user_abort( true );
+ if ( function_exists( 'fastcgi_finish_request' ) ) {
+ fastcgi_finish_request();
+ } elseif ( function_exists( 'litespeed_finish_request' ) ) {
+ litespeed_finish_request();
+ }
+
+ foreach ( $queued as $submission_id ) {
+ $this->deliver( $submission_id );
+ }
+ }
+
+ /**
+ * Schedule first attempts on WP-Cron so the visitor never waits on the receiver.
+ *
+ * @param int[] $queued Submission IDs.
+ */
+ private function hand_off_to_cron( array $queued ): void {
+ $spawn = false;
+ foreach ( $queued as $submission_id ) {
+ if ( true === wp_schedule_single_event( time(), self::RETRY_HOOK, array( $submission_id ), true ) ) {
+ $spawn = true;
+ continue;
+ }
+ $this->deliver( $submission_id ); // The scheduler refused: send now rather than lose it.
+ }
+
+ // spawn_cron() redirects under ALTERNATE_WP_CRON, which can't work after output.
+ $alternate = defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON;
+ $disabled = defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON;
+ if ( $spawn && ! $alternate && ! $disabled && ! wp_doing_cron() ) {
+ spawn_cron();
+ }
+ }
+
+ /** Daily cron entry point; action callbacks must not return a value. */
+ public function run_stranded_sweep(): void {
+ Form_Webhook_Recovery::reschedule_stranded();
+ }
+
+ /**
+ * WP-Cron retry handler.
+ *
+ * @param int $submission_id Submission post ID.
+ */
+ public function retry( $submission_id ) {
+ $submission_id = absint( $submission_id );
+
+ if ( ! self::is_submission( $submission_id ) || 'pending' !== Form_Webhook_Status::get_status( $submission_id ) || 'trash' === get_post_status( $submission_id ) ) {
+ return;
+ }
+
+ $this->deliver( $submission_id );
+ }
+
+ /**
+ * Manually resend: reset attempts and deliver now. Gets a new delivery ID,
+ * so a receiver that de-duplicates on X-DSGo-Delivery accepts it.
+ *
+ * @param int $submission_id Submission post ID.
+ * @return string 'delivered', 'pending', 'failed', or 'invalid' when there is nothing to resend.
+ */
+ public function resend( int $submission_id ): string {
+ if ( ! self::is_submission( $submission_id ) || '' === (string) get_post_meta( $submission_id, '_dsg_webhook_url', true ) ) {
+ return 'invalid';
+ }
+
+ wp_clear_scheduled_hook( self::RETRY_HOOK, array( $submission_id ) );
+ update_post_meta( $submission_id, '_dsg_webhook_delivery_id', wp_generate_uuid4() );
+ update_post_meta( $submission_id, '_dsg_webhook_attempts', 0 );
+ update_post_meta( $submission_id, '_dsg_webhook_status', 'pending' );
+
+ return $this->deliver( $submission_id );
+ }
+
+ /**
+ * Make one delivery attempt and record the outcome.
+ *
+ * @param int $submission_id Submission post ID.
+ * @return string 'delivered', 'pending' (retry scheduled) or 'failed'.
+ */
+ public function deliver( int $submission_id ): string {
+ $form_id = (string) get_post_meta( $submission_id, '_dsg_form_id', true );
+ $url = Form_Webhook_Request::allowed_url( (string) get_post_meta( $submission_id, '_dsg_webhook_url', true ), $form_id, $submission_id );
+
+ if ( '' === $url ) {
+ return $this->record_failure( $submission_id, $form_id, 0, __( 'The webhook URL is not a valid public http(s) address, or it was blocked by a filter.', 'airo-wp' ), false );
+ }
+
+ $request = Form_Webhook_Request::build( $submission_id );
+
+ update_post_meta( $submission_id, '_dsg_webhook_attempts', (int) get_post_meta( $submission_id, '_dsg_webhook_attempts', true ) + 1 );
+ update_post_meta( $submission_id, '_dsg_webhook_last_attempt', time() );
+ update_post_meta( $submission_id, '_dsg_webhook_signed', $request['signed'] ? 'yes' : 'no' );
+
+ $result = Form_Webhook_Request::send( $url, $request );
+ $code = $result['code'];
+ update_post_meta( $submission_id, '_dsg_webhook_last_code', $code );
+
+ if ( $code >= 200 && $code < 300 ) {
+ update_post_meta( $submission_id, '_dsg_webhook_status', 'delivered' );
+ update_post_meta( $submission_id, '_dsg_webhook_delivered_date', current_time( 'mysql' ) );
+ delete_post_meta( $submission_id, '_dsg_webhook_last_error' );
+ /**
+ * Fires after a webhook delivery succeeds.
+ *
+ * @since 2.10.0
+ *
+ * @param int $submission_id Submission post ID.
+ * @param string $form_id Form ID.
+ * @param int $code HTTP status code.
+ */
+ do_action( 'airowp_form_webhook_delivered', $submission_id, $form_id, $code );
+ return 'delivered';
+ }
+
+ return $this->record_failure( $submission_id, $form_id, $code, $result['error'], Form_Webhook_Request::is_retryable( $code ) );
+ }
+
+ /**
+ * Record a failed attempt; schedule a retry when attempts remain.
+ *
+ * @param int $submission_id Submission post ID.
+ * @param string $form_id Form ID.
+ * @param int $code HTTP code (0 when there was no response).
+ * @param string $error Error message.
+ * @param bool $retryable Whether another attempt could succeed.
+ * @return string 'pending' or 'failed'.
+ */
+ private function record_failure( int $submission_id, string $form_id, int $code, string $error, bool $retryable ): string {
+ update_post_meta( $submission_id, '_dsg_webhook_last_error', wp_slash( mb_substr( $error, 0, 500 ) ) );
+
+ $delays = $this->retry_delays();
+ $attempts = (int) get_post_meta( $submission_id, '_dsg_webhook_attempts', true );
+
+ if ( $retryable && $attempts >= 1 && $attempts <= count( $delays ) ) {
+ $scheduled = wp_schedule_single_event( time() + $delays[ $attempts - 1 ], self::RETRY_HOOK, array( $submission_id ), true );
+ if ( true === $scheduled ) {
+ update_post_meta( $submission_id, '_dsg_webhook_status', 'pending' );
+ return 'pending';
+ }
+
+ $reason = $scheduled->get_error_message();
+ /* translators: %s: reason the scheduler gave, may be empty */
+ $error = trim( sprintf( __( 'Could not schedule a retry. %s', 'airo-wp' ), $reason ) );
+ update_post_meta( $submission_id, '_dsg_webhook_last_error', wp_slash( mb_substr( $error, 0, 500 ) ) );
+ }
+
+ update_post_meta( $submission_id, '_dsg_webhook_status', 'failed' );
+ /**
+ * Fires when a webhook delivery gives up: retries are exhausted, the
+ * error is permanent, or the URL is not allowed.
+ *
+ * @since 2.10.0
+ *
+ * @param int $submission_id Submission post ID.
+ * @param string $form_id Form ID.
+ * @param string $error Last error message.
+ * @param int $code Last HTTP code, 0 without a response.
+ */
+ do_action( 'airowp_form_webhook_failed', $submission_id, $form_id, $error, $code );
+ return 'failed';
+ }
+
+ /**
+ * Seconds before each retry; 0 retries on the next cron run. The count sets how many retries happen.
+ *
+ * @return int[] Delays.
+ */
+ private function retry_delays(): array {
+ /**
+ * Filters the seconds before each retry. The count is the number of
+ * retries; an empty array disables them.
+ *
+ * @since 2.10.0
+ *
+ * @param int[] $delays Delays. Default 60, 300, 1800, 7200.
+ */
+ $delays = apply_filters( 'airowp_form_webhook_retry_delays', self::DEFAULT_RETRY_DELAYS );
+
+ return array_values( array_map( 'absint', (array) $delays ) );
+ }
+
+ /**
+ * Whether an ID is a stored form submission.
+ *
+ * @param int $submission_id Post ID.
+ * @return bool
+ */
+ private static function is_submission( int $submission_id ): bool {
+ return $submission_id > 0 && 'dsgo_form_submission' === get_post_type( $submission_id );
+ }
+}
diff --git a/includes/Blocks/Common/Forms/FormWebhooksAdmin.php b/includes/Blocks/Common/Forms/FormWebhooksAdmin.php
new file mode 100644
index 0000000..ec8db82
--- /dev/null
+++ b/includes/Blocks/Common/Forms/FormWebhooksAdmin.php
@@ -0,0 +1,228 @@
+webhooks = $webhooks;
+
+ add_filter( 'manage_dsgo_form_submission_posts_columns', array( $this, 'add_column' ), 20 );
+ add_action( 'manage_dsgo_form_submission_posts_custom_column', array( $this, 'render_column' ), 10, 2 );
+ add_filter( 'post_row_actions', array( $this, 'row_actions' ), 10, 2 );
+ add_action( 'add_meta_boxes_dsgo_form_submission', array( $this, 'maybe_add_meta_box' ) );
+ add_action( 'admin_post_' . Form_Webhooks::RESEND_ACTION, array( $this, 'handle_resend' ) );
+ add_action( 'admin_notices', array( $this, 'resend_notice' ) );
+ add_filter( 'removable_query_args', array( $this, 'removable_query_args' ) );
+ }
+
+ /**
+ * Insert the Webhook column before Date.
+ *
+ * @param array $columns Columns.
+ * @return array Columns.
+ */
+ public function add_column( $columns ) {
+ $out = array();
+ foreach ( $columns as $key => $label ) {
+ if ( 'date' === $key ) {
+ $out['airowp_webhook'] = __( 'Webhook', 'airo-wp' );
+ }
+ $out[ $key ] = $label;
+ }
+ if ( ! isset( $out['airowp_webhook'] ) ) {
+ $out['airowp_webhook'] = __( 'Webhook', 'airo-wp' );
+ }
+ return $out;
+ }
+
+ /**
+ * Render the Webhook column.
+ *
+ * @param string $column Column key.
+ * @param int $post_id Submission ID.
+ */
+ public function render_column( $column, $post_id ) {
+ if ( 'airowp_webhook' !== $column ) {
+ return;
+ }
+ $label = Form_Webhook_Status::label( (int) $post_id );
+ if ( '' === $label ) {
+ echo '—' . esc_html__( 'No webhook', 'airo-wp' ) . '';
+ return;
+ }
+ // All at least 4.5:1 on the white and striped list-table rows.
+ $colors = array(
+ 'delivered' => '#007017',
+ 'failed' => '#d63638',
+ 'pending' => '#996800',
+ );
+ $status = Form_Webhook_Status::get_status( (int) $post_id );
+ $color = isset( $colors[ $status ] ) ? $colors[ $status ] : 'inherit';
+ echo '' . esc_html( $label ) . '';
+ }
+
+ /**
+ * Add a Resend webhook row action.
+ *
+ * @param array $actions Row actions.
+ * @param \WP_Post $post Post.
+ * @return array Row actions.
+ */
+ public function row_actions( $actions, $post ) {
+ if ( ! $post instanceof \WP_Post || 'dsgo_form_submission' !== $post->post_type || ! $this->has_webhook( $post->ID ) ) {
+ return $actions;
+ }
+ $actions['airowp_resend_webhook'] = sprintf(
+ '%3$s',
+ esc_url( Form_Webhook_Status::resend_url( $post->ID ) ),
+ /* translators: %d: submission ID */
+ esc_attr( sprintf( __( 'Resend webhook for submission %d', 'airo-wp' ), $post->ID ) ),
+ esc_html__( 'Resend webhook', 'airo-wp' )
+ );
+ return $actions;
+ }
+
+ /**
+ * Register the delivery meta box for submissions that have a webhook.
+ *
+ * @param \WP_Post $post Submission.
+ */
+ public function maybe_add_meta_box( $post ) {
+ if ( ! $this->has_webhook( $post->ID ) ) {
+ return;
+ }
+ add_meta_box( 'airowp_webhook_delivery', __( 'Webhook delivery', 'airo-wp' ), array( $this, 'render_meta_box' ), 'dsgo_form_submission', 'side', 'default' );
+ }
+
+ /**
+ * Render delivery details. Shows only the receiver's host: some webhook URLs are credentials.
+ *
+ * @param \WP_Post $post Submission.
+ */
+ public function render_meta_box( $post ) {
+ $id = (int) $post->ID;
+ $host = (string) wp_parse_url( (string) get_post_meta( $id, '_dsg_webhook_url', true ), PHP_URL_HOST );
+ $code = (int) get_post_meta( $id, '_dsg_webhook_last_code', true );
+ $error = (string) get_post_meta( $id, '_dsg_webhook_last_error', true );
+ $date = (string) get_post_meta( $id, '_dsg_webhook_delivered_date', true );
+ $rows = array(
+ __( 'Status', 'airo-wp' ) => Form_Webhook_Status::label( $id ),
+ __( 'Receiver', 'airo-wp' ) => $host,
+ __( 'Attempts', 'airo-wp' ) => (string) (int) get_post_meta( $id, '_dsg_webhook_attempts', true ),
+ );
+ $signed = (string) get_post_meta( $id, '_dsg_webhook_signed', true );
+ if ( '' !== $signed ) {
+ $rows[ __( 'Signature', 'airo-wp' ) ] = 'yes' === $signed
+ ? __( 'Signed', 'airo-wp' )
+ : __( 'Unsigned — no webhook secret configured', 'airo-wp' );
+ }
+ if ( $code ) {
+ /* translators: %d: HTTP status code */
+ $rows[ __( 'Last response', 'airo-wp' ) ] = sprintf( __( 'HTTP %d', 'airo-wp' ), $code );
+ }
+ if ( '' !== $error ) {
+ $rows[ __( 'Last error', 'airo-wp' ) ] = $error;
+ }
+ if ( '' !== $date ) {
+ $rows[ __( 'Delivered', 'airo-wp' ) ] = mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $date );
+ }
+
+ echo '';
+ foreach ( $rows as $label => $value ) {
+ echo '| ' . esc_html( $label ) . ' | ' . esc_html( $value ) . ' |
';
+ }
+ echo '
';
+ echo '' . esc_html__( 'Resend webhook', 'airo-wp' ) . '
';
+ }
+
+ /**
+ * Handle the admin-post Resend request.
+ */
+ public function handle_resend() {
+ $submission_id = isset( $_GET['submission'] ) ? absint( wp_unslash( $_GET['submission'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Verified on the next line.
+ check_admin_referer( Form_Webhooks::RESEND_ACTION . '_' . $submission_id );
+
+ if ( ! current_user_can( 'manage_options' ) ) {
+ wp_die( esc_html__( 'Sorry, you are not allowed to resend webhooks.', 'airo-wp' ), '', array( 'response' => 403 ) );
+ }
+
+ $result = $this->webhooks->resend( $submission_id );
+ $fallback = admin_url( 'edit.php?post_type=dsgo_form_submission' );
+ $referer = wp_get_referer();
+
+ wp_safe_redirect( add_query_arg( 'airowp_webhook_resent', $result, $referer ? $referer : $fallback ) );
+ exit;
+ }
+
+ /**
+ * Let WordPress strip the resend flag from the URL so the notice does not persist.
+ *
+ * @param string[] $args Removable query args.
+ * @return string[] Args.
+ */
+ public function removable_query_args( $args ) {
+ $args = (array) $args;
+ $args[] = 'airowp_webhook_resent';
+ return $args;
+ }
+
+ /**
+ * Notice after a resend.
+ */
+ public function resend_notice() {
+ // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only flag set by our own redirect.
+ $result = isset( $_GET['airowp_webhook_resent'] ) ? sanitize_key( wp_unslash( $_GET['airowp_webhook_resent'] ) ) : '';
+ $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
+ if ( '' === $result || ! $screen || 'dsgo_form_submission' !== $screen->post_type ) {
+ return;
+ }
+
+ // Type, ARIA role (a full page load is otherwise not announced), message.
+ $messages = array(
+ 'delivered' => array( 'success', 'status', __( 'Webhook delivered.', 'airo-wp' ) ),
+ 'pending' => array( 'warning', 'status', __( 'Webhook delivery failed; it will be retried automatically.', 'airo-wp' ) ),
+ 'failed' => array( 'error', 'alert', __( 'Webhook delivery failed. See the submission for details.', 'airo-wp' ) ),
+ 'invalid' => array( 'error', 'alert', __( 'This submission has no webhook to resend.', 'airo-wp' ) ),
+ );
+ if ( ! isset( $messages[ $result ] ) ) {
+ return;
+ }
+ list( $type, $role, $message ) = $messages[ $result ];
+ printf( '', esc_attr( $type ), esc_attr( $role ), esc_html( $message ) );
+ }
+
+ /**
+ * Whether a submission has a webhook URL recorded.
+ *
+ * @param int $post_id Submission ID.
+ * @return bool
+ */
+ private function has_webhook( $post_id ) {
+ return '' !== (string) get_post_meta( (int) $post_id, '_dsg_webhook_url', true );
+ }
+}
diff --git a/includes/Blocks/Common/Query/Controller.php b/includes/Blocks/Common/Query/Controller.php
index 8f9aa04..c6f4c1d 100644
--- a/includes/Blocks/Common/Query/Controller.php
+++ b/includes/Blocks/Common/Query/Controller.php
@@ -67,6 +67,19 @@ public function register_routes() {
'default' => '',
'sanitize_callback' => 'esc_url_raw',
),
+ // Whether the page holds other Queries, so the rendered
+ // controls and pagination use per-Query URL keys.
+ 'multiQuery' => array(
+ 'type' => 'boolean',
+ 'default' => false,
+ ),
+ // A random-order Query's first-paint seed, so later pages
+ // continue the same shuffle.
+ 'seed' => array(
+ 'type' => 'integer',
+ 'default' => 0,
+ 'sanitize_callback' => 'absint',
+ ),
),
)
);
@@ -259,11 +272,13 @@ public function handle_preview( \WP_REST_Request $request ) {
if ( 'users' === $source ) {
$user_query = new \WP_User_Query(
- array(
- 'number' => $per_page,
- 'orderby' => 'registered',
- 'order' => 'DESC',
- 'fields' => array( 'ID', 'display_name' ),
+ self::restrict_preview_users(
+ array(
+ 'number' => $per_page,
+ 'orderby' => 'registered',
+ 'order' => 'DESC',
+ 'fields' => array( 'ID', 'display_name' ),
+ )
)
);
$items = array();
@@ -281,7 +296,14 @@ public function handle_preview( \WP_REST_Request $request ) {
$taxonomy = isset( $attributes['taxonomy'] )
? sanitize_key( $attributes['taxonomy'] )
: 'category';
- $terms = get_terms(
+ if ( ! self::can_preview_taxonomy( $taxonomy ) ) {
+ return new \WP_Error(
+ 'rest_forbidden',
+ __( 'You cannot preview this taxonomy.', 'airo-wp' ),
+ array( 'status' => 403 )
+ );
+ }
+ $terms = get_terms(
array(
'taxonomy' => $taxonomy,
'number' => $per_page,
@@ -308,6 +330,23 @@ public function handle_preview( \WP_REST_Request $request ) {
return rest_ensure_response( array() );
}
+ /**
+ * Whether the current user may see a taxonomy's terms in an editor preview.
+ *
+ * Only taxonomies meant to be seen (public or with an admin UI) that the user
+ * can assign terms from. Internal taxonomies stay hidden from contributors.
+ *
+ * @param string $taxonomy Taxonomy slug.
+ * @return bool
+ */
+ public static function can_preview_taxonomy( string $taxonomy ): bool {
+ $object = get_taxonomy( $taxonomy );
+ if ( ! $object ) {
+ return false;
+ }
+ return ( ! empty( $object->public ) || ! empty( $object->show_ui ) ) && current_user_can( $object->cap->assign_terms );
+ }
+
/**
* Returns the current filter index status.
*
@@ -522,7 +561,8 @@ public function handle_render( \WP_REST_Request $request ) {
$source['queryId'],
$source['innerBlocks'],
$request,
- $source['sourcePostId']
+ $source['sourcePostId'],
+ isset( $source['pageContext'] ) && is_array( $source['pageContext'] ) ? $source['pageContext'] : array()
);
}
@@ -540,6 +580,21 @@ public function handle_preview_render( \WP_REST_Request $request ) {
$query_id = (string) $request->get_param( 'queryId' );
$source = sanitize_key( (string) ( $attributes['source'] ?? 'posts' ) );
+ // The terms renderer reads its taxonomies from taxQuery clauses
+ // (defaulting to category), so those are what must be previewable.
+ if ( 'terms' === $source ) {
+ $taxonomies = self::clause_taxonomies( (array) ( $attributes['taxQuery']['clauses'] ?? array() ) );
+ foreach ( $taxonomies ? $taxonomies : array( 'category' ) as $taxonomy ) {
+ if ( taxonomy_exists( $taxonomy ) && ! self::can_preview_taxonomy( $taxonomy ) ) {
+ return new \WP_Error(
+ 'rest_forbidden',
+ __( 'You cannot preview this taxonomy.', 'airo-wp' ),
+ array( 'status' => 403 )
+ );
+ }
+ }
+ }
+
// Anyone who can edit posts can preview, so a query is limited to post
// types they could already see or edit — never coupons, orders, etc.
// Every source but users and terms can reach the posts renderer:
@@ -558,9 +613,17 @@ public function handle_preview_render( \WP_REST_Request $request ) {
// each path to them, after the query-scoped filter too: its name comes
// from the caller's queryId.
$restrict = array( __CLASS__, 'restrict_preview_post_types' );
+ $users = array( __CLASS__, 'restrict_preview_users' );
+ $terms = array( __CLASS__, 'restrict_preview_terms' );
$hooks = array( 'airowp_query_args', 'airowp_query_' . $query_id . '_args' );
foreach ( $hooks as $hook ) {
add_filter( $hook, $restrict, PHP_INT_MAX );
+ if ( 'users' === $source ) {
+ add_filter( $hook, $users, PHP_INT_MAX );
+ }
+ if ( 'terms' === $source ) {
+ add_filter( $hook, $terms, PHP_INT_MAX );
+ }
}
try {
@@ -574,8 +637,71 @@ public function handle_preview_render( \WP_REST_Request $request ) {
} finally {
foreach ( $hooks as $hook ) {
remove_filter( $hook, $restrict, PHP_INT_MAX );
+ remove_filter( $hook, $users, PHP_INT_MAX );
+ remove_filter( $hook, $terms, PHP_INT_MAX );
+ }
+ }
+ }
+
+ /**
+ * Taxonomies named by taxQuery clauses, including those in nested groups.
+ *
+ * @param array $clauses taxQuery clauses.
+ * @return string[] Taxonomy slugs.
+ */
+ private static function clause_taxonomies( array $clauses ): array {
+ $taxonomies = array();
+ foreach ( $clauses as $clause ) {
+ if ( ! is_array( $clause ) ) {
+ continue;
+ }
+ if ( isset( $clause['clauses'] ) && is_array( $clause['clauses'] ) ) {
+ $taxonomies = array_merge( $taxonomies, self::clause_taxonomies( $clause['clauses'] ) );
+ } elseif ( ! empty( $clause['taxonomy'] ) ) {
+ $taxonomies[] = sanitize_key( (string) $clause['taxonomy'] );
}
}
+ return array_values( array_unique( array_filter( $taxonomies ) ) );
+ }
+
+ /**
+ * Narrow an editor preview's term query to taxonomies the user may preview.
+ *
+ * A backstop for the request check: it applies to the final get_terms()
+ * args, however a renderer or filter chose the taxonomies.
+ *
+ * @param mixed $args get_terms() args (other sources carry no taxonomy).
+ * @return mixed Args limited to previewable taxonomies.
+ */
+ public static function restrict_preview_terms( $args ) {
+ if ( ! is_array( $args ) || ! isset( $args['taxonomy'] ) ) {
+ return $args;
+ }
+ $allowed = array_values( array_filter( (array) $args['taxonomy'], array( __CLASS__, 'can_preview_taxonomy' ) ) );
+ if ( empty( $allowed ) ) {
+ // An empty taxonomy list means "every taxonomy" to get_terms().
+ $args['include'] = array( 0 );
+ return $args;
+ }
+ $args['taxonomy'] = $allowed;
+ return $args;
+ }
+
+ /**
+ * Narrow an editor preview's user query for someone who can't list users.
+ *
+ * They see only people with published posts, who are public already through
+ * their author archives, rather than every account on the site.
+ *
+ * @param mixed $args WP_User_Query args.
+ * @return mixed Args, limited to authors when the user can't list users.
+ */
+ public static function restrict_preview_users( $args ) {
+ if ( ! is_array( $args ) || current_user_can( 'list_users' ) ) {
+ return $args;
+ }
+ $args['has_published_posts'] = true;
+ return $args;
}
/**
@@ -633,9 +759,13 @@ private static function can_preview_post_type( $post_type ) {
* @param int|null $source_post_id Post holding the query (0 outside
* post content), or null to emit
* no refresh source.
- * @return \WP_REST_Response
+ * @param array|null $page_context Page facts recorded in the signed
+ * definition at first paint (current
+ * post, inherited archive vars), or
+ * null for an editor preview.
+ * @return \WP_REST_Response|\WP_Error
*/
- private function render_request( array $attributes, $query_id, $inner_html, \WP_REST_Request $request, $source_post_id ) {
+ private function render_request( array $attributes, $query_id, $inner_html, \WP_REST_Request $request, $source_post_id, $page_context = null ) {
$page = max( 1, (int) $request->get_param( 'page' ) );
$params = (array) $request->get_param( 'params' );
$current_url = (string) $request->get_param( 'currentUrl' );
@@ -652,10 +782,27 @@ private function render_request( array $attributes, $query_id, $inner_html, \WP_
// (eats `+`, collapses whitespace) and this value is only ever restored
// to the superglobal, never echoed or used in HTML.
$original_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- restore-only, see comment above.
- $allowed_keys = apply_filters( 'airowp_query_url_params', array( 'q', 'sort' ) );
+ $scoping = AIRO_WP_PLUGIN_DIR . 'build/blocks/query/param-scoping.php';
+ if ( ! file_exists( $scoping ) ) {
+ return new \WP_Error( 'airowp_query_unavailable', __( 'Query rendering is unavailable.', 'airo-wp' ), array( 'status' => 500 ) );
+ }
+ require_once $scoping; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- build artifact; path resolved from plugin directory
+
+ // Same list first paint reads: WooCommerce's filter blocks write
+ // min_price / max_price / rating_filter and query_type_ (which
+ // pairs with filter_). They are bare keys, never query-scoped.
+ $allowed_keys = apply_filters( 'airowp_query_url_params', array( 'q', 'sort', 'min_price', 'max_price', 'rating_filter' ) );
+ $own_id = sanitize_key( (string) $query_id );
foreach ( $params as $key => $value ) {
$key = (string) $key;
- if ( in_array( $key, $allowed_keys, true ) || 0 === strpos( $key, 'filter_' ) ) {
+ // Per-Query keys (`q__{queryId}`) resolve by their bare name, the
+ // same way airowp_query_owned_request_params() reads them back.
+ // Other Queries' filter_* keys pass through so this render's
+ // controls and chips see the whole URL, as on first paint.
+ list( $bare, $scope ) = airowp_query_split_param_key( sanitize_key( $key ), $own_id );
+ $is_wildcard = 0 === strpos( $bare, 'filter_' ) || 0 === strpos( $bare, 'query_type_' );
+ $allowed = in_array( $bare, $allowed_keys, true ) || $is_wildcard;
+ if ( $allowed && ( '' === $scope || $scope === $own_id || $is_wildcard ) ) {
// REST-supplied values are sanitized downstream before use in
// WP_Query / SQL / HTML, but nested block renders may pass
// through filter hooks or third-party code that reads $_GET
@@ -667,6 +814,14 @@ private function render_request( array $attributes, $query_id, $inner_html, \WP_
}
}
}
+ // The browser can see the whole page; this render sees one Query.
+ $original_multi = $GLOBALS['airowp_query_force_multi'] ?? null;
+ $GLOBALS['airowp_query_force_multi'] = (bool) $request->get_param( 'multiQuery' );
+ // This request has no page of its own: replay the facts first paint saw.
+ $original_page_context = $GLOBALS['airowp_query_request_context'] ?? null;
+ if ( is_array( $page_context ) ) {
+ $GLOBALS['airowp_query_request_context'] = $page_context;
+ }
if ( '' !== $current_url ) {
$parsed = wp_parse_url( $current_url );
if ( is_array( $parsed ) && isset( $parsed['path'] ) ) {
@@ -681,6 +836,7 @@ private function render_request( array $attributes, $query_id, $inner_html, \WP_
'inner_html' => $inner_html,
'params' => $params,
'refresh_source_post_id' => $source_post_id,
+ 'rand_seed' => absint( $request->get_param( 'seed' ) ),
);
try {
@@ -697,6 +853,16 @@ static function () use ( $attributes, $context ) {
} finally {
$_GET = $original_get; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$_SERVER['REQUEST_URI'] = $original_uri;
+ if ( null === $original_multi ) {
+ unset( $GLOBALS['airowp_query_force_multi'] );
+ } else {
+ $GLOBALS['airowp_query_force_multi'] = $original_multi;
+ }
+ if ( null === $original_page_context ) {
+ unset( $GLOBALS['airowp_query_request_context'] );
+ } else {
+ $GLOBALS['airowp_query_request_context'] = $original_page_context;
+ }
}
return rest_ensure_response( $result );
diff --git a/includes/Blocks/Common/Query/FilterIndex.php b/includes/Blocks/Common/Query/FilterIndex.php
index 431ea39..b7e3e40 100644
--- a/includes/Blocks/Common/Query/FilterIndex.php
+++ b/includes/Blocks/Common/Query/FilterIndex.php
@@ -261,6 +261,43 @@ private static function resolve_filter_values( string $object_type, int $object_
return array();
}
+ /**
+ * Deletes index rows that point at a deleted term.
+ *
+ * Core's wp_delete_term() detaches posts without firing set_object_terms, so
+ * the per-post hooks never see it and the rows would keep counting a term
+ * that no longer exists.
+ *
+ * @param int $term_id Deleted term ID.
+ * @param string $taxonomy Taxonomy the term belonged to.
+ * @return void
+ */
+ public static function remove_term_values( int $term_id, string $taxonomy ): void {
+ if ( ! self::table_exists() ) {
+ return;
+ }
+ global $wpdb;
+ $removed = false;
+ foreach ( FilterRegistry::all() as $filter_key => $config ) {
+ if ( 'taxonomy' !== ( $config['type'] ?? '' ) || ( $config['source'] ?? '' ) !== $taxonomy ) {
+ continue;
+ }
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $wpdb->delete(
+ self::table_name(),
+ array(
+ 'filter_key' => (string) $filter_key,
+ 'filter_value' => (string) $term_id,
+ ),
+ array( '%s', '%s' )
+ );
+ $removed = true;
+ }
+ if ( $removed ) {
+ self::bump_counts_cache();
+ }
+ }
+
/**
* Deletes all index rows for a given object.
*
@@ -327,11 +364,21 @@ public static function count_for_options( string $filter_key, array $option_valu
// Exclude self-filter from intersection — OR semantics within a group.
unset( $active_filters[ $key ] );
+ // The index stores each post's directly-assigned terms, but the query a
+ // filter drives matches a term's descendants too (include_children).
+ // Count and intersect the same way, or a parent term reads lower than
+ // the results it returns. Resolved at read time so existing indexes
+ // stay correct without a rebuild.
+ $families = self::option_families( $key, $string_values );
+ foreach ( $active_filters as $f_key => $f_values ) {
+ $active_filters[ $f_key ] = self::expand_with_descendants( (string) $f_key, array_map( 'strval', (array) $f_values ) );
+ }
+
// Cache lookup. Key is (epoch, filter_key, option_values, active_filters, post_type).
// The epoch is bumped on every index write, so cached entries remain valid
// until the next reindex/remove/rebuild. Skipped in tests where the
// per-request table_exists cache can race with the drop-table teardown.
- $cache_key = self::build_counts_cache_key( $key, $string_values, $active_filters, $post_type );
+ $cache_key = self::build_counts_cache_key( $key, $string_values, $active_filters, $post_type, $families );
$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
if ( is_array( $cached ) ) {
return $cached;
@@ -375,31 +422,115 @@ public static function count_for_options( string $filter_key, array $option_valu
}
}
- $value_placeholders = implode( ',', array_fill( 0, count( $string_values ), '%s' ) );
- $sql = "SELECT filter_value, COUNT(DISTINCT object_id) AS cnt
+ // Options with no descendants share one grouped query; an option whose
+ // family spans several terms needs its own DISTINCT count so a post in
+ // two child terms still counts once.
+ $simple = array();
+ $nested = array();
+ foreach ( $string_values as $value ) {
+ if ( count( $families[ $value ] ) > 1 ) {
+ $nested[ $value ] = $families[ $value ];
+ } else {
+ $simple[] = $value;
+ }
+ }
+
+ if ( ! empty( $simple ) ) {
+ $value_placeholders = implode( ',', array_fill( 0, count( $simple ), '%s' ) );
+ $sql = "SELECT filter_value, COUNT(DISTINCT object_id) AS cnt
FROM {$table}
WHERE filter_key = %s AND filter_value IN ({$value_placeholders}){$post_type_sql}
{$intersect_sql}
GROUP BY filter_value";
- $params = array_merge( array( $key ), $string_values, $post_type_params, $intersect_params );
+ $params = array_merge( array( $key ), $simple, $post_type_params, $intersect_params );
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
- $rows = $wpdb->get_results( $wpdb->prepare( $sql, $params ) );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $rows = $wpdb->get_results( $wpdb->prepare( $sql, $params ) );
- if ( is_array( $rows ) ) {
- foreach ( $rows as $row ) {
- if ( array_key_exists( $row->filter_value, $counts ) ) {
- $counts[ $row->filter_value ] = (int) $row->cnt;
+ if ( is_array( $rows ) ) {
+ foreach ( $rows as $row ) {
+ if ( array_key_exists( $row->filter_value, $counts ) ) {
+ $counts[ $row->filter_value ] = (int) $row->cnt;
+ }
}
}
}
+ foreach ( $nested as $value => $family ) {
+ $value_placeholders = implode( ',', array_fill( 0, count( $family ), '%s' ) );
+ $sql = "SELECT COUNT(DISTINCT object_id)
+ FROM {$table}
+ WHERE filter_key = %s AND filter_value IN ({$value_placeholders}){$post_type_sql}
+ {$intersect_sql}";
+
+ $params = array_merge( array( $key ), $family, $post_type_params, $intersect_params );
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $counts[ (string) $value ] = (int) $wpdb->get_var( $wpdb->prepare( $sql, $params ) );
+ }
+
wp_cache_set( $cache_key, $counts, self::CACHE_GROUP, self::CACHE_TTL ); // phpcs:ignore WordPressVIPMinimum.Performance.LowExpiryCacheTime.CacheTimeUndetermined -- CACHE_TTL = 300 seconds (VIP minimum)
return $counts;
}
+ /**
+ * The taxonomy a taxonomy-type filter indexes, when it is hierarchical.
+ *
+ * @param string $filter_key Filter key.
+ * @return string Taxonomy name, or '' for meta filters and flat taxonomies.
+ */
+ private static function hierarchical_taxonomy( string $filter_key ): string {
+ $config = FilterRegistry::get( $filter_key );
+ if ( ! $config || 'taxonomy' !== ( $config['type'] ?? '' ) || empty( $config['source'] ) ) {
+ return '';
+ }
+ $taxonomy = (string) $config['source'];
+
+ return is_taxonomy_hierarchical( $taxonomy ) ? $taxonomy : '';
+ }
+
+ /**
+ * Map each option value to the term IDs it counts: itself plus descendants.
+ *
+ * @param string $filter_key Filter key.
+ * @param string[] $values Option values (term IDs for taxonomy filters).
+ * @return array Value => IDs; always contains the value itself.
+ */
+ private static function option_families( string $filter_key, array $values ): array {
+ $taxonomy = self::hierarchical_taxonomy( $filter_key );
+ $families = array();
+ foreach ( $values as $value ) {
+ $family = array( (string) $value );
+ if ( '' !== $taxonomy && ctype_digit( (string) $value ) ) {
+ $children = get_term_children( (int) $value, $taxonomy );
+ if ( is_array( $children ) ) {
+ $family = array_merge( $family, array_map( 'strval', $children ) );
+ }
+ }
+ $families[ (string) $value ] = array_values( array_unique( $family ) );
+ }
+
+ return $families;
+ }
+
+ /**
+ * Add descendants to a list of selected values (an active filter group).
+ *
+ * @param string $filter_key Filter key.
+ * @param string[] $values Selected values.
+ * @return string[] Values plus their descendants.
+ */
+ private static function expand_with_descendants( string $filter_key, array $values ): array {
+ $expanded = array();
+ foreach ( self::option_families( sanitize_key( $filter_key ), $values ) as $family ) {
+ $expanded = array_merge( $expanded, $family );
+ }
+
+ return array_values( array_unique( $expanded ) );
+ }
+
/**
* Builds a cache key for count_for_options() that scopes the cached value to
* the current cache epoch + the full argument shape. Any index write bumps
@@ -409,9 +540,10 @@ public static function count_for_options( string $filter_key, array $option_valu
* @param array $string_values Sorted, unique option values.
* @param array $active_filters Active filter state (minus self-filter).
* @param string $post_type Post-type scope or empty string for all.
+ * @param array $families Option value => term IDs it counts (itself and descendants).
* @return string
*/
- private static function build_counts_cache_key( string $filter_key, array $string_values, array $active_filters, string $post_type = '' ): string {
+ private static function build_counts_cache_key( string $filter_key, array $string_values, array $active_filters, string $post_type = '', array $families = array() ): string {
$epoch = self::get_counts_epoch();
// Sort values and active filters for stable key regardless of input order.
sort( $string_values );
@@ -424,7 +556,7 @@ private static function build_counts_cache_key( string $filter_key, array $strin
}
}
return 'cfo:' . $epoch . ':' . md5(
- $filter_key . '|' . wp_json_encode( $string_values ) . '|' . wp_json_encode( $active_filters ) . '|pt=' . $post_type
+ $filter_key . '|' . wp_json_encode( $string_values ) . '|' . wp_json_encode( $active_filters ) . '|pt=' . $post_type . '|fam=' . wp_json_encode( $families )
);
}
diff --git a/includes/Blocks/Common/Query/FilterIndexCLI.php b/includes/Blocks/Common/Query/FilterIndexCLI.php
index 77f3e40..4624f5e 100644
--- a/includes/Blocks/Common/Query/FilterIndexCLI.php
+++ b/includes/Blocks/Common/Query/FilterIndexCLI.php
@@ -52,6 +52,10 @@ public function rebuild( $args, $assoc_args ): void {
$batch = (int) \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 200 );
$result = FilterIndexRebuilder::rebuild_all( array( 'batch_size' => $batch ) );
+ if ( 'locked' === ( $result['status'] ?? '' ) ) {
+ \WP_CLI::error( 'Another rebuild is already running. Try again when it finishes.' );
+ }
+
if ( 'error' === ( $result['status'] ?? '' ) ) {
\WP_CLI::error( sprintf( 'Rebuild failed (status: %s).', $result['status'] ) );
}
@@ -99,6 +103,10 @@ public function rebuild_filter( $args, $assoc_args ): void {
return;
}
+ if ( 'locked' === ( $result['status'] ?? '' ) ) {
+ \WP_CLI::error( 'Another rebuild is already running. Try again when it finishes.' );
+ }
+
if ( 'error' === ( $result['status'] ?? '' ) ) {
\WP_CLI::error( 'Rebuild failed.' );
}
diff --git a/includes/Blocks/Common/Query/FilterIndexHooks.php b/includes/Blocks/Common/Query/FilterIndexHooks.php
index bd63092..2896ce8 100644
--- a/includes/Blocks/Common/Query/FilterIndexHooks.php
+++ b/includes/Blocks/Common/Query/FilterIndexHooks.php
@@ -54,6 +54,7 @@ public static function register_hooks(): void {
self::$registered = true;
add_action( 'save_post', array( __CLASS__, 'on_save_post' ), 20, 2 );
add_action( 'deleted_post', array( __CLASS__, 'on_deleted_post' ), 20, 1 );
+ add_action( 'delete_term', array( __CLASS__, 'on_delete_term' ), 20, 3 );
add_action( 'set_object_terms', array( __CLASS__, 'on_set_object_terms' ), 20, 4 );
add_action( 'added_post_meta', array( __CLASS__, 'on_post_meta_changed' ), 20, 3 );
add_action( 'updated_post_meta', array( __CLASS__, 'on_post_meta_changed' ), 20, 3 );
@@ -229,6 +230,18 @@ public static function on_deleted_post( int $post_id ): void {
FilterIndex::remove_object( 'post', $post_id );
}
+ /**
+ * Purges index rows for a deleted term.
+ *
+ * @param int $term_id Term ID.
+ * @param int $tt_id Unused — term taxonomy ID.
+ * @param string $taxonomy Taxonomy slug.
+ * @return void
+ */
+ public static function on_delete_term( $term_id, $tt_id, $taxonomy ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed
+ FilterIndex::remove_term_values( (int) $term_id, (string) $taxonomy );
+ }
+
/**
* Reindexes a post when its taxonomy terms are changed, but only when
* the taxonomy is tracked by at least one registered filter.
diff --git a/includes/Blocks/Common/Query/FilterIndexRebuilder.php b/includes/Blocks/Common/Query/FilterIndexRebuilder.php
index 33a4173..6891419 100644
--- a/includes/Blocks/Common/Query/FilterIndexRebuilder.php
+++ b/includes/Blocks/Common/Query/FilterIndexRebuilder.php
@@ -81,6 +81,15 @@ private static function acquire_lock(): bool {
return (bool) add_option( self::LOCK_OPTION, time(), '', false );
}
+ /**
+ * Pushes the lock's timestamp forward so a long rebuild never outlives it.
+ *
+ * @return void
+ */
+ private static function refresh_lock(): void {
+ update_option( self::LOCK_OPTION, time(), false );
+ }
+
/**
* Releases the rebuild mutex by deleting the lock option.
*
@@ -91,7 +100,7 @@ private static function release_lock(): void {
}
/**
- * Truncates the index and repopulates it from all published posts.
+ * Repopulates the index from all published posts, then prunes stale rows.
*
* Batch-scans the posts table in chunks of $args['batch_size'] (default 200,
* minimum 50). Writes progress to FilterIndex::OPTION_STATUS so callers can
@@ -162,23 +171,6 @@ private static function do_rebuild_all( array $args ): array {
}
$table = FilterIndex::table_name();
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
- $truncated = $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', $table ) );
- FilterIndex::bump_counts_cache();
- if ( false === $truncated ) {
- self::write_status(
- array(
- 'in_progress' => false,
- 'error' => 'truncate_failed',
- 'updated_at' => time(),
- )
- );
- return array(
- 'status' => 'error',
- 'processed' => 0,
- 'total_rows' => 0,
- );
- }
// Keyset pagination: track the last ID seen and query `WHERE ID > $last_id`.
// OFFSET degrades quadratically because MySQL must scan all skipped rows;
@@ -208,6 +200,7 @@ private static function do_rebuild_all( array $args ): array {
}
$ids_count = count( $ids );
+ self::refresh_lock();
self::write_status(
array(
'in_progress' => $ids_count === $batch_size,
@@ -217,6 +210,8 @@ private static function do_rebuild_all( array $args ): array {
);
} while ( $ids_count === $batch_size );
+ self::prune_stale_rows( $table );
+
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$total_rows = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table ) );
$duration_ms = (int) ( ( microtime( true ) - $started_at ) * 1000 );
@@ -238,6 +233,48 @@ private static function do_rebuild_all( array $args ): array {
);
}
+ /**
+ * Removes rows the rebuild did not rewrite: posts that are gone or no
+ * longer published, and filter keys that are no longer registered.
+ *
+ * The index is rewritten object by object instead of truncated up front, so
+ * filter counts stay populated while a rebuild runs.
+ *
+ * @param string $table Index table name.
+ * @return void
+ */
+ private static function prune_stale_rows( string $table ): void {
+ global $wpdb;
+ // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table maintenance; %i escapes identifiers.
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $wpdb->query(
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $wpdb->prepare(
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ "DELETE i FROM %i i LEFT JOIN {$wpdb->posts} p ON p.ID = i.object_id AND p.post_status = 'publish' WHERE i.object_type = 'post' AND p.ID IS NULL",
+ $table
+ )
+ );
+ $keys = array_map( 'strval', array_keys( FilterRegistry::all() ) );
+ if ( empty( $keys ) ) {
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $wpdb->query( $wpdb->prepare( 'DELETE FROM %i', $table ) );
+ } else {
+ $placeholders = implode( ',', array_fill( 0, count( $keys ), '%s' ) );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $wpdb->query(
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
+ $wpdb->prepare(
+ // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- placeholders are generated from the key count.
+ "DELETE FROM %i WHERE filter_key NOT IN ({$placeholders})",
+ array_merge( array( $table ), $keys )
+ )
+ );
+ }
+ // phpcs:enable
+ FilterIndex::bump_counts_cache();
+ }
+
/**
* Wipes all index rows for a single filter key and repopulates them.
*
@@ -299,11 +336,6 @@ private static function do_rebuild_filter( string $key, array $args ): array {
$table = FilterIndex::table_name();
$batch_size = max( self::MIN_BATCH_SIZE, (int) ( $args['batch_size'] ?? self::DEFAULT_BATCH_SIZE ) );
- // Delete all rows for this key in one statement — fast regardless of row count.
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
- $wpdb->delete( $table, array( 'filter_key' => $key ), array( '%s' ) );
- FilterIndex::bump_counts_cache();
-
self::write_status(
array(
'in_progress' => true,
@@ -338,6 +370,7 @@ private static function do_rebuild_filter( string $key, array $args ): array {
}
$ids_count = count( $ids );
+ self::refresh_lock();
self::write_status(
array(
'in_progress' => $ids_count === $batch_size,
@@ -347,6 +380,8 @@ private static function do_rebuild_filter( string $key, array $args ): array {
);
} while ( $ids_count === $batch_size );
+ self::prune_stale_rows( $table );
+
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$total_rows = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE filter_key = %s', $table, $key ) );
@@ -393,7 +428,10 @@ public static function status(): array {
// also elapses — the two TTLs are aligned but a poll can still race
// a new click, so unlock explicitly.
if ( ! empty( $status['in_progress'] ) && ! empty( $status['started_at'] ) ) {
- if ( time() - (int) $status['started_at'] > 5 * MINUTE_IN_SECONDS ) {
+ // Idle time since the last batch, not total runtime: a big rebuild
+ // legitimately runs longer than the lock TTL.
+ $last_activity = max( (int) $status['started_at'], (int) ( $status['updated_at'] ?? 0 ) );
+ if ( time() - $last_activity > self::LOCK_TTL ) {
$status['in_progress'] = false;
$status['error'] = 'timed_out';
update_option( FilterIndex::OPTION_STATUS, $status, false );
diff --git a/includes/Blocks/Common/Query/RefreshSource.php b/includes/Blocks/Common/Query/RefreshSource.php
index 152389f..f155916 100644
--- a/includes/Blocks/Common/Query/RefreshSource.php
+++ b/includes/Blocks/Common/Query/RefreshSource.php
@@ -7,11 +7,14 @@
* itself put on a page, wherever it was placed — post content, a template or
* template part, a synced pattern, a widget, or another query's item.
*
- * So first paint embeds the query's definition (attributes + inner blocks)
- * with an HMAC signature, and the route renders only a definition whose
- * signature verifies. The payload is base64 in a data attribute because it
- * passes through the_content: filters like capital_P_dangit() rewrite text
- * inside inline ` inside a title
+ // would otherwise close the element early.
+ echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wp_json_encode() output with script-closing sequences neutralised.
}
}
diff --git a/src/blocks/breadcrumbs/style.scss b/src/blocks/breadcrumbs/style.scss
index 40e98f9..5ca8274 100644
--- a/src/blocks/breadcrumbs/style.scss
+++ b/src/blocks/breadcrumbs/style.scss
@@ -5,17 +5,19 @@
* Uses low-specificity selectors with :where() for easy overriding.
*/
+@use '../../styles/variables' as *;
+@use '../../styles/mixins' as *;
+
.airo-wp-breadcrumbs {
// Block container
display: block;
max-width: 100%;
overflow-wrap: break-word;
- word-wrap: break-word;
// Prefix text
&__prefix {
display: inline-block;
- margin-right: 0.5em;
+ margin-inline-end: 0.5em;
opacity: 0.8;
}
@@ -29,7 +31,7 @@
}
&.is-content-justification-right {
- text-align: right;
+ text-align: end;
.airo-wp-breadcrumbs__list {
justify-content: flex-end;
@@ -55,8 +57,9 @@
margin: 0;
padding: 0;
max-width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
+ // No overflow clipping here: it would cut off the focus ring.
+ // Truncation lives on the link / text spans below.
+ min-width: 0;
// Current page item styling
&--current {
@@ -71,7 +74,7 @@
&__link {
color: inherit;
text-decoration: none;
- transition: color 0.2s ease, text-decoration 0.2s ease;
+ transition: color $airo-wp-duration-fast $airo-wp-easing, text-decoration $airo-wp-duration-fast $airo-wp-easing;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
@@ -81,9 +84,11 @@
text-decoration: underline;
}
- &:focus {
+ // The link clips its own overflow for truncation, so an outset ring
+ // would be cut off. Draw it inside the link's box instead.
+ &:focus-visible {
outline: 2px solid currentcolor;
- outline-offset: 2px;
+ outline-offset: -2px;
}
}
@@ -111,7 +116,7 @@
&__home-icon {
display: inline-flex;
align-items: center;
- margin-right: 0.25em;
+ margin-inline-end: 0.25em;
flex-shrink: 0;
}
@@ -126,7 +131,7 @@
/**
* Responsive adjustments
*/
-@media (max-width: 600px) {
+@media (max-width: #{$breakpoint-small}) {
.airo-wp-breadcrumbs {
@@ -135,7 +140,7 @@
}
&__prefix {
- margin-right: 0.35em;
+ margin-inline-end: 0.35em;
}
}
}
diff --git a/src/blocks/breadcrumbs/view.js b/src/blocks/breadcrumbs/view.js
deleted file mode 100644
index 4704114..0000000
--- a/src/blocks/breadcrumbs/view.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/**
- * Breadcrumbs Block - Frontend JavaScript
- *
- * Injects Schema.org BreadcrumbList JSON-LD for improved SEO.
- */
-
-document.addEventListener('DOMContentLoaded', function () {
- initBreadcrumbs();
-});
-document.addEventListener('airo-wp-content-loaded', initBreadcrumbs);
-
-/**
- * Initialize all breadcrumb blocks on the page
- */
-function initBreadcrumbs() {
- const breadcrumbBlocks = document.querySelectorAll(
- '.airo-wp-breadcrumbs[data-airo-wp-breadcrumbs]'
- );
-
- if (!breadcrumbBlocks || breadcrumbBlocks.length === 0) {
- return;
- }
-
- breadcrumbBlocks.forEach((block) => {
- try {
- // Prevent duplicate initialization
- if (block.hasAttribute('data-airo-wp-schema-injected')) {
- return;
- }
- block.setAttribute('data-airo-wp-schema-injected', 'true');
-
- // Parse breadcrumb data
- const breadcrumbData = JSON.parse(
- block.getAttribute('data-airo-wp-breadcrumbs')
- );
-
- if (!breadcrumbData || breadcrumbData.length === 0) {
- return;
- }
-
- // Generate and inject Schema.org JSON-LD
- injectSchemaMarkup(breadcrumbData);
- } catch (error) {
- // Silently fail - breadcrumbs still work without Schema.org
- // eslint-disable-next-line no-console
- console.error('airo-wp Breadcrumbs: Schema.org error', error);
- }
- });
-}
-
-/**
- * Generate and inject Schema.org BreadcrumbList JSON-LD
- *
- * @param {Array} breadcrumbs - Array of breadcrumb items
- */
-function injectSchemaMarkup(breadcrumbs) {
- // Build Schema.org BreadcrumbList structure
- const schemaData = {
- '@context': 'https://schema.org',
- '@type': 'BreadcrumbList',
- itemListElement: breadcrumbs.map((item, index) => {
- const listItem = {
- '@type': 'ListItem',
- position: item.position || index + 1,
- name: item.title,
- };
-
- // Add item URL to schema (all breadcrumb items have URLs).
- if (item.url) {
- listItem.item = item.url;
- }
-
- return listItem;
- }),
- };
-
- // Check if Schema.org markup already exists for breadcrumbs
- const existingSchema = document.querySelector(
- 'script[type="application/ld+json"][data-airo-wp-breadcrumbs-schema]'
- );
-
- if (existingSchema) {
- // Update existing schema
- existingSchema.textContent = JSON.stringify(schemaData);
- } else {
- // Create new schema script tag
- const scriptTag = document.createElement('script');
- scriptTag.type = 'application/ld+json';
- scriptTag.setAttribute('data-airo-wp-breadcrumbs-schema', 'true');
- scriptTag.textContent = JSON.stringify(schemaData);
-
- // Inject before closing