=","value":18}, "then": {"action":"show","target":"field_key"} } * ], * "actions": [ * { "type": "email|webhook|save|custom", "settings": {...}, "requires": ["actions.email"] } * ], * // version is managed by storage; optional client-supplied value ignored * } */ namespace SubtleForms\Support; if ( ! defined( 'ABSPATH' ) ) { exit; } use InvalidArgumentException; use SubtleForms\Fields\FieldRegistry; use SubtleForms\Plugin; final class SchemaValidator { /** * A field key (the field ID in the builder): letters, numbers, _ and -, * up to 64 characters (2.4.1; "-" and the length limit are new). */ const KEY_PATTERN = '/^[a-zA-Z0-9_-]{1,64}$/'; /** * Keys the browser sends with every entry beside the answers. A field * with one of these keys would lose its answer (2.4.1). */ const RESERVED_KEYS = RequestKeys::BUILT_IN; /** * Keys of fields inside steps, columns and containers that repeat a key * used elsewhere in the form, or use a reserved or invalid key. Fields in * the top-level list are checked by the main loops; a Repeater's own * fields are answered inside each group, so they only clash with each * other (2.4.1). * * @param array $schema Schema. * @return array */ public static function nestedKeyProblems( array $schema ): array { // How often each key appears in the top-level list (checked by the // main loops) and among every answered field. $top = array(); foreach ( (array) ( $schema['fields'] ?? array() ) as $field ) { if ( is_array( $field ) && isset( $field['key'] ) && is_string( $field['key'] ) ) { $top[ $field['key'] ] = ( $top[ $field['key'] ] ?? 0 ) + 1; } } $all = array(); foreach ( FieldMapper::fields( $schema ) as $entry ) { $key = (string) $entry['key']; $all[ $key ] = ( $all[ $key ] ?? 0 ) + 1; } $problems = array(); foreach ( $all as $key => $count ) { $key = (string) $key; if ( $count > 1 && $count > ( $top[ $key ] ?? 0 ) ) { /* translators: %s: field key */ $problems[] = array( 'key' => $key, 'message' => sprintf( __( 'Two fields use the ID %s. Give one of them another ID.', 'subtleforms' ), $key ) ); continue; } if ( isset( $top[ $key ] ) ) { continue; } if ( ! preg_match( self::KEY_PATTERN, $key ) ) { /* translators: %s: field key */ $problems[] = array( 'key' => $key, 'message' => sprintf( __( 'The field ID %s can only use letters, numbers, _ and -, up to 64 characters.', 'subtleforms' ), $key ) ); } elseif ( RequestKeys::has( (string) $key ) ) { /* translators: %s: field key */ $problems[] = array( 'key' => $key, 'message' => sprintf( __( 'SubtleForms uses %s itself. Give the field another ID.', 'subtleforms' ), $key ) ); } } // A Repeater's fields are answered inside each group, so each Repeater // is its own namespace: its fields may repeat an ID used outside it, // but not each other's, and the same character and reserved rules // apply (review of #47). foreach ( self::repeaters( (array) ( $schema['fields'] ?? array() ) ) as $repeater ) { $name = (string) ( $repeater['key'] ?? ( $repeater['config']['key'] ?? '' ) ); $counts = array(); // A wrapped node keeps its fields in config.children. $children = Repeater::children( $repeater ); if ( ! $children && isset( $repeater['config']['children'] ) && is_array( $repeater['config']['children'] ) ) { $children = array_values( array_filter( $repeater['config']['children'], 'is_array' ) ); } foreach ( FieldMapper::fields( array( 'fields' => $children ) ) as $entry ) { $key = (string) $entry['key']; $counts[ $key ] = ( $counts[ $key ] ?? 0 ) + 1; } foreach ( $counts as $key => $count ) { $key = (string) $key; if ( $count > 1 ) { /* translators: 1: Repeater field ID, 2: field ID */ $problems[] = array( 'key' => $key, 'message' => sprintf( __( 'Two fields in the repeater %1$s use the ID %2$s. Give one of them another ID.', 'subtleforms' ), $name, $key ) ); } elseif ( ! preg_match( self::KEY_PATTERN, $key ) ) { /* translators: %s: field key */ $problems[] = array( 'key' => $key, 'message' => sprintf( __( 'The field ID %s can only use letters, numbers, _ and -, up to 64 characters.', 'subtleforms' ), $key ) ); } elseif ( RequestKeys::has( (string) $key ) ) { /* translators: %s: field key */ $problems[] = array( 'key' => $key, 'message' => sprintf( __( 'SubtleForms uses %s itself. Give the field another ID.', 'subtleforms' ), $key ) ); } } } return $problems; } /** * Every Repeater in a field list, at any depth, including Repeaters * inside another Repeater. * * @param array $fields Field list. * @return array Repeater nodes. */ private static function repeaters( array $fields ): array { $out = array(); foreach ( $fields as $node ) { if ( ! is_array( $node ) ) { continue; } if ( Repeater::isRepeater( $node ) ) { $out[] = $node; } $lists = array( $node['children'] ?? null, $node['fields'] ?? null, $node['config']['children'] ?? null ); foreach ( (array) ( $node['columns'] ?? array() ) as $column ) { if ( is_array( $column ) ) { $lists[] = isset( $column[0] ) ? $column : ( $column['fields'] ?? ( $column['children'] ?? null ) ); } } foreach ( $lists as $list ) { if ( is_array( $list ) ) { $out = array_merge( $out, self::repeaters( $list ) ); } } } return $out; } /** * Allowed field types for freemium core. Extensions may add more. * * @var string[] */ private array $allowedFieldTypes; /** * Whether a well-formed type nothing registers is kept. See * keepUnregisteredTypes(). */ private bool $keepUnregistered = false; public const CORE_TYPES = array( 'text', 'email', 'textarea', 'number', 'phone', 'tel', 'url', 'password', 'checkbox', 'consent', 'radio', 'multiple_choice', 'dropdown', 'select', 'country', 'chained_select', 'date', 'time', 'datetime', 'image_upload', 'file_upload', 'rating', 'range_slider', 'color_picker', 'rich_text', 'net_promoter_score', 'checkbox_grid', 'dynamic_field', 'post_selection', 'html', 'hidden', 'address', 'section_break', 'disclaimer', 'form_step', 'step', 'repeat_field', 'one_column_container', 'two_column_container', 'three_column_container', 'four_column_container', 'five_column_container', 'six_column_container', 'repeat_container', 'group_container', 'tabs_container', 'accordion_container', 'tab_panel', 'accordion_panel', 'recaptcha', 'hcaptcha', 'turnstile', 'action_hook', 'save_resume', ); public function __construct( ?array $allowedFieldTypes = null ) { $this->allowedFieldTypes = $this->resolveAllowedFieldTypes( $allowedFieldTypes ); } private function resolveAllowedFieldTypes( ?array $allowedFieldTypes ): array { if ( is_array( $allowedFieldTypes ) && ! empty( $allowedFieldTypes ) ) { return array_values( array_unique( array_map( 'strval', $allowedFieldTypes ) ) ); } if ( class_exists( Plugin::class ) ) { try { $registry = Plugin::instance()->get( FieldRegistry::class ); if ( $registry instanceof FieldRegistry ) { $types = array_keys( $registry->all() ); if ( ! empty( $types ) ) { // include legacy aliases such as 'select' $types[] = 'select'; $types = array_merge( $types, \SubtleForms\Fields\FieldTypeAvailability::knownTypes() ); return array_values( array_unique( $types ) ); } } } catch ( \Throwable $e ) { // Fallback handled below } } return array_values( array_unique( array_merge( self::CORE_TYPES, \SubtleForms\Fields\FieldTypeAvailability::knownTypes() ) ) ); } /** * Keep a well-formed field type that nothing registers. A form made while * an add-on was active holds that add-on's fields; saving, copying or * importing the form on a site without the add-on must not refuse them. * Used where a form is stored. Text that is new (for example from an * assistant) is still checked against the registered types. * * @return $this */ public function keepUnregisteredTypes(): self { $this->keepUnregistered = true; return $this; } /** * Whether a field type may be saved. * * @param string $type Field type. */ private function typeAllowed( string $type ): bool { if ( in_array( $type, $this->allowedFieldTypes, true ) ) { return true; } return $this->keepUnregistered && 1 === preg_match( '/^[a-z][a-z0-9_]{0,63}$/', $type ); } /** * Validate schema array. Throws InvalidArgumentException on first failure. */ public function validate( array $schema ): bool { // Schema version is required (root level) if ( ! isset( $schema['schema_version'] ) ) { throw new InvalidArgumentException( 'Schema must contain a schema_version field.' ); } if ( ! is_int( $schema['schema_version'] ) || $schema['schema_version'] < 1 ) { throw new InvalidArgumentException( 'schema_version must be a positive integer.' ); } // Root checks if ( empty( $schema['metadata'] ) || ! is_array( $schema['metadata'] ) ) { throw new InvalidArgumentException( 'Schema must contain a metadata object.' ); } if ( empty( $schema['metadata']['name'] ) || ! is_string( $schema['metadata']['name'] ) ) { throw new InvalidArgumentException( 'Metadata.name is required and must be a string.' ); } // Status if present if ( isset( $schema['metadata']['status'] ) && ! in_array( $schema['metadata']['status'], array( 'draft', 'published', 'archived' ), true ) ) { throw new InvalidArgumentException( 'Metadata.status must be one of draft, published or archived.' ); } // Fields if ( ! isset( $schema['fields'] ) || ! is_array( $schema['fields'] ) ) { throw new InvalidArgumentException( 'Schema must include a fields array.' ); } $keys = array(); foreach ( $schema['fields'] as $i => $field ) { if ( ! is_array( $field ) ) { throw new InvalidArgumentException( "Each field must be an object (index {$i})." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( empty( $field['type'] ) || ! is_string( $field['type'] ) ) { throw new InvalidArgumentException( "Field at index {$i} must have a string 'type'." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( ! $this->typeAllowed( $field['type'] ) ) { throw new InvalidArgumentException( "Field type '{$field['type']}' at index {$i} is not allowed." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( empty( $field['key'] ) || ! is_string( $field['key'] ) ) { throw new InvalidArgumentException( "Field at index {$i} must have a string 'key'." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( ! preg_match( self::KEY_PATTERN, $field['key'] ) ) { throw new InvalidArgumentException( "Field key '{$field['key']}' at index {$i} contains invalid characters." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( RequestKeys::has( (string) $field['key'] ) ) { throw new InvalidArgumentException( "Field key '{$field['key']}' at index {$i} is reserved." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( in_array( $field['key'], $keys, true ) ) { throw new InvalidArgumentException( "Duplicate field key '{$field['key']}' at index {$i}." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } $keys[] = $field['key']; if ( isset( $field['label'] ) && ! is_string( $field['label'] ) ) { throw new InvalidArgumentException( "Field label for '{$field['key']}' must be a string." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( isset( $field['settings'] ) && ! is_array( $field['settings'] ) ) { throw new InvalidArgumentException( "Field settings for '{$field['key']}' must be an object." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( isset( $field['validations'] ) && ! is_array( $field['validations'] ) ) { throw new InvalidArgumentException( "Field validations for '{$field['key']}' must be an object." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } // Validate field-level conditions if ( isset( $field['config']['conditions'] ) && ! is_array( $field['config']['conditions'] ) ) { throw new InvalidArgumentException( "Field conditions for '{$field['key']}' must be an array." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( isset( $field['config']['conditions'] ) && is_array( $field['config']['conditions'] ) ) { foreach ( $field['config']['conditions'] as $ci => $cond ) { if ( ! is_array( $cond ) ) { throw new InvalidArgumentException( "Condition {$ci} for field '{$field['key']}' must be an object." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( empty( $cond['sourceField'] ) || ! is_string( $cond['sourceField'] ) ) { throw new InvalidArgumentException( "Condition {$ci} for field '{$field['key']}' must have a string 'sourceField'." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( empty( $cond['operator'] ) || ! is_string( $cond['operator'] ) ) { throw new InvalidArgumentException( "Condition {$ci} for field '{$field['key']}' must have a string 'operator'." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( empty( $cond['effect'] ) || ! is_string( $cond['effect'] ) ) { throw new InvalidArgumentException( "Condition {$ci} for field '{$field['key']}' must have a string 'effect'." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } } } } // A single checkbox is one yes/no box; a list of options belongs to // Multiple choice (2.2.1, bug 7). $checkboxErrors = self::checkboxOptionErrors( $schema['fields'], 'fields' ); if ( $checkboxErrors ) { throw new InvalidArgumentException( $checkboxErrors[0]['message'] ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } foreach ( self::panelNestingProblems( $schema ) as $problem ) { throw new InvalidArgumentException( $problem['message'] ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } // Conditional logic (permissive but structured) if ( isset( $schema['logic'] ) ) { if ( ! is_array( $schema['logic'] ) ) { throw new InvalidArgumentException( 'Schema.logic must be an array of rules.' ); } foreach ( $schema['logic'] as $i => $rule ) { if ( ! is_array( $rule ) || ! isset( $rule['if'] ) || ! isset( $rule['then'] ) ) { throw new InvalidArgumentException( "Logic rule at index {$i} must contain 'if' and 'then' objects." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } $cond = $rule['if']; if ( ! is_array( $cond ) || empty( $cond['field'] ) || empty( $cond['operator'] ) || ! array_key_exists( 'value', $cond ) ) { throw new InvalidArgumentException( "Logic.if at index {$i} must contain 'field','operator' and 'value'." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( ! is_string( $cond['field'] ) || ! is_string( $cond['operator'] ) ) { throw new InvalidArgumentException( "Logic.if.field and operator must be strings at index {$i}." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } $then = $rule['then']; if ( ! is_array( $then ) || empty( $then['action'] ) ) { throw new InvalidArgumentException( "Logic.then at index {$i} must contain an 'action' key." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } } } // Actions (pipeline steps) validation if ( isset( $schema['actions'] ) ) { if ( ! is_array( $schema['actions'] ) ) { throw new InvalidArgumentException( 'Schema.actions must be an array.' ); } foreach ( $schema['actions'] as $i => $act ) { if ( ! is_array( $act ) || empty( $act['type'] ) || ! is_string( $act['type'] ) ) { throw new InvalidArgumentException( "Action at index {$i} must be an object with string 'type'." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( isset( $act['settings'] ) && ! is_array( $act['settings'] ) ) { throw new InvalidArgumentException( "Action.settings for '{$act['type']}' must be an object." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( isset( $act['requires'] ) && ! is_array( $act['requires'] ) ) { throw new InvalidArgumentException( "Action.requires for '{$act['type']}' must be an array of capability strings." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( isset( $act['skippable'] ) && ! is_bool( $act['skippable'] ) ) { throw new InvalidArgumentException( "Action.skippable for '{$act['type']}' must be boolean." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } } } // If version present, ensure integer if ( isset( $schema['version'] ) && ! is_int( $schema['version'] ) ) { throw new InvalidArgumentException( 'Schema.version must be an integer when present.' ); } foreach ( self::nestedKeyProblems( $schema ) as $problem ) { throw new InvalidArgumentException( $problem['message'] ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } return true; } /** * Validate schema and return structured errors instead of throwing. * * Error shape: * - path: string (e.g. "metadata.title", "fields[0].key") * - message: string * - fieldKey?: string (when applicable) * - index?: int (when applicable) */ public function validateWithErrors( array $schema ): array { $errors = array(); $push = static function ( array &$errors, string $path, string $message, array $meta = array() ): void { $errors[] = array_merge( array( 'path' => $path, 'message' => $message, ), $meta ); }; if ( ! isset( $schema['schema_version'] ) ) { $push( $errors, 'schema_version', 'Schema must contain a schema_version field.' ); } elseif ( ! is_int( $schema['schema_version'] ) || $schema['schema_version'] < 1 ) { $push( $errors, 'schema_version', 'schema_version must be a positive integer.' ); } if ( empty( $schema['metadata'] ) || ! is_array( $schema['metadata'] ) ) { $push( $errors, 'metadata', 'Schema must contain a metadata object.' ); } else { if ( empty( $schema['metadata']['name'] ) || ! is_string( $schema['metadata']['name'] ) ) { $push( $errors, 'metadata.name', 'Metadata.name is required and must be a string.' ); } if ( isset( $schema['metadata']['status'] ) && ! in_array( $schema['metadata']['status'], array( 'draft', 'published', 'archived' ), true ) ) { $push( $errors, 'metadata.status', 'Metadata.status must be one of draft, published or archived.' ); } } if ( ! isset( $schema['fields'] ) || ! is_array( $schema['fields'] ) ) { $push( $errors, 'fields', 'Schema must include a fields array.' ); } else { $keys = array(); foreach ( $schema['fields'] as $i => $field ) { if ( ! is_array( $field ) ) { $push( $errors, "fields[{$i}]", "Each field must be an object (index {$i}).", array( 'index' => $i ) ); continue; } $fieldKey = isset( $field['key'] ) && is_string( $field['key'] ) ? $field['key'] : null; if ( empty( $field['type'] ) || ! is_string( $field['type'] ) ) { $push( $errors, "fields[{$i}].type", "Field at index {$i} must have a string 'type'.", array_filter( array( 'index' => $i, 'fieldKey' => $fieldKey, ), fn( $v ) => $v !== null ) ); } elseif ( ! $this->typeAllowed( $field['type'] ) ) { $push( $errors, "fields[{$i}].type", "Field type '{$field['type']}' at index {$i} is not allowed.", array_filter( array( 'index' => $i, 'fieldKey' => $fieldKey, ), fn( $v ) => $v !== null ) ); } if ( empty( $field['key'] ) || ! is_string( $field['key'] ) ) { $push( $errors, "fields[{$i}].key", "Field at index {$i} must have a string 'key'.", array( 'index' => $i ) ); } else { if ( RequestKeys::has( (string) $field['key'] ) ) { $push( $errors, "fields[{$i}].key", /* translators: %s: field key */ sprintf( __( 'SubtleForms uses %s itself. Give the field another ID.', 'subtleforms' ), $field['key'] ), array( 'index' => $i, 'fieldKey' => $field['key'], ) ); } if ( ! preg_match( self::KEY_PATTERN, $field['key'] ) ) { $push( $errors, "fields[{$i}].key", "Field key '{$field['key']}' at index {$i} contains invalid characters.", array( 'index' => $i, 'fieldKey' => $field['key'], ) ); } if ( in_array( $field['key'], $keys, true ) ) { $push( $errors, "fields[{$i}].key", "Duplicate field key '{$field['key']}' at index {$i}.", array( 'index' => $i, 'fieldKey' => $field['key'], ) ); } else { $keys[] = $field['key']; } } if ( isset( $field['label'] ) && ! is_string( $field['label'] ) ) { $push( $errors, "fields[{$i}].label", "Field label for '{$fieldKey}' must be a string.", array_filter( array( 'index' => $i, 'fieldKey' => $fieldKey, ), fn( $v ) => $v !== null ) ); } if ( isset( $field['settings'] ) && ! is_array( $field['settings'] ) ) { $push( $errors, "fields[{$i}].settings", "Field settings for '{$fieldKey}' must be an object.", array_filter( array( 'index' => $i, 'fieldKey' => $fieldKey, ), fn( $v ) => $v !== null ) ); } if ( isset( $field['validations'] ) && ! is_array( $field['validations'] ) ) { $push( $errors, "fields[{$i}].validations", "Field validations for '{$fieldKey}' must be an object.", array_filter( array( 'index' => $i, 'fieldKey' => $fieldKey, ), fn( $v ) => $v !== null ) ); } } } if ( isset( $schema['fields'] ) && is_array( $schema['fields'] ) ) { foreach ( self::checkboxOptionErrors( $schema['fields'], 'fields' ) as $error ) { $errors[] = $error; } } if ( isset( $schema['fields'] ) && is_array( $schema['fields'] ) ) { foreach ( self::panelNestingProblems( $schema ) as $problem ) { $errors[] = $problem; } } if ( isset( $schema['logic'] ) && ! is_array( $schema['logic'] ) ) { $push( $errors, 'logic', 'Schema.logic must be an array of rules.' ); } if ( isset( $schema['actions'] ) && ! is_array( $schema['actions'] ) ) { $push( $errors, 'actions', 'Schema.actions must be an array.' ); } if ( isset( $schema['version'] ) && ! is_int( $schema['version'] ) ) { $push( $errors, 'version', 'Schema.version must be an integer when present.' ); } // One CAPTCHA field per provider: the provider answers with one token // per form, so a second field of the same kind could never pass (2.4.0). $captchas = \SubtleForms\Support\Captcha\FieldCaptcha::fields( $schema ); foreach ( self::nestedKeyProblems( $schema ) as $problem ) { $push( $errors, 'fields', $problem['message'], array( 'fieldKey' => $problem['key'] ) ); } foreach ( \SubtleForms\Support\Captcha\FieldCaptcha::repeated( $captchas ) as $field ) { $push( $errors, 'fields.' . (string) ( $field['id'] ?? '' ), sprintf( /* translators: %s: CAPTCHA provider name, such as reCAPTCHA */ __( 'A form can have only one %s field. Remove the extra one or choose another provider for it.', 'subtleforms' ), \SubtleForms\Support\Captcha\FieldCaptcha::label( \SubtleForms\Support\Captcha\FieldCaptcha::provider( $field ) ) ), array( 'field_id' => (string) ( $field['id'] ?? '' ) ) ); } return $errors; } /** * Validate schema for publishing (stricter rules than draft). * Ensures form is ready for public use. */ public function validateForPublishing( array $schema ): bool { // First run standard validation $this->validate( $schema ); // Additional publishing requirements if ( empty( $schema['fields'] ) || count( $schema['fields'] ) === 0 ) { throw new InvalidArgumentException( 'Cannot publish: Form must contain at least one field.' ); } // Ensure metadata has a title for published forms if ( empty( $schema['metadata']['title'] ) || trim( $schema['metadata']['title'] ) === '' ) { throw new InvalidArgumentException( 'Cannot publish: Form must have a title.' ); } // Check for at least one input field (not just containers/layout) $inputFieldTypes = null; // Every field that takes an answer counts (2.3.0). $hasInputField = $this->hasInputFieldRecursive( $schema['fields'], $inputFieldTypes ); if ( ! $hasInputField ) { throw new InvalidArgumentException( 'Cannot publish: Form must contain at least one input field (not just layout elements).' ); } return true; } /** * Publishing validation with structured errors (no exceptions). */ public function validateForPublishingWithErrors( array $schema ): array { $errors = $this->validateWithErrors( $schema ); $push = static function ( array &$errors, string $path, string $message, array $meta = array() ): void { $errors[] = array_merge( array( 'path' => $path, 'message' => $message, ), $meta ); }; if ( ! isset( $schema['fields'] ) || ! is_array( $schema['fields'] ) || count( $schema['fields'] ) === 0 ) { $push( $errors, 'fields', 'Cannot publish: Form must contain at least one field.' ); } if ( empty( $schema['metadata'] ) || ! is_array( $schema['metadata'] ) || empty( $schema['metadata']['title'] ) || trim( (string) $schema['metadata']['title'] ) === '' ) { $push( $errors, 'metadata.title', 'Cannot publish: Form must have a title.' ); } $inputFieldTypes = null; // Every field that takes an answer counts (2.3.0). if ( isset( $schema['fields'] ) && is_array( $schema['fields'] ) && count( $schema['fields'] ) > 0 ) { $hasInputField = $this->hasInputFieldRecursive( $schema['fields'], $inputFieldTypes ); if ( ! $hasInputField ) { $push( $errors, 'fields', 'Cannot publish: Form must contain at least one input field (not just layout elements).' ); } } return $errors; } /** * Single checkboxes that carry a list of options, anywhere in the tree. * * @param array $fields Field list. * @param string $path Path of the list, for error messages. * @return array */ public static function checkboxOptionErrors( array $fields, string $path ): array { $errors = array(); foreach ( $fields as $i => $field ) { if ( ! is_array( $field ) ) { continue; } $here = "{$path}[{$i}]"; if ( ( $field['type'] ?? '' ) === 'checkbox' ) { $options = $field['options'] ?? ( $field['config']['options'] ?? null ); if ( is_array( $options ) && count( $options ) > 0 ) { $key = (string) ( $field['key'] ?? ( $field['config']['key'] ?? '' ) ); $errors[] = array( 'path' => "{$here}.options", /* translators: %s: field key */ 'message' => sprintf( __( 'The single checkbox "%s" has a list of options. Use a Multiple choice field for several options.', 'subtleforms' ), $key ), 'fieldKey' => $key, ); } } foreach ( array( 'children', 'fields' ) as $childKey ) { if ( isset( $field[ $childKey ] ) && is_array( $field[ $childKey ] ) && self::isList( $field[ $childKey ] ) ) { $errors = array_merge( $errors, self::checkboxOptionErrors( $field[ $childKey ], "{$here}.{$childKey}" ) ); } } if ( isset( $field['columns'] ) && is_array( $field['columns'] ) ) { foreach ( $field['columns'] as $c => $column ) { if ( is_array( $column ) && self::isList( $column ) ) { $errors = array_merge( $errors, self::checkboxOptionErrors( $column, "{$here}.columns[{$c}]" ) ); } } } } return $errors; } /** * Panel containers (Tabs, Accordion) and the panel type each one holds. * * @var array */ public const PANEL_TYPES = array( 'tabs_container' => 'tab_panel', 'accordion_container' => 'accordion_panel', ); /** * Where Tabs, Accordion and their panels may not sit (2.9.0): a panel only * inside its own container, a container holding nothing but its panels, * no Page Break inside a panel container, no Tabs inside Tabs and no * Accordion inside an Accordion at any depth, and neither inside a * Repeater at any depth. Mirrors the builder (resolveDrop.js). * * @param array $schema Schema. * @return array */ public static function panelNestingProblems( array $schema ): array { $problems = array(); self::walkPanels( (array) ( $schema['fields'] ?? array() ), 'fields', '', array(), false, $problems ); return $problems; } /** * Walk a field list for panelNestingProblems(). * * @param array $nodes Field list. * @param string $path Path of the list. * @param string $parent Type of the parent node. * @param array $ancestors Types of the panel containers above. * @param bool $inRepeat Whether a Repeater is above. * @param array $problems Collected problems. */ private static function walkPanels( array $nodes, string $path, string $parent, array $ancestors, bool $inRepeat, array &$problems ): void { foreach ( $nodes as $i => $node ) { if ( ! is_array( $node ) ) { continue; } $type = (string) ( $node['type'] ?? '' ); $key = (string) ( $node['key'] ?? ( $node['config']['key'] ?? '' ) ); $here = "{$path}[{$i}]"; $add = static function ( string $message ) use ( &$problems, $here, $key ): void { $problems[] = array( 'path' => $here, 'message' => $message, 'fieldKey' => $key, ); }; $owner = array_search( $type, self::PANEL_TYPES, true ); if ( false !== $owner && $parent !== $owner ) { $add( __( 'A tab or section can only sit inside its own Tabs or Accordion.', 'subtleforms' ) ); } if ( isset( self::PANEL_TYPES[ $parent ] ) && self::PANEL_TYPES[ $parent ] !== $type ) { $add( __( 'Tabs and Accordion can only hold their own tabs or sections. Put fields inside a tab or section.', 'subtleforms' ) ); } if ( 'step' === $type && ( $ancestors || isset( self::PANEL_TYPES[ $parent ] ) ) ) { $add( __( 'A Page Break cannot sit inside Tabs or an Accordion.', 'subtleforms' ) ); } if ( isset( self::PANEL_TYPES[ $type ] ) ) { if ( in_array( $type, $ancestors, true ) ) { $add( __( 'Tabs cannot sit inside Tabs, and an Accordion cannot sit inside an Accordion.', 'subtleforms' ) ); } if ( $inRepeat ) { $add( __( 'Tabs and Accordion cannot sit inside a Repeater.', 'subtleforms' ) ); } } $below = isset( self::PANEL_TYPES[ $type ] ) ? array_merge( $ancestors, array( $type ) ) : $ancestors; $repeat = $inRepeat || Repeater::TYPE === $type; foreach ( array( 'children', 'fields' ) as $childKey ) { if ( isset( $node[ $childKey ] ) && is_array( $node[ $childKey ] ) && self::isList( $node[ $childKey ] ) ) { self::walkPanels( $node[ $childKey ], "{$here}.{$childKey}", $type, $below, $repeat, $problems ); } } if ( isset( $node['columns'] ) && is_array( $node['columns'] ) ) { foreach ( $node['columns'] as $c => $column ) { if ( is_array( $column ) && self::isList( $column ) ) { self::walkPanels( $column, "{$here}.columns[{$c}]", $type, $below, $repeat, $problems ); } } } } } /** * Whether an array is a plain list (0..n-1 keys). * * @param array $value Array. * @return bool */ private static function isList( array $value ): bool { return array_keys( $value ) === range( 0, count( $value ) - 1 ) || array() === $value; } /** * Field types that hold no answer. */ private const LAYOUT_TYPES = array( 'html', 'section_break', 'disclaimer', 'step', 'form_step', 'repeat_field', 'recaptcha', 'hcaptcha', 'turnstile', 'captcha', 'action_hook', 'save_resume', 'hidden', 'tab_panel', 'accordion_panel' ); /** * Whether a field type takes an answer from the visitor. * * Before 2.3 only a short list of basic types counted, so a form made * only of, say, a Signature or Rich text field could not be published. * * @param string $type Field type. * @return bool */ public static function takesAnswer( string $type ): bool { if ( '' === $type || in_array( $type, self::LAYOUT_TYPES, true ) || substr( $type, -10 ) === '_container' ) { return false; } return ! in_array( $type, \SubtleForms\Fields\FieldTypeAvailability::noAnswerTypes(), true ); } private function hasInputFieldRecursive( array $fields, ?array $inputFieldTypes = null ): bool { foreach ( $fields as $field ) { if ( ! is_array( $field ) ) { continue; } if ( isset( $field['type'] ) && is_string( $field['type'] ) && self::takesAnswer( $field['type'] ) ) { return true; } // 'children' is the canonical key written by the JS serializer (denormalizeTree). // 'fields' is the legacy key kept for backward-compat. foreach ( array( 'children', 'fields' ) as $childKey ) { if ( isset( $field[ $childKey ] ) && is_array( $field[ $childKey ] ) ) { if ( $this->hasInputFieldRecursive( $field[ $childKey ], $inputFieldTypes ) ) { return true; } } } if ( isset( $field['columns'] ) && is_array( $field['columns'] ) && substr( (string) ( $field['type'] ?? '' ), -10 ) === '_container' ) { foreach ( $field['columns'] as $column ) { if ( is_array( $column ) && $this->hasInputFieldRecursive( $column, $inputFieldTypes ) ) { return true; } } } } return false; } }