all() * и передают его в конструкторы (Scorer, Policy), чтобы оставаться тестируемыми. */ class Settings { /** Имя опции. */ const OPTION = 'agentlane_settings'; /** Группа для register_setting() / settings_fields(). */ const GROUP = 'agentlane_settings_group'; /** Допустимые действия политики. */ const ACTIONS = array( 'allow', 'queue', 'block' ); /** @var Settings|null */ private static $instance = null; /** @var array|null Кэш опции на время запроса (сырое значение из БД). */ private $stored = null; /** * Единственный экземпляр. * * @return Settings */ public static function instance(): Settings { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Значения по умолчанию (контракт 5.6). * * honeypot_field_name здесь пустой: реальное имя генерирует ensure_defaults() при установке. * notify_email пустой означает "email администратора", подставляется в all(). * * @return array */ public static function defaults(): array { $block_message = 'This form does not accept automated submissions. If you are an agent acting for a person, state your purpose in the agent field.'; if ( function_exists( '__' ) ) { $block_message = __( 'This form does not accept automated submissions. If you are an agent acting for a person, state your purpose in the agent field.', 'agent-lane' ); } $defaults = array( 'queue_threshold' => 55, 'block_threshold' => 90, 'honeypot_field_name' => '', 'token_min_age' => 3, 'token_max_age' => 86400, 'bind_token_to_client' => true, 'store_full_ip' => false, 'retention_days' => 30, 'verify_signed_agents' => false, 'policy_overrides' => array(), 'declared_agent_action' => 'queue', 'block_message' => $block_message, 'notify_email' => '', 'notify_on_release' => true, 'notify_on_hold' => true, ); if ( function_exists( 'apply_filters' ) ) { /** * Значения настроек по умолчанию. * * @param array $defaults Массив настроек. */ $defaults = (array) apply_filters( 'agentlane_settings_defaults', $defaults ); } return $defaults; } /** * Все настройки: сохранённые поверх значений по умолчанию, с подстановкой email администратора. * * @return array */ public function all(): array { $settings = array_merge( self::defaults(), $this->stored() ); if ( '' === (string) $settings['notify_email'] ) { $settings['notify_email'] = (string) get_option( 'admin_email', '' ); } return $settings; } /** * Одна настройка. * * @param string $key Ключ. * @param mixed $default Значение, если ключа нет даже в defaults(). * @return mixed */ public function get( string $key, $default = null ) { $all = $this->all(); return array_key_exists( $key, $all ) ? $all[ $key ] : $default; } /** * Записать одну настройку. * * @param string $key Ключ. * @param mixed $value Значение. * @return bool */ public function set( string $key, $value ): bool { return $this->update( array( $key => $value ) ); } /** * Записать несколько настроек. Недостающие ключи берутся из текущих значений, * поэтому булевы настройки не сбрасываются (в отличие от sanitize() для формы). * * @param array $values Частичный массив настроек. * @return bool */ public function update( array $values ): bool { $merged = array_merge( $this->all(), $values ); $clean = $this->sanitize( $merged ); $result = update_option( self::OPTION, $clean, false ); $this->stored = $clean; return $result; } /** * Переопределение политики для агента или null, если его нет. * * @param string $agent_id Id агента из каталога. * @return string|null allow|queue|block */ public function policy_for( string $agent_id ): ?string { $overrides = (array) $this->get( 'policy_overrides', array() ); return isset( $overrides[ $agent_id ] ) ? (string) $overrides[ $agent_id ] : null; } /** * Сброс кэша (например, после switch_to_blog). * * @return void */ public function reload(): void { $this->stored = null; } /** * Регистрация опции в Settings API. WP6 может использовать settings_fields( Settings::GROUP ). * * @return void */ public function register(): void { register_setting( self::GROUP, self::OPTION, array( 'type' => 'array', 'sanitize_callback' => array( $this, 'sanitize' ), 'default' => self::defaults(), 'show_in_rest' => false, ) ); } /** * Санитизация полного массива настроек (callback для register_setting). * * Булевы ключи, которых нет во входе, считаются false (так присылает форма с чекбоксами). * Остальные недостающие ключи берутся из сохранённых значений. * * @param mixed $input Сырые данные. * @return array */ public function sanitize( $input ): array { $input = is_array( $input ) ? $input : array(); $current = array_merge( self::defaults(), $this->stored() ); $clean = array(); $clean['queue_threshold'] = $this->int_in_range( $input, $current, 'queue_threshold', 1, 100 ); $clean['block_threshold'] = $this->int_in_range( $input, $current, 'block_threshold', 1, 100 ); if ( $clean['block_threshold'] < $clean['queue_threshold'] ) { $clean['block_threshold'] = $clean['queue_threshold']; } $honeypot = isset( $input['honeypot_field_name'] ) ? strtolower( trim( (string) $input['honeypot_field_name'] ) ) : ''; if ( ! self::is_valid_field_name( $honeypot ) ) { $honeypot = (string) $current['honeypot_field_name']; } if ( ! self::is_valid_field_name( $honeypot ) ) { $honeypot = self::generate_field_name(); } $clean['honeypot_field_name'] = $honeypot; $clean['token_min_age'] = $this->int_in_range( $input, $current, 'token_min_age', 0, 60 ); $clean['token_max_age'] = $this->int_in_range( $input, $current, 'token_max_age', 600, 86400 ); $clean['retention_days'] = $this->int_in_range( $input, $current, 'retention_days', 0, 3650 ); $clean['bind_token_to_client'] = ! empty( $input['bind_token_to_client'] ); $clean['store_full_ip'] = ! empty( $input['store_full_ip'] ); $clean['verify_signed_agents'] = ! empty( $input['verify_signed_agents'] ); $clean['notify_on_release'] = ! empty( $input['notify_on_release'] ); // Added in 0.2.0: a settings array saved by 0.1.0 has no such key and keeps the default (on). $clean['notify_on_hold'] = array_key_exists( 'notify_on_hold', $input ) ? ! empty( $input['notify_on_hold'] ) : (bool) $current['notify_on_hold']; $clean['policy_overrides'] = array(); if ( isset( $input['policy_overrides'] ) && is_array( $input['policy_overrides'] ) ) { foreach ( $input['policy_overrides'] as $agent_id => $action ) { $agent_id = sanitize_key( (string) $agent_id ); $action = sanitize_key( (string) $action ); if ( '' === $agent_id || ! in_array( $action, self::ACTIONS, true ) ) { continue; // Пустое или "default" = убрать переопределение. } $clean['policy_overrides'][ $agent_id ] = $action; } } $declared = isset( $input['declared_agent_action'] ) ? sanitize_key( (string) $input['declared_agent_action'] ) : ''; if ( ! in_array( $declared, self::ACTIONS, true ) ) { $declared = (string) $current['declared_agent_action']; } $clean['declared_agent_action'] = $declared; $message = isset( $input['block_message'] ) ? sanitize_textarea_field( (string) $input['block_message'] ) : ''; if ( '' === trim( $message ) ) { $message = (string) $current['block_message']; } $clean['block_message'] = mb_substr( $message, 0, 500 ); $email = isset( $input['notify_email'] ) ? sanitize_email( (string) $input['notify_email'] ) : ''; if ( '' !== $email && ! is_email( $email ) ) { $email = ''; } // The administrator email is stored as empty, so it follows a later change of that email. if ( '' !== $email && 0 === strcasecmp( $email, (string) get_option( 'admin_email', '' ) ) ) { $email = ''; } $clean['notify_email'] = $email; return $clean; } /** * Гарантирует, что опция существует и имя honeypot-поля сгенерировано. Вызывается установщиком. * * @return void */ public static function ensure_defaults(): void { $settings = self::instance(); $stored = $settings->stored(); $merged = array_merge( self::defaults(), $stored ); if ( ! self::is_valid_field_name( (string) $merged['honeypot_field_name'] ) ) { $merged['honeypot_field_name'] = self::generate_field_name(); } $clean = $settings->sanitize( $merged ); if ( $clean !== $stored ) { update_option( self::OPTION, $clean, false ); $settings->stored = $clean; } } /** * Новое случайное имя honeypot-поля (при "Regenerate" в настройках). * * @return string Новое имя. */ public function regenerate_honeypot_name(): string { $name = self::generate_field_name(); $this->set( 'honeypot_field_name', $name ); return $name; } /** * Случайное имя поля: 10 символов, первая буква, дальше буквы и цифры. * * @param int $length Длина. * @return string */ public static function generate_field_name( int $length = 10 ): string { $letters = 'abcdefghijklmnopqrstuvwxyz'; $alnum = $letters . '0123456789'; $length = max( 3, min( 30, $length ) ); $name = $letters[ random_int( 0, strlen( $letters ) - 1 ) ]; for ( $i = 1; $i < $length; $i++ ) { $name .= $alnum[ random_int( 0, strlen( $alnum ) - 1 ) ]; } return $name; } /** * Имя поля формы: буква, затем буквы, цифры, подчёркивание, 3..30 символов. * * @param string $name Имя. * @return bool */ public static function is_valid_field_name( string $name ): bool { return 1 === preg_match( '/^[a-z][a-z0-9_]{2,29}$/', $name ); } /** * Сырое значение опции из БД (массив), с кэшем на запрос. * * @return array */ private function stored(): array { if ( null === $this->stored ) { $value = get_option( self::OPTION, array() ); $this->stored = is_array( $value ) ? $value : array(); } return $this->stored; } /** * Целое из входа в диапазоне; при отсутствии ключа берётся текущее значение. * * @param array $input Вход. * @param array $current Текущие значения. * @param string $key Ключ. * @param int $min Минимум. * @param int $max Максимум. * @return int */ private function int_in_range( array $input, array $current, string $key, int $min, int $max ): int { $raw = array_key_exists( $key, $input ) ? $input[ $key ] : $current[ $key ]; $value = is_numeric( $raw ) ? (int) $raw : (int) $current[ $key ]; return max( $min, min( $max, $value ) ); } }