v1.3.0
PriviMetrics 2
- <?php
-
- declare(strict_types=1);
- require_once __DIR__ . '/functions.php';
-
- header('Content-Type: application/json; charset=utf-8');
- header('X-Content-Type-Options: nosniff');
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Methods: GET, OPTIONS');
- header('Access-Control-Allow-Headers: Authorization, X-API-Key');
-
- function pmApiRespond(int $status, array $body, int $cacheSeconds = 0): void
- {
- http_response_code($status);
- header($cacheSeconds > 0 ? 'Cache-Control: public, max-age=' . $cacheSeconds : 'Cache-Control: no-store');
- $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE;
- if (pmQueryString('pretty') === '1') $flags |= JSON_PRETTY_PRINT;
- echo json_encode($body, $flags);
- exit;
- }
-
- if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
- http_response_code(204);
- exit;
- }
-
- if (!envIsInstalled()) {
- pmApiRespond(503, ['error' => 'PriviMetrics is not installed yet.']);
- }
-
- require_once __DIR__ . '/storage.php';
- require_once __DIR__ . '/stats.php';
-
- $key = trim((string) ($_SERVER['HTTP_X_API_KEY'] ?? ''));
- if ($key === '' && preg_match('/^Bearer\s+(\S+)$/i', (string) ($_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? ''), $m)) {
- $key = $m[1];
- }
- if ($key === '') {
- $key = trim(pmQueryString('key'));
- }
- $code = trim(pmQueryString('site'));
-
- $storage = new StorageManager();
- $site = null;
- $fields = [];
- $private = false;
-
- if ($key !== '') {
- foreach ($storage->listSites() as $candidate) {
- $candidateKey = (string) ($candidate['api_key'] ?? '');
- if ($candidateKey !== '' && !empty($candidate['api_key_enabled']) && hash_equals($candidateKey, $key)) {
- $site = $candidate;
- break;
- }
- }
- if (!$site) {
- pmApiRespond(401, ['error' => 'This API key is not valid or API key access is turned off.']);
- }
- $private = true;
- $fields = PM_API_ALL_FIELDS;
- } elseif ($code !== '') {
- $site = $storage->findSiteByTrackingCode($code);
- if (!$site || empty($site['api_public'])) {
- pmApiRespond(404, ['error' => 'Public stats are not available for this site.']);
- }
- $fields = array_filter(explode(',', pmValidApiFields($site['api_public_fields'] ?? PM_API_DEFAULT_PUBLIC_FIELDS)));
- if (!$fields) {
- pmApiRespond(404, ['error' => 'This site does not share any public stats.']);
- }
- } else {
- pmApiRespond(400, [
- 'error' => 'Pass ?site=TRACKING_CODE for public stats, or send your API key in the X-API-Key header.',
- 'params' => ['range' => implode('|', array_keys(PM_RANGE_OPTIONS)), 'from' => 'YYYY-MM-DD (range=custom)', 'to' => 'YYYY-MM-DD (range=custom)', 'limit' => '1-1000, default 10', 'pretty' => '1'],
- ]);
- }
-
- $clientId = $private ? 'key' : getClientIP();
- if (!checkRateLimit('api_' . $site['id'] . '_' . $clientId, $private ? 120 : 60, 60)) {
- header('Retry-After: 60');
- pmApiRespond(429, ['error' => 'Too many requests. Try again in a minute.']);
- }
-
- $limit = max(1, min(1000, (int) pmQueryString('limit', '10')));
- $data = pmComputeSiteStats(
- $storage,
- $site,
- pmQueryString('range', '30d'),
- pmQueryString('from'),
- pmQueryString('to'),
- array_values($fields),
- $limit
- );
- $data['access'] = $private ? 'api_key' : 'public';
- $data['generated_at'] = date('c');
-
- pmApiRespond(200, $data, $private ? 0 : 60);
-