Request.php 16 KB

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