WebOrbiton
v3.0.0.0

FlatlyPage

49 lines · 1.9 KB
  1. <?php
  2. require_once __DIR__ . '/../config.php';
  3. ​
  4. header('Content-Type: application/json; charset=utf-8');
  5. header('Cache-Control: no-store');
  6. header('X-Content-Type-Options: nosniff');
  7. ​
  8. function analytics_respond(int $status, array $payload): void
  9. {
  10. http_response_code($status);
  11. echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
  12. exit;
  13. }
  14. ​
  15. if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  16. header('Allow: POST');
  17. analytics_respond(405, ['ok' => false, 'error' => 'Method not allowed.']);
  18. }
  19. ​
  20. if (!is_logged_in()) {
  21. analytics_respond(401, ['ok' => false, 'error' => 'Your session has expired. Reload the page and log in again.']);
  22. }
  23. check_ip_ban();
  24. ​
  25. if (!verify_csrf_token((string) ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''))) {
  26. analytics_respond(403, ['ok' => false, 'error' => 'Invalid security token. Reload the page and try again.']);
  27. }
  28. ​
  29. $maxBody = 4194304;
  30. if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > $maxBody) {
  31. analytics_respond(413, ['ok' => false, 'error' => 'The scripts are too large.']);
  32. }
  33. ​
  34. // The settings arrive base64-encoded so hosting firewalls don't block a body containing <script>.
  35. $input = json_decode((string) file_get_contents('php://input', false, null, 0, $maxBody + 1), true);
  36. $decoded = is_array($input) && is_string($input['payload'] ?? null) ? base64_decode($input['payload'], true) : false;
  37. $data = $decoded !== false ? json_decode($decoded, true) : null;
  38. if (!is_array($data)) {
  39. analytics_respond(400, ['ok' => false, 'error' => 'Invalid request.']);
  40. }
  41. ​
  42. $system = get_system_settings();
  43. $system['analytics'] = flatly_clean_analytics($data);
  44. if (!save_page('system', $system)) {
  45. analytics_respond(500, ['ok' => false, 'error' => 'Could not write data/system.php. Check the folder permissions.']);
  46. }
  47. ​
  48. analytics_respond(200, ['ok' => true, 'analytics' => $system['analytics']]);
  49. ​