Request.php 11 KB

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