4
0

Request.php 13 KB

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