4
0

Request.php 11 KB

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