$bot['id'], 'category' => $bot['category'], 'path' => Aeoora_Util::log_path(), 'post_id' => $post_id, 'resource' => self::$resource ? self::$resource : self::detect_resource( $status ), 'status' => $status, 'ip' => Aeoora_Util::client_ip(), 'ua' => Aeoora_Util::user_agent(), ); self::record( $hit ); /** * Fires after a crawler visit is logged. The hit carries the full IP * (the log itself stores it anonymized when that setting is on). * aeoora Cloud's sender listens here only while connected. * * @param array $hit Hit: bot, category, path, post_id, resource, status, ip, ua. * @param array $bot Bot entry from the crawler database. */ do_action( 'aeoora_crawler_hit', $hit, $bot ); } /** * Store a hit and bump the daily rollup. * * @param array $hit Hit data. * @return bool Whether the detailed log row was stored. */ public static function record( array $hit ) { global $wpdb; if ( ! Aeoora_Install::ready() ) { return false; // Tables not created (yet): never log an error per crawler visit. } $ip = isset( $hit['ip'] ) ? $hit['ip'] : ''; if ( $ip && Aeoora_Settings::get( 'tracking', 'anonymize_ip', true ) ) { $ip = Aeoora_Util::anonymize_ip( $ip ); } $now = Aeoora_Util::now(); $stored = false; $quiet = $wpdb->suppress_errors( true ); // Never print a DB error into a crawler's response. // The daily totals always count; the detailed log is rate-limited for // unidentified bots, which anyone can fake to flood it. if ( ! self::throttled( (string) $hit['bot'] ) ) { $stored = (bool) $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery Aeoora_Install::table( Aeoora_Install::TABLE_HITS ), array( 'ts' => $now, 'bot' => substr( (string) $hit['bot'], 0, 64 ), 'category' => substr( (string) $hit['category'], 0, 20 ), 'path' => substr( (string) $hit['path'], 0, 255 ), 'post_id' => (int) $hit['post_id'], 'resource' => substr( (string) $hit['resource'], 0, 16 ), 'status' => (int) $hit['status'], 'ip' => substr( (string) $ip, 0, 45 ), 'ua' => substr( (string) $hit['ua'], 0, 512 ), ), array( '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%s', '%s' ) ); } self::bump_daily( 'bot', $hit['bot'], $hit['category'] ); $wpdb->suppress_errors( $quiet ); return $stored; } /** * Is the detailed log of this bot over its per-minute limit? By default * only unidentified bots are limited (120 log rows a minute); filter * `aeoora_log_rate_limit` to limit others too (0 = no limit). * * @param string $bot Bot id. * @return bool */ private static function throttled( $bot ) { $limit = (int) apply_filters( 'aeoora_log_rate_limit', 'unknown-bot' === $bot ? 120 : 0, $bot ); if ( $limit <= 0 ) { return false; } if ( wp_using_ext_object_cache() ) { $key = 'rate:' . md5( $bot ) . ':' . (int) floor( time() / 60 ); wp_cache_add( $key, 0, 'aeoora', 2 * MINUTE_IN_SECONDS ); return (int) wp_cache_incr( $key, 1, 'aeoora' ) > $limit; } global $wpdb; $hits = Aeoora_Install::table( Aeoora_Install::TABLE_HITS ); // Bounded by the limit, and served by the (bot, ts) index. $n = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM (SELECT 1 FROM %i WHERE bot = %s AND ts >= %s LIMIT %d) x", $hits, $bot, gmdate( 'Y-m-d H:i:s', time() - MINUTE_IN_SECONDS ), $limit + 1 ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. return $n > $limit; } /** * Increment a daily rollup counter. * * @param string $kind bot|ref. * @param string $item Item id. * @param string $category Category. */ public static function bump_daily( $kind, $item, $category = '' ) { global $wpdb; if ( ! Aeoora_Install::ready() ) { return; } $table = Aeoora_Install::table( Aeoora_Install::TABLE_DAILY ); $day = wp_date( 'Y-m-d' ); $quiet = $wpdb->suppress_errors( true ); $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. $wpdb->prepare( 'INSERT INTO %i (day, kind, item, category, hits) VALUES (%s, %s, %s, %s, 1) ON DUPLICATE KEY UPDATE hits = hits + 1', $table, $day, substr( $kind, 0, 8 ), substr( (string) $item, 0, 64 ), substr( (string) $category, 0, 20 ) ) ); $wpdb->suppress_errors( $quiet ); } /** * Guess the resource type of the current request. * * @param int $status HTTP status. * @return string */ private static function detect_resource( $status ) { $path = strtolower( Aeoora_Util::relative_path() ); if ( 'robots.txt' === $path ) { return 'robots'; } if ( preg_match( '~sitemap[^/]*\.xml(\.gz)?$~', $path ) || false !== strpos( $path, 'wp-sitemap' ) ) { return 'sitemap'; } if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { return 'rest'; } if ( function_exists( 'is_feed' ) && did_action( 'wp' ) && is_feed() ) { return 'feed'; } if ( preg_match( '~\.(jpe?g|png|gif|webp|avif|svg|pdf|zip|mp4|mp3|css|js)$~', $path ) ) { return 'file'; } if ( 404 === $status ) { return '404'; } if ( $status >= 300 && $status < 400 ) { return 'redirect'; } return 'html'; } /** * Delete log rows older than the retention window, in batches of 10,000 * for at most $budget seconds. Also keeps the detailed log under a size * cap (filter `aeoora_max_log_rows`, default 3 million rows) whatever the * retention, so a flood can never fill the database. * * @param int $budget Seconds. * @return bool True when everything due was deleted; false when time ran out. */ public static function prune( $budget = 20 ) { global $wpdb; if ( ! Aeoora_Install::ready() ) { return true; } $start = microtime( true ); $days = max( 1, (int) Aeoora_Settings::get( 'tracking', 'retention_days', 30 ) ); $hits = Aeoora_Install::table( Aeoora_Install::TABLE_HITS ); $refs = Aeoora_Install::table( Aeoora_Install::TABLE_REFERRALS ); $daily = Aeoora_Install::table( Aeoora_Install::TABLE_DAILY ); $batch = 10000; $quiet = $wpdb->suppress_errors( true ); $done = true; // AI referral rows hold no personal data: they are kept for at least 12 months. $jobs = array( array( $hits, gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) ), array( $refs, gmdate( 'Y-m-d H:i:s', time() - max( $days, 365 ) * DAY_IN_SECONDS ) ), ); foreach ( $jobs as $job ) { do { if ( microtime( true ) - $start > $budget ) { $done = false; break 2; } $deleted = (int) $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE ts < %s LIMIT %d", $job[0], $job[1], $batch ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. } while ( $deleted >= $batch ); } $max = (int) apply_filters( 'aeoora_max_log_rows', 3000000 ); if ( $done && $max > 0 ) { $span = $wpdb->get_row( $wpdb->prepare( "SELECT MIN(id) lo, MAX(id) hi FROM %i", $hits ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. // Ids are sequential, so MAX - MIN bounds the row count: only count when it could be over. if ( $span && (int) $span->hi - (int) $span->lo + 1 > $max ) { $edge = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i ORDER BY id DESC LIMIT 1 OFFSET %d", $hits, $max ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. while ( $edge > 0 ) { if ( microtime( true ) - $start > $budget ) { $done = false; break; } $deleted = (int) $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE id <= %d LIMIT %d", $hits, $edge, $batch ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. if ( $deleted < $batch ) { break; } } } } $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE day < %s", $daily, gmdate( 'Y-m-d', time() - 400 * DAY_IN_SECONDS ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- custom table, no core API. $wpdb->suppress_errors( $quiet ); return $done; } /** * WP Rocket: user agents that must never get a cached page. * * @param array $uas Existing list. * @return array */ public static function rocket_reject_ua( $uas ) { $uas = (array) $uas; $bypass = Aeoora_Settings::get( 'tracking', 'cache_bypass', false ); foreach ( Aeoora_Bots::all() as $id => $bot ) { if ( ! empty( $bot['regex'] ) || ! empty( $bot['either'] ) || '' === $bot['pattern'] ) { continue; } $blocked = 'block' === Aeoora_Bots::policy( $id ) && Aeoora_Settings::get( 'blocker', 'enabled', true ); if ( $blocked || ( $bypass && Aeoora_Bots::is_ai_category( $bot['category'] ) && ! empty( $bot['token'] ) ) ) { // WP Rocket joins these into a regular expression (in .htaccess too): // text typed by the site owner is escaped so it can never break it. $uas[] = empty( $bot['custom'] ) ? $bot['pattern'] : preg_quote( $bot['pattern'], '#' ); } } return array_values( array_unique( $uas ) ); } }