Request.php 11 KB

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