Request.php 13 KB

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