URI.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * URI Class
  41. *
  42. * Parses URIs and determines routing
  43. *
  44. * @package CodeIgniter
  45. * @subpackage Libraries
  46. * @category URI
  47. * @author EllisLab Dev Team
  48. * @link https://codeigniter.com/user_guide/libraries/uri.html
  49. */
  50. class CI_URI {
  51. /**
  52. * List of cached URI segments
  53. *
  54. * @var array
  55. */
  56. public $keyval = array();
  57. /**
  58. * Current URI string
  59. *
  60. * @var string
  61. */
  62. public $uri_string = '';
  63. /**
  64. * List of URI segments
  65. *
  66. * Starts at 1 instead of 0.
  67. *
  68. * @var array
  69. */
  70. public $segments = array();
  71. /**
  72. * List of routed URI segments
  73. *
  74. * Starts at 1 instead of 0.
  75. *
  76. * @var array
  77. */
  78. public $rsegments = array();
  79. /**
  80. * Permitted URI chars
  81. *
  82. * PCRE character group allowed in URI segments
  83. *
  84. * @var string
  85. */
  86. protected $_permitted_uri_chars;
  87. /**
  88. * Class constructor
  89. *
  90. * @return void
  91. */
  92. public function __construct()
  93. {
  94. $this->config =& load_class('Config', 'core');
  95. // If query strings are enabled, we don't need to parse any segments.
  96. // However, they don't make sense under CLI.
  97. if (is_cli() OR $this->config->item('enable_query_strings') !== TRUE)
  98. {
  99. $this->_permitted_uri_chars = $this->config->item('permitted_uri_chars');
  100. // If it's a CLI request, ignore the configuration
  101. if (is_cli())
  102. {
  103. $uri = $this->_parse_argv();
  104. }
  105. else
  106. {
  107. $protocol = $this->config->item('uri_protocol');
  108. empty($protocol) && $protocol = 'REQUEST_URI';
  109. switch ($protocol)
  110. {
  111. case 'AUTO': // For BC purposes only
  112. case 'REQUEST_URI':
  113. $uri = $this->_parse_request_uri();
  114. break;
  115. case 'QUERY_STRING':
  116. $uri = $this->_parse_query_string();
  117. break;
  118. case 'PATH_INFO':
  119. default:
  120. $uri = isset($_SERVER[$protocol])
  121. ? $_SERVER[$protocol]
  122. : $this->_parse_request_uri();
  123. break;
  124. }
  125. }
  126. $this->_set_uri_string($uri);
  127. }
  128. log_message('info', 'URI Class Initialized');
  129. }
  130. // --------------------------------------------------------------------
  131. /**
  132. * Set URI String
  133. *
  134. * @param string $str
  135. * @return void
  136. */
  137. protected function _set_uri_string($str)
  138. {
  139. // Filter out control characters and trim slashes
  140. $this->uri_string = trim(remove_invisible_characters($str, FALSE), '/');
  141. if ($this->uri_string !== '')
  142. {
  143. // Remove the URL suffix, if present
  144. if (($suffix = (string) $this->config->item('url_suffix')) !== '')
  145. {
  146. $slen = strlen($suffix);
  147. if (substr($this->uri_string, -$slen) === $suffix)
  148. {
  149. $this->uri_string = substr($this->uri_string, 0, -$slen);
  150. }
  151. }
  152. $this->segments[0] = NULL;
  153. // Populate the segments array
  154. foreach (explode('/', trim($this->uri_string, '/')) as $val)
  155. {
  156. $val = trim($val);
  157. // Filter segments for security
  158. $this->filter_uri($val);
  159. if ($val !== '')
  160. {
  161. $this->segments[] = $val;
  162. }
  163. }
  164. unset($this->segments[0]);
  165. }
  166. }
  167. // --------------------------------------------------------------------
  168. /**
  169. * Parse REQUEST_URI
  170. *
  171. * Will parse REQUEST_URI and automatically detect the URI from it,
  172. * while fixing the query string if necessary.
  173. *
  174. * @return string
  175. */
  176. protected function _parse_request_uri()
  177. {
  178. if ( ! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']))
  179. {
  180. return '';
  181. }
  182. // parse_url() returns false if no host is present, but the path or query string
  183. // contains a colon followed by a number
  184. $uri = parse_url('http://dummy'.$_SERVER['REQUEST_URI']);
  185. $query = isset($uri['query']) ? $uri['query'] : '';
  186. $uri = isset($uri['path']) ? $uri['path'] : '';
  187. if (isset($_SERVER['SCRIPT_NAME'][0]))
  188. {
  189. if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
  190. {
  191. $uri = (string) substr($uri, strlen($_SERVER['SCRIPT_NAME']));
  192. }
  193. elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
  194. {
  195. $uri = (string) substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
  196. }
  197. }
  198. // This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct
  199. // URI is found, and also fixes the QUERY_STRING server var and $_GET array.
  200. if (trim($uri, '/') === '' && strncmp($query, '/', 1) === 0)
  201. {
  202. $query = explode('?', $query, 2);
  203. $uri = $query[0];
  204. $_SERVER['QUERY_STRING'] = isset($query[1]) ? $query[1] : '';
  205. }
  206. else
  207. {
  208. $_SERVER['QUERY_STRING'] = $query;
  209. }
  210. parse_str($_SERVER['QUERY_STRING'], $_GET);
  211. if ($uri === '/' OR $uri === '')
  212. {
  213. return '/';
  214. }
  215. // Do some final cleaning of the URI and return it
  216. return $this->_remove_relative_directory($uri);
  217. }
  218. // --------------------------------------------------------------------
  219. /**
  220. * Parse QUERY_STRING
  221. *
  222. * Will parse QUERY_STRING and automatically detect the URI from it.
  223. *
  224. * @return string
  225. */
  226. protected function _parse_query_string()
  227. {
  228. $uri = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
  229. if (trim($uri, '/') === '')
  230. {
  231. return '';
  232. }
  233. elseif (strncmp($uri, '/', 1) === 0)
  234. {
  235. $uri = explode('?', $uri, 2);
  236. $_SERVER['QUERY_STRING'] = isset($uri[1]) ? $uri[1] : '';
  237. $uri = $uri[0];
  238. }
  239. parse_str($_SERVER['QUERY_STRING'], $_GET);
  240. return $this->_remove_relative_directory($uri);
  241. }
  242. // --------------------------------------------------------------------
  243. /**
  244. * Parse CLI arguments
  245. *
  246. * Take each command line argument and assume it is a URI segment.
  247. *
  248. * @return string
  249. */
  250. protected function _parse_argv()
  251. {
  252. $args = array_slice($_SERVER['argv'], 1);
  253. return $args ? implode('/', $args) : '';
  254. }
  255. // --------------------------------------------------------------------
  256. /**
  257. * Remove relative directory (../) and multi slashes (///)
  258. *
  259. * Do some final cleaning of the URI and return it, currently only used in self::_parse_request_uri()
  260. *
  261. * @param string $uri
  262. * @return string
  263. */
  264. protected function _remove_relative_directory($uri)
  265. {
  266. $uris = array();
  267. $tok = strtok($uri, '/');
  268. while ($tok !== FALSE)
  269. {
  270. if (( ! empty($tok) OR $tok === '0') && $tok !== '..')
  271. {
  272. $uris[] = $tok;
  273. }
  274. $tok = strtok('/');
  275. }
  276. return implode('/', $uris);
  277. }
  278. // --------------------------------------------------------------------
  279. /**
  280. * Filter URI
  281. *
  282. * Filters segments for malicious characters.
  283. *
  284. * @param string $str
  285. * @return void
  286. */
  287. public function filter_uri(&$str)
  288. {
  289. if ( ! empty($str) && ! empty($this->_permitted_uri_chars) && ! preg_match('/^['.$this->_permitted_uri_chars.']+$/i'.(UTF8_ENABLED ? 'u' : ''), $str))
  290. {
  291. show_error('The URI you submitted has disallowed characters.', 400);
  292. }
  293. }
  294. // --------------------------------------------------------------------
  295. /**
  296. * Fetch URI Segment
  297. *
  298. * @see CI_URI::$segments
  299. * @param int $n Index
  300. * @param mixed $no_result What to return if the segment index is not found
  301. * @return mixed
  302. */
  303. public function segment($n, $no_result = NULL)
  304. {
  305. return isset($this->segments[$n]) ? $this->segments[$n] : $no_result;
  306. }
  307. // --------------------------------------------------------------------
  308. /**
  309. * Fetch URI "routed" Segment
  310. *
  311. * Returns the re-routed URI segment (assuming routing rules are used)
  312. * based on the index provided. If there is no routing, will return
  313. * the same result as CI_URI::segment().
  314. *
  315. * @see CI_URI::$rsegments
  316. * @see CI_URI::segment()
  317. * @param int $n Index
  318. * @param mixed $no_result What to return if the segment index is not found
  319. * @return mixed
  320. */
  321. public function rsegment($n, $no_result = NULL)
  322. {
  323. return isset($this->rsegments[$n]) ? $this->rsegments[$n] : $no_result;
  324. }
  325. // --------------------------------------------------------------------
  326. /**
  327. * URI to assoc
  328. *
  329. * Generates an associative array of URI data starting at the supplied
  330. * segment index. For example, if this is your URI:
  331. *
  332. * example.com/user/search/name/joe/location/UK/gender/male
  333. *
  334. * You can use this method to generate an array with this prototype:
  335. *
  336. * array (
  337. * name => joe
  338. * location => UK
  339. * gender => male
  340. * )
  341. *
  342. * @param int $n Index (default: 3)
  343. * @param array $default Default values
  344. * @return array
  345. */
  346. public function uri_to_assoc($n = 3, $default = array())
  347. {
  348. return $this->_uri_to_assoc($n, $default, 'segment');
  349. }
  350. // --------------------------------------------------------------------
  351. /**
  352. * Routed URI to assoc
  353. *
  354. * Identical to CI_URI::uri_to_assoc(), only it uses the re-routed
  355. * segment array.
  356. *
  357. * @see CI_URI::uri_to_assoc()
  358. * @param int $n Index (default: 3)
  359. * @param array $default Default values
  360. * @return array
  361. */
  362. public function ruri_to_assoc($n = 3, $default = array())
  363. {
  364. return $this->_uri_to_assoc($n, $default, 'rsegment');
  365. }
  366. // --------------------------------------------------------------------
  367. /**
  368. * Internal URI-to-assoc
  369. *
  370. * Generates a key/value pair from the URI string or re-routed URI string.
  371. *
  372. * @used-by CI_URI::uri_to_assoc()
  373. * @used-by CI_URI::ruri_to_assoc()
  374. * @param int $n Index (default: 3)
  375. * @param array $default Default values
  376. * @param string $which Array name ('segment' or 'rsegment')
  377. * @return array
  378. */
  379. protected function _uri_to_assoc($n = 3, $default = array(), $which = 'segment')
  380. {
  381. if ( ! is_numeric($n))
  382. {
  383. return $default;
  384. }
  385. if (isset($this->keyval[$which], $this->keyval[$which][$n]))
  386. {
  387. return $this->keyval[$which][$n];
  388. }
  389. $total_segments = "total_{$which}s";
  390. $segment_array = "{$which}_array";
  391. if ($this->$total_segments() < $n)
  392. {
  393. return (count($default) === 0)
  394. ? array()
  395. : array_fill_keys($default, NULL);
  396. }
  397. $segments = array_slice($this->$segment_array(), ($n - 1));
  398. $i = 0;
  399. $lastval = '';
  400. $retval = array();
  401. foreach ($segments as $seg)
  402. {
  403. if ($i % 2)
  404. {
  405. $retval[$lastval] = $seg;
  406. }
  407. else
  408. {
  409. $retval[$seg] = NULL;
  410. $lastval = $seg;
  411. }
  412. $i++;
  413. }
  414. if (count($default) > 0)
  415. {
  416. foreach ($default as $val)
  417. {
  418. if ( ! array_key_exists($val, $retval))
  419. {
  420. $retval[$val] = NULL;
  421. }
  422. }
  423. }
  424. // Cache the array for reuse
  425. isset($this->keyval[$which]) OR $this->keyval[$which] = array();
  426. $this->keyval[$which][$n] = $retval;
  427. return $retval;
  428. }
  429. // --------------------------------------------------------------------
  430. /**
  431. * Assoc to URI
  432. *
  433. * Generates a URI string from an associative array.
  434. *
  435. * @param array $array Input array of key/value pairs
  436. * @return string URI string
  437. */
  438. public function assoc_to_uri($array)
  439. {
  440. $temp = array();
  441. foreach ((array) $array as $key => $val)
  442. {
  443. $temp[] = $key;
  444. $temp[] = $val;
  445. }
  446. return implode('/', $temp);
  447. }
  448. // --------------------------------------------------------------------
  449. /**
  450. * Slash segment
  451. *
  452. * Fetches an URI segment with a slash.
  453. *
  454. * @param int $n Index
  455. * @param string $where Where to add the slash ('trailing' or 'leading')
  456. * @return string
  457. */
  458. public function slash_segment($n, $where = 'trailing')
  459. {
  460. return $this->_slash_segment($n, $where, 'segment');
  461. }
  462. // --------------------------------------------------------------------
  463. /**
  464. * Slash routed segment
  465. *
  466. * Fetches an URI routed segment with a slash.
  467. *
  468. * @param int $n Index
  469. * @param string $where Where to add the slash ('trailing' or 'leading')
  470. * @return string
  471. */
  472. public function slash_rsegment($n, $where = 'trailing')
  473. {
  474. return $this->_slash_segment($n, $where, 'rsegment');
  475. }
  476. // --------------------------------------------------------------------
  477. /**
  478. * Internal Slash segment
  479. *
  480. * Fetches an URI Segment and adds a slash to it.
  481. *
  482. * @used-by CI_URI::slash_segment()
  483. * @used-by CI_URI::slash_rsegment()
  484. *
  485. * @param int $n Index
  486. * @param string $where Where to add the slash ('trailing' or 'leading')
  487. * @param string $which Array name ('segment' or 'rsegment')
  488. * @return string
  489. */
  490. protected function _slash_segment($n, $where = 'trailing', $which = 'segment')
  491. {
  492. $leading = $trailing = '/';
  493. if ($where === 'trailing')
  494. {
  495. $leading = '';
  496. }
  497. elseif ($where === 'leading')
  498. {
  499. $trailing = '';
  500. }
  501. return $leading.$this->$which($n).$trailing;
  502. }
  503. // --------------------------------------------------------------------
  504. /**
  505. * Segment Array
  506. *
  507. * @return array CI_URI::$segments
  508. */
  509. public function segment_array()
  510. {
  511. return $this->segments;
  512. }
  513. // --------------------------------------------------------------------
  514. /**
  515. * Routed Segment Array
  516. *
  517. * @return array CI_URI::$rsegments
  518. */
  519. public function rsegment_array()
  520. {
  521. return $this->rsegments;
  522. }
  523. // --------------------------------------------------------------------
  524. /**
  525. * Total number of segments
  526. *
  527. * @return int
  528. */
  529. public function total_segments()
  530. {
  531. return count($this->segments);
  532. }
  533. // --------------------------------------------------------------------
  534. /**
  535. * Total number of routed segments
  536. *
  537. * @return int
  538. */
  539. public function total_rsegments()
  540. {
  541. return count($this->rsegments);
  542. }
  543. // --------------------------------------------------------------------
  544. /**
  545. * Fetch URI string
  546. *
  547. * @return string CI_URI::$uri_string
  548. */
  549. public function uri_string()
  550. {
  551. return $this->uri_string;
  552. }
  553. // --------------------------------------------------------------------
  554. /**
  555. * Fetch Re-routed URI string
  556. *
  557. * @return string
  558. */
  559. public function ruri_string()
  560. {
  561. return ltrim(load_class('Router', 'core')->directory, '/').implode('/', $this->rsegments);
  562. }
  563. }