node tree (array). Nothing else. * * Option is created lazily on the first successful save(). Every read is * treated as untrusted input: malformed data degrades to "group absent", * never to a fatal and never to a fail-open. * * Save discipline mirrors Rule_Saver::prepare() (risk stamping, custom * condition authorization, structural validation, limits) EXCEPT that a * group save that fails validation or limits is refused and stores nothing. * A group has no fallback flag and no invalid-state envelope; a stored but * broken group would be indistinguishable from a missing one, so refusing * at save time is the honest behaviour. No gtfg_rule_before_save filter, * no save marker, no ext. */ final class Groups { const OPTION = 'gtfg_groups'; const MAX_ID_LENGTH = 64; /** * All groups. * * @return array id -> node tree. Missing/corrupt option -> empty. */ public static function all() { $raw = function_exists( 'get_option' ) ? get_option( self::OPTION, array() ) : array(); if ( ! is_array( $raw ) ) { return array(); } $out = array(); foreach ( $raw as $id => $tree ) { if ( ! is_string( $id ) || '' === $id ) { continue; } if ( ! self::valid_id( $id ) ) { continue; } if ( ! is_array( $tree ) || ! Rule::looks_like_node( $tree ) ) { continue; } $out[ $id ] = $tree; } return $out; } /** * One group's tree. * * @param mixed $id Group id. * @return array|null Node tree, or null when absent / not a valid node. */ public static function get( $id ) { if ( ! is_string( $id ) || '' === $id || ! self::valid_id( $id ) ) { return null; } $all = self::all(); return isset( $all[ $id ] ) ? $all[ $id ] : null; } /** * Save one group. * * @param mixed $id Group id (will be lowercased and validated). * @param mixed $tree Node tree. * @param int $user_id Saving user id (0 for system writes). * @return true|\WP_Error True on success; WP_Error on refusal. On refusal, * the stored option is unchanged. */ public static function save( $id, $tree, $user_id ) { $id = is_string( $id ) ? strtolower( $id ) : ''; if ( ! self::valid_id( $id ) ) { return self::error( 'invalid_id', __( 'Group ids must be 1-64 characters using a-z, 0-9, hyphen or underscore.', 'gateforge' ) ); } if ( ! is_array( $tree ) || ! Rule::looks_like_node( $tree ) ) { return self::error( 'not_a_node', __( 'The group must be a single rule node.', 'gateforge' ) ); } $shape_error = self::validate_structure( $tree ); if ( null !== $shape_error ) { return self::error( 'malformed', $shape_error ); } $stats = self::measure( $tree ); if ( $stats['nodes'] > Rule::MAX_NODES || $stats['depth'] > Rule::MAX_DEPTH || $stats['max_list'] > Registry::MAX_LIST_ITEMS ) { return self::error( 'too_large', __( 'The group exceeds the depth, node or list-size limit.', 'gateforge' ) ); } $registry = Registry::instance(); $registry->ensure_loaded(); $prior = self::get( $id ); $stamps = array(); if ( null !== $prior ) { self::collect_stamps( $prior, $stamps ); } $stamped = self::stamp( $tree, $registry, $stamps, (int) $user_id ); $all = self::all(); $all[ $id ] = $stamped; // Lazy creation: this is the first and only place the option is written. $updated = function_exists( 'update_option' ) ? update_option( self::OPTION, $all, false ) : false; if ( ! $updated && function_exists( 'add_option' ) ) { $updated = add_option( self::OPTION, $all, '', false ); } if ( ! $updated && function_exists( 'get_option' ) ) { // update_option returns false when the value is unchanged; verify. $check = get_option( self::OPTION ); $updated = is_array( $check ) && isset( $check[ $id ] ) && $check[ $id ] === $stamped; } if ( ! $updated ) { return self::error( 'storage_failed', __( 'The group could not be written to the database.', 'gateforge' ) ); } return true; } /** * Delete one group. Missing id is not an error. * * @param mixed $id Group id. * @return true */ public static function delete( $id ) { $id = is_string( $id ) ? strtolower( $id ) : ''; if ( '' === $id ) { return true; } $all = self::all(); if ( ! isset( $all[ $id ] ) ) { return true; } unset( $all[ $id ] ); if ( function_exists( 'update_option' ) ) { update_option( self::OPTION, $all, false ); } return true; } /** * Validate an id. * * @param mixed $id Candidate. * @return bool */ public static function valid_id( $id ) { if ( ! is_string( $id ) || '' === $id ) { return false; } if ( strlen( $id ) > self::MAX_ID_LENGTH ) { return false; } return (bool) preg_match( '/^[a-z0-9][a-z0-9_\-]*$/', $id ); } /** * Recursively check node well-formedness. Returns null when OK, or a * human-readable problem description. * * @param mixed $node Node. * @return string|null */ private static function validate_structure( $node ) { if ( ! is_array( $node ) ) { return __( 'A node is not an array.', 'gateforge' ); } if ( array_key_exists( 'unknown', $node ) ) { return null; // Unknown nodes are kept as-is. } if ( isset( $node['cond'] ) ) { if ( ! is_string( $node['cond'] ) || '' === $node['cond'] ) { return __( 'A condition node is missing its condition name.', 'gateforge' ); } return null; } $op = isset( $node['op'] ) ? $node['op'] : null; if ( 'not' === $op ) { if ( ! isset( $node['item'] ) ) { return __( 'A NOT node has no item.', 'gateforge' ); } return self::validate_structure( $node['item'] ); } if ( 'all' === $op || 'any' === $op ) { if ( ! isset( $node['items'] ) || ! is_array( $node['items'] ) ) { return __( 'An ALL/ANY node has no items list.', 'gateforge' ); } foreach ( $node['items'] as $child ) { $sub = self::validate_structure( $child ); if ( null !== $sub ) { return $sub; } } return null; } if ( 'ref' === $op ) { if ( ! isset( $node['id'] ) || ! is_string( $node['id'] ) || '' === $node['id'] ) { return __( 'A ref node is missing its group id.', 'gateforge' ); } return null; } return __( 'A node uses an unrecognised shape.', 'gateforge' ); } /** * Measure a tree with the same counters as Rule::measure(). * * @param array $tree Tree. * @return array{nodes:int,depth:int,max_list:int} */ private static function measure( array $tree ) { $stats = array( 'nodes' => 0, 'depth' => 0, 'max_list' => 0, ); self::walk_measure( $tree, 1, $stats ); return $stats; } /** * Recursive measure with early stop. * * @param mixed $node Node. * @param int $depth Depth. * @param array $stats Stats (by reference). */ private static function walk_measure( $node, $depth, array &$stats ) { ++$stats['nodes']; if ( $depth > $stats['depth'] ) { $stats['depth'] = $depth; } if ( $stats['nodes'] > Rule::MAX_NODES || $depth > Rule::MAX_DEPTH || ! is_array( $node ) ) { return; } if ( isset( $node['args'] ) && is_array( $node['args'] ) ) { foreach ( $node['args'] as $arg ) { if ( is_array( $arg ) && count( $arg ) > $stats['max_list'] ) { $stats['max_list'] = count( $arg ); } } } if ( isset( $node['items'] ) && is_array( $node['items'] ) ) { foreach ( $node['items'] as $child ) { self::walk_measure( $child, $depth + 1, $stats ); if ( $stats['nodes'] > Rule::MAX_NODES ) { return; } } } if ( isset( $node['item'] ) ) { self::walk_measure( $node['item'], $depth + 1, $stats ); } } /** * Collect prior risk stamps by condition name (mirrors Rule_Saver). * * @param mixed $node Node. * @param array $stamps Stamps (by reference). */ private static function collect_stamps( $node, array &$stamps ) { if ( ! is_array( $node ) ) { return; } if ( isset( $node['cond'] ) && is_string( $node['cond'] ) && isset( $node['risk'] ) ) { $stamps[ strtolower( $node['cond'] ) ] = 'location' === $node['risk'] ? 'location' : 'audience'; } if ( isset( $node['items'] ) && is_array( $node['items'] ) ) { foreach ( $node['items'] as $c ) { self::collect_stamps( $c, $stamps ); } } if ( isset( $node['item'] ) ) { self::collect_stamps( $node['item'], $stamps ); } } /** * Stamp risk and authorization on every cond node (mirrors Rule_Saver::stamp). * * @param mixed $node Node. * @param Registry $registry Registry. * @param array $stamps Previous stamps by name. * @param int $user_id Saving user. * @return mixed */ private static function stamp( $node, Registry $registry, array $stamps, $user_id ) { if ( ! is_array( $node ) ) { return $node; } if ( isset( $node['cond'] ) && is_string( $node['cond'] ) ) { $name = strtolower( $node['cond'] ); $def = $registry->get( $name ); if ( $def ) { $node['risk'] = $def['risk']; if ( 'custom' === $def['source'] && '' !== $def['min_cap'] ) { $allowed = $user_id > 0 && function_exists( 'user_can' ) && user_can( $user_id, $def['min_cap'] ); if ( ! $allowed && empty( $node['denied'] ) ) { $node['denied'] = true; } elseif ( $allowed ) { unset( $node['denied'] ); } } } elseif ( isset( $node['risk'] ) && in_array( $node['risk'], array( 'audience', 'location' ), true ) && isset( $stamps[ $name ] ) ) { $node['risk'] = $stamps[ $name ]; } else { $node['risk'] = 'audience'; } return $node; } if ( isset( $node['items'] ) && is_array( $node['items'] ) ) { foreach ( $node['items'] as $i => $c ) { $node['items'][ $i ] = self::stamp( $c, $registry, $stamps, $user_id ); } } if ( isset( $node['item'] ) ) { $node['item'] = self::stamp( $node['item'], $registry, $stamps, $user_id ); } return $node; } /** * Build a WP_Error for refusal. * * @param string $code Machine-readable code. * @param string $message Message. * @return \WP_Error */ private static function error( $code, $message ) { if ( class_exists( '\\WP_Error' ) ) { return new \WP_Error( 'gtfg_group_' . $code, $message, array( 'code' => $code ) ); } // Never reached on a live site (WP_Error is always present); kept so the // class is loadable in a bare test harness that does not stub WP_Error. return new \WP_Error( 'gtfg_group_' . $code, $message ); } }