4
0

Request.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Licensed under AGPL3 <https://www.gnu.org/licenses/>
  6. */
  7. /**
  8. * The Minz_Request class represents the HTTP request
  9. */
  10. class Minz_Request {
  11. private static string $controller_name = '';
  12. private static string $action_name = '';
  13. /** @var array<string,mixed> */
  14. private static array $params = [];
  15. private static string $default_controller_name = 'index';
  16. private static string $default_action_name = 'index';
  17. /** @var array{c?:string,a?:string,params?:array<string,mixed>} */
  18. private static array $originalRequest = [];
  19. /**
  20. * Getters
  21. */
  22. public static function controllerName(): string {
  23. return self::$controller_name;
  24. }
  25. public static function actionName(): string {
  26. return self::$action_name;
  27. }
  28. /** @return array<string,mixed> */
  29. public static function params(): array {
  30. return self::$params;
  31. }
  32. /**
  33. * Read the URL parameter
  34. * @param string $key Key name
  35. * @param mixed $default default value, if no parameter is given
  36. * @param bool $specialchars `true` to return special characters, `false` (default) to XML-encode them
  37. * @return mixed value of the parameter
  38. */
  39. #[Deprecated('Use typed versions instead')]
  40. public static function param(string $key, mixed $default = false, bool $specialchars = false): mixed {
  41. if (isset(self::$params[$key])) {
  42. $p = self::$params[$key];
  43. if (is_string($p) || is_array($p)) {
  44. return $specialchars ? $p : Minz_Helper::htmlspecialchars_utf8($p);
  45. } else {
  46. return $p;
  47. }
  48. } else {
  49. return $default;
  50. }
  51. }
  52. public static function hasParam(string $key): bool {
  53. return isset(self::$params[$key]);
  54. }
  55. /**
  56. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  57. * @return array<string|int,string|array<int|string,string|int|bool>>
  58. */
  59. public static function paramArray(string $key, bool $plaintext = false): array {
  60. if (empty(self::$params[$key]) || !is_array(self::$params[$key])) {
  61. return [];
  62. }
  63. $result = [];
  64. foreach (self::$params[$key] as $k => $v) {
  65. if (is_string($v)) {
  66. $result[$k] = $v;
  67. } elseif (is_array($v)) {
  68. $vs = [];
  69. foreach ($v as $k2 => $v2) {
  70. if (is_string($v2) || is_int($v2) || is_bool($v2)) {
  71. $vs[$k2] = $v2;
  72. }
  73. }
  74. $result[$k] = $vs;
  75. }
  76. }
  77. return $plaintext ? $result : Minz_Helper::htmlspecialchars_utf8($result);
  78. }
  79. /**
  80. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  81. * @return list<string>
  82. */
  83. public static function paramArrayString(string $key, bool $plaintext = false): array {
  84. if (empty(self::$params[$key]) || !is_array(self::$params[$key])) {
  85. return [];
  86. }
  87. $result = array_filter(self::$params[$key], 'is_string');
  88. $result = array_values($result);
  89. return $plaintext ? $result : Minz_Helper::htmlspecialchars_utf8($result);
  90. }
  91. /**
  92. * @return list<int>
  93. */
  94. public static function paramArrayInt(string $key): array {
  95. if (empty(self::$params[$key]) || !is_array(self::$params[$key])) {
  96. return [];
  97. }
  98. $result = array_filter(self::$params[$key], 'is_numeric');
  99. $result = array_map('intval', $result);
  100. return array_values($result);
  101. }
  102. public static function paramTernary(string $key): ?bool {
  103. if (isset(self::$params[$key])) {
  104. $p = self::$params[$key];
  105. $tp = is_string($p) ? trim($p) : true;
  106. if ($tp === '' || $tp === 'null') {
  107. return null;
  108. } elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') {
  109. return false;
  110. }
  111. return true;
  112. }
  113. return null;
  114. }
  115. public static function paramBoolean(string $key): bool {
  116. if (null === $value = self::paramTernary($key)) {
  117. return false;
  118. }
  119. return $value;
  120. }
  121. public static function paramIntNull(string $key): ?int {
  122. return is_numeric(self::$params[$key] ?? null) ? (int)self::$params[$key] : null;
  123. }
  124. public static function paramInt(string $key): int {
  125. if (!empty(self::$params[$key]) && is_numeric(self::$params[$key])) {
  126. return (int)self::$params[$key];
  127. }
  128. return 0;
  129. }
  130. /**
  131. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  132. * @param bool $trim `false` to skip trimming whitespace surrounding the parameter, `true` (default) to trim whitespace
  133. */
  134. public static function paramStringNull(string $key, bool $plaintext = false, bool $trim = true): ?string {
  135. if (isset(self::$params[$key])) {
  136. $s = self::$params[$key];
  137. if (is_string($s)) {
  138. if ($trim) {
  139. $s = trim($s);
  140. }
  141. return $plaintext ? $s : htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  142. }
  143. if (is_int($s) || is_bool($s)) {
  144. return (string)$s;
  145. }
  146. }
  147. return null;
  148. }
  149. /**
  150. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  151. * @param bool $trim `false` to skip trimming whitespace surrounding the parameter, `true` (default) to trim whitespace
  152. */
  153. public static function paramString(string $key, bool $plaintext = false, bool $trim = true): string {
  154. return self::paramStringNull($key, $plaintext, $trim) ?? '';
  155. }
  156. /**
  157. * Extract text lines to array.
  158. *
  159. * It will return an array where each cell contains one line of a text. The new line
  160. * character is used to break the text into lines. This method is well suited to use
  161. * to split textarea content.
  162. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  163. * @return list<string>|null
  164. */
  165. public static function paramTextToArrayNull(string $key, bool $plaintext = false): ?array {
  166. if (isset(self::$params[$key]) && is_string(self::$params[$key])) {
  167. $result = preg_split('/\R/u', self::$params[$key]) ?: [];
  168. return $plaintext ? $result : Minz_Helper::htmlspecialchars_utf8($result);
  169. }
  170. return null;
  171. }
  172. /**
  173. * Extract text lines to array.
  174. *
  175. * It will return an array where each cell contains one line of a text. The new line
  176. * character is used to break the text into lines. This method is well suited to use
  177. * to split textarea content.
  178. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  179. * @return list<string>
  180. */
  181. public static function paramTextToArray(string $key, bool $plaintext = false): array {
  182. return self::paramTextToArrayNull($key, $plaintext) ?? [];
  183. }
  184. public static function defaultControllerName(): string {
  185. return self::$default_controller_name;
  186. }
  187. public static function defaultActionName(): string {
  188. return self::$default_action_name;
  189. }
  190. /** @return array{c:string,a:string,params:array<string,mixed>} */
  191. public static function currentRequest(): array {
  192. return [
  193. 'c' => self::$controller_name,
  194. 'a' => self::$action_name,
  195. 'params' => self::$params,
  196. ];
  197. }
  198. /** @return array{c?:string,a?:string,params?:array<string,mixed>} */
  199. public static function originalRequest(): array {
  200. return self::$originalRequest;
  201. }
  202. /**
  203. * @param array<string,mixed>|null $extraParams
  204. * @return array{c:string,a:string,params:array<string,mixed>}
  205. */
  206. public static function modifiedCurrentRequest(?array $extraParams = null): array {
  207. unset(self::$params['ajax']);
  208. $currentRequest = self::currentRequest();
  209. if (null !== $extraParams) {
  210. $currentRequest['params'] = array_merge($currentRequest['params'], $extraParams);
  211. }
  212. unset($currentRequest['params']['rid']);
  213. return $currentRequest;
  214. }
  215. /**
  216. * Setters
  217. */
  218. public static function _controllerName(string $controller_name): void {
  219. self::$controller_name = ctype_alnum($controller_name) ? $controller_name : '';
  220. }
  221. public static function _actionName(string $action_name): void {
  222. self::$action_name = ctype_alnum($action_name) ? $action_name : '';
  223. }
  224. /** @param array<string,mixed> $params */
  225. public static function _params(array $params): void {
  226. self::$params = $params;
  227. }
  228. public static function _param(string $key, ?string $value = null): void {
  229. if ($value === null) {
  230. unset(self::$params[$key]);
  231. } else {
  232. self::$params[$key] = $value;
  233. }
  234. }
  235. /**
  236. * Initializes the request
  237. */
  238. public static function init(): void {
  239. self::_params(array_filter($_GET, 'is_string', ARRAY_FILTER_USE_KEY));
  240. self::initJSON();
  241. }
  242. public static function is(string $controller_name, string $action_name): bool {
  243. return self::$controller_name === $controller_name &&
  244. self::$action_name === $action_name;
  245. }
  246. /**
  247. * Use CONN_REMOTE_ADDR (if available, to be robust even when using Apache mod_remoteip) or REMOTE_ADDR environment variable to determine the connection IP.
  248. */
  249. public static function connectionRemoteAddress(): string {
  250. $remoteIp = is_string($_SERVER['CONN_REMOTE_ADDR'] ?? null) ? $_SERVER['CONN_REMOTE_ADDR'] : '';
  251. if ($remoteIp == '') {
  252. $remoteIp = is_string($_SERVER['REMOTE_ADDR'] ?? null) ? $_SERVER['REMOTE_ADDR'] : '';
  253. }
  254. if ($remoteIp == 0) {
  255. $remoteIp = '';
  256. }
  257. return $remoteIp;
  258. }
  259. /**
  260. * Returns `PATH_INFO` accounting for a bug when sometimes it may contain `SCRIPT_NAME` value instead of blank
  261. */
  262. public static function pathInfo(): string {
  263. $pathInfo = $_SERVER['PATH_INFO'] ?? $_SERVER['ORIG_PATH_INFO'] ?? null;
  264. if (!is_string($pathInfo)) {
  265. return '';
  266. }
  267. $scriptName = $_SERVER['SCRIPT_NAME'] ?? null;
  268. if ($scriptName === $pathInfo) {
  269. return '';
  270. }
  271. return $pathInfo;
  272. }
  273. /**
  274. * Return true if the request is over HTTPS, false otherwise (HTTP)
  275. */
  276. public static function isHttps(): bool {
  277. $header = is_string($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PROTO'] : '';
  278. if ('' !== $header) {
  279. return 'https' === strtolower($header);
  280. }
  281. return 'on' === ($_SERVER['HTTPS'] ?? '');
  282. }
  283. /**
  284. * Try to guess the base URL from $_SERVER information
  285. *
  286. * @return string base url (e.g. http://example.com)
  287. */
  288. public static function guessBaseUrl(): string {
  289. $protocol = self::extractProtocol();
  290. $host = self::extractHost();
  291. $port = self::extractPortForUrl();
  292. $prefix = self::extractPrefix();
  293. $path = self::extractPath();
  294. return filter_var("{$protocol}://{$host}{$port}{$prefix}{$path}", FILTER_SANITIZE_URL) ?: '';
  295. }
  296. private static function extractProtocol(): string {
  297. return self::isHttps() ? 'https' : 'http';
  298. }
  299. private static function extractHost(): string {
  300. $host = is_string($_SERVER['HTTP_X_FORWARDED_HOST'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : '';
  301. if ($host !== '') {
  302. return parse_url("http://{$host}", PHP_URL_HOST) ?: 'localhost';
  303. }
  304. $host = is_string($_SERVER['HTTP_HOST'] ?? null) ? $_SERVER['HTTP_HOST'] : '';
  305. if ($host !== '') {
  306. // Might contain a port number, and mind IPv6 addresses
  307. return parse_url("http://{$host}", PHP_URL_HOST) ?: 'localhost';
  308. }
  309. $host = is_string($_SERVER['SERVER_NAME'] ?? null) ? $_SERVER['SERVER_NAME'] : '';
  310. if ($host !== '') {
  311. return $host;
  312. }
  313. return 'localhost';
  314. }
  315. private static function extractPort(): int {
  316. $port = is_numeric($_SERVER['HTTP_X_FORWARDED_PORT'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PORT'] : '';
  317. if ($port !== '') {
  318. return intval($port);
  319. }
  320. $proto = is_string($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PROTO'] : '';
  321. if ($proto !== '') {
  322. return 'https' === strtolower($proto) ? 443 : 80;
  323. }
  324. $port = is_numeric($_SERVER['SERVER_PORT'] ?? null) ? $_SERVER['SERVER_PORT'] : '';
  325. if ($port !== '') {
  326. return intval($port);
  327. }
  328. return self::isHttps() ? 443 : 80;
  329. }
  330. private static function extractPortForUrl(): string {
  331. if (self::isHttps() && 443 !== $port = self::extractPort()) {
  332. return ":{$port}";
  333. }
  334. if (!self::isHttps() && 80 !== $port = self::extractPort()) {
  335. return ":{$port}";
  336. }
  337. return '';
  338. }
  339. private static function extractPrefix(): string {
  340. $prefix = is_string($_SERVER['HTTP_X_FORWARDED_PREFIX'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PREFIX'] : '';
  341. if ($prefix !== '') {
  342. return rtrim($prefix, '/ ');
  343. }
  344. return '';
  345. }
  346. private static function extractPath(): string {
  347. $path = is_string($_SERVER['REQUEST_URI'] ?? null) ? $_SERVER['REQUEST_URI'] : '';
  348. if ($path !== '') {
  349. $path = parse_url($path, PHP_URL_PATH) ?: '';
  350. return substr($path, -1) === '/' ? rtrim($path, '/') : dirname($path);
  351. }
  352. return '';
  353. }
  354. /**
  355. * Return the base_url from configuration
  356. * @throws Minz_ConfigurationException
  357. */
  358. public static function getBaseUrl(): string {
  359. $conf = Minz_Configuration::get('system');
  360. $url = trim($conf->base_url, ' /\\"');
  361. return filter_var($url, FILTER_SANITIZE_URL) ?: '';
  362. }
  363. /**
  364. * Resolve a hostname to its first found IP address (IPv4 or IPv6).
  365. *
  366. * @param string $hostname the hostname to resolve (from IP to DNS)
  367. * @return string|null the resolved IP address, or null if resolution fails
  368. */
  369. private static function resolveHostname(string $hostname): ?string {
  370. if (filter_var($hostname, FILTER_VALIDATE_IP) !== false) {
  371. return $hostname; // Already an IP address
  372. }
  373. $fqdn = rtrim($hostname, '.') . '.'; // Ensure fully qualified domain name
  374. $records = @dns_get_record($fqdn, DNS_A + DNS_AAAA);
  375. if (!is_array($records) || empty($records)) {
  376. return null;
  377. }
  378. // Return the first resolved IP (IPv4 or IPv6)
  379. if (is_string($records[0]['ip'] ?? null)) {
  380. return $records[0]['ip'];
  381. }
  382. if (is_string($records[0]['ipv6'] ?? null)) {
  383. return $records[0]['ipv6'];
  384. }
  385. return null;
  386. }
  387. /**
  388. * Test whether a given server address appears to be publicly accessible.
  389. *
  390. * @param string $address the address to test, which can be an URL with a DNS or an IP.
  391. * @return bool true if server does not appear to be on some kind of local network, false otherwise (probably public).
  392. */
  393. public static function serverIsPublic(string $address, bool $allowDnsResolve = true): bool {
  394. if (strlen($address) < strlen('http://a.bc')) {
  395. return false;
  396. }
  397. $host = parse_url($address, PHP_URL_HOST);
  398. if (!is_string($host)) {
  399. return false;
  400. }
  401. $is_public = (str_contains($host, '.') || str_contains($host, ':')) // TLD
  402. && !preg_match('/(^|\\.)(ipv6-)?(internal|intranet|lan|local|localdomain|localhost)6?$/', $host) // DNS
  403. && !preg_match('/^(10|127|172[.](1[6-9]|2[0-9]|3[01])|192[.]168)[.]/', $host) // IPv4
  404. && !preg_match('/^(\\[)?(::1|f[c-d][0-9a-f]{2}:|fe80:)(\\])?/i', $host); // IPv6
  405. // If $host looks public and is not an IP address, try to resolve it
  406. if ($allowDnsResolve && $is_public && filter_var($host, FILTER_VALIDATE_IP) === false) {
  407. $resolvedIp = self::resolveHostname($host);
  408. if ($resolvedIp !== null && $resolvedIp !== $host) {
  409. $resolvedAddress = str_contains($resolvedIp, ':') ? "http://[{$resolvedIp}]/" : "http://{$resolvedIp}/";
  410. if ($resolvedAddress !== $address) {
  411. $is_public &= self::serverIsPublic($resolvedAddress, $allowDnsResolve);
  412. }
  413. }
  414. }
  415. return (bool)$is_public;
  416. }
  417. private static function requestId(): string {
  418. if (!is_string($_GET['rid'] ?? null) || !ctype_xdigit($_GET['rid'])) {
  419. $_GET['rid'] = uniqid();
  420. }
  421. return $_GET['rid'];
  422. }
  423. private static function setNotification(string $type, string $content, string $notificationName = ''): void {
  424. Minz_Session::lock();
  425. $requests = Minz_Session::paramArray('requests');
  426. $requests[self::requestId()] = [
  427. 'time' => time(),
  428. 'notification' => [ 'type' => $type, 'content' => $content, 'notificationName' => $notificationName ],
  429. ];
  430. Minz_Session::_param('requests', $requests);
  431. Minz_Session::unlock();
  432. }
  433. public static function setGoodNotification(string $content, string $notificationName = ''): void {
  434. self::setNotification('good', $content, $notificationName);
  435. }
  436. public static function setBadNotification(string $content, string $notificationName = ''): void {
  437. self::setNotification('bad', $content, $notificationName);
  438. }
  439. /**
  440. * @param $pop true (default) to remove the notification, false to keep it.
  441. * @return array{type:string,content:string,notificationName:string}|null
  442. */
  443. public static function getNotification(bool $pop = true): ?array {
  444. $notif = null;
  445. Minz_Session::lock();
  446. /** @var array<string,array{time:int,notification:array{type:string,content:string,notificationName:string}}> */
  447. $requests = Minz_Session::paramArray('requests');
  448. if (!empty($requests)) {
  449. //Delete abandoned notifications
  450. $requests = array_filter($requests, static function (array $r) { return $r['time'] > time() - 3600; });
  451. $requestId = self::requestId();
  452. if (!empty($requests[$requestId]['notification'])) {
  453. $notif = $requests[$requestId]['notification'];
  454. if ($pop) {
  455. unset($requests[$requestId]);
  456. }
  457. }
  458. Minz_Session::_param('requests', $requests);
  459. }
  460. Minz_Session::unlock();
  461. return $notif;
  462. }
  463. /**
  464. * Restart a request
  465. * @param array{c?:string,a?:string,params?:array<string,mixed>} $url an array presentation of the URL to route to
  466. * @param bool $redirect If true, uses an HTTP redirection, and if false (default), performs an internal dispatcher redirection.
  467. * @param int $httpCode Only for a redirection: an HTTP error status code (4xx, 5xx) to send instead of a 3xx redirection.
  468. * Since browsers do not follow the `Location` header of such a response, an HTML redirection (with JS or `<meta http-equiv="refresh">`) is used instead.
  469. * @throws Minz_ConfigurationException
  470. */
  471. public static function forward(array $url = [], bool $redirect = false, int $httpCode = 0): void {
  472. if (empty(Minz_Request::originalRequest())) {
  473. self::$originalRequest = $url;
  474. }
  475. $url = Minz_Url::checkControllerUrl($url);
  476. $url['params']['rid'] = self::requestId();
  477. if ($redirect) {
  478. $location = Minz_Url::display($url, 'php', 'root'); // `/i/...`
  479. if ($httpCode >= 400 && $httpCode <= 599) {
  480. $nonce = bin2hex(random_bytes(16));
  481. http_response_code($httpCode);
  482. header('Content-Type: text/html; charset=UTF-8');
  483. header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; script-src 'nonce-$nonce'");
  484. header('X-Content-Type-Options: nosniff');
  485. $location = htmlspecialchars($location, ENT_QUOTES, 'UTF-8');
  486. // JavaScript helps prevent the redirect page from flashing.
  487. // See: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script#blocking
  488. echo <<<HTML
  489. <!DOCTYPE html>
  490. <html>
  491. <head>
  492. <meta charset="UTF-8">
  493. <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
  494. <meta name="color-scheme" content="light dark">
  495. <meta http-equiv="refresh" content="0; url=$location">
  496. <script nonce="$nonce" blocking="render" data-target="$location">
  497. location.replace(document.currentScript.dataset.target);
  498. </script>
  499. <title>$httpCode</title>
  500. </head>
  501. <body>
  502. <p>Redirecting.</p>
  503. </body>
  504. </html>
  505. HTML;
  506. } else {
  507. header('Location: ' . $location);
  508. }
  509. exit();
  510. } else {
  511. self::_controllerName($url['c']);
  512. self::_actionName($url['a']);
  513. $merge = array_merge(self::$params, $url['params']);
  514. self::_params($merge);
  515. Minz_Dispatcher::reset();
  516. }
  517. }
  518. /**
  519. * Wrappers good notifications + redirection
  520. * @param string $msg notification content
  521. * @param array{c?:string,a?:string,params?:array<string,mixed>} $url url array to where we should be forwarded
  522. */
  523. public static function good(string $msg, array $url = [], string $notificationName = '', bool $showNotification = true): void {
  524. if ($showNotification) {
  525. Minz_Request::setGoodNotification($msg);
  526. }
  527. Minz_Request::forward($url, true);
  528. }
  529. /**
  530. * Wrappers bad notifications + redirection
  531. * @param string $msg notification content
  532. * @param array{c?:string,a?:string,params?:array<string,mixed>} $url url array to where we should be forwarded
  533. */
  534. public static function bad(string $msg, array $url = [], string $notificationName = ''): void {
  535. Minz_Request::setBadNotification($msg, $notificationName);
  536. Minz_Request::forward($url, true);
  537. }
  538. /**
  539. * Allows receiving POST data as application/json
  540. */
  541. private static function initJSON(): void {
  542. if (!str_starts_with(self::extractContentType(), 'application/json')) {
  543. return;
  544. }
  545. $ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576);
  546. if ($ORIGINAL_INPUT == false) {
  547. return;
  548. }
  549. if (!is_array($json = json_decode($ORIGINAL_INPUT, true))) {
  550. return;
  551. }
  552. foreach ($json as $k => $v) {
  553. if (!isset($_POST[$k])) {
  554. $_POST[$k] = $v;
  555. }
  556. }
  557. }
  558. private static function extractContentType(): string {
  559. $contentType = is_string($_SERVER['CONTENT_TYPE'] ?? null) ? $_SERVER['CONTENT_TYPE'] : '';
  560. return strtolower(trim($contentType));
  561. }
  562. public static function isPost(): bool {
  563. return 'POST' === ($_SERVER['REQUEST_METHOD'] ?? '');
  564. }
  565. public static function tokenIsOk(): bool {
  566. $token_param = self::paramString('token');
  567. if ($token_param == '') {
  568. return false;
  569. }
  570. $username = self::paramString('user');
  571. if ($username == '') {
  572. return false;
  573. }
  574. $conf = FreshRSS_UserConfiguration::getForUser($username);
  575. if ($conf === null || !$conf->enabled || !hash_equals($conf->token, $token_param)) {
  576. return false;
  577. }
  578. return true;
  579. }
  580. /**
  581. * @return list<string>
  582. */
  583. public static function getPreferredLanguages(): array {
  584. $acceptLanguage = is_string($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
  585. if (preg_match_all('/(^|,)\s*(?P<lang>[^;,]+)/', $acceptLanguage, $matches) > 0) {
  586. return $matches['lang'];
  587. }
  588. return [Minz_Translate::DEFAULT_LANGUAGE];
  589. }
  590. }