WebOrbiton
v3.0.0.2

FlatlyPage

48 lines · 1.8 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 expired. Reload the page and sign 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' => 'Your session timed out. 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' => 'Your scripts are too large to save.']);
  32. }
  33. ​
  34. $input = json_decode((string) file_get_contents('php://input', false, null, 0, $maxBody + 1), true);
  35. $decoded = is_array($input) && is_string($input['payload'] ?? null) ? base64_decode($input['payload'], true) : false;
  36. $data = $decoded !== false ? json_decode($decoded, true) : null;
  37. if (!is_array($data)) {
  38. analytics_respond(400, ['ok' => false, 'error' => 'Something went wrong. Reload the page and try again.']);
  39. }
  40. ​
  41. $system = get_system_settings();
  42. $system['analytics'] = flatly_clean_analytics($data);
  43. if (!save_page('system', $system)) {
  44. analytics_respond(500, ['ok' => false, 'error' => "Couldn't save. Check the folder permissions on your server."]);
  45. }
  46. ​
  47. analytics_respond(200, ['ok' => true, 'analytics' => $system['analytics']]);
  48. ​