Rest.inc.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * api/Rest.inc.php
  4. *
  5. * Base REST class. Fixed for PHP 8 compatibility:
  6. * - Removed get_magic_quotes_gpc() which was removed in PHP 8.0
  7. * - cleanInputs() no longer calls stripslashes conditionally
  8. */
  9. class REST
  10. {
  11. public array $_allow = [];
  12. public string $_content_type = 'application/json';
  13. public array $_request = [];
  14. private string $_method = '';
  15. private int $_code = 200;
  16. public function __construct()
  17. {
  18. $this->inputs();
  19. }
  20. public function get_referer(): string
  21. {
  22. return $_SERVER['HTTP_REFERER'] ?? '';
  23. }
  24. public function response(string $data, int $status): void
  25. {
  26. $this->_code = $status;
  27. $this->set_headers();
  28. echo $data;
  29. exit;
  30. }
  31. private function get_status_message(): string
  32. {
  33. $status = [
  34. 100 => 'Continue',
  35. 200 => 'OK',
  36. 201 => 'Created',
  37. 204 => 'No Content',
  38. 301 => 'Moved Permanently',
  39. 302 => 'Found',
  40. 400 => 'Bad Request',
  41. 401 => 'Unauthorized',
  42. 403 => 'Forbidden',
  43. 404 => 'Not Found',
  44. 405 => 'Method Not Allowed',
  45. 406 => 'Not Acceptable',
  46. 409 => 'Conflict',
  47. 500 => 'Internal Server Error',
  48. ];
  49. return $status[$this->_code] ?? 'Internal Server Error';
  50. }
  51. public function get_request_method(): string
  52. {
  53. return $_SERVER['REQUEST_METHOD'];
  54. }
  55. private function inputs(): void
  56. {
  57. switch ($this->get_request_method()) {
  58. case 'POST':
  59. $this->_request = $this->cleanInputs($_POST);
  60. break;
  61. case 'GET':
  62. case 'DELETE':
  63. $this->_request = $this->cleanInputs($_GET);
  64. break;
  65. case 'PUT':
  66. parse_str(file_get_contents('php://input'), $input);
  67. $this->_request = $this->cleanInputs($input);
  68. break;
  69. default:
  70. $this->response('', 406);
  71. }
  72. }
  73. private function cleanInputs(array|string $data): array|string
  74. {
  75. if (is_array($data)) {
  76. return array_map([$this, 'cleanInputs'], $data);
  77. }
  78. // PHP 8: magic_quotes were removed; just strip tags and trim
  79. return trim(strip_tags((string) $data));
  80. }
  81. private function set_headers(): void
  82. {
  83. header('HTTP/1.1 ' . $this->_code . ' ' . $this->get_status_message());
  84. header('Content-Type: ' . $this->_content_type);
  85. }
  86. }