Request.php 11 KB

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