Request.php 13 KB

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