*/ public static function defaults(): array { return [ 'title' => '', 'description' => '', 'canonical' => '', 'robots' => [ 'index' => true, 'follow' => true, 'noarchive' => false, 'noimageindex' => false, 'nosnippet' => false, 'max_snippet' => null, 'max_image_preview' => null, 'max_video_preview' => null, ], 'og' => [ 'title' => '', 'description' => '', 'image' => '', 'image_alt' => '', 'image_id' => 0, 'type' => '', ], 'twitter' => [ 'card' => 'summary_large_image', 'title' => '', 'description' => '', 'image' => '', 'image_id' => 0, ], 'focus_keywords' => [], 'schema' => [], 'flags' => [ 'pillar' => false, 'cornerstone' => false, 'breadcrumb_title' => '', ], ]; } /** * Normalize an X or Twitter handle to its bare, bounded form. * * Shared by head rendering and the admin save path so both agree on * what a stored handle means. The renderer prefixes the emitted value * with an at sign, so this returns the handle without one. * * @param mixed $handle Raw handle. * @return string Bare handle, empty when nothing valid remains. */ public static function sanitizeTwitterHandle( mixed $handle ): string { $handle = is_scalar( $handle ) ? trim( (string) $handle ) : ''; if ( str_starts_with( $handle, '@' ) ) { $handle = substr( $handle, 1 ); } $handle = preg_replace( '/[^A-Za-z0-9_]/', '', $handle ) ?? ''; return substr( $handle, 0, 15 ); } /** * Decode a stored meta value to a payload array. * * Object typed meta is serialized by core on write, older rows may * hold JSON, so both shapes decode. Anything unreadable yields an * empty array (callers fail open). * * @param mixed $raw Stored meta value. * @return array Payload array or empty array. */ public static function decodeMetaValue( mixed $raw ): array { if ( is_array( $raw ) ) { return $raw; } if ( ! is_string( $raw ) || '' === $raw ) { return []; } if ( str_starts_with( $raw, 'a:' ) || str_starts_with( $raw, 'O:' ) ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- decodes legacy serialized rows with object creation disabled, JSON handled below. $unserialized = unserialize( $raw, [ 'allowed_classes' => false ] ); if ( false !== $unserialized && is_array( $unserialized ) ) { return $unserialized; } return []; } $decoded = json_decode( $raw, true ); if ( is_array( $decoded ) ) { return $decoded; } return []; } /** * Deep-sanitize a payload array. * * Unknown top-level keys are dropped; missing keys are filled from defaults. * * @param mixed $payload Raw payload. * @return array */ public static function sanitize( mixed $payload ): array { $defaults = self::defaults(); // WordPress can call a registered meta sanitize callback with a scalar, // for example a form field value or a write from other code. A strict // array parameter would throw a type error, so non array input is // mapped to the same shape an empty array produces instead. if ( ! is_array( $payload ) ) { return $defaults; } $out = $defaults; if ( isset( $payload['title'] ) ) { $out['title'] = sanitize_text_field( self::scalarString( $payload['title'] ) ); } if ( isset( $payload['description'] ) ) { $out['description'] = sanitize_text_field( self::scalarString( $payload['description'] ) ); } if ( isset( $payload['canonical'] ) ) { $canonical = esc_url_raw( self::scalarString( $payload['canonical'] ) ); // Protocol-relative or off-site canonicals are dropped so an // editor value can never point the canonical off-site. Empty // falls back to the permalink at render time. if ( '' !== $canonical && ! self::isHomeUrl( $canonical ) ) { $canonical = ''; } $out['canonical'] = $canonical; } if ( isset( $payload['robots'] ) && is_array( $payload['robots'] ) ) { $robots = $payload['robots']; foreach ( [ 'index', 'follow', 'noarchive', 'noimageindex', 'nosnippet' ] as $flag ) { if ( ! array_key_exists( $flag, $robots ) ) { continue; } // A nested array is malformed input, not truthy input. Keep // the documented default instead of silently flipping the // flag through PHP's array to bool coercion. $value = self::nullableBool( $robots[ $flag ] ); if ( null !== $value ) { $out['robots'][ $flag ] = $value; } } // A non numeric string normalizes to null, never 0: 0 is the // explicit "no snippet" budget, so coercing malformed input to // it would silently change meaning. if ( array_key_exists( 'max_snippet', $robots ) ) { $out['robots']['max_snippet'] = self::nullableInt( $robots['max_snippet'] ); } if ( array_key_exists( 'max_image_preview', $robots ) ) { $out['robots']['max_image_preview'] = self::previewValue( $robots['max_image_preview'] ); } if ( array_key_exists( 'max_video_preview', $robots ) ) { $out['robots']['max_video_preview'] = self::nullableInt( $robots['max_video_preview'] ); } } if ( isset( $payload['og'] ) && is_array( $payload['og'] ) ) { $og = $payload['og']; if ( array_key_exists( 'title', $og ) ) { $out['og']['title'] = sanitize_text_field( self::scalarString( $og['title'] ) ); } if ( array_key_exists( 'description', $og ) ) { $out['og']['description'] = sanitize_text_field( self::scalarString( $og['description'] ) ); } if ( array_key_exists( 'image', $og ) ) { $out['og']['image'] = esc_url_raw( self::scalarString( $og['image'] ) ); } if ( array_key_exists( 'image_alt', $og ) ) { $out['og']['image_alt'] = sanitize_text_field( self::scalarString( $og['image_alt'] ) ); } if ( array_key_exists( 'image_id', $og ) ) { $out['og']['image_id'] = self::scalarAbsint( $og['image_id'] ); } if ( array_key_exists( 'type', $og ) ) { $out['og']['type'] = sanitize_text_field( self::scalarString( $og['type'] ) ); } } if ( isset( $payload['twitter'] ) && is_array( $payload['twitter'] ) ) { $tw = $payload['twitter']; if ( array_key_exists( 'card', $tw ) ) { $out['twitter']['card'] = sanitize_text_field( self::scalarString( $tw['card'] ) ); } if ( array_key_exists( 'title', $tw ) ) { $out['twitter']['title'] = sanitize_text_field( self::scalarString( $tw['title'] ) ); } if ( array_key_exists( 'description', $tw ) ) { $out['twitter']['description'] = sanitize_text_field( self::scalarString( $tw['description'] ) ); } if ( array_key_exists( 'image', $tw ) ) { $out['twitter']['image'] = esc_url_raw( self::scalarString( $tw['image'] ) ); } if ( array_key_exists( 'image_id', $tw ) ) { $out['twitter']['image_id'] = self::scalarAbsint( $tw['image_id'] ); } } if ( isset( $payload['focus_keywords'] ) && is_array( $payload['focus_keywords'] ) ) { $keywords = []; foreach ( $payload['focus_keywords'] as $kw ) { $clean = sanitize_text_field( self::scalarString( $kw ) ); if ( '' !== $clean ) { $keywords[] = $clean; } } $out['focus_keywords'] = $keywords; } if ( isset( $payload['schema'] ) && is_array( $payload['schema'] ) ) { $out['schema'] = self::sanitizeSchema( $payload['schema'] ); } if ( isset( $payload['flags'] ) && is_array( $payload['flags'] ) ) { $flags = $payload['flags']; if ( array_key_exists( 'pillar', $flags ) ) { $out['flags']['pillar'] = self::nullableBool( $flags['pillar'] ) ?? false; } if ( array_key_exists( 'cornerstone', $flags ) ) { $out['flags']['cornerstone'] = self::nullableBool( $flags['cornerstone'] ) ?? false; } if ( array_key_exists( 'breadcrumb_title', $flags ) ) { $out['flags']['breadcrumb_title'] = sanitize_text_field( self::scalarString( $flags['breadcrumb_title'] ) ); } } return $out; } /** * Cast a string field value without the "Array" trap. * * A nested array posted for a string field must not be cast to the * literal string "Array". Only scalars are cast; anything else becomes * an empty string, which the existing sanitizers already accept. * * @param mixed $value Raw value. * @return string The result. */ private static function scalarString( mixed $value ): string { return is_scalar( $value ) ? (string) $value : ''; } /** * Whether a canonical URL stays on the home host. * * Relative paths, fragments and query strings are allowed. Absolute * and protocol-relative URLs must match the home host so an editor * value can never point the canonical off-site. * * @param string $url Sanitized canonical candidate. * @return bool True when the URL is home-hosted or relative. */ private static function isHomeUrl( string $url ): bool { if ( '' === $url ) { return true; } if ( str_starts_with( $url, '//' ) ) { return false; } $parts = parse_url( $url ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- canonical host check only, result strictly type checked, wp_parse_url unavailable in unit tests. if ( ! is_array( $parts ) ) { return false; } if ( ! isset( $parts['host'] ) ) { // A URL without a host must be relative or protocol-relative; // protocol-relative is rejected above. A scheme without a host // (mailto:, tel:) is never a home-hosted canonical. if ( isset( $parts['scheme'] ) ) { return false; } return true; } if ( ! function_exists( 'home_url' ) ) { return true; } $home_parts = parse_url( (string) home_url( '/' ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- canonical host check only, result strictly type checked, wp_parse_url unavailable in unit tests. if ( ! is_array( $home_parts ) || ! isset( $home_parts['host'] ) ) { return true; } return strtolower( (string) $parts['host'] ) === strtolower( (string) $home_parts['host'] ); } /** * Normalize a boolean field without the array coercion trap. * * Only documented boolean shapes are accepted: real booleans, 0/1 * integers, and the usual checkbox strings. Anything else, including a * nested array or object, returns null so the caller keeps the documented * default rather than PHP's array-to-bool coercion. * * @param mixed $value Raw boolean field. * @return bool|null The result. */ private static function nullableBool( mixed $value ): ?bool { if ( is_bool( $value ) ) { return $value; } if ( is_int( $value ) ) { if ( 0 === $value ) { return false; } if ( 1 === $value ) { return true; } return null; } if ( is_string( $value ) ) { $normalized = strtolower( trim( $value ) ); if ( in_array( $normalized, [ '1', 'true', 'yes', 'on' ], true ) ) { return true; } if ( in_array( $normalized, [ '0', 'false', 'no', 'off', '' ], true ) ) { return false; } } return null; } /** * Normalize an attachment id without the array coercion trap. * * `absint()` on a nested array becomes 1 in PHP, which would silently * attach an unrelated image. Only scalars are accepted; anything else is * zero, the documented "no image" value. * * @param mixed $value Raw id field. * @return int The result. */ private static function scalarAbsint( mixed $value ): int { if ( ! is_scalar( $value ) || ! is_numeric( $value ) ) { return 0; } return absint( $value ); } /** * Normalize a robots budget to a nullable integer. * * Null, an empty string, and any non numeric string become null so a * malformed client value never silently becomes 0. Integers and numeric * strings keep their value. * * @param mixed $value Raw budget value. * @return int|null The result. */ private static function nullableInt( mixed $value ): ?int { if ( is_int( $value ) ) { return $value; } if ( is_float( $value ) ) { return (int) $value; } if ( is_string( $value ) && is_numeric( $value ) ) { return (int) $value; } return null; } /** * Normalize a max-image-preview value to a nullable string. * * Null and blank input become null. Numeric input keeps an integer * shape, any other scalar keeps its sanitized string so "large" and * "standard" survive untouched. * * @param mixed $value Raw preview value. * @return string|int|null The result. */ private static function previewValue( mixed $value ): string|int|null { if ( null === $value || ( is_string( $value ) && '' === trim( $value ) ) ) { return null; } if ( is_int( $value ) ) { return $value; } if ( is_numeric( $value ) ) { return (int) $value; } if ( is_scalar( $value ) ) { return sanitize_text_field( (string) $value ); } return null; } /** * Sanitize the schema payload. * * Empty input stays an empty list so fresh rows stay lean. A legacy * flat list keeps array rows only. Any other non empty array is * normalized to the object shape from the class docblock. * * Legacy list rows are intentionally retained for backward compatibility. * They are never rendered as HTML: the schema graph is JSON-encoded with * HEX flags, and the schema pieces consume only known object fields. Any * unsafe string still passes through `wp_kses_post()` or JSON encoding at * the final sink, so this shape is retained deliberately rather than * being silently rewritten. * * @param array $raw Raw schema value. * @return array|array */ private static function sanitizeSchema( array $raw ): array { if ( [] === $raw ) { return []; } if ( array_is_list( $raw ) ) { $schema = []; foreach ( $raw as $item ) { if ( is_array( $item ) ) { $schema[] = $item; } } return $schema; } $faq = $raw['faq'] ?? []; if ( ! is_array( $faq ) ) { $faq = []; } return [ 'type' => SchemaTypes::normalizeOrEmpty( $raw['type'] ?? null ), 'disabled' => self::nullableBool( $raw['disabled'] ?? null ) ?? false, 'fields' => self::sanitizeSchemaFields( $raw['fields'] ?? [] ), 'faq' => [ 'questions' => self::sanitizeFaqQuestions( $faq['questions'] ?? [] ), ], 'howto' => self::sanitizeHowto( $raw['howto'] ?? [] ), 'custom' => self::sanitizeCustom( $raw['custom'] ?? [] ), ]; } /** * Sanitize the free form string map for per type overrides. * * String keys only, scalar values cast to string, max 50 entries * with each value capped at 2000 chars. Anything else is dropped. * * @param mixed $raw Raw fields value. * @return array */ private static function sanitizeSchemaFields( mixed $raw ): array { if ( ! is_array( $raw ) || [] === $raw ) { return []; } $fields = []; foreach ( $raw as $key => $value ) { if ( count( $fields ) >= 50 ) { break; } $name = sanitize_text_field( (string) $key ); if ( '' === $name ) { continue; } if ( ! is_scalar( $value ) ) { continue; } $fields[ $name ] = self::truncate( (string) $value, 2000 ); } return $fields; } /** * Sanitize FAQ rows. * * Each row keeps a question and answer pair. Rows with an empty * question are dropped. Kept rows cap at 100. The answer keeps * safe rich HTML through the same wp_kses_post path the block * output uses, so formatting survives regardless of source. * * @param mixed $raw Raw questions value. * @return array */ private static function sanitizeFaqQuestions( mixed $raw ): array { if ( ! is_array( $raw ) ) { return []; } $rows = []; foreach ( $raw as $row ) { if ( count( $rows ) >= 100 ) { break; } if ( ! is_array( $row ) ) { continue; } $question = isset( $row['question'] ) ? sanitize_text_field( self::scalarString( $row['question'] ) ) : ''; if ( '' === trim( $question ) ) { continue; } $answer = isset( $row['answer'] ) ? self::kses( self::scalarString( $row['answer'] ) ) : ''; $rows[] = [ 'question' => $question, 'answer' => $answer, ]; } return array_values( $rows ); } /** * Sanitize the HowTo block. * * Steps keep title, text, and image (image via esc_url_raw). Rows * with both an empty title and empty text are dropped. Kept steps * cap at 100. Name, totalTime, and cost stay plain strings. Step * text keeps safe rich HTML through the same wp_kses_post path * the block output uses, so formatting survives regardless of * source. * * @param mixed $raw Raw howto value. * @return array{name: string, steps: array, totalTime: string, cost: string} */ private static function sanitizeHowto( mixed $raw ): array { $out = [ 'name' => '', 'steps' => [], 'totalTime' => '', 'cost' => '', ]; if ( ! is_array( $raw ) || array_is_list( $raw ) ) { return $out; } if ( isset( $raw['name'] ) ) { $out['name'] = sanitize_text_field( self::scalarString( $raw['name'] ) ); } if ( isset( $raw['steps'] ) && is_array( $raw['steps'] ) ) { $steps = []; foreach ( $raw['steps'] as $row ) { if ( count( $steps ) >= 100 ) { break; } if ( ! is_array( $row ) ) { continue; } $title = isset( $row['title'] ) ? sanitize_text_field( self::scalarString( $row['title'] ) ) : ''; $text = isset( $row['text'] ) ? self::kses( self::scalarString( $row['text'] ) ) : ''; if ( '' === trim( $title ) && '' === trim( $text ) ) { continue; } $image = isset( $row['image'] ) ? esc_url_raw( self::scalarString( $row['image'] ) ) : ''; $steps[] = [ 'title' => $title, 'text' => $text, 'image' => $image, ]; } $out['steps'] = array_values( $steps ); } if ( isset( $raw['totalTime'] ) ) { $out['totalTime'] = sanitize_text_field( self::scalarString( $raw['totalTime'] ) ); } if ( isset( $raw['cost'] ) ) { $out['cost'] = sanitize_text_field( self::scalarString( $raw['cost'] ) ); } return $out; } /** * Filter rich text through wp_kses_post. * * Mirrors the block piece path so the same content keeps its * formatting regardless of authoring source. Falls back to * strip_tags when WP is not loaded, as in unit tests. * * @param string $text Raw text. * @return string The result. */ private static function kses( string $text ): string { if ( function_exists( 'wp_kses_post' ) ) { $clean = wp_kses_post( $text ); if ( is_string( $clean ) ) { return $clean; } } // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- fallback for contexts without WP loaded, where wp_strip_all_tags is also unavailable. return strip_tags( $text ); } /** * Sanitize the raw JSON object for advanced users. * * Keeps JSON safe scalars (plus null) and arrays. PHP objects, * resources, and other shapes are dropped. Nesting deeper than 5 * levels is cut, total keys cap at 200. Invalid content becomes * an empty array. * * @param mixed $raw Raw custom value. * @return array */ private static function sanitizeCustom( mixed $raw ): array { if ( ! is_array( $raw ) || [] === $raw ) { return []; } $keys = 0; return self::sanitizeCustomArray( $raw, 1, $keys ); } /** * Recurse into a custom value level. * * @param array $raw Raw level. * @param int $depth Current depth, starts at 1. * @param int $keys Running total of kept keys. * @return array */ private static function sanitizeCustomArray( array $raw, int $depth, int &$keys ): array { $out = []; if ( $depth > 5 ) { return []; } foreach ( $raw as $key => $value ) { if ( $keys >= 200 ) { break; } if ( is_array( $value ) ) { $out[ $key ] = self::sanitizeCustomArray( $value, $depth + 1, $keys ); ++$keys; } elseif ( is_scalar( $value ) || null === $value ) { $out[ $key ] = $value; ++$keys; } } return $out; } /** * Cap a string at a max length, multibyte safe when available. * * @param string $value Raw string. * @param int $max Max length in chars. * @return string The result. */ private static function truncate( string $value, int $max ): string { if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) { if ( mb_strlen( $value ) <= $max ) { return $value; } $cut = mb_substr( $value, 0, $max ); return $cut; } if ( strlen( $value ) <= $max ) { return $value; } $cut = substr( $value, 0, $max ); return $cut; } /** * Get permissive schema for per-user prefs (_rankkernel_user_prefs). * * Allows arbitrary keys with scalar or array-of-scalar values. * * @return array */ public static function userPrefsSchema(): array { return [ 'type' => 'object', 'additionalProperties' => [ 'oneOf' => [ [ 'type' => 'string' ], [ 'type' => 'integer' ], [ 'type' => 'number' ], [ 'type' => 'boolean' ], [ 'type' => 'array', 'items' => [ 'oneOf' => [ [ 'type' => 'string' ], [ 'type' => 'integer' ], [ 'type' => 'number' ], [ 'type' => 'boolean' ], ], ], ], [ 'type' => 'object', 'additionalProperties' => true, ], ], ], ]; } /** * Get REST schema for register_meta show_in_rest. * * @return array */ public static function restSchema(): array { return [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'title' => [ 'type' => 'string' ], 'description' => [ 'type' => 'string' ], 'canonical' => [ 'type' => 'string', 'format' => 'uri', ], 'robots' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'index' => [ 'type' => 'boolean' ], 'follow' => [ 'type' => 'boolean' ], 'noarchive' => [ 'type' => 'boolean' ], 'noimageindex' => [ 'type' => 'boolean' ], 'nosnippet' => [ 'type' => 'boolean' ], // max_snippet and max_video_preview accept a string // so an over loose client can never hard block a save // with an empty or malformed value; sanitize() is the // authority that turns those into null. 'max_snippet' => [ 'type' => [ 'integer', 'string', 'null' ] ], 'max_image_preview' => [ 'type' => [ 'string', 'integer', 'null' ] ], 'max_video_preview' => [ 'type' => [ 'integer', 'string', 'null' ] ], ], ], 'og' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'title' => [ 'type' => 'string' ], 'description' => [ 'type' => 'string' ], 'image' => [ 'type' => 'string', 'format' => 'uri', ], 'image_alt' => [ 'type' => 'string' ], 'image_id' => [ 'type' => 'integer' ], 'type' => [ 'type' => 'string' ], ], ], 'twitter' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'card' => [ 'type' => 'string' ], 'title' => [ 'type' => 'string' ], 'description' => [ 'type' => 'string' ], 'image' => [ 'type' => 'string', 'format' => 'uri', ], 'image_id' => [ 'type' => 'integer' ], ], ], 'focus_keywords' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ], ], 'schema' => [ 'type' => 'object', 'properties' => [ 'type' => [ 'type' => 'string' ], 'fields' => [ 'type' => 'object', 'additionalProperties' => [ 'type' => 'string' ], ], 'faq' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'questions' => [ 'type' => 'array', 'items' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'question' => [ 'type' => 'string' ], 'answer' => [ 'type' => 'string' ], ], ], ], ], ], 'howto' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'name' => [ 'type' => 'string' ], 'steps' => [ 'type' => 'array', 'items' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'title' => [ 'type' => 'string' ], 'text' => [ 'type' => 'string' ], 'image' => [ 'type' => 'string', 'format' => 'uri', ], ], ], ], 'totalTime' => [ 'type' => 'string' ], 'cost' => [ 'type' => 'string' ], ], ], 'custom' => [ 'type' => 'object' ], ], ], 'flags' => [ 'type' => 'object', 'additionalProperties' => false, 'properties' => [ 'pillar' => [ 'type' => 'boolean' ], 'cornerstone' => [ 'type' => 'boolean' ], 'breadcrumb_title' => [ 'type' => 'string' ], ], ], ], ]; } }