Request.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  6. */
  7. /**
  8. * Request représente la requête http
  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. * Getteurs
  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. * @deprecated use typed versions instead
  39. */
  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. */
  133. public static function paramStringNull(string $key, bool $plaintext = false): ?string {
  134. if (isset(self::$params[$key])) {
  135. $s = self::$params[$key];
  136. if (is_string($s)) {
  137. $s = trim($s);
  138. return $plaintext ? $s : htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  139. }
  140. if (is_int($s) || is_bool($s)) {
  141. return (string)$s;
  142. }
  143. }
  144. return null;
  145. }
  146. /**
  147. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  148. */
  149. public static function paramString(string $key, bool $plaintext = false): string {
  150. return self::paramStringNull($key, $plaintext) ?? '';
  151. }
  152. /**
  153. * Extract text lines to array.
  154. *
  155. * It will return an array where each cell contains one line of a text. The new line
  156. * character is used to break the text into lines. This method is well suited to use
  157. * to split textarea content.
  158. * @param bool $plaintext `true` to return special characters without any escaping (unsafe), `false` (default) to XML-encode them
  159. * @return list<string>
  160. */
  161. public static function paramTextToArray(string $key, bool $plaintext = false): array {
  162. if (isset(self::$params[$key]) && is_string(self::$params[$key])) {
  163. $result = preg_split('/\R/u', self::$params[$key]) ?: [];
  164. return $plaintext ? $result : Minz_Helper::htmlspecialchars_utf8($result);
  165. }
  166. return [];
  167. }
  168. public static function defaultControllerName(): string {
  169. return self::$default_controller_name;
  170. }
  171. public static function defaultActionName(): string {
  172. return self::$default_action_name;
  173. }
  174. /** @return array{c:string,a:string,params:array<string,mixed>} */
  175. public static function currentRequest(): array {
  176. return [
  177. 'c' => self::$controller_name,
  178. 'a' => self::$action_name,
  179. 'params' => self::$params,
  180. ];
  181. }
  182. /** @return array{c?:string,a?:string,params?:array<string,mixed>} */
  183. public static function originalRequest(): array {
  184. return self::$originalRequest;
  185. }
  186. /**
  187. * @param array<string,mixed>|null $extraParams
  188. * @return array{c:string,a:string,params:array<string,mixed>}
  189. */
  190. public static function modifiedCurrentRequest(?array $extraParams = null): array {
  191. unset(self::$params['ajax']);
  192. $currentRequest = self::currentRequest();
  193. if (null !== $extraParams) {
  194. $currentRequest['params'] = array_merge($currentRequest['params'], $extraParams);
  195. }
  196. return $currentRequest;
  197. }
  198. /**
  199. * Setteurs
  200. */
  201. public static function _controllerName(string $controller_name): void {
  202. self::$controller_name = ctype_alnum($controller_name) ? $controller_name : '';
  203. }
  204. public static function _actionName(string $action_name): void {
  205. self::$action_name = ctype_alnum($action_name) ? $action_name : '';
  206. }
  207. /** @param array<string,mixed> $params */
  208. public static function _params(array $params): void {
  209. self::$params = $params;
  210. }
  211. public static function _param(string $key, ?string $value = null): void {
  212. if ($value === null) {
  213. unset(self::$params[$key]);
  214. } else {
  215. self::$params[$key] = $value;
  216. }
  217. }
  218. /**
  219. * Initialise la Request
  220. */
  221. public static function init(): void {
  222. self::_params(array_filter($_GET, 'is_string', ARRAY_FILTER_USE_KEY));
  223. self::initJSON();
  224. }
  225. public static function is(string $controller_name, string $action_name): bool {
  226. return self::$controller_name === $controller_name &&
  227. self::$action_name === $action_name;
  228. }
  229. /**
  230. * Return true if the request is over HTTPS, false otherwise (HTTP)
  231. */
  232. public static function isHttps(): bool {
  233. $header = is_string($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PROTO'] : '';
  234. if ('' !== $header) {
  235. return 'https' === strtolower($header);
  236. }
  237. return 'on' === ($_SERVER['HTTPS'] ?? '');
  238. }
  239. /**
  240. * Try to guess the base URL from $_SERVER information
  241. *
  242. * @return string base url (e.g. http://example.com)
  243. */
  244. public static function guessBaseUrl(): string {
  245. $protocol = self::extractProtocol();
  246. $host = self::extractHost();
  247. $port = self::extractPortForUrl();
  248. $prefix = self::extractPrefix();
  249. $path = self::extractPath();
  250. return filter_var("{$protocol}://{$host}{$port}{$prefix}{$path}", FILTER_SANITIZE_URL) ?: '';
  251. }
  252. private static function extractProtocol(): string {
  253. return self::isHttps() ? 'https' : 'http';
  254. }
  255. private static function extractHost(): string {
  256. $host = is_string($_SERVER['HTTP_X_FORWARDED_HOST'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : '';
  257. if ($host !== '') {
  258. return parse_url("http://{$host}", PHP_URL_HOST) ?: 'localhost';
  259. }
  260. $host = is_string($_SERVER['HTTP_HOST'] ?? null) ? $_SERVER['HTTP_HOST'] : '';
  261. if ($host !== '') {
  262. // Might contain a port number, and mind IPv6 addresses
  263. return parse_url("http://{$host}", PHP_URL_HOST) ?: 'localhost';
  264. }
  265. $host = is_string($_SERVER['SERVER_NAME'] ?? null) ? $_SERVER['SERVER_NAME'] : '';
  266. if ($host !== '') {
  267. return $host;
  268. }
  269. return 'localhost';
  270. }
  271. private static function extractPort(): int {
  272. $port = is_numeric($_SERVER['HTTP_X_FORWARDED_PORT'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PORT'] : '';
  273. if ($port !== '') {
  274. return intval($port);
  275. }
  276. $proto = is_string($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PROTO'] : '';
  277. if ($proto !== '') {
  278. return 'https' === strtolower($proto) ? 443 : 80;
  279. }
  280. $port = is_numeric($_SERVER['SERVER_PORT'] ?? null) ? $_SERVER['SERVER_PORT'] : '';
  281. if ($port !== '') {
  282. return intval($port);
  283. }
  284. return self::isHttps() ? 443 : 80;
  285. }
  286. private static function extractPortForUrl(): string {
  287. if (self::isHttps() && 443 !== $port = self::extractPort()) {
  288. return ":{$port}";
  289. }
  290. if (!self::isHttps() && 80 !== $port = self::extractPort()) {
  291. return ":{$port}";
  292. }
  293. return '';
  294. }
  295. private static function extractPrefix(): string {
  296. $prefix = is_string($_SERVER['HTTP_X_FORWARDED_PREFIX'] ?? null) ? $_SERVER['HTTP_X_FORWARDED_PREFIX'] : '';
  297. if ($prefix !== '') {
  298. return rtrim($prefix, '/ ');
  299. }
  300. return '';
  301. }
  302. private static function extractPath(): string {
  303. $path = is_string($_SERVER['REQUEST_URI'] ?? null) ? $_SERVER['REQUEST_URI'] : '';
  304. if ($path !== '') {
  305. $path = parse_url($path, PHP_URL_PATH) ?: '';
  306. return substr($path, -1) === '/' ? rtrim($path, '/') : dirname($path);
  307. }
  308. return '';
  309. }
  310. /**
  311. * Return the base_url from configuration
  312. * @throws Minz_ConfigurationException
  313. */
  314. public static function getBaseUrl(): string {
  315. $conf = Minz_Configuration::get('system');
  316. $url = trim($conf->base_url, ' /\\"');
  317. return filter_var($url, FILTER_SANITIZE_URL) ?: '';
  318. }
  319. /**
  320. * Test if a given server address is publicly accessible.
  321. *
  322. * Note: for the moment it tests only if address is corresponding to a
  323. * localhost address.
  324. *
  325. * @param string $address the address to test, can be an IP or a URL.
  326. * @return bool true if server is accessible, false otherwise.
  327. * @todo improve test with a more valid technique (e.g. test with an external server?)
  328. */
  329. public static function serverIsPublic(string $address): bool {
  330. if (strlen($address) < strlen('http://a.bc')) {
  331. return false;
  332. }
  333. $host = parse_url($address, PHP_URL_HOST);
  334. if (!is_string($host)) {
  335. return false;
  336. }
  337. $is_public = !in_array($host, [
  338. 'localhost',
  339. 'localhost.localdomain',
  340. '[::1]',
  341. 'ip6-localhost',
  342. 'localhost6',
  343. 'localhost6.localdomain6',
  344. ], true);
  345. if ($is_public) {
  346. $is_public &= !preg_match('/^(10|127|172[.]16|192[.]168)[.]/', $host);
  347. $is_public &= !preg_match('/^(\[)?(::1$|fc00::|fe80::)/i', $host);
  348. }
  349. return (bool)$is_public;
  350. }
  351. private static function requestId(): string {
  352. if (!is_string($_GET['rid'] ?? null) || !ctype_xdigit($_GET['rid'])) {
  353. $_GET['rid'] = uniqid();
  354. }
  355. return $_GET['rid'];
  356. }
  357. private static function setNotification(string $type, string $content, string $notificationName = ''): void {
  358. Minz_Session::lock();
  359. $requests = Minz_Session::paramArray('requests');
  360. $requests[self::requestId()] = [
  361. 'time' => time(),
  362. 'notification' => [ 'type' => $type, 'content' => $content, 'notificationName' => $notificationName ],
  363. ];
  364. Minz_Session::_param('requests', $requests);
  365. Minz_Session::unlock();
  366. }
  367. public static function setGoodNotification(string $content, string $notificationName = ''): void {
  368. self::setNotification('good', $content, $notificationName);
  369. }
  370. public static function setBadNotification(string $content, string $notificationName = ''): void {
  371. self::setNotification('bad', $content, $notificationName);
  372. }
  373. /**
  374. * @param $pop true (default) to remove the notification, false to keep it.
  375. * @return array{type:string,content:string,notificationName:string}|null
  376. */
  377. public static function getNotification(bool $pop = true): ?array {
  378. $notif = null;
  379. Minz_Session::lock();
  380. /** @var array<string,array{time:int,notification:array{type:string,content:string,notificationName:string}}> */
  381. $requests = Minz_Session::paramArray('requests');
  382. if (!empty($requests)) {
  383. //Delete abandoned notifications
  384. $requests = array_filter($requests, static function (array $r) { return $r['time'] > time() - 3600; });
  385. $requestId = self::requestId();
  386. if (!empty($requests[$requestId]['notification'])) {
  387. $notif = $requests[$requestId]['notification'];
  388. if ($pop) {
  389. unset($requests[$requestId]);
  390. }
  391. }
  392. Minz_Session::_param('requests', $requests);
  393. }
  394. Minz_Session::unlock();
  395. return $notif;
  396. }
  397. /**
  398. * Restart a request
  399. * @param array{c?:string,a?:string,params?:array<string,mixed>} $url an array presentation of the URL to route to
  400. * @param bool $redirect If true, uses an HTTP redirection, and if false (default), performs an internal dispatcher redirection.
  401. * @throws Minz_ConfigurationException
  402. */
  403. public static function forward(array $url = [], bool $redirect = false): void {
  404. if (empty(Minz_Request::originalRequest())) {
  405. self::$originalRequest = $url;
  406. }
  407. $url = Minz_Url::checkControllerUrl($url);
  408. $url['params']['rid'] = self::requestId();
  409. if ($redirect) {
  410. header('Location: ' . Minz_Url::display($url, 'php', 'root'));
  411. exit();
  412. } else {
  413. self::_controllerName($url['c']);
  414. self::_actionName($url['a']);
  415. $merge = array_merge(self::$params, $url['params']);
  416. self::_params($merge);
  417. Minz_Dispatcher::reset();
  418. }
  419. }
  420. /**
  421. * Wrappers good notifications + redirection
  422. * @param string $msg notification content
  423. * @param array{c?:string,a?:string,params?:array<string,mixed>} $url url array to where we should be forwarded
  424. */
  425. public static function good(string $msg, array $url = [], string $notificationName = '', bool $showNotification = true): void {
  426. if ($showNotification) {
  427. Minz_Request::setGoodNotification($msg);
  428. }
  429. Minz_Request::forward($url, true);
  430. }
  431. /**
  432. * Wrappers bad notifications + redirection
  433. * @param string $msg notification content
  434. * @param array{c?:string,a?:string,params?:array<string,mixed>} $url url array to where we should be forwarded
  435. */
  436. public static function bad(string $msg, array $url = [], string $notificationName = ''): void {
  437. Minz_Request::setBadNotification($msg, $notificationName);
  438. Minz_Request::forward($url, true);
  439. }
  440. /**
  441. * Allows receiving POST data as application/json
  442. */
  443. private static function initJSON(): void {
  444. if (!str_starts_with(self::extractContentType(), 'application/json')) {
  445. return;
  446. }
  447. $ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576);
  448. if ($ORIGINAL_INPUT == false) {
  449. return;
  450. }
  451. if (!is_array($json = json_decode($ORIGINAL_INPUT, true))) {
  452. return;
  453. }
  454. foreach ($json as $k => $v) {
  455. if (!isset($_POST[$k])) {
  456. $_POST[$k] = $v;
  457. }
  458. }
  459. }
  460. private static function extractContentType(): string {
  461. $contentType = is_string($_SERVER['CONTENT_TYPE'] ?? null) ? $_SERVER['CONTENT_TYPE'] : '';
  462. return strtolower(trim($contentType));
  463. }
  464. public static function isPost(): bool {
  465. return 'POST' === ($_SERVER['REQUEST_METHOD'] ?? '');
  466. }
  467. /**
  468. * @return list<string>
  469. */
  470. public static function getPreferredLanguages(): array {
  471. $acceptLanguage = is_string($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
  472. if (preg_match_all('/(^|,)\s*(?P<lang>[^;,]+)/', $acceptLanguage, $matches) > 0) {
  473. return $matches['lang'];
  474. }
  475. return [Minz_Translate::DEFAULT_LANGUAGE];
  476. }
  477. }