← Back
Editing: class-cal-aiv-dispatcher.php
<?php if (!defined('ABSPATH')) { exit; } /** * Sends one matched bot hit to the unauthenticated /collect route, never while the visitor waits. */ class CAL_AIV_Dispatcher { const QUEUE_PREFIX = 'cal_aiv_q_'; // Reached only when WP-Cron never runs; dropping events beats growing wp_options forever. const QUEUE_MAX = 1000; const MAX_BODY_BYTES = 16384; const FLUSH_BATCH = 50; public static function run() { $event = self::build_event(); if ($event === null) { return; } // WordPress's 'blocking' => false still waits in curl_exec, so the visitor's connection is closed first. if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); self::send($event); } elseif (function_exists('litespeed_finish_request')) { litespeed_finish_request(); self::send($event); } else { // e.g. Apache mod_php can't close the response early, so WP-Cron sends it from its own request. self::enqueue($event); } } public static function flush() { global $wpdb; if (!cal_aiv_is_enabled()) { self::clear_queue(); return; } // No WordPress API lists options by prefix. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $names = $wpdb->get_col($wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s ORDER BY option_id LIMIT %d", $wpdb->esc_like(self::QUEUE_PREFIX) . '%', self::FLUSH_BATCH )); foreach ($names as $name) { $event = get_option($name); // Deleting first claims the event, so overlapping cron runs don't send it twice. if (!delete_option($name) || !is_array($event) || empty($event['url']) || empty($event['body'])) { continue; } self::send($event); } if (count($names) === self::FLUSH_BATCH) { wp_schedule_single_event(time(), 'cal_aiv_flush'); } } public static function clear_queue() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query($wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like(self::QUEUE_PREFIX) . '%' )); wp_clear_scheduled_hook('cal_aiv_flush'); } private static function build_event() { $bot = CAL_AIV_Detector::get_matched(); if ($bot === null) { return null; } $publisher_id = cal_aiv_publisher_id(); if (!$publisher_id) { return null; } // The endpoint 400s on these; send nothing rather than a doomed request. $bot_name = substr(preg_replace('/[^A-Za-z0-9 ._-]/', '', $bot['bot_name']), 0, 128); $methods = array('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'); if ($bot_name === '' || strlen($bot['url']) > 2048 || !in_array($bot['method'], $methods, true) || $bot['client_ip'] === '') { return null; } $payload = array( 'sourceVersion' => PUBLISHER_MASTERTAG_PLUGIN_VERSION, 'source' => 'WORDPRESS_PLUGIN', 'provider' => 'WORDPRESS', 'eventType' => 'AI_VISIBILITY', 'domain' => $bot['hostname'], 'url' => self::utf8($bot['url']), 'method' => $bot['method'], 'statusCode' => (int) (http_response_code() ?: 200), 'userAgent' => self::truncate($bot['user_agent'], 1024), 'referer' => self::truncate($bot['referer'], 2048), 'origin' => self::truncate($bot['origin'], 2048), 'clientIp' => $bot['client_ip'], 'botName' => $bot_name, ); // Body must be a JSON string: an array is sent form-encoded and gets a 415. // Unescaped so field caps hold; escaping can triple non-ASCII and push the body past /collect's 16 KiB limit. $body = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if (!is_string($body) || $body === '' || strlen($body) > self::MAX_BODY_BYTES) { return null; } return array( 'url' => sprintf('https://api.awin.com/publishers/%d/ai-visibility/access-logs/collect', $publisher_id), 'body' => $body, ); } private static function send($event) { wp_remote_post($event['url'], array( 'headers' => array('Content-Type' => 'application/json'), 'body' => $event['body'], 'timeout' => 1, 'sslverify' => true, )); } private static function enqueue($event) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $queued = (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like(self::QUEUE_PREFIX) . '%' )); if ($queued >= self::QUEUE_MAX) { return; } // One row per event: appending to a single option would lose events to concurrent bot hits. add_option(self::QUEUE_PREFIX . str_replace('.', '', uniqid('', true)) . wp_rand(100, 999), $event, '', 'no'); if (!wp_next_scheduled('cal_aiv_flush')) { wp_schedule_single_event(time(), 'cal_aiv_flush'); } } private static function truncate($value, $max) { return $value === null ? null : self::utf8(substr($value, 0, $max)); } // json_encode fails on invalid UTF-8, including a multibyte character cut in half by substr. private static function utf8($value) { if ($value === '' || preg_match('//u', $value)) { return $value; } if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($value, 'UTF-8', 'UTF-8'); } // Neither extension is required; '@' doesn't stop an undefined-function fatal. if (!function_exists('iconv')) { return ''; } $clean = @iconv('UTF-8', 'UTF-8//IGNORE', $value); return $clean === false ? '' : $clean; } }
Save File
Cancel