v1.3.0
PriviMetrics 2
- <?php
-
- declare(strict_types=1);
-
- define('PM_ROOT', __DIR__);
- define('PM_DATA_DIR', PM_ROOT . '/data');
- define('PM_ENV_DIR', dirname(PM_ROOT));
- define('PM_ENV_FILE', PM_ENV_DIR . '/.pm-env');
-
- require_once __DIR__ . '/sources.php';
-
- function envLoad(bool $forceReload = false): array
- {
- static $cache = null;
- if ($cache !== null && !$forceReload) return $cache;
-
- $cache = [];
- if (!file_exists(PM_ENV_FILE)) return $cache;
-
- $lines = file(PM_ENV_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- foreach ($lines as $line) {
- $line = trim($line);
- if ($line === '' || str_starts_with($line, '#')) continue;
- if (!str_contains($line, '=')) continue;
-
- [$key, $value] = explode('=', $line, 2);
- $key = trim($key);
- $value = trim($value);
-
- if (strlen($value) >= 2) {
- $first = $value[0];
- $last = $value[strlen($value) - 1];
- if (($first === '"' && $last === '"') || ($first === "'" && $last === "'")) {
- $value = substr($value, 1, -1);
- }
- }
- $cache[$key] = $value;
- }
- return $cache;
- }
-
- function env(string $key, $default = null)
- {
- $env = envLoad();
- return $env[$key] ?? $default;
- }
-
- function envSet(string $key, string $value): bool
- {
- $lines = [];
- if (file_exists(PM_ENV_FILE)) {
- $raw = file(PM_ENV_FILE, FILE_IGNORE_NEW_LINES);
- if ($raw !== false) $lines = $raw;
- }
-
- $needsQuotes = $value === '' || preg_match('/[\s#"\']/', $value) === 1;
- $escaped = str_replace('"', '\\"', $value);
- $newLine = $key . '=' . ($needsQuotes ? '"' . $escaped . '"' : $escaped);
-
- $found = false;
- foreach ($lines as &$line) {
- $trimmed = trim($line);
- if ($trimmed === '' || str_starts_with($trimmed, '#') || !str_contains($trimmed, '=')) continue;
- [$k] = explode('=', $trimmed, 2);
- if (trim($k) === $key) {
- $line = $newLine;
- $found = true;
- break;
- }
- }
- unset($line);
-
- if (!$found) {
- $lines[] = $newLine;
- }
-
- $lockFile = PM_ENV_FILE . '.lock';
- $fp = fopen($lockFile, 'c');
- $ok = false;
- if ($fp && flock($fp, LOCK_EX)) {
- $ok = file_put_contents(PM_ENV_FILE, implode("\n", $lines) . "\n", LOCK_EX) !== false;
- flock($fp, LOCK_UN);
- fclose($fp);
- }
-
- envLoad_resetCache();
-
- return $ok;
- }
-
- function envLoad_resetCache(): void
- {
- envLoad(true);
- }
-
- function envSetMany(array $updates): bool
- {
- $lines = [];
- if (file_exists(PM_ENV_FILE)) {
- $raw = file(PM_ENV_FILE, FILE_IGNORE_NEW_LINES);
- if ($raw !== false) $lines = $raw;
- }
- $seen = [];
-
- foreach ($lines as $i => $line) {
- $trimmed = trim($line);
- if ($trimmed === '' || str_starts_with($trimmed, '#') || !str_contains($trimmed, '=')) continue;
- [$key] = explode('=', $trimmed, 2);
- $key = trim($key);
- if (array_key_exists($key, $updates)) {
- $val = (string) $updates[$key];
- $needsQuotes = $val === '' || preg_match('/\s|#/', $val) === 1;
- $lines[$i] = $key . '=' . ($needsQuotes ? '"' . str_replace('"', '\\"', $val) . '"' : $val);
- $seen[$key] = true;
- }
- }
-
- foreach ($updates as $k => $v) {
- if (isset($seen[$k])) continue;
- $v = (string) $v;
- $needsQuotes = $v === '' || preg_match('/\s|#/', $v) === 1;
- $lines[] = $k . '=' . ($needsQuotes ? '"' . str_replace('"', '\\"', $v) . '"' : $v);
- }
-
- $ok = file_put_contents(PM_ENV_FILE, implode("\n", $lines) . "\n") !== false;
- envLoad_resetCache();
- return $ok;
- }
-
- function envIsInstalled(): bool
- {
- return file_exists(PM_ENV_FILE) && env('APP_INSTALLED') === 'true';
- }
-
- function startSecureSession(): void
- {
- if (session_status() === PHP_SESSION_NONE) {
- ini_set('session.cookie_httponly', '1');
- ini_set('session.use_only_cookies', '1');
- ini_set('session.cookie_samesite', 'Lax');
- ini_set('session.cookie_lifetime', '0');
- ini_set('session.gc_maxlifetime', '86400');
-
- if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
- ini_set('session.cookie_secure', '1');
- }
-
- session_name('PRIVIMETRICS_SESSION');
- session_start();
-
- if (!isset($_SESSION['created'])) {
- $_SESSION['created'] = time();
- } elseif (time() - $_SESSION['created'] > 1800) {
- session_regenerate_id(true);
- $_SESSION['created'] = time();
- }
- }
- }
-
- function requireLogin(): void
- {
- startSecureSession();
- if (empty($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
- header('Location: login.php');
- exit;
- }
- $timeout = (int) env('SESSION_TIMEOUT', '86400');
- if (isset($_SESSION['login_time']) && (time() - $_SESSION['login_time']) > $timeout) {
- session_unset();
- session_destroy();
- header('Location: login.php?timeout=1');
- exit;
- }
- $_SESSION['last_activity'] = time();
- }
-
- function generateCSRFToken(): string
- {
- startSecureSession();
- if (empty($_SESSION['csrf_token'])) {
- $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
- }
- return $_SESSION['csrf_token'];
- }
-
- function verifyCSRFToken(?string $token): bool
- {
- startSecureSession();
- return !empty($_SESSION['csrf_token']) && is_string($token) && hash_equals($_SESSION['csrf_token'], $token);
- }
-
- function sanitize($input): string
- {
- return htmlspecialchars(strip_tags(trim((string) $input)), ENT_QUOTES, 'UTF-8');
- }
-
- function anonymizeIP(string $ip): string
- {
- if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
- return preg_replace('/\.\d+$/', '.0', $ip);
- } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
- return preg_replace('/:[^:]+:[^:]+$/', ':0:0', $ip);
- }
- return '0.0.0.0';
- }
-
- function getClientIP(): string
- {
- return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
- }
-
- function pmDailySalt(): string
- {
- static $salt = null;
- if ($salt !== null) return $salt;
-
- $today = gmdate('Y-m-d');
- $dir = PM_DATA_DIR . '/cache';
- if (!is_dir($dir)) @mkdir($dir, 0755, true);
-
- $fp = @fopen($dir . '/daily-salt.json', 'c+');
- if (!$fp || !flock($fp, LOCK_EX)) {
- if ($fp) fclose($fp);
- return $salt = bin2hex(random_bytes(32));
- }
-
- $data = json_decode((string) stream_get_contents($fp), true);
- if (is_array($data) && ($data['date'] ?? '') === $today && preg_match('/^[a-f0-9]{64}$/', (string) ($data['salt'] ?? ''))) {
- $salt = $data['salt'];
- } else {
- $salt = bin2hex(random_bytes(32));
- ftruncate($fp, 0);
- rewind($fp);
- fwrite($fp, json_encode(['date' => $today, 'salt' => $salt]));
- fflush($fp);
- }
- flock($fp, LOCK_UN);
- fclose($fp);
- return $salt;
- }
-
- function pmVisitorHash(string $ip, string $userAgent, string $domain): string
- {
- return substr(hash_hmac('sha256', $ip . '|' . $userAgent . '|' . strtolower($domain), pmDailySalt()), 0, 32);
- }
-
- function getUserAgent(): string
- {
- return sanitize($_SERVER['HTTP_USER_AGENT'] ?? 'Unknown');
- }
-
- function isDNTEnabled(): bool
- {
- return isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] === '1';
- }
-
- function hashPassword(string $password): string
- {
- return password_hash($password, PASSWORD_ARGON2ID);
- }
-
- function verifyPassword(string $password, string $hash): bool
- {
- return password_verify($password, $hash);
- }
-
- function generateID(): string
- {
- return bin2hex(random_bytes(4)) . uniqid('', true);
- }
-
- function formatNumber($number): string
- {
- $number = (float) $number;
- if ($number >= 1000000) return round($number / 1000000, 1) . 'm';
- if ($number >= 1000) return round($number / 1000, 1) . 'k';
- return (string) (int) $number;
- }
-
- function validateDomain(string $domain): bool
- {
- $domain = strtolower(trim($domain));
- return filter_var('http://' . $domain, FILTER_VALIDATE_URL) !== false;
- }
-
- function checkDomainMatch(string $allowed, string $current, string $mode): bool
- {
- $allowed = strtolower(trim($allowed));
- $current = strtolower(trim($current));
-
- $allowed = preg_replace('#^https?://#', '', $allowed);
- $allowed = preg_replace('#/.*$#', '', $allowed);
- $current = preg_replace('#^https?://#', '', $current);
- $current = preg_replace('#/.*$#', '', $current);
-
- switch ($mode) {
- case 'full':
- return $current === $allowed || (bool) preg_match('/\.' . preg_quote($allowed, '/') . '$/', $current);
- case 'main':
- return $current === $allowed;
- case 'none':
- return true;
- default:
- return false;
- }
- }
-
- function checkRateLimit(string $identifier, int $maxAttempts = 60, int $timeWindow = 60): bool
- {
- $cacheDir = PM_DATA_DIR . '/cache';
- if (!is_dir($cacheDir)) {
- mkdir($cacheDir, 0755, true);
- }
- $cacheFile = $cacheDir . '/rate_' . md5($identifier) . '.txt';
-
- $data = null;
- if (file_exists($cacheFile)) {
- $raw = file_get_contents($cacheFile);
- $data = $raw !== false ? json_decode($raw, true) : null;
- }
-
- if ($data && isset($data['time'], $data['count']) && $data['time'] > time() - $timeWindow) {
- if ($data['count'] >= $maxAttempts) {
- return false;
- }
- $data['count']++;
- } else {
- $data = ['count' => 1, 'time' => time()];
- }
-
- file_put_contents($cacheFile, json_encode($data), LOCK_EX);
- return true;
- }
-
- function getCountryFromIP(string $ip): array
- {
- $provider = env('GEO_PROVIDER', 'privacy-friendly');
- $modulePath = PM_ROOT . "/getCountryFrom/{$provider}.php";
-
- if (file_exists($modulePath)) {
- require_once $modulePath;
- if (function_exists('pm_fetch_location')) {
- $data = pm_fetch_location($ip);
- return [
- 'country' => $data['country'] ?? 'Unknown',
- 'code' => $data['code'] ?? 'XX',
- ];
- }
- }
-
- return ['country' => 'Unknown', 'code' => 'XX'];
- }
-
- const PM_RANGE_OPTIONS = [
- 'live' => 'Live (last 60 min)',
- '12h' => 'Last 12 hours',
- '24h' => 'Today',
- '2d' => 'Last 2 days',
- '5d' => 'Last 5 days',
- '7d' => 'Last 7 days',
- '14d' => 'Last 14 days',
- '30d' => 'Last 30 days',
- '90d' => 'Last 90 days',
- '182d' => 'Last 182 days',
- '1y' => 'Last year',
- 'all' => 'All time',
- 'custom' => 'Custom range',
- ];
-
- function pmParseDay(?string $value): ?int
- {
- if ($value === null || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) return null;
- $date = DateTime::createFromFormat('!Y-m-d', $value);
- return $date && $date->format('Y-m-d') === $value ? $date->getTimestamp() : null;
- }
-
- function pmBucketForSpan(int $start, int $end): string
- {
- $days = (int) floor(($end - $start) / 86400) + 1;
- if ($days <= 1) return 'hour';
- return $days <= 190 ? 'day' : 'month';
- }
-
- function getDateRange(string $range = '7d', ?string $from = null, ?string $to = null): array
- {
- $now = time();
- $todayStart = strtotime('today 00:00:00');
-
- if ($range === 'live') {
- return ['start' => $now - ($now % 60) - 59 * 60, 'end' => $now, 'bucket' => 'minute'];
- }
- if ($range === '12h' || $range === '2d') {
- $hourStart = (int) strtotime(date('Y-m-d H:00:00', $now));
- $hours = $range === '12h' ? 12 : 48;
- return ['start' => $hourStart - ($hours - 1) * 3600, 'end' => $now, 'bucket' => 'hourly'];
- }
- if ($range === '24h') {
- return ['start' => $todayStart, 'end' => strtotime('tomorrow 00:00:00') - 1, 'bucket' => 'hour'];
- }
- if ($range === '1y') {
- return ['start' => strtotime(date('Y-m-01', strtotime('-11 months', strtotime(date('Y-m-01')))) . ' 00:00:00'), 'end' => $now, 'bucket' => 'month'];
- }
- if ($range === 'all') {
- return ['start' => 0, 'end' => $now, 'bucket' => 'auto'];
- }
- if ($range === 'custom') {
- $start = pmParseDay($from);
- $endDay = pmParseDay($to);
- if ($start !== null && $endDay !== null) {
- if ($start > $endDay) [$start, $endDay] = [$endDay, $start];
- $endDay = min($endDay, $todayStart);
- $start = min($start, $endDay);
- $end = strtotime('+1 day', $endDay) - 1;
- return ['start' => $start, 'end' => $end, 'bucket' => pmBucketForSpan($start, $end)];
- }
- $range = '7d';
- }
- if (preg_match('/^(\d+)d$/', $range, $m) && isset(PM_RANGE_OPTIONS[$range])) {
- $days = (int) $m[1];
- return ['start' => strtotime('-' . ($days - 1) . ' days', $todayStart), 'end' => $now, 'bucket' => 'day'];
- }
- return ['start' => strtotime('-6 days', $todayStart), 'end' => $now, 'bucket' => 'day'];
- }
-
- function pmTimelineSlots(string $bucket, int $start, int $end): array
- {
- $now = time();
- $slots = [];
- if ($bucket === 'minute') {
- for ($ts = $start - ($start % 60); $ts <= $end && count($slots) < 400; $ts += 60) {
- $slots[date('Y-m-d H:i', $ts)] = $ts > $now;
- }
- return $slots;
- }
- if ($bucket === 'hourly') {
- for ($ts = (int) strtotime(date('Y-m-d H:00:00', $start)); $ts <= $end && count($slots) < 400; $ts += 3600) {
- $slots[date('Y-m-d H:00', $ts)] = $ts > $now;
- }
- return $slots;
- }
- if ($bucket === 'hour') {
- $dayStart = strtotime(date('Y-m-d', $start) . ' 00:00:00');
- for ($h = 0; $h < 24; $h++) {
- $ts = strtotime('+' . $h . ' hours', $dayStart);
- $slots[sprintf('%02d:00', $h)] = $ts > $now;
- }
- return $slots;
- }
- $cursor = new DateTime(date($bucket === 'month' ? 'Y-m-01' : 'Y-m-d', $start));
- $last = new DateTime(date($bucket === 'month' ? 'Y-m-01' : 'Y-m-d', $end));
- $step = $bucket === 'month' ? '+1 month' : '+1 day';
- $format = $bucket === 'month' ? 'Y-m' : 'Y-m-d';
- while ($cursor <= $last && count($slots) < 400) {
- $slots[$cursor->format($format)] = $cursor->getTimestamp() > $now;
- $cursor->modify($step);
- }
- return $slots;
- }
-
- function pmPixel(): string
- {
- return base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
- }
-
- function pmEmitPixelAndExit(): void
- {
- header('Content-Type: image/gif');
- header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
- header('Pragma: no-cache');
- echo pmPixel();
- exit;
- }
-
- function pmRateLimitFor(string $storageType): array
- {
- $limits = [
- 'xml' => ['requests' => (int) env('RATE_LIMIT_XML', '2'), 'window' => 1],
- 'mysql' => ['requests' => (int) env('RATE_LIMIT_MYSQL', '5'), 'window' => 1],
- 'pmaf' => ['requests' => (int) env('RATE_LIMIT_PMAF', '5'), 'window' => 1],
- ];
- return $limits[$storageType] ?? ['requests' => 2, 'window' => 1];
- }
-
- function pmDbParamsError(string $host, string $port, string $name): ?string
- {
- if (!preg_match('/^[A-Za-z0-9._:\[\]-]+$/', $host)) {
- return 'Invalid MySQL host.';
- }
- if (!ctype_digit($port) || (int) $port < 1 || (int) $port > 65535) {
- return 'Invalid MySQL port.';
- }
- if (!preg_match('/^[A-Za-z0-9_$-]+$/', $name)) {
- return 'Invalid MySQL database name (allowed: letters, digits, _ $ -).';
- }
- return null;
- }
-
- function pmSecurityHeaders(): void
- {
- header('X-Content-Type-Options: nosniff');
- header('X-Frame-Options: DENY');
- header('Referrer-Policy: same-origin');
- }
-
- function extractUtmSource(string $pageUrl): string
- {
- $query = parse_url($pageUrl, PHP_URL_QUERY);
- if (!$query) return '';
- parse_str($query, $params);
- if (empty($params['utm_source'])) return '';
- return sanitize($params['utm_source']);
- }
-
- const PM_TOGGLEABLE_FEATURES = ['traffic_sources', 'visitor_countries', 'search_queries', 'browser_detection'];
-
- const PM_FEATURES_DEFAULT_OFF = ['browser_detection', 'search_engines', 'crawlers'];
-
- function pmFeatureGlobalEnabled(string $feature): bool
- {
- $map = [
- 'traffic_sources' => 'FEATURE_TRAFFIC_SOURCES',
- 'visitor_countries' => 'FEATURE_VISITOR_COUNTRIES',
- 'search_queries' => 'FEATURE_SEARCH_QUERIES',
- 'device_type' => 'FEATURE_DEVICE_TYPE',
- 'browser_detection' => 'FEATURE_BROWSER_DETECTION',
- 'search_engines' => 'FEATURE_SEARCH_ENGINES',
- 'crawlers' => 'FEATURE_CRAWLERS',
- ];
- $key = $map[$feature] ?? null;
- if (!$key) return true;
- $default = in_array($feature, PM_FEATURES_DEFAULT_OFF, true) ? 'false' : 'true';
- return env($key, $default) === 'true';
- }
-
- function pmFeatureEnabledForSite(?array $site, string $feature): bool
- {
- $global = pmFeatureGlobalEnabled($feature);
- if (!$site) return $global;
-
- $overrideKey = $feature . '_mode';
- $mode = $site[$overrideKey] ?? 'inherit';
-
- if ($mode === 'on') return true;
- if ($mode === 'off') return false;
- return $global;
- }
-
- function pmQueryString(string $key, string $default = ''): string
- {
- $value = $_GET[$key] ?? $default;
- return is_string($value) ? $value : $default;
- }
-
- function pmValidFeatureMode(?string $mode): string
- {
- return in_array($mode, ['inherit', 'on', 'off'], true) ? $mode : 'inherit';
- }
-
- function pmBrowserCatalog(): array
- {
- return [
- 'chrome' => 'Chrome',
- 'chromium' => 'Chromium',
- 'firefox' => 'Firefox',
- 'safari' => 'Safari',
- 'edge' => 'Microsoft Edge',
- 'edge-legacy' => 'Edge Legacy',
- 'ie' => 'Internet Explorer',
- 'opera' => 'Opera',
- 'opera-gx' => 'Opera GX',
- 'opera-mini' => 'Opera Mini',
- 'opera-neon' => 'Opera Neon',
- 'opera-air' => 'Opera Air',
- 'brave' => 'Brave',
- 'vivaldi' => 'Vivaldi',
- 'samsung' => 'Samsung Internet',
- 'yandex' => 'Yandex Browser',
- 'uc' => 'UC Browser',
- 'comet' => 'Comet (Perplexity)',
- 'atlas' => 'ChatGPT Atlas',
- 'dia' => 'Dia',
- 'genspark' => 'Genspark',
- 'fellou' => 'Fellou',
- 'sigmaos' => 'SigmaOS',
- 'arc' => 'Arc',
- 'orion' => 'Orion',
- 'tor' => 'Tor Browser',
- 'mullvad' => 'Mullvad Browser',
- 'librewolf' => 'LibreWolf',
- 'waterfox' => 'Waterfox',
- 'floorp' => 'Floorp',
- 'zen' => 'Zen Browser',
- 'pale-moon' => 'Pale Moon',
- 'basilisk' => 'Basilisk',
- 'seamonkey' => 'SeaMonkey',
- 'icecat' => 'GNU IceCat',
- 'k-meleon' => 'K-Meleon',
- 'firefox-focus' => 'Firefox Focus',
- 'duckduckgo' => 'DuckDuckGo',
- 'ghostery' => 'Ghostery',
- 'cromite' => 'Cromite',
- 'ungoogled-chromium' => 'Ungoogled Chromium',
- 'helium' => 'Helium',
- 'thorium' => 'Thorium',
- 'supermium' => 'Supermium',
- 'iridium' => 'Iridium',
- 'ladybird' => 'Ladybird',
- 'wavebox' => 'Wavebox',
- 'comodo-dragon' => 'Comodo Dragon',
- 'avast-secure' => 'Avast Secure Browser',
- 'avg-secure' => 'AVG Secure Browser',
- 'epic' => 'Epic Privacy Browser',
- 'maxthon' => 'Maxthon',
- 'midori' => 'Midori',
- 'falkon' => 'Falkon',
- 'konqueror' => 'Konqueror',
- 'gnome-web' => 'GNOME Web',
- 'qutebrowser' => 'qutebrowser',
- 'otter' => 'Otter Browser',
- 'min' => 'Min',
- 'netsurf' => 'NetSurf',
- 'avant' => 'Avant Browser',
- 'sleipnir' => 'Sleipnir',
- 'kiwi' => 'Kiwi Browser',
- 'via' => 'Via Browser',
- 'aloha' => 'Aloha Browser',
- 'dolphin' => 'Dolphin',
- 'puffin' => 'Puffin',
- 'whale' => 'Naver Whale',
- 'coccoc' => 'Cốc Cốc',
- 'qq' => 'QQ Browser',
- '360' => '360 Browser',
- 'sogou' => 'Sogou Browser',
- 'baidu' => 'Baidu Browser',
- 'huawei' => 'Huawei Browser',
- 'mi' => 'Mi Browser',
- 'vivo' => 'vivo Browser',
- 'heytap' => 'HeyTap Browser',
- 'phoenix' => 'Phoenix Browser',
- 'silk' => 'Amazon Silk',
- 'nintendo' => 'Nintendo Browser',
- 'facebook' => 'Facebook (in-app)',
- 'instagram' => 'Instagram (in-app)',
- 'tiktok' => 'TikTok (in-app)',
- 'wechat' => 'WeChat (in-app)',
- 'line' => 'LINE (in-app)',
- 'telegram' => 'Telegram (in-app)',
- 'snapchat' => 'Snapchat (in-app)',
- 'pinterest' => 'Pinterest (in-app)',
- 'linkedin' => 'LinkedIn (in-app)',
- 'android-webview' => 'Android WebView',
- 'bot' => 'Bots and crawlers',
- 'unknown' => 'Unknown',
- ];
- }
-
- function pmBrowserName(string $slug): string
- {
- return pmBrowserCatalog()[$slug] ?? 'Unknown';
- }
-
- function pmBrowserIconPath(string $slug): string
- {
- $file = 'assets/browsers/' . $slug . '.webp';
- return is_file(__DIR__ . '/' . $file) ? $file : 'assets/browsers/unknown.webp';
- }
-
- function pmBrowserFromUserAgent(string $userAgent): string
- {
- static $cache = [];
- if (array_key_exists($userAgent, $cache)) return $cache[$userAgent];
- if (count($cache) >= PM_DETECT_CACHE_LIMIT) $cache = [];
- return $cache[$userAgent] = pmBrowserMatchUserAgent($userAgent);
- }
-
- function pmBrowserMatchUserAgent(string $userAgent): string
- {
- if ($userAgent === '' || strtolower($userAgent) === 'unknown') return 'unknown';
- if (pmCrawlerFromUserAgent($userAgent) !== null) return 'bot';
-
- $slug = pmMatchRules(pmBrowserRegex(), $userAgent);
- if ($slug !== null) return $slug;
-
- if (preg_match('/CriOS|Chrome\//', $userAgent)) {
- if (preg_match('/; wv\)/', $userAgent)) return 'android-webview';
- if (str_contains($userAgent, 'Chromium/')) return 'chromium';
- return 'chrome';
- }
-
- if (str_contains($userAgent, 'AppleWebKit') && preg_match('/Safari\/|iPhone|iPad|iPod|Macintosh/', $userAgent)) {
- return 'safari';
- }
-
- return 'unknown';
- }
-
- function pmBrowserRegex(): array
- {
- static $compiled = null;
- if ($compiled !== null) return $compiled;
-
- $rules = [
- 'facebook' => '/FBAN|FBAV|FB_IAB|FBIOS/',
- 'instagram' => '/Instagram/',
- 'tiktok' => '/musical_ly|BytedanceWebview|TikTok|trill_/i',
- 'wechat' => '/MicroMessenger/',
- 'line' => '/\sLine\//',
- 'telegram' => '/Telegram/i',
- 'snapchat' => '/Snapchat/',
- 'pinterest' => '/Pinterest/',
- 'linkedin' => '/LinkedInApp/',
- 'comet' => '/\bComet\//',
- 'atlas' => '/ChatGPT[\s-]?Atlas|\bAtlas\//',
- 'dia' => '/\bDia\//',
- 'genspark' => '/Genspark/i',
- 'fellou' => '/Fellou/i',
- 'sigmaos' => '/SigmaOS/i',
- 'arc' => '/\bArc\//',
- 'opera-gx' => '/OPRGX|Opera\s?GX/i',
- 'opera-neon' => '/OPRNeon|Opera\s?Neon/i',
- 'opera-air' => '/OPRAir|Opera\s?Air/i',
- 'opera-mini' => '/Opera Mini|OPiOS.*Mini/',
- 'edge-legacy' => '/\bEdge\/\d/',
- 'edge' => '/\bEdg(A|iOS)?\//',
- 'yandex' => '/YaBrowser|YaSearchBrowser|Yowser/',
- 'samsung' => '/SamsungBrowser/',
- 'uc' => '/UCBrowser|UCWEB|UBrowser/',
- 'vivaldi' => '/Vivaldi/',
- 'brave' => '/\bBrave\b/',
- 'whale' => '/\bWhale\//',
- 'coccoc' => '/coc_coc_browser/i',
- 'qq' => '/M?QQBrowser/',
- '360' => '/360SE|360EE|QihooBrowser|QHBrowser/',
- 'sogou' => '/MetaSr|SogouMobileBrowser|SE 2\.X/',
- 'baidu' => '/baiduboxapp|BIDUBrowser|baidubrowser/i',
- 'huawei' => '/HuaweiBrowser/',
- 'mi' => '/MiuiBrowser/',
- 'vivo' => '/VivoBrowser/i',
- 'heytap' => '/HeyTapBrowser|OppoBrowser/i',
- 'phoenix' => '/\bPHX\//',
- 'maxthon' => '/Maxthon|MXiOS/',
- 'puffin' => '/Puffin/',
- 'silk' => '/\bSilk\//',
- 'sleipnir' => '/Sleipnir/',
- 'nintendo' => '/NintendoBrowser|Nintendo (Switch|WiiU|3DS)/',
- 'aloha' => '/AlohaBrowser/i',
- 'duckduckgo' => '/DuckDuckGo\/|\bDdg\//',
- 'ghostery' => '/Ghostery/i',
- 'firefox-focus' => '/\bFocus\/|\bKlar\//',
- 'mullvad' => '/Mullvad/i',
- 'librewolf' => '/LibreWolf/i',
- 'waterfox' => '/Waterfox/i',
- 'floorp' => '/Floorp/i',
- 'zen' => '/\bZen\//',
- 'pale-moon' => '/PaleMoon/',
- 'basilisk' => '/Basilisk/',
- 'seamonkey' => '/SeaMonkey/',
- 'icecat' => '/IceCat/',
- 'k-meleon' => '/K-Meleon/',
- 'thorium' => '/Thorium/',
- 'helium' => '/\bHelium\//',
- 'supermium' => '/Supermium/',
- 'iridium' => '/Iridium/',
- 'cromite' => '/Cromite/i',
- 'ladybird' => '/Ladybird/',
- 'wavebox' => '/Wavebox/',
- 'comodo-dragon' => '/Comodo_Dragon|\bDragon\/\d/',
- 'avast-secure' => '/\bAvast\/|\bASW\//',
- 'avg-secure' => '/\bAVG\//',
- 'epic' => '/\bEpic\//',
- 'midori' => '/Midori/',
- 'falkon' => '/Falkon|QupZilla/',
- 'konqueror' => '/Konqueror/',
- 'gnome-web' => '/Epiphany/',
- 'qutebrowser' => '/qutebrowser/',
- 'otter' => '/\bOtter\//',
- 'min' => '/\bmin\/\d/',
- 'netsurf' => '/NetSurf/',
- 'avant' => '/Avant Browser/',
- 'kiwi' => '/Kiwi/',
- 'dolphin' => '/Dolphin|Dolfin/',
- 'opera' => '/\bOPR\/|\bOpera\b|OPiOS/',
- 'ie' => '/MSIE |Trident\//',
- 'firefox' => '/Firefox\/|FxiOS/',
- ];
-
- return $compiled = pmCompileRules($rules);
- }
-
- function pmBrowserFromHint(string $hint): ?string
- {
- $key = preg_replace('/[^a-z0-9]/', '', strtolower($hint));
- if ($key === '') return null;
-
- $aliases = [
- 'microsoftedge' => 'edge',
- 'chatgptatlas' => 'atlas',
- 'perplexitycomet' => 'comet',
- 'yabrowser' => 'yandex',
- 'naverwhale' => 'whale',
- 'samsunginternet' => 'samsung',
- ];
- if (isset($aliases[$key])) return $aliases[$key];
-
- foreach (pmBrowserCatalog() as $slug => $name) {
- $slug = (string) $slug;
- if ($slug === 'unknown') continue;
- $nameKey = preg_replace('/[^a-z0-9]/', '', strtolower((string) preg_replace('/\s*\(.*\)$/', '', $name)));
- if ($key === $nameKey || $key === str_replace('-', '', $slug)) return $slug;
- }
- return null;
- }
-
- function pmDetectBrowser(string $userAgent, string $hint = ''): string
- {
- $fromUa = pmBrowserFromUserAgent($userAgent);
- if ($hint === '') return $fromUa;
-
- $fromHint = pmBrowserFromHint($hint);
- if ($fromHint === null) return $fromUa;
-
- if ($fromUa === 'opera' && str_starts_with($fromHint, 'opera-')) return $fromHint;
-
- $generic = ['chrome', 'chromium', 'safari', 'firefox', 'android-webview', 'unknown'];
- return in_array($fromUa, $generic, true) ? $fromHint : $fromUa;
- }
-