Request.php 13 KB

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