Request.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. } else {
  49. return Minz_Helper::htmlspecialchars_utf8($p);
  50. }
  51. } else {
  52. return $default;
  53. }
  54. }
  55. /** @return array<string|int,string|array<string,string>> */
  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 bool|null */
  63. public static function paramTernary(string $key) {
  64. if (isset(self::$params[$key])) {
  65. $p = self::$params[$key];
  66. $tp = is_string($p) ? trim($p) : true;
  67. if ($tp === '' || $tp === 'null') {
  68. return null;
  69. } elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') {
  70. return false;
  71. }
  72. return true;
  73. }
  74. return null;
  75. }
  76. public static function paramBoolean(string $key): bool {
  77. if (null === $value = self::paramTernary($key)) {
  78. return false;
  79. }
  80. return $value;
  81. }
  82. public static function paramInt(string $key): int {
  83. if (!empty(self::$params[$key])) {
  84. return intval(self::$params[$key]);
  85. }
  86. return 0;
  87. }
  88. public static function paramString(string $key, bool $specialchars = false): string {
  89. if (isset(self::$params[$key])) {
  90. $s = self::$params[$key];
  91. if (is_string($s)) {
  92. $s = trim($s);
  93. return $specialchars ? $s : htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  94. }
  95. if (is_int($s) || is_bool($s)) {
  96. return (string)$s;
  97. }
  98. }
  99. return '';
  100. }
  101. /**
  102. * Extract text lines to array.
  103. *
  104. * It will return an array where each cell contains one line of a text. The new line
  105. * character is used to break the text into lines. This method is well suited to use
  106. * to split textarea content.
  107. * @param array<string> $default
  108. * @return array<string>
  109. */
  110. public static function paramTextToArray(string $key, array $default = []): array {
  111. if (isset(self::$params[$key])) {
  112. return preg_split('/\R/', self::$params[$key]);
  113. }
  114. return $default;
  115. }
  116. public static function defaultControllerName(): string {
  117. return self::$default_controller_name;
  118. }
  119. public static function defaultActionName(): string {
  120. return self::$default_action_name;
  121. }
  122. /** @return array{'c':string,'a':string,'params':array<string,mixed>} */
  123. public static function currentRequest(): array {
  124. return [
  125. 'c' => self::$controller_name,
  126. 'a' => self::$action_name,
  127. 'params' => self::$params,
  128. ];
  129. }
  130. /** @return array{'c':string,'a':string,'params':array<string,mixed>}|null */
  131. public static function originalRequest(): ?array {
  132. return self::$originalRequest;
  133. }
  134. /**
  135. * @param array<string,mixed>|null $extraParams
  136. * @return array{'c':string,'a':string,'params':array<string,mixed>}
  137. */
  138. public static function modifiedCurrentRequest(?array $extraParams = null): array {
  139. unset(self::$params['ajax']);
  140. $currentRequest = self::currentRequest();
  141. if (null !== $extraParams) {
  142. $currentRequest['params'] = array_merge($currentRequest['params'], $extraParams);
  143. }
  144. return $currentRequest;
  145. }
  146. /**
  147. * Setteurs
  148. */
  149. public static function _controllerName(string $controller_name): void {
  150. self::$controller_name = $controller_name;
  151. }
  152. public static function _actionName(string $action_name): void {
  153. self::$action_name = $action_name;
  154. }
  155. /** @param array<string,string> $params */
  156. public static function _params(array $params): void {
  157. self::$params = $params;
  158. }
  159. /** @param array|mixed $value */
  160. public static function _param(string $key, $value = false): void {
  161. if ($value === false) {
  162. unset(self::$params[$key]);
  163. } else {
  164. self::$params[$key] = $value;
  165. }
  166. }
  167. /**
  168. * Initialise la Request
  169. */
  170. public static function init(): void {
  171. self::initJSON();
  172. }
  173. public static function is(string $controller_name, string $action_name): bool {
  174. return self::$controller_name === $controller_name &&
  175. self::$action_name === $action_name;
  176. }
  177. /**
  178. * Return true if the request is over HTTPS, false otherwise (HTTP)
  179. */
  180. public static function isHttps(): bool {
  181. $header = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '';
  182. if ('' != $header) {
  183. return 'https' === strtolower($header);
  184. }
  185. return 'on' === ($_SERVER['HTTPS'] ?? '');
  186. }
  187. /**
  188. * Try to guess the base URL from $_SERVER information
  189. *
  190. * @return string base url (e.g. http://example.com)
  191. */
  192. public static function guessBaseUrl(): string {
  193. $protocol = self::extractProtocol();
  194. $host = self::extractHost();
  195. $port = self::extractPortForUrl();
  196. $prefix = self::extractPrefix();
  197. $path = self::extractPath();
  198. return filter_var("{$protocol}://{$host}{$port}{$prefix}{$path}", FILTER_SANITIZE_URL);
  199. }
  200. private static function extractProtocol(): string {
  201. if (self::isHttps()) {
  202. return 'https';
  203. }
  204. return 'http';
  205. }
  206. private static function extractHost(): string {
  207. if ('' != $host = ($_SERVER['HTTP_X_FORWARDED_HOST'] ?? '')) {
  208. return parse_url("http://{$host}", PHP_URL_HOST);
  209. }
  210. if ('' != $host = ($_SERVER['HTTP_HOST'] ?? '')) {
  211. // Might contain a port number, and mind IPv6 addresses
  212. return parse_url("http://{$host}", PHP_URL_HOST);
  213. }
  214. if ('' != $host = ($_SERVER['SERVER_NAME'] ?? '')) {
  215. return $host;
  216. }
  217. return 'localhost';
  218. }
  219. private static function extractPort(): int {
  220. if ('' != $port = ($_SERVER['HTTP_X_FORWARDED_PORT'] ?? '')) {
  221. return intval($port);
  222. }
  223. if ('' != $proto = ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) {
  224. return 'https' === strtolower($proto) ? 443 : 80;
  225. }
  226. if ('' != $port = ($_SERVER['SERVER_PORT'] ?? '')) {
  227. return intval($port);
  228. }
  229. return self::isHttps() ? 443 : 80;
  230. }
  231. private static function extractPortForUrl(): string {
  232. if (self::isHttps() && 443 !== $port = self::extractPort()) {
  233. return ":{$port}";
  234. }
  235. if (!self::isHttps() && 80 !== $port = self::extractPort()) {
  236. return ":{$port}";
  237. }
  238. return '';
  239. }
  240. private static function extractPrefix(): string {
  241. if ('' != $prefix = ($_SERVER['HTTP_X_FORWARDED_PREFIX'] ?? '')) {
  242. return rtrim($prefix, '/ ');
  243. }
  244. return '';
  245. }
  246. private static function extractPath(): string {
  247. $path = $_SERVER['REQUEST_URI'] ?? '';
  248. if ($path != '') {
  249. $path = parse_url($path, PHP_URL_PATH);
  250. return substr($path, -1) === '/' ? rtrim($path, '/') : dirname($path);
  251. }
  252. return '';
  253. }
  254. /**
  255. * Return the base_url from configuration
  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 boolean 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 (!$host) {
  278. return false;
  279. }
  280. $is_public = !in_array($host, array(
  281. 'localhost',
  282. 'localhost.localdomain',
  283. '[::1]',
  284. 'ip6-localhost',
  285. 'localhost6',
  286. 'localhost6.localdomain6',
  287. ));
  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::param('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. /** @return array<string,string>|null */
  317. public static function getNotification(): ?array {
  318. $notif = null;
  319. Minz_Session::lock();
  320. $requests = Minz_Session::param('requests');
  321. if ($requests) {
  322. //Delete abandoned notifications
  323. $requests = array_filter($requests, function ($r) { return isset($r['time']) && $r['time'] > time() - 3600; });
  324. $requestId = self::requestId();
  325. if (!empty($requests[$requestId]['notification'])) {
  326. $notif = $requests[$requestId]['notification'];
  327. unset($requests[$requestId]);
  328. }
  329. Minz_Session::_param('requests', $requests);
  330. }
  331. Minz_Session::unlock();
  332. return $notif;
  333. }
  334. /**
  335. * Relance une requête
  336. * @param string|array{'c'?:string,'a'?:string,'params'?:array<string,mixed>} $url l'url vers laquelle est relancée la requête
  337. * @param bool $redirect si vrai, force la redirection http
  338. * > sinon, le dispatcher recharge en interne
  339. */
  340. public static function forward($url = [], bool $redirect = false): void {
  341. if (empty(Minz_Request::originalRequest())) {
  342. self::$originalRequest = $url;
  343. }
  344. if (!is_array($url)) {
  345. header('Location: ' . $url);
  346. exit();
  347. }
  348. $url = Minz_Url::checkControllerUrl($url);
  349. $url['params']['rid'] = self::requestId();
  350. if ($redirect) {
  351. header('Location: ' . Minz_Url::display($url, 'php', 'root'));
  352. exit();
  353. } else {
  354. self::_controllerName($url['c']);
  355. self::_actionName($url['a']);
  356. self::_params(array_merge(
  357. self::$params,
  358. $url['params']
  359. ));
  360. Minz_Dispatcher::reset();
  361. }
  362. }
  363. /**
  364. * Wrappers good notifications + redirection
  365. * @param string $msg notification content
  366. * @param array{'c'?:string,'a'?:string,'params'?:array<string,mixed>} $url url array to where we should be forwarded
  367. */
  368. public static function good(string $msg, array $url = []): void {
  369. Minz_Request::setGoodNotification($msg);
  370. Minz_Request::forward($url, true);
  371. }
  372. /**
  373. * Wrappers bad notifications + redirection
  374. * @param string $msg notification content
  375. * @param array{'c'?:string,'a'?:string,'params'?:array<string,mixed>} $url url array to where we should be forwarded
  376. */
  377. public static function bad(string $msg, array $url = []): void {
  378. Minz_Request::setBadNotification($msg);
  379. Minz_Request::forward($url, true);
  380. }
  381. /**
  382. * Allows receiving POST data as application/json
  383. */
  384. private static function initJSON(): void {
  385. if ('application/json' !== self::extractContentType()) {
  386. return;
  387. }
  388. if ('' === $ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576)) {
  389. return;
  390. }
  391. if (null === $json = json_decode($ORIGINAL_INPUT, true)) {
  392. return;
  393. }
  394. foreach ($json as $k => $v) {
  395. if (!isset($_POST[$k])) {
  396. $_POST[$k] = $v;
  397. }
  398. }
  399. }
  400. private static function extractContentType(): string {
  401. return strtolower(trim($_SERVER['CONTENT_TYPE'] ?? ''));
  402. }
  403. public static function isPost(): bool {
  404. return 'POST' === ($_SERVER['REQUEST_METHOD'] ?? '');
  405. }
  406. /**
  407. * @return array<string>
  408. */
  409. public static function getPreferredLanguages() {
  410. if (preg_match_all('/(^|,)\s*(?P<lang>[^;,]+)/', $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '', $matches)) {
  411. return $matches['lang'];
  412. }
  413. return array('en');
  414. }
  415. }