few large files"). * * Numeric and string-length bounds not explicitly given by the shared * contract (e.g. a word-count ceiling, or how many banned phrases a * blueprint may list) are this class's own, deliberately generous, * documented limits, not a product requirement. They exist only so * "reject out-of-range values" has a concrete range to enforce for every * numeric/array field, including ones the shared contract left open. * * @package AIPT\Core\ContentStructure\Domain * @since 2.8.0 */ namespace AIPT\Core\ContentStructure\Domain; defined( 'ABSPATH' ) || exit; /** * Stateless validators shared by DefinitionNormalizer's per-generator logic. */ final class DefinitionPrimitives { const AI_ITEMS_MIN = 1; const AI_ITEMS_MAX = 20; const DATA_ITEMS_MIN = 1; const DATA_ITEMS_MAX = 50; const TITLE_PARTS_MIN = 1; const TITLE_PARTS_MAX = 10; const TITLE_MAX_CHARS_MIN = 30; const TITLE_MAX_CHARS_MAX = 200; const FAQ_GROUP_COUNT_MIN = 1; const FAQ_GROUP_COUNT_MAX = 6; const FAQ_MAX_QUESTIONS_MIN = 1; const FAQ_MAX_QUESTIONS_MAX = 20; const IMAGE_ALT_MAX_CHARS_MIN = 40; const IMAGE_ALT_MAX_CHARS_MAX = 250; const TAXONOMY_SAMPLE_PRODUCTS_MIN = 5; const TAXONOMY_SAMPLE_PRODUCTS_MAX = 20; const NAME_MAX_LEN = 80; const HEADING_TEXT_MAX_LEN = 120; const FOCUS_MAX_LEN = 200; const FIXED_TEXT_MAX_LEN = 4000; const FALLBACK_TEXT_MAX_LEN = 600; const INSTRUCTION_MAX_LEN = 500; const RULE_INSTRUCTION_TEXT_MAX_LEN = 1000; const RULE_INSTRUCTIONS_MAX = 10; const TITLE_PART_TEXT_MAX_LEN = 60; const TITLE_KEYWORDS_MAX = 10; const TITLE_KEYWORD_MAX_LEN = 60; const SECTIONS_MAX = 20; const CONDITION_VALUE_MAX_LEN = 200; const VOICE_NOTE_MAX_LEN = 500; const BANNED_PHRASE_MAX_LEN = 100; const BANNED_PHRASES_MAX = 50; const ALLOWED_DOMAINS_MAX = 50; const ALLOWED_DOMAIN_MAX_LEN = 255; const SOURCE_POLICY_ITEMS_MAX = 50; const PRODUCT_FIELDS_MAX = 50; const WORD_TARGET_MAX = 1000; const HARD_WORD_LIMIT_MAX = 5000; const PART_MAX_CHARS_MAX = 200; const TOKEN_TEXT_MAX_LEN = 60; const SEO_TITLE_CHARS_MAX = 300; const SEO_DESC_CHARS_MAX = 500; const FAQ_ANSWER_TARGET_MAX = 400; const FAQ_ANSWER_HARD_MAX = 800; const GROUP_TOPIC_MAX_LEN = 200; const CONDITION_OPERATORS = array( 'not_empty', 'empty', 'equals', 'contains' ); /** * Build one error/notice record. * * @param string $path Dotted/indexed path, e.g. "structure.sections[2].length.targetMax". * @param string $code Short machine-readable code. * @param string $message Human-readable message. * @return array{path:string,code:string,message:string} */ public static function issue( string $path, string $code, string $message ): array { return array( 'path' => $path, 'code' => $code, 'message' => $message, ); } /** * Coerce to bool, defaulting when the input is not already a bool. * * @param mixed $value Candidate value. * @param bool $default Default when $value isn't a bool. * @return bool */ public static function boolOr( $value, bool $default ): bool { return is_bool( $value ) ? $value : $default; } /** * Validate that $value is one of $allowed (strict string match). * * @param mixed $value Candidate value. * @param string[] $allowed Allowed values. * @return bool */ public static function inEnum( $value, array $allowed ): bool { return is_string( $value ) && in_array( $value, $allowed, true ); } /** * Section/part/token/group id shape: one lowercase letter followed by * 2-39 lowercase letters, digits, underscores or dashes (3-40 chars * total): the `BlueprintSection.id` pattern, reused for * every other id in the schema. * * @param mixed $value Candidate id. * @return bool */ public static function isValidId( $value ): bool { return is_string( $value ) && 1 === preg_match( '/^[a-z][a-z0-9_-]{2,39}$/D', $value ); } /** * Sanitize a single-line plain-text field and report whether it exceeds * $max_len (caller decides whether that is a rejectable error). * * @param mixed $value Raw value. * @param int $max_len Maximum character length. * @return array{value:string,overLimit:bool} */ public static function singleLineText( $value, int $max_len ): array { $text = is_string( $value ) ? trim( sanitize_text_field( $value ) ) : ''; return array( 'value' => $text, 'overLimit' => mb_strlen( $text, 'UTF-8' ) > $max_len, ); } /** * Sanitize a multi-line plain-text field (line breaks preserved) and * report whether it exceeds $max_len. * * @param mixed $value Raw value. * @param int $max_len Maximum character length. * @return array{value:string,overLimit:bool} */ public static function multiLineText( $value, int $max_len ): array { $text = is_string( $value ) ? trim( sanitize_textarea_field( $value ) ) : ''; return array( 'value' => $text, 'overLimit' => mb_strlen( $text, 'UTF-8' ) > $max_len, ); } /** * Sanitize `fixedText` with the Blueprint fixed-text HTML allowlist * (p, br, strong, em, b, i, a[href], ul, ol, li) and * report whether sanitization changed the text (caller emits a notice, * never silently). * * @param mixed $value Raw value. * @return array{value:string,changed:bool,overLimit:bool} */ public static function fixedText( $value ): array { $raw = is_string( $value ) ? trim( $value ) : ''; $allowed = array( 'p' => array(), 'br' => array(), 'strong' => array(), 'em' => array(), 'b' => array(), 'i' => array(), 'a' => array( 'href' => true ), 'ul' => array(), 'ol' => array(), 'li' => array(), ); $sanitized = '' !== $raw ? wp_kses( $raw, $allowed ) : ''; $normalized_raw = ( '' !== $raw && function_exists( 'wp_kses_normalize_entities' ) ) ? wp_kses_normalize_entities( $raw ) : $raw; return array( 'value' => $sanitized, 'changed' => $sanitized !== $normalized_raw, 'overLimit' => mb_strlen( $sanitized, 'UTF-8' ) > self::FIXED_TEXT_MAX_LEN, ); } /** * Normalize a WordRange {targetMin, targetMax, hardMax}. * * @param mixed $input Raw input (expected array). * @param array $default Default WordRange when a key is missing. * @param string $path Error path prefix. * @param array &$errors Collected errors. * @return array{targetMin:int,targetMax:int,hardMax:int|null} */ public static function wordRange( $input, array $default, string $path, array &$errors ): array { $input = is_array( $input ) ? $input : array(); $target_min = self::intOr( $input['targetMin'] ?? null, $default['targetMin'] ); $target_max = self::intOr( $input['targetMax'] ?? null, $default['targetMax'] ); $hard_max = array_key_exists( 'hardMax', $input ) ? $input['hardMax'] : $default['hardMax']; if ( $target_min < 0 || $target_min > self::WORD_TARGET_MAX ) { $errors[] = self::issue( $path . '.targetMin', 'out_of_range', __( 'Target minimum is out of range.', 'ai-product-tools' ) ); } if ( $target_max < 0 || $target_max > self::WORD_TARGET_MAX ) { $errors[] = self::issue( $path . '.targetMax', 'out_of_range', __( 'Target maximum is out of range.', 'ai-product-tools' ) ); } if ( $target_min > $target_max ) { $errors[] = self::issue( $path . '.targetMax', 'invalid_range', __( 'Target maximum must be at least the target minimum.', 'ai-product-tools' ) ); } if ( null !== $hard_max ) { $hard_max = self::intOr( $hard_max, 0 ); if ( $hard_max > self::HARD_WORD_LIMIT_MAX || $hard_max < 0 ) { $errors[] = self::issue( $path . '.hardMax', 'out_of_range', __( 'Hard maximum is out of range.', 'ai-product-tools' ) ); } elseif ( $hard_max < $target_max ) { $errors[] = self::issue( $path . '.hardMax', 'invalid_range', __( 'Hard maximum must be at least the target maximum.', 'ai-product-tools' ) ); } } return array( 'targetMin' => $target_min, 'targetMax' => $target_max, 'hardMax' => $hard_max, ); } /** * Normalize an `items` cap {max}. * * Item length follows the section's length range and the template's * detail level. A `targetWords` key saved by an earlier version, which * no screen set and generation never read, is dropped. * * @param mixed $input Raw input (expected array). * @param array $default Default when a key is missing. * @param string $mode 'ai' (1..20) or 'data' (1..50) — decides the bound on `max`. * @param string $path Error path prefix. * @param array &$errors Collected errors. * @return array{max:int} */ public static function items( $input, array $default, string $mode, string $path, array &$errors ): array { $input = is_array( $input ) ? $input : array(); $min = 'data' === $mode ? self::DATA_ITEMS_MIN : self::AI_ITEMS_MIN; $max_bound = 'data' === $mode ? self::DATA_ITEMS_MAX : self::AI_ITEMS_MAX; $max = self::intOr( $input['max'] ?? null, $default['max'] ); if ( $max < $min || $max > $max_bound ) { $errors[] = self::issue( $path . '.max', 'out_of_range', __( 'Item limit is out of range.', 'ai-product-tools' ) ); } return array( 'max' => $max ); } /** * Normalize a `heading` {mode, text}. * * @param mixed $input Raw input (expected array). * @param array $default Default when a key is missing. * @param string $path Error path prefix. * @param array &$errors Collected errors. * @return array{mode:string,text:string} */ public static function heading( $input, array $default, string $path, array &$errors ): array { $input = is_array( $input ) ? $input : array(); $mode = $input['mode'] ?? $default['mode']; if ( ! self::inEnum( $mode, array( 'none', 'fixed', 'ai' ) ) ) { $errors[] = self::issue( $path . '.mode', 'invalid_enum', __( 'Invalid heading mode.', 'ai-product-tools' ) ); $mode = $default['mode']; } $text_result = self::singleLineText( $input['text'] ?? $default['text'], self::HEADING_TEXT_MAX_LEN ); if ( $text_result['overLimit'] ) { $errors[] = self::issue( $path . '.text', 'too_long', __( 'Heading text is too long.', 'ai-product-tools' ) ); } return array( 'mode' => $mode, 'text' => $text_result['value'], ); } /** * Normalize a `missing` {policy, fallbackText}. * * @param mixed $input Raw input (expected array). * @param array $default Default when a key is missing. * @param string[] $allowed_policies Allowed policy values for this unit kind. * @param string $path Error path prefix. * @param array &$errors Collected errors. * @return array{policy:string,fallbackText:string} */ public static function missingPolicy( $input, array $default, array $allowed_policies, string $path, array &$errors ): array { $input = is_array( $input ) ? $input : array(); $policy = $input['policy'] ?? $default['policy']; if ( ! self::inEnum( $policy, $allowed_policies ) ) { $errors[] = self::issue( $path . '.policy', 'invalid_enum', __( 'Invalid missing-data policy.', 'ai-product-tools' ) ); $policy = $allowed_policies[0]; } $fallback_result = self::multiLineText( $input['fallbackText'] ?? $default['fallbackText'], self::FALLBACK_TEXT_MAX_LEN ); if ( $fallback_result['overLimit'] ) { $errors[] = self::issue( $path . '.fallbackText', 'too_long', __( 'Fallback text is too long.', 'ai-product-tools' ) ); } return array( 'policy' => $policy, 'fallbackText' => $fallback_result['value'], ); } /** * Whether $ref is a usable FieldRef: known to FieldCatalog for $scope, * and — for a `meta:` ref specifically — both allowlisted AND the * caller's context explicitly allows custom fields for this normalize() * call ("meta: refs only if allowlisted and allowCustomFields"). * Omitting the context flag fails closed. * * @param string $ref Candidate FieldRef. * @param FieldCatalog $fields Field catalog. * @param string $scope 'product' | 'term' | 'image'. * @param bool $allow_custom_fields Context flag. * @return bool */ public static function validFieldRef( string $ref, FieldCatalog $fields, string $scope, bool $allow_custom_fields ): bool { if ( $fields->isStoredRef( $ref ) ) { return true; } if ( 0 === strpos( $ref, 'meta:' ) && ! $allow_custom_fields ) { return false; } return $fields->isValidRef( $ref, $scope ); } /** * Message for a field ref that is not available, naming the ref so the * merchant can find it. * * @param mixed $ref Submitted FieldRef. * @return string */ public static function unavailableFieldMessage( $ref ): string { if ( ! is_string( $ref ) || '' === $ref ) { return __( 'This field is not available.', 'ai-product-tools' ); } /* translators: %s: field reference such as meta:material. */ return sprintf( __( 'The field "%s" is not available. Remove it to save.', 'ai-product-tools' ), $ref ); } /** * Normalize a `condition` {enabled, field, operator, value}. `field` is * validated as a real FieldRef only when enabled === true: a disabled * condition's field is never evaluated, so an inert placeholder (e.g. * '') is not an error (see SectionCatalog's class docblock for why the * catalog default ships this way). * * @param mixed $input Raw input (expected array). * @param array $default Default when a key is missing. * @param FieldCatalog $fields Field catalog. * @param string $scope 'product' | 'term' | 'image'. * @param bool $allow_custom_fields Context flag. * @param string $path Error path prefix. * @param array &$errors Collected errors. * @return array{enabled:bool,field:string,operator:string,value:string} */ public static function condition( $input, array $default, FieldCatalog $fields, string $scope, bool $allow_custom_fields, string $path, array &$errors ): array { $input = is_array( $input ) ? $input : array(); $enabled = self::boolOr( $input['enabled'] ?? $default['enabled'], false ); $field = is_string( $input['field'] ?? null ) ? $input['field'] : $default['field']; if ( $enabled && '' !== $field && ! self::validFieldRef( $field, $fields, $scope, $allow_custom_fields ) ) { $errors[] = self::issue( $path . '.field', 'invalid_field_ref', __( 'This field is not available for a condition.', 'ai-product-tools' ) ); } $operator = $input['operator'] ?? $default['operator']; if ( ! self::inEnum( $operator, self::CONDITION_OPERATORS ) ) { $errors[] = self::issue( $path . '.operator', 'invalid_enum', __( 'Invalid condition operator.', 'ai-product-tools' ) ); $operator = self::CONDITION_OPERATORS[0]; } $value_result = self::singleLineText( $input['value'] ?? $default['value'], self::CONDITION_VALUE_MAX_LEN ); if ( $value_result['overLimit'] ) { $errors[] = self::issue( $path . '.value', 'too_long', __( 'Condition value is too long.', 'ai-product-tools' ) ); } return array( 'enabled' => $enabled, 'field' => $field, 'operator' => $operator, 'value' => $value_result['value'], ); } /** * Normalize a `sources` selection {inherit, refs}. Each ref must be * 'product' or 'src:' with in $known_source_ids. * * @param mixed $input Raw input (expected array). * @param array $default Default when a key is missing. * @param int[] $known_source_ids Ids valid for 'src:' refs. * @param string $path Error path prefix. * @param array &$errors Collected errors. * @return array{inherit:bool,refs:string[]} */ public static function sectionSources( $input, array $default, array $known_source_ids, string $path, array &$errors ): array { $input = is_array( $input ) ? $input : array(); $inherit = self::boolOr( $input['inherit'] ?? $default['inherit'], true ); $raw_refs = is_array( $input['refs'] ?? null ) ? $input['refs'] : $default['refs']; if ( count( $raw_refs ) > self::SOURCE_POLICY_ITEMS_MAX ) { $errors[] = self::issue( $path . '.refs', 'too_many', __( 'Too many sources selected.', 'ai-product-tools' ) ); $raw_refs = array_slice( $raw_refs, 0, self::SOURCE_POLICY_ITEMS_MAX ); } $refs = array(); foreach ( $raw_refs as $i => $ref ) { if ( self::isValidSourceRef( $ref, $known_source_ids ) ) { $refs[] = $ref; } else { $errors[] = self::issue( $path . '.refs[' . $i . ']', 'unknown_source_ref', __( 'Unknown source reference.', 'ai-product-tools' ) ); } } return array( 'inherit' => $inherit, 'refs' => $refs, ); } /** * Whether $ref is 'product' or 'src:' with known. * * @param mixed $ref Candidate SourceRef. * @param int[] $known_source_ids Ids valid for 'src:' refs. * @return bool */ public static function isValidSourceRef( $ref, array $known_source_ids ): bool { if ( 'product' === $ref ) { return true; } if ( ! is_string( $ref ) || 1 !== preg_match( '/^src:(\d+)$/D', $ref, $match ) ) { return false; } return in_array( (int) $match[1], $known_source_ids, true ); } /** * Normalize a `fields` selection {mode, keys} (data mode field picker). * * @param mixed $input Raw input (expected array). * @param array $default Default when a key is missing. * @param FieldCatalog $fields Field catalog. * @param string $scope 'product' | 'term' | 'image'. * @param bool $allow_custom_fields Context flag. * @param string $path Error path prefix. * @param array &$errors Collected errors. * @return array{mode:string,keys:string[]} */ public static function fields( $input, array $default, FieldCatalog $fields, string $scope, bool $allow_custom_fields, string $path, array &$errors ): array { $input = is_array( $input ) ? $input : array(); $mode = $input['mode'] ?? $default['mode']; if ( ! self::inEnum( $mode, array( 'all', 'selected' ) ) ) { $errors[] = self::issue( $path . '.mode', 'invalid_enum', __( 'Invalid field selection mode.', 'ai-product-tools' ) ); $mode = 'all'; } if ( 'all' !== $mode ) { $raw_keys = is_array( $input['keys'] ?? null ) ? $input['keys'] : $default['keys']; if ( count( $raw_keys ) > self::PRODUCT_FIELDS_MAX ) { $errors[] = self::issue( $path . '.keys', 'too_many', __( 'Too many fields selected.', 'ai-product-tools' ) ); $raw_keys = array_slice( $raw_keys, 0, self::PRODUCT_FIELDS_MAX ); } $keys = array(); foreach ( $raw_keys as $i => $key ) { if ( is_string( $key ) && self::validFieldRef( $key, $fields, $scope, $allow_custom_fields ) ) { $keys[] = $key; } else { $errors[] = self::issue( $path . '.keys[' . $i . ']', 'invalid_field_ref', self::unavailableFieldMessage( $key ) ); } } } else { $keys = array(); } return array( 'mode' => $mode, 'keys' => $keys, ); } /** * Flag a DATA-mode section left in "selected" fields mode with nothing * selected: it would resolve to no content at all, so saving it is * rejected instead of silently accepted (audit item * `definition-semantic-validation-gaps`). "All attributes" mode (whose * `keys` is always empty by contract) and every non-data mode are never * flagged. * * Gated by $validate_on_save so this only runs when a definition is * actually being saved (create/update): an already-stored * definition resolved for execution (a run pin, a live/manual pick, or a * built-in template) must keep executing unchanged even if it predates * this rule. Also gated by the section's own $enabled, the same way the * sibling whole-blueprint check (requireAnEnabledSection()) only counts * enabled sections: a section the merchant has deliberately turned off * never runs at generation time, so it being incomplete must not block * saving an otherwise-valid blueprint (audit item * `disabled-section-blocks-save-via-new-validation`). * * @param string $mode Normalized section `mode`. * @param array $fields Normalized `fields` {mode,keys}. * @param bool $enabled Normalized section `enabled`. * @param bool $validate_on_save Whether this normalize() call is a save. * @param string $path This section's own error path (no trailing dot). * @param array &$errors Collected errors. */ public static function requireDataFieldsSelected( string $mode, array $fields, bool $enabled, bool $validate_on_save, string $path, array &$errors ): void { if ( ! $validate_on_save || ! $enabled || 'data' !== $mode || 'selected' !== $fields['mode'] || ! empty( $fields['keys'] ) ) { return; } $errors[] = self::issue( $path . '.fields', 'no_fields_selected', __( 'This section has no fields selected.', 'ai-product-tools' ) ); } /** * Flag a FIXED-mode section with no text: it would render as an empty * block. Gated by $validate_on_save and by the section's own $enabled * (see requireDataFieldsSelected()). * * @param string $mode Normalized section `mode`. * @param string $fixed_text Normalized (sanitized) `fixedText`. * @param bool $enabled Normalized section `enabled`. * @param bool $validate_on_save Whether this normalize() call is a save. * @param string $path This section's own error path (no trailing dot). * @param array &$errors Collected errors. */ public static function requireFixedTextPresent( string $mode, string $fixed_text, bool $enabled, bool $validate_on_save, string $path, array &$errors ): void { if ( ! $validate_on_save || ! $enabled || 'fixed' !== $mode || '' !== trim( $fixed_text ) ) { return; } $errors[] = self::issue( $path . '.fixedText', 'fixed_text_empty', __( 'This fixed section has no text.', 'ai-product-tools' ) ); } /** * Flag a section-list blueprint with no enabled section (none at all, or * every one turned off): it would generate no content whatsoever, * including the "Start blank" starting point itself (an empty `sections` * list vacuously has no enabled section). Gated by $validate_on_save * (see requireDataFieldsSelected()); "Start blank" still opens a normal, * editable, unsaved draft client-side, only its save is rejected. * * @param array[] $sections Normalized BlueprintSection list. * @param bool $validate_on_save Whether this normalize() call is a save. * @param string $path The whole section list's error path (no index). * @param array &$errors Collected errors. */ public static function requireAnEnabledSection( array $sections, bool $validate_on_save, string $path, array &$errors ): void { if ( ! $validate_on_save ) { return; } foreach ( $sections as $section ) { if ( ! empty( $section['enabled'] ) ) { return; } } $errors[] = self::issue( $path, 'no_enabled_section', __( 'Turn on at least one section.', 'ai-product-tools' ) ); } /** * Validate an id's format and uniqueness within its own list. Invalid * or duplicate ids are rejected (error), never silently replaced: * section ids are validated and must be unique, with duplicates * rejected. * * @param mixed $value Raw id value. * @param string $path Error path for this item (no trailing dot). * @param array &$seen_ids Ids already used earlier in this list (mutated). * @param array &$errors Collected errors. * @return string The id as given (even when invalid; callers persist * whatever was sent so a rejected save round-trips to the * same error rather than a different, silently-assigned id). */ public static function normalizeId( $value, string $path, array &$seen_ids, array &$errors ): string { $id = is_string( $value ) ? $value : ''; if ( ! self::isValidId( $id ) ) { $errors[] = self::issue( $path . '.id', 'invalid_format', __( 'Invalid id.', 'ai-product-tools' ) ); } elseif ( isset( $seen_ids[ $id ] ) ) { $errors[] = self::issue( $path . '.id', 'duplicate_id', __( 'Duplicate id.', 'ai-product-tools' ) ); } else { $seen_ids[ $id ] = true; } return $id; } /** * Coerce to int, defaulting when the input is not numeric. * * @param mixed $value Candidate value. * @param mixed $default Default when $value is not numeric. * @return int */ public static function intOr( $value, $default ): int { if ( is_int( $value ) ) { return $value; } if ( is_numeric( $value ) ) { return (int) $value; } return is_numeric( $default ) ? (int) $default : 0; } }