WebOrbiton
v1.3.0

PriviMetrics 2

97 lines · 3.3 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. require_once __DIR__ . '/functions.php';
  5. ​
  6. header('Content-Type: application/json; charset=utf-8');
  7. header('X-Content-Type-Options: nosniff');
  8. header('Access-Control-Allow-Origin: *');
  9. header('Access-Control-Allow-Methods: GET, OPTIONS');
  10. header('Access-Control-Allow-Headers: Authorization, X-API-Key');
  11. ​
  12. function pmApiRespond(int $status, array $body, int $cacheSeconds = 0): void
  13. {
  14. http_response_code($status);
  15. header($cacheSeconds > 0 ? 'Cache-Control: public, max-age=' . $cacheSeconds : 'Cache-Control: no-store');
  16. $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE;
  17. if (pmQueryString('pretty') === '1') $flags |= JSON_PRETTY_PRINT;
  18. echo json_encode($body, $flags);
  19. exit;
  20. }
  21. ​
  22. if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
  23. http_response_code(204);
  24. exit;
  25. }
  26. ​
  27. if (!envIsInstalled()) {
  28. pmApiRespond(503, ['error' => 'PriviMetrics is not installed yet.']);
  29. }
  30. ​
  31. require_once __DIR__ . '/storage.php';
  32. require_once __DIR__ . '/stats.php';
  33. ​
  34. $key = trim((string) ($_SERVER['HTTP_X_API_KEY'] ?? ''));
  35. if ($key === '' && preg_match('/^Bearer\s+(\S+)$/i', (string) ($_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? ''), $m)) {
  36. $key = $m[1];
  37. }
  38. if ($key === '') {
  39. $key = trim(pmQueryString('key'));
  40. }
  41. $code = trim(pmQueryString('site'));
  42. ​
  43. $storage = new StorageManager();
  44. $site = null;
  45. $fields = [];
  46. $private = false;
  47. ​
  48. if ($key !== '') {
  49. foreach ($storage->listSites() as $candidate) {
  50. $candidateKey = (string) ($candidate['api_key'] ?? '');
  51. if ($candidateKey !== '' && !empty($candidate['api_key_enabled']) && hash_equals($candidateKey, $key)) {
  52. $site = $candidate;
  53. break;
  54. }
  55. }
  56. if (!$site) {
  57. pmApiRespond(401, ['error' => 'This API key is not valid or API key access is turned off.']);
  58. }
  59. $private = true;
  60. $fields = PM_API_ALL_FIELDS;
  61. } elseif ($code !== '') {
  62. $site = $storage->findSiteByTrackingCode($code);
  63. if (!$site || empty($site['api_public'])) {
  64. pmApiRespond(404, ['error' => 'Public stats are not available for this site.']);
  65. }
  66. $fields = array_filter(explode(',', pmValidApiFields($site['api_public_fields'] ?? PM_API_DEFAULT_PUBLIC_FIELDS)));
  67. if (!$fields) {
  68. pmApiRespond(404, ['error' => 'This site does not share any public stats.']);
  69. }
  70. } else {
  71. pmApiRespond(400, [
  72. 'error' => 'Pass ?site=TRACKING_CODE for public stats, or send your API key in the X-API-Key header.',
  73. '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'],
  74. ]);
  75. }
  76. ​
  77. $clientId = $private ? 'key' : getClientIP();
  78. if (!checkRateLimit('api_' . $site['id'] . '_' . $clientId, $private ? 120 : 60, 60)) {
  79. header('Retry-After: 60');
  80. pmApiRespond(429, ['error' => 'Too many requests. Try again in a minute.']);
  81. }
  82. ​
  83. $limit = max(1, min(1000, (int) pmQueryString('limit', '10')));
  84. $data = pmComputeSiteStats(
  85. $storage,
  86. $site,
  87. pmQueryString('range', '30d'),
  88. pmQueryString('from'),
  89. pmQueryString('to'),
  90. array_values($fields),
  91. $limit
  92. );
  93. $data['access'] = $private ? 'api_key' : 'public';
  94. $data['generated_at'] = date('c');
  95. ​
  96. pmApiRespond(200, $data, $private ? 0 : 60);
  97. ​