Request.php 14 KB

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