prefix}agentlane_queue and serves * the admin screens (People / Automation tabs, dashboard widget, menu badge). * * Rules: * - Automation items (action queue|block) are stored with their sanitized fields. * - People items (action allow) are stored as a light copy: meta only, no fields. * Only the newest PEOPLE_KEEP rows are kept. * - Nothing is hard-deleted by the owner: Delete sets status "deleted"; the * retention cron (purge_older_than) removes rows physically. * - Mark as bot adds the row fingerprint to the option agentlane_blocklist. * * The table itself is created by the installer (WP1) using schema_sql(). * * @package AgentLane */ declare( strict_types=1 ); namespace AgentLane; if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Class Queue */ class Queue { const TABLE_SUFFIX = 'agentlane_queue'; const OPTION_BLOCKLIST = 'agentlane_blocklist'; /** Object cache group and key for the held count shown in the menu badge. */ const CACHE_GROUP = 'agentlane'; const CACHE_HELD_COUNT = 'held_count'; const OPTION_STATS = 'agentlane_stats'; const OPTION_SETTINGS = 'agentlane_settings'; /** GMT time of the last daily summary (see send_digest()). */ const OPTION_DIGEST_LAST = 'agentlane_digest_last'; /** How many submissions the daily summary lists one by one. */ const DIGEST_LIST_MAX = 10; const STATUS_HELD = 'held'; const STATUS_RELEASED = 'released'; const STATUS_DELETED = 'deleted'; const STATUS_HUMAN = 'human'; const TAB_PEOPLE = 'people'; const TAB_AUTOMATION = 'automation'; /** How many allowed (People) rows to keep as a light copy. */ const PEOPLE_KEEP = 200; /** Blocked submissions are kept this many days regardless of retention. */ const BLOCK_RETENTION_DAYS = 7; /** Upper bound for the fingerprint blocklist option. */ const BLOCKLIST_MAX = 1000; /** Daily counters are kept this many days. */ const STATS_KEEP_DAYS = 60; /** Max stored field value length, in characters. */ const FIELD_MAX_LENGTH = 5000; /** Max number of fields stored per submission. */ const FIELDS_MAX = 100; const CLASSES = array( 'human', 'agent_declared', 'agent_verified', 'agent_suspected', 'bot' ); const ACTIONS = array( 'allow', 'queue', 'block' ); /** * Shared instance (convenience for static callers such as Router). * * @var Queue|null */ private static $instance = null; /** * Returns a shared instance. The class is stateless, so `new Queue()` is fine too. * * @return Queue */ public static function instance(): Queue { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Full table name with the WordPress prefix. * * @return string */ public static function table_name(): string { global $wpdb; return $wpdb->prefix . self::TABLE_SUFFIX; } /** * dbDelta-compatible CREATE TABLE statement. Called by the installer (WP1). * * @param string $table Full table name. * @param string $charset_collate Result of $wpdb->get_charset_collate(). * @return string */ public static function schema_sql( string $table, string $charset_collate ): string { return "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, created_at datetime NOT NULL, form_source varchar(20) NOT NULL DEFAULT '', form_id varchar(100) NOT NULL DEFAULT '', class varchar(20) NOT NULL DEFAULT 'human', score tinyint(3) unsigned NOT NULL DEFAULT 0, action varchar(10) NOT NULL DEFAULT 'allow', agent_name varchar(100) NULL DEFAULT NULL, reasons longtext NULL, fields longtext NULL, ip varchar(45) NOT NULL DEFAULT '', ua text NULL, status varchar(20) NOT NULL DEFAULT 'held', fingerprint char(64) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY status_created (status,created_at), KEY class_created (class,created_at), KEY fingerprint (fingerprint) ) {$charset_collate};"; } /* ------------------------------------------------------------------ */ /* Write side */ /* ------------------------------------------------------------------ */ /** * Stores a scored submission. Returns the new row id, or 0 on failure. * * Allowed submissions are stored as a light copy (no fields) with status * "human". Queued and blocked submissions keep their sanitized fields and * get status "held". * * @param Verdict $verdict Scorer + Policy result. * @param RequestContext $ctx Request context. * @param SubmissionData $data Submission payload. * @return int */ public function insert( Verdict $verdict, RequestContext $ctx, SubmissionData $data ): int { global $wpdb; $action = in_array( (string) $verdict->action, self::ACTIONS, true ) ? (string) $verdict->action : 'queue'; $class = in_array( (string) $verdict->class, self::CLASSES, true ) ? (string) $verdict->class : 'bot'; $allow = ( 'allow' === $action ); $ip_full = isset( $ctx->ip_full ) ? (string) $ctx->ip_full : ''; $ip = ( '' !== $ip_full ) ? $ip_full : (string) $ctx->ip; $agent_name = null; if ( isset( $verdict->agent_name ) && '' !== (string) $verdict->agent_name ) { $agent_name = mb_substr( sanitize_text_field( (string) $verdict->agent_name ), 0, 100 ); } $fields_json = null; if ( ! $allow ) { $fields_json = wp_json_encode( $this->sanitize_fields( is_array( $data->fields ) ? $data->fields : array() ) ); } $row = array( 'created_at' => current_time( 'mysql', true ), 'form_source' => mb_substr( sanitize_key( (string) $data->form_source ), 0, 20 ), 'form_id' => mb_substr( sanitize_text_field( (string) $data->form_id ), 0, 100 ), 'class' => $class, 'score' => max( 0, min( 100, (int) $verdict->score ) ), 'action' => $action, 'agent_name' => $agent_name, 'reasons' => wp_json_encode( $this->sanitize_reasons( is_array( $verdict->reasons ) ? $verdict->reasons : array() ) ), 'fields' => $fields_json, 'ip' => mb_substr( sanitize_text_field( $ip ), 0, 45 ), 'ua' => mb_substr( sanitize_text_field( (string) $ctx->ua ), 0, 1000 ), 'status' => $allow ? self::STATUS_HUMAN : self::STATUS_HELD, 'fingerprint' => self::fingerprint( $ctx, $data ), ); $formats = array( '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ); $ok = $wpdb->insert( self::table_name(), $row, $formats ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, written through $wpdb->insert()/update() with formats. if ( false === $ok ) { return 0; } $id = (int) $wpdb->insert_id; self::flush_count_cache(); $this->bump_stats( $class ); if ( $allow ) { $this->trim_people(); } return $id; } /** * Marks a held item as released: status "released", owner gets an email * with the full fields (when notify_on_release is on), and the action * `agentlane_released` fires so adapters can re-deliver if they want. * * @param int $id Row id. * @return bool */ public function release( int $id ): bool { global $wpdb; self::flush_count_cache(); $row = $this->get( $id ); if ( null === $row || self::STATUS_HELD !== $row['status'] ) { return false; } $updated = $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, written through $wpdb->insert()/update() with formats. self::table_name(), array( 'status' => self::STATUS_RELEASED ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); if ( false === $updated ) { return false; } $row['status'] = self::STATUS_RELEASED; if ( $this->setting_bool( 'notify_on_release', true ) ) { $this->email_owner( $row ); } do_action( 'agentlane_released', $row ); return true; } /** * Soft delete: status "deleted". The row is removed physically by purge_older_than(). * * @param int $id Row id. * @return bool */ public function delete( int $id ): bool { global $wpdb; self::flush_count_cache(); $row = $this->get( $id ); if ( null === $row || self::STATUS_DELETED === $row['status'] ) { return false; } $updated = $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, written through $wpdb->insert()/update() with formats. self::table_name(), array( 'status' => self::STATUS_DELETED ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); if ( false === $updated ) { return false; } do_action( 'agentlane_deleted', $row ); return true; } /** * Adds the row fingerprint to the local blocklist option and labels the row as bot. * * @param int $id Row id. * @return bool */ public function mark_bot( int $id ): bool { global $wpdb; self::flush_count_cache(); $row = $this->get( $id ); if ( null === $row || '' === $row['fingerprint'] ) { return false; } self::blocklist_add( $row['fingerprint'] ); if ( 'bot' !== $row['class'] ) { $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, written through $wpdb->insert()/update() with formats. self::table_name(), array( 'class' => 'bot' ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); $row['class'] = 'bot'; } do_action( 'agentlane_marked_bot', $row ); return true; } /** * Retention. Removes held and released rows older than $days, blocked rows * older than BLOCK_RETENTION_DAYS, every soft-deleted row, and trims the * People copy. Returns the number of removed rows. * * @param int $days Retention in days (min 1). * @return int */ public function purge_older_than( int $days ): int { global $wpdb; self::flush_count_cache(); $table = self::table_name(); $days = max( 1, $days ); $cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $days * 86400 ) ); $bcutoff = gmdate( 'Y-m-d H:i:s', time() - ( self::BLOCK_RETENTION_DAYS * 86400 ) ); $removed = 0; // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, values through $wpdb->prepare(); no WP API for custom tables. $n = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE status IN (%s, %s) AND created_at < %s", self::STATUS_HELD, self::STATUS_RELEASED, $cutoff ) ); $removed += is_int( $n ) ? $n : 0; $n = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE action = %s AND created_at < %s", 'block', $bcutoff ) ); $removed += is_int( $n ) ? $n : 0; $n = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE status = %s", self::STATUS_DELETED ) ); $removed += is_int( $n ) ? $n : 0; // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL $removed += $this->trim_people(); $this->trim_stats(); return $removed; } /* ------------------------------------------------------------------ */ /* Read side */ /* ------------------------------------------------------------------ */ /** * Returns one hydrated row or null. * * @param int $id Row id. * @return array|null */ public function get( int $id ): ?array { global $wpdb; $table = self::table_name(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, values through $wpdb->prepare(); no WP API for custom tables. $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * Paged listing for the admin table. * * Args: tab (people|automation), paged, per_page, orderby * (created_at|score|class|form_source|id), order (ASC|DESC), search. * * @param array $args Query args. * @return array { items: array[], total: int, paged: int, per_page: int } */ public function list( array $args ): array { global $wpdb; $args = wp_parse_args( $args, array( 'tab' => self::TAB_AUTOMATION, 'paged' => 1, 'per_page' => 20, 'orderby' => 'created_at', 'order' => 'DESC', 'search' => '', ) ); $table = self::table_name(); $per_page = max( 1, min( 200, (int) $args['per_page'] ) ); $paged = max( 1, (int) $args['paged'] ); $offset = ( $paged - 1 ) * $per_page; // Column and direction come from literals, never from the request. switch ( (string) $args['orderby'] ) { case 'score': $orderby = 'score'; break; case 'class': $orderby = 'class'; break; case 'form_source': $orderby = 'form_source'; break; case 'id': $orderby = 'id'; break; default: $orderby = 'created_at'; } $order = ( 'ASC' === strtoupper( (string) $args['order'] ) ) ? 'ASC' : 'DESC'; $order_by = sanitize_sql_orderby( $orderby . ' ' . $order ); if ( false === $order_by ) { $order_by = 'created_at DESC'; } // People = delivered and released rows, Automation = held rows. Two values either // way, so every query below has a fixed set of placeholders. if ( self::TAB_PEOPLE === (string) $args['tab'] ) { $status_a = self::STATUS_HUMAN; $status_b = self::STATUS_RELEASED; } else { $status_a = self::STATUS_HELD; $status_b = self::STATUS_HELD; } $search = trim( (string) $args['search'] ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, ORDER BY column and direction from the literals above, values through $wpdb->prepare(); no WP API for custom tables. if ( '' !== $search ) { $like = '%' . $wpdb->esc_like( $search ) . '%'; $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE status IN (%s, %s) AND (fields LIKE %s OR ua LIKE %s OR ip LIKE %s OR agent_name LIKE %s OR form_id LIKE %s)", $status_a, $status_b, $like, $like, $like, $like, $like ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE status IN (%s, %s) AND (fields LIKE %s OR ua LIKE %s OR ip LIKE %s OR agent_name LIKE %s OR form_id LIKE %s) ORDER BY " . esc_sql( $order_by ) . ', id DESC LIMIT %d OFFSET %d', $status_a, $status_b, $like, $like, $like, $like, $like, $per_page, $offset ), ARRAY_A ); } else { $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE status IN (%s, %s)", $status_a, $status_b ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE status IN (%s, %s) ORDER BY " . esc_sql( $order_by ) . ', id DESC LIMIT %d OFFSET %d', $status_a, $status_b, $per_page, $offset ), ARRAY_A ); } // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $items = array(); if ( is_array( $rows ) ) { foreach ( $rows as $row ) { $items[] = $this->hydrate( $row ); } } return array( 'items' => $items, 'total' => $total, 'paged' => $paged, 'per_page' => $per_page, ); } /** * Counts non-deleted rows per class. With $days > 0 only rows newer than * $days are counted. Note: People rows are capped at PEOPLE_KEEP, so for * accurate human counts over time use stats(). * * @param int $days Optional window in days. * @return array class => count (all classes present). */ public function count_by_class( int $days = 0 ): array { global $wpdb; $table = self::table_name(); $counts = array_fill_keys( self::CLASSES, 0 ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, values through $wpdb->prepare(); no WP API for custom tables. if ( $days > 0 ) { $since = gmdate( 'Y-m-d H:i:s', time() - ( $days * 86400 ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT class, COUNT(*) AS n FROM {$table} WHERE status <> %s AND created_at >= %s GROUP BY class", self::STATUS_DELETED, $since ), ARRAY_A ); } else { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT class, COUNT(*) AS n FROM {$table} WHERE status <> %s GROUP BY class", self::STATUS_DELETED ), ARRAY_A ); } // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL if ( is_array( $rows ) ) { foreach ( $rows as $row ) { $counts[ (string) $row['class'] ] = (int) $row['n']; } } return $counts; } /** * Counts non-deleted rows per status (held, released, human). * * @return array status => count. */ public function count_by_status(): array { global $wpdb; $table = self::table_name(); $counts = array( self::STATUS_HELD => 0, self::STATUS_RELEASED => 0, self::STATUS_HUMAN => 0, ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, values through $wpdb->prepare(); no WP API for custom tables. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT status, COUNT(*) AS n FROM {$table} WHERE status <> %s GROUP BY status", self::STATUS_DELETED ), ARRAY_A ); // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( is_array( $rows ) ) { foreach ( $rows as $row ) { $counts[ (string) $row['status'] ] = (int) $row['n']; } } return $counts; } /** * Number of items currently held (Automation tab, menu badge). * * @return int */ public function count_held(): int { if ( function_exists( 'wp_cache_get' ) ) { $cached = wp_cache_get( self::CACHE_HELD_COUNT, self::CACHE_GROUP ); if ( false !== $cached ) { return (int) $cached; } } $counts = $this->count_by_status(); $held = (int) $counts[ self::STATUS_HELD ]; if ( function_exists( 'wp_cache_set' ) ) { wp_cache_set( self::CACHE_HELD_COUNT, $held, self::CACHE_GROUP, 60 ); } return $held; } /** * Drops the cached held count after any write (menu badge reads it on every admin request). * * @return void */ private static function flush_count_cache(): void { if ( function_exists( 'wp_cache_delete' ) ) { wp_cache_delete( self::CACHE_HELD_COUNT, self::CACHE_GROUP ); } } /** * Per-class totals for the last N days from the daily counters option. * Unlike count_by_class() this is not affected by trimming or retention. * * @param int $days Window in days (today counts as day 1). * @return array class => count, plus 'total'. */ public function stats( int $days = 7 ): array { $days = max( 1, $days ); $daily = get_option( self::OPTION_STATS, array() ); $totals = array_fill_keys( self::CLASSES, 0 ); $from = gmdate( 'Y-m-d', time() - ( ( $days - 1 ) * 86400 ) ); if ( is_array( $daily ) ) { foreach ( $daily as $day => $classes ) { if ( ! is_array( $classes ) || (string) $day < $from ) { continue; } foreach ( $classes as $class => $n ) { if ( isset( $totals[ $class ] ) ) { $totals[ $class ] += (int) $n; } } } } $totals['total'] = array_sum( $totals ); return $totals; } /** * True when the same fingerprint was stored within the last $seconds. * Useful for the "identical submission in last 24h" heuristic (Scorer, WP3). * * @param string $fingerprint sha256 hex. * @param int $seconds Window, default 24h. * @return bool */ public function seen_recently( string $fingerprint, int $seconds = 86400 ): bool { global $wpdb; if ( '' === $fingerprint ) { return false; } $table = self::table_name(); $since = gmdate( 'Y-m-d H:i:s', time() - max( 1, $seconds ) ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, values through $wpdb->prepare(); no WP API for custom tables. $n = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE fingerprint = %s AND created_at >= %s", $fingerprint, $since ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $n > 0; } /* ------------------------------------------------------------------ */ /* Fingerprint + blocklist */ /* ------------------------------------------------------------------ */ /** * sha256 of ua + truncated ip + text_blob. Used for duplicate detection and * the blocklist. Router (WP5) calls Queue::fingerprint() so both sides agree. * * @param RequestContext $ctx Request context. * @param SubmissionData $data Submission payload. * @return string */ public static function fingerprint( RequestContext $ctx, SubmissionData $data ): string { return hash( 'sha256', (string) $ctx->ua . '|' . (string) $ctx->ip . '|' . (string) $data->text_blob ); } /** * Alias of fingerprint(). * * @param RequestContext $ctx Request context. * @param SubmissionData $data Submission payload. * @return string */ public static function fingerprint_for( RequestContext $ctx, SubmissionData $data ): string { return self::fingerprint( $ctx, $data ); } /** * True when the fingerprint was marked as bot by the owner. * TODO (integrator): Scorer/Router should call this and add a strong reason when true. * * @param string $fingerprint sha256 hex. * @return bool */ public static function is_blocklisted( string $fingerprint ): bool { if ( '' === $fingerprint ) { return false; } $list = get_option( self::OPTION_BLOCKLIST, array() ); return is_array( $list ) && in_array( $fingerprint, $list, true ); } /** * Adds a fingerprint to the blocklist option (deduplicated, capped). * * @param string $fingerprint sha256 hex. * @return void */ public static function blocklist_add( string $fingerprint ): void { $fingerprint = strtolower( preg_replace( '/[^a-f0-9]/i', '', $fingerprint ) ); if ( 64 !== strlen( $fingerprint ) ) { return; } $list = get_option( self::OPTION_BLOCKLIST, array() ); if ( ! is_array( $list ) ) { $list = array(); } if ( in_array( $fingerprint, $list, true ) ) { return; } $list[] = $fingerprint; if ( count( $list ) > self::BLOCKLIST_MAX ) { $list = array_slice( $list, -self::BLOCKLIST_MAX ); } update_option( self::OPTION_BLOCKLIST, array_values( $list ), false ); // Not autoloaded: read only on form submissions. } /* ------------------------------------------------------------------ */ /* Labels (shared by admin screens and emails) */ /* ------------------------------------------------------------------ */ /** * Human label for a verdict class. * * @param string $class Verdict class. * @return string */ public static function class_label( string $class ): string { switch ( $class ) { case 'human': return __( 'Person', 'agent-lane' ); case 'agent_declared': return __( 'Declared agent', 'agent-lane' ); case 'agent_verified': return __( 'Verified agent', 'agent-lane' ); case 'agent_suspected': return __( 'Suspected agent', 'agent-lane' ); case 'bot': return __( 'Bot', 'agent-lane' ); default: return $class; } } /** * Human label for a form source. * * @param string $source Form source id. * @return string */ public static function form_label( string $source ): string { switch ( $source ) { case 'cf7': return __( 'Contact Form 7', 'agent-lane' ); case 'wpforms': return __( 'WPForms', 'agent-lane' ); case 'gravity': return __( 'Gravity Forms', 'agent-lane' ); case 'elementor': return __( 'Elementor Forms', 'agent-lane' ); case 'comments': return __( 'Comments', 'agent-lane' ); default: return $source; } } /** * Human label for a row status. * * @param string $status Row status. * @return string */ public static function status_label( string $status ): string { switch ( $status ) { case self::STATUS_HELD: return __( 'Held', 'agent-lane' ); case self::STATUS_RELEASED: return __( 'Released', 'agent-lane' ); case self::STATUS_HUMAN: return __( 'Delivered', 'agent-lane' ); case self::STATUS_DELETED: return __( 'Deleted', 'agent-lane' ); default: return $status; } } /* ------------------------------------------------------------------ */ /* Internals */ /* ------------------------------------------------------------------ */ /** * Casts a raw DB row into a typed array with decoded JSON. * * @param array $row Raw row. * @return array */ private function hydrate( array $row ): array { $reasons = json_decode( (string) ( $row['reasons'] ?? '' ), true ); $fields = null; if ( null !== ( $row['fields'] ?? null ) && '' !== (string) $row['fields'] ) { $decoded = json_decode( (string) $row['fields'], true ); $fields = is_array( $decoded ) ? $decoded : array(); } return array( 'id' => (int) $row['id'], 'created_at' => (string) $row['created_at'], 'form_source' => (string) $row['form_source'], 'form_id' => (string) $row['form_id'], 'class' => (string) $row['class'], 'score' => (int) $row['score'], 'action' => (string) $row['action'], 'agent_name' => isset( $row['agent_name'] ) ? (string) $row['agent_name'] : '', 'reasons' => is_array( $reasons ) ? $reasons : array(), 'fields' => $fields, 'ip' => (string) $row['ip'], 'ua' => isset( $row['ua'] ) ? (string) $row['ua'] : '', 'status' => (string) $row['status'], 'fingerprint' => (string) $row['fingerprint'], ); } /** * Sanitizes submitted fields for storage: plain text only, capped length * and count, plugin-internal fields dropped. * * @param array $fields name => value. * @return array */ private function sanitize_fields( array $fields ): array { $out = array(); $honeypot = (string) $this->setting( 'honeypot_field_name', '' ); $count = 0; foreach ( $fields as $name => $value ) { if ( $count >= self::FIELDS_MAX ) { break; } $name = mb_substr( sanitize_text_field( (string) $name ), 0, 100 ); if ( '' === $name || 0 === strpos( $name, 'agentlane_' ) || ( '' !== $honeypot && $name === $honeypot ) ) { continue; } if ( is_array( $value ) ) { $value = implode( ', ', array_map( 'strval', $this->flatten( $value ) ) ); } elseif ( is_scalar( $value ) || null === $value ) { $value = (string) $value; } else { continue; } $value = mb_substr( sanitize_textarea_field( $value ), 0, self::FIELD_MAX_LENGTH ); $out[ $name ] = $value; ++$count; } return $out; } /** * Flattens nested arrays (checkbox groups etc.) to a list of scalars. * * @param array $value Nested array. * @return array */ private function flatten( array $value ): array { $out = array(); foreach ( $value as $item ) { if ( is_array( $item ) ) { $out = array_merge( $out, $this->flatten( $item ) ); } elseif ( is_scalar( $item ) ) { $out[] = $item; } } return $out; } /** * Keeps reasons small and plain: code, weight, detail. * * @param array $reasons List of reason arrays. * @return array */ private function sanitize_reasons( array $reasons ): array { $out = array(); foreach ( $reasons as $reason ) { if ( ! is_array( $reason ) ) { continue; } $out[] = array( 'code' => mb_substr( sanitize_key( (string) ( $reason['code'] ?? '' ) ), 0, 50 ), 'weight' => (int) ( $reason['weight'] ?? 0 ), 'detail' => mb_substr( sanitize_text_field( (string) ( $reason['detail'] ?? '' ) ), 0, 300 ), ); if ( count( $out ) >= 20 ) { break; } } return $out; } /** * Keeps only the newest PEOPLE_KEEP allowed rows. Returns removed count. * * @return int */ private function trim_people(): int { global $wpdb; $table = self::table_name(); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, values through $wpdb->prepare(); no WP API for custom tables. $threshold = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE status = %s ORDER BY id DESC LIMIT 1 OFFSET %d", self::STATUS_HUMAN, self::PEOPLE_KEEP ) ); if ( null === $threshold ) { return 0; } $n = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE status = %s AND id <= %d", self::STATUS_HUMAN, (int) $threshold ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL return is_int( $n ) ? $n : 0; } /** * Increments today's counter for a class in the stats option. * * @param string $class Verdict class. * @return void */ private function bump_stats( string $class ): void { $daily = get_option( self::OPTION_STATS, array() ); if ( ! is_array( $daily ) ) { $daily = array(); } $today = gmdate( 'Y-m-d' ); if ( ! isset( $daily[ $today ] ) || ! is_array( $daily[ $today ] ) ) { $daily[ $today ] = array(); } $daily[ $today ][ $class ] = (int) ( $daily[ $today ][ $class ] ?? 0 ) + 1; if ( count( $daily ) > self::STATS_KEEP_DAYS ) { ksort( $daily ); $daily = array_slice( $daily, -self::STATS_KEEP_DAYS, null, true ); } update_option( self::OPTION_STATS, $daily, false ); } /** * Drops daily counters older than STATS_KEEP_DAYS. * * @return void */ private function trim_stats(): void { $daily = get_option( self::OPTION_STATS, array() ); if ( ! is_array( $daily ) || count( $daily ) <= self::STATS_KEEP_DAYS ) { return; } ksort( $daily ); update_option( self::OPTION_STATS, array_slice( $daily, -self::STATS_KEEP_DAYS, null, true ), false ); } /** * Daily summary: tells the owner how many submissions were held since the last * summary. Counts only what waits for a decision (status held, action queue); * blocked submissions are not reported. Sends nothing when the setting * notify_on_hold is off or when nothing new was held. * * @return int Number of submissions reported (0 = no email). */ public function send_digest(): int { global $wpdb; if ( ! $this->setting_bool( 'notify_on_hold', true ) ) { return 0; } $table = self::table_name(); $last = (string) get_option( self::OPTION_DIGEST_LAST, '' ); if ( 1 !== preg_match( '/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $last ) ) { $last = gmdate( 'Y-m-d H:i:s', time() - 86400 ); } $now = gmdate( 'Y-m-d H:i:s' ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- custom table: name from $wpdb->prefix and a constant, values through $wpdb->prepare(); no WP API for custom tables. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE status = %s AND action = %s AND created_at > %s AND created_at <= %s ORDER BY id DESC LIMIT %d", self::STATUS_HELD, 'queue', $last, $now, 500 ), ARRAY_A ); // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared update_option( self::OPTION_DIGEST_LAST, $now, false ); if ( ! is_array( $rows ) || empty( $rows ) ) { return 0; } $to = $this->owner_email(); if ( '' === $to ) { return 0; } $count = count( $rows ); $site = wp_specialchars_decode( (string) get_option( 'blogname' ), ENT_QUOTES ); $subject = sprintf( /* translators: 1: site name, 2: number of submissions */ _n( '[%1$s] %2$d submission is waiting for review', '[%1$s] %2$d submissions are waiting for review', $count, 'agent-lane' ), $site, $count ); $lines = array(); $lines[] = sprintf( /* translators: %d: number of submissions */ _n( 'Agent Lane held %d new submission since the last summary. It was not delivered and waits for your decision.', 'Agent Lane held %d new submissions since the last summary. They were not delivered and wait for your decision.', $count, 'agent-lane' ), $count ); $lines[] = ''; foreach ( array_slice( $rows, 0, self::DIGEST_LIST_MAX ) as $raw ) { $row = $this->hydrate( $raw ); $reason = ''; if ( ! empty( $row['reasons'][0] ) ) { $reason = (string) ( $row['reasons'][0]['detail'] ?? $row['reasons'][0]['code'] ?? '' ); } $lines[] = sprintf( /* translators: 1: form label, 2: class label, 3: score 0..100, 4: main reason */ __( '- %1$s, %2$s, score %3$d: %4$s', 'agent-lane' ), self::form_label( $row['form_source'] ), self::class_label( $row['class'] ), $row['score'], $reason ); } if ( $count > self::DIGEST_LIST_MAX ) { /* translators: %d: number of further submissions */ $lines[] = sprintf( __( '... and %d more', 'agent-lane' ), $count - self::DIGEST_LIST_MAX ); } $lines[] = ''; $lines[] = __( 'Open the queue to read them. Release anything that came from a real person: you get its full text by email.', 'agent-lane' ); $lines[] = admin_url( 'admin.php?page=agent-lane&tab=automation' ); $lines[] = ''; $lines[] = __( 'To stop this summary, turn off "Daily summary" under Agent Lane > Settings.', 'agent-lane' ); /** * Filters the daily summary email before sending. * * @param array $mail { to, subject, body, headers } * @param array $rows Raw rows of the held submissions (newest first). */ $mail = apply_filters( 'agentlane_digest_email', array( 'to' => $to, 'subject' => $subject, 'body' => implode( "\n", $lines ), 'headers' => array( 'Content-Type: text/plain; charset=UTF-8' ), ), $rows ); wp_mail( $mail['to'], $mail['subject'], $mail['body'], $mail['headers'] ); return $count; } /** * Address that receives release copies and the daily summary: the notification * email from settings, or the site admin email. * * @return string Valid address or ''. */ private function owner_email(): string { $to = sanitize_email( (string) $this->setting( 'notify_email', '' ) ); if ( ! is_email( $to ) ) { $to = (string) get_option( 'admin_email' ); } return is_email( $to ) ? $to : ''; } /** * Emails the owner a plain-text copy of a released submission. * * @param array $row Hydrated row. * @return bool */ private function email_owner( array $row ): bool { $to = $this->owner_email(); if ( '' === $to ) { return false; } $site = wp_specialchars_decode( (string) get_option( 'blogname' ), ENT_QUOTES ); $form = self::form_label( $row['form_source'] ); if ( '' !== $row['form_id'] ) { $form .= ' #' . $row['form_id']; } /* translators: 1: site name, 2: form label */ $subject = sprintf( __( '[%1$s] Released submission from %2$s', 'agent-lane' ), $site, $form ); $lines = array(); $lines[] = __( 'A submission held by Agent Lane was released. It is now treated as sent by a person.', 'agent-lane' ); $lines[] = ''; $fields = is_array( $row['fields'] ) ? $row['fields'] : array(); if ( empty( $fields ) ) { $lines[] = __( '(no fields were stored for this submission)', 'agent-lane' ); } else { foreach ( $fields as $name => $value ) { $lines[] = $name . ': ' . $value; } } $lines[] = ''; $lines[] = str_repeat( '-', 40 ); /* translators: %s: form label */ $lines[] = sprintf( __( 'Form: %s', 'agent-lane' ), $form ); /* translators: 1: class label, 2: score 0..100 */ $lines[] = sprintf( __( 'Class: %1$s, score %2$d', 'agent-lane' ), self::class_label( $row['class'] ), $row['score'] ); if ( '' !== $row['agent_name'] ) { /* translators: %s: agent name */ $lines[] = sprintf( __( 'Agent: %s', 'agent-lane' ), $row['agent_name'] ); } /* translators: %s: date and time (UTC) */ $lines[] = sprintf( __( 'Received: %s UTC', 'agent-lane' ), $row['created_at'] ); /* translators: %s: IP address */ $lines[] = sprintf( __( 'IP: %s', 'agent-lane' ), $row['ip'] ); if ( ! empty( $row['reasons'] ) ) { $lines[] = __( 'Reasons:', 'agent-lane' ); foreach ( $row['reasons'] as $reason ) { $lines[] = ' ' . (string) ( $reason['detail'] ?? $reason['code'] ?? '' ) . ' (+' . (int) ( $reason['weight'] ?? 0 ) . ')'; } } $lines[] = ''; // Slug must match AgentLane\Admin\Admin::PAGE_QUEUE. $lines[] = admin_url( 'admin.php?page=agent-lane&tab=people' ); $body = implode( "\n", $lines ); /** * Filters the release email before sending. * * @param array $mail { to, subject, body, headers } * @param array $row Hydrated row. */ $mail = apply_filters( 'agentlane_release_email', array( 'to' => $to, 'subject' => $subject, 'body' => $body, 'headers' => array( 'Content-Type: text/plain; charset=UTF-8' ), ), $row ); return (bool) wp_mail( $mail['to'], $mail['subject'], $mail['body'], $mail['headers'] ); } /** * Reads a plugin setting through AgentLane\Settings (WP1) when available, * otherwise straight from the option. * * @param string $key Setting key. * @param mixed $default Fallback. * @return mixed */ private function setting( string $key, $default = null ) { $settings_class = __NAMESPACE__ . '\Settings'; if ( class_exists( $settings_class ) && method_exists( $settings_class, 'instance' ) ) { $settings = Settings::instance(); if ( is_object( $settings ) && method_exists( $settings, 'get' ) ) { return $settings->get( $key, $default ); } } $all = get_option( self::OPTION_SETTINGS, array() ); if ( is_array( $all ) && array_key_exists( $key, $all ) ) { return $all[ $key ]; } return $default; } /** * Boolean setting helper. * * @param string $key Setting key. * @param bool $default Fallback. * @return bool */ private function setting_bool( string $key, bool $default ): bool { $value = $this->setting( $key, $default ); if ( is_string( $value ) ) { return in_array( strtolower( $value ), array( '1', 'true', 'yes', 'on' ), true ); } return (bool) $value; } }