db = $db; $this->table = $table; } public function log( string $bot_slug, string $bot_name, string $ua, string $url, string $action ): void { $settings = aicrg_get_settings(); if ( empty( $settings['log_enabled'] ) ) { return; } $data = [ 'time' => current_time( 'mysql' ), 'bot_slug' => sanitize_title( $bot_slug ), 'bot_name' => sanitize_text_field( $bot_name ), 'user_agent' => aicrg_truncate( sanitize_textarea_field( $ua ), 500 ), 'url' => aicrg_truncate( esc_url_raw( $url ), 500 ), 'action' => in_array( $action, [ 'allowed', 'blocked' ], true ) ? $action : 'allowed', ]; $formats = [ '%s', '%s', '%s', '%s', '%s', '%s' ]; $inserted = $this->db->insert( $this->table, $data, $formats ); if ( false !== $inserted ) { $this->prune_logs( absint( $settings['log_limit'] ?? 500 ) ); } } public function get_logs( array $args = [] ): array { $defaults = [ 'limit' => 50, 'offset' => 0 ]; $args = wp_parse_args( $args, $defaults ); $limit = absint( $args['limit'] ); $offset = absint( $args['offset'] ); $query = $this->db->prepare( "SELECT * FROM {$this->table} ORDER BY time DESC LIMIT %d OFFSET %d", $limit, $offset ); return $this->db->get_results( $query, ARRAY_A ) ?: []; } public function count_logs(): int { return (int) $this->db->get_var( "SELECT COUNT(*) FROM {$this->table}" ); } public function clear_logs(): void { $this->db->query( "DELETE FROM {$this->table}" ); } public function get_activity_trend( int $days = 7 ): array { $days = max( 1, $days ); $query = $this->db->prepare( "SELECT DATE(time) as day, SUM(CASE WHEN action = 'blocked' THEN 1 ELSE 0 END) as blocked, SUM(CASE WHEN action = 'allowed' THEN 1 ELSE 0 END) as allowed, COUNT(*) as total FROM {$this->table} WHERE time >= DATE_SUB( %s, INTERVAL %d DAY ) GROUP BY DATE(time) ORDER BY day DESC", current_time( 'mysql' ), $days ); $rows = $this->db->get_results( $query, ARRAY_A ) ?: []; return array_reverse( $rows ); } private function prune_logs( int $limit ): void { if ( $limit <= 0 ) { return; } $count = (int) $this->db->get_var( "SELECT COUNT(*) FROM {$this->table}" ); if ( $count <= $limit ) { return; } $ids = $this->db->get_col( $this->db->prepare( "SELECT id FROM {$this->table} ORDER BY time DESC LIMIT %d, 18446744073709551615", $limit ) ); if ( ! empty( $ids ) ) { $placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); $query = $this->db->prepare( "DELETE FROM {$this->table} WHERE id IN ($placeholders)", ...array_map( 'intval', $ids ) ); $this->db->query( $query ); } } }