Request.php 11 KB

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