Uri.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  1. <?php
  2. /**
  3. * @package Grav.Common
  4. *
  5. * @copyright Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common;
  9. use Grav\Common\Config\Config;
  10. use Grav\Common\Language\Language;
  11. use Grav\Common\Page\Page;
  12. use Grav\Common\Page\Pages;
  13. use Grav\Framework\Route\RouteFactory;
  14. use Grav\Framework\Uri\UriFactory;
  15. use Grav\Framework\Uri\UriPartsFilter;
  16. class Uri
  17. {
  18. const HOSTNAME_REGEX = '/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/';
  19. /** @var \Grav\Framework\Uri\Uri */
  20. protected static $currentUri;
  21. /** @var \Grav\Framework\Route\Route */
  22. protected static $currentRoute;
  23. public $url;
  24. // Uri parts.
  25. protected $scheme;
  26. protected $user;
  27. protected $password;
  28. protected $host;
  29. protected $port;
  30. protected $path;
  31. protected $query;
  32. protected $fragment;
  33. // Internal stuff.
  34. protected $base;
  35. protected $basename;
  36. protected $content_path;
  37. protected $extension;
  38. protected $env;
  39. protected $paths;
  40. protected $queries;
  41. protected $params;
  42. protected $root;
  43. protected $root_path;
  44. protected $uri;
  45. protected $content_type;
  46. protected $post;
  47. /**
  48. * Uri constructor.
  49. * @param string|array $env
  50. */
  51. public function __construct($env = null)
  52. {
  53. if (is_string($env)) {
  54. $this->createFromString($env);
  55. } else {
  56. $this->createFromEnvironment(is_array($env) ? $env : $_SERVER);
  57. }
  58. }
  59. /**
  60. * Initialize the URI class with a url passed via parameter.
  61. * Used for testing purposes.
  62. *
  63. * @param string $url the URL to use in the class
  64. *
  65. * @return $this
  66. */
  67. public function initializeWithUrl($url = '')
  68. {
  69. if ($url) {
  70. $this->createFromString($url);
  71. }
  72. return $this;
  73. }
  74. /**
  75. * Initialize the URI class by providing url and root_path arguments
  76. *
  77. * @param string $url
  78. * @param string $root_path
  79. *
  80. * @return $this
  81. */
  82. public function initializeWithUrlAndRootPath($url, $root_path)
  83. {
  84. $this->initializeWithUrl($url);
  85. $this->root_path = $root_path;
  86. return $this;
  87. }
  88. /**
  89. * Validate a hostname
  90. *
  91. * @param string $hostname The hostname
  92. *
  93. * @return boolean
  94. */
  95. public function validateHostname($hostname)
  96. {
  97. return (bool)preg_match(static::HOSTNAME_REGEX, $hostname);
  98. }
  99. /**
  100. * Initializes the URI object based on the url set on the object
  101. */
  102. public function init()
  103. {
  104. $grav = Grav::instance();
  105. /** @var Config $config */
  106. $config = $grav['config'];
  107. /** @var Language $language */
  108. $language = $grav['language'];
  109. // add the port to the base for non-standard ports
  110. if ($this->port !== null && $config->get('system.reverse_proxy_setup') === false) {
  111. $this->base .= ':' . (string)$this->port;
  112. }
  113. // Handle custom base
  114. $custom_base = rtrim($grav['config']->get('system.custom_base_url'), '/');
  115. if ($custom_base) {
  116. $custom_parts = parse_url($custom_base);
  117. $orig_root_path = $this->root_path;
  118. $this->root_path = isset($custom_parts['path']) ? rtrim($custom_parts['path'], '/') : '';
  119. if (isset($custom_parts['scheme'])) {
  120. $this->base = $custom_parts['scheme'] . '://' . $custom_parts['host'];
  121. $this->root = $custom_base;
  122. } else {
  123. $this->root = $this->base . $this->root_path;
  124. }
  125. $this->uri = Utils::replaceFirstOccurrence($orig_root_path, $this->root_path, $this->uri);
  126. } else {
  127. $this->root = $this->base . $this->root_path;
  128. }
  129. $this->url = $this->base . $this->uri;
  130. $uri = str_replace(static::filterPath($this->root), '', $this->url);
  131. // remove the setup.php based base if set:
  132. $setup_base = $grav['pages']->base();
  133. if ($setup_base) {
  134. $uri = preg_replace('|^' . preg_quote($setup_base, '|') . '|', '', $uri);
  135. }
  136. // process params
  137. $uri = $this->processParams($uri, $config->get('system.param_sep'));
  138. // set active language
  139. $uri = $language->setActiveFromUri($uri);
  140. // split the URL and params
  141. $bits = parse_url($uri);
  142. //process fragment
  143. if (isset($bits['fragment'])) {
  144. $this->fragment = $bits['fragment'];
  145. }
  146. // Get the path. If there's no path, make sure pathinfo() still returns dirname variable
  147. $path = isset($bits['path']) ? $bits['path'] : '/';
  148. // remove the extension if there is one set
  149. $parts = pathinfo($path);
  150. // set the original basename
  151. $this->basename = $parts['basename'];
  152. // set the extension
  153. if (isset($parts['extension'])) {
  154. $this->extension = $parts['extension'];
  155. }
  156. $valid_page_types = implode('|', $config->get('system.pages.types'));
  157. // Strip the file extension for valid page types
  158. if (preg_match('/\.(' . $valid_page_types . ')$/', $parts['basename'])) {
  159. $path = rtrim(str_replace(DIRECTORY_SEPARATOR, DS, $parts['dirname']), DS) . '/' . $parts['filename'];
  160. }
  161. // set the new url
  162. $this->url = $this->root . $path;
  163. $this->path = static::cleanPath($path);
  164. $this->content_path = trim(str_replace($this->base, '', $this->path), '/');
  165. if ($this->content_path !== '') {
  166. $this->paths = explode('/', $this->content_path);
  167. }
  168. // Set some Grav stuff
  169. $grav['base_url_absolute'] = $config->get('system.custom_base_url') ?: $this->rootUrl(true);
  170. $grav['base_url_relative'] = $this->rootUrl(false);
  171. $grav['base_url'] = $config->get('system.absolute_urls') ? $grav['base_url_absolute'] : $grav['base_url_relative'];
  172. RouteFactory::setRoot($this->root_path);
  173. RouteFactory::setLanguage($language->getLanguageURLPrefix());
  174. }
  175. /**
  176. * Return URI path.
  177. *
  178. * @param string $id
  179. *
  180. * @return string|string[]
  181. */
  182. public function paths($id = null)
  183. {
  184. if ($id !== null) {
  185. return $this->paths[$id];
  186. }
  187. return $this->paths;
  188. }
  189. /**
  190. * Return route to the current URI. By default route doesn't include base path.
  191. *
  192. * @param bool $absolute True to include full path.
  193. * @param bool $domain True to include domain. Works only if first parameter is also true.
  194. *
  195. * @return string
  196. */
  197. public function route($absolute = false, $domain = false)
  198. {
  199. return ($absolute ? $this->rootUrl($domain) : '') . '/' . implode('/', $this->paths);
  200. }
  201. /**
  202. * Return full query string or a single query attribute.
  203. *
  204. * @param string $id Optional attribute. Get a single query attribute if set
  205. * @param bool $raw If true and $id is not set, return the full query array. Otherwise return the query string
  206. *
  207. * @return string|array Returns an array if $id = null and $raw = true
  208. */
  209. public function query($id = null, $raw = false)
  210. {
  211. if ($id !== null) {
  212. return isset($this->queries[$id]) ? $this->queries[$id] : null;
  213. }
  214. if ($raw) {
  215. return $this->queries;
  216. }
  217. if (!$this->queries) {
  218. return '';
  219. }
  220. return http_build_query($this->queries);
  221. }
  222. /**
  223. * Return all or a single query parameter as a URI compatible string.
  224. *
  225. * @param string $id Optional parameter name.
  226. * @param boolean $array return the array format or not
  227. *
  228. * @return null|string|array
  229. */
  230. public function params($id = null, $array = false)
  231. {
  232. $config = Grav::instance()['config'];
  233. $sep = $config->get('system.param_sep');
  234. $params = null;
  235. if ($id === null) {
  236. if ($array) {
  237. return $this->params;
  238. }
  239. $output = [];
  240. foreach ($this->params as $key => $value) {
  241. $output[] = "{$key}{$sep}{$value}";
  242. $params = '/' . implode('/', $output);
  243. }
  244. } elseif (isset($this->params[$id])) {
  245. if ($array) {
  246. return $this->params[$id];
  247. }
  248. $params = "/{$id}{$sep}{$this->params[$id]}";
  249. }
  250. return $params;
  251. }
  252. /**
  253. * Get URI parameter.
  254. *
  255. * @param string $id
  256. *
  257. * @return bool|string
  258. */
  259. public function param($id)
  260. {
  261. if (isset($this->params[$id])) {
  262. return html_entity_decode(rawurldecode($this->params[$id]));
  263. }
  264. return false;
  265. }
  266. /**
  267. * Gets the Fragment portion of a URI (eg #target)
  268. *
  269. * @param string $fragment
  270. *
  271. * @return string|null
  272. */
  273. public function fragment($fragment = null)
  274. {
  275. if ($fragment !== null) {
  276. $this->fragment = $fragment;
  277. }
  278. return $this->fragment;
  279. }
  280. /**
  281. * Return URL.
  282. *
  283. * @param bool $include_host Include hostname.
  284. *
  285. * @return string
  286. */
  287. public function url($include_host = false)
  288. {
  289. if ($include_host) {
  290. return $this->url;
  291. }
  292. $url = str_replace($this->base, '', rtrim($this->url, '/'));
  293. return $url ?: '/';
  294. }
  295. /**
  296. * Return the Path
  297. *
  298. * @return String The path of the URI
  299. */
  300. public function path()
  301. {
  302. return $this->path;
  303. }
  304. /**
  305. * Return the Extension of the URI
  306. *
  307. * @param string|null $default
  308. *
  309. * @return string The extension of the URI
  310. */
  311. public function extension($default = null)
  312. {
  313. if (!$this->extension) {
  314. $this->extension = $default;
  315. }
  316. return $this->extension;
  317. }
  318. public function method()
  319. {
  320. $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';
  321. if ($method === 'POST' && isset($_SERVER['X-HTTP-METHOD-OVERRIDE'])) {
  322. $method = strtoupper($_SERVER['X-HTTP-METHOD-OVERRIDE']);
  323. }
  324. return $method;
  325. }
  326. /**
  327. * Return the scheme of the URI
  328. *
  329. * @param bool $raw
  330. * @return string The scheme of the URI
  331. */
  332. public function scheme($raw = false)
  333. {
  334. if (!$raw) {
  335. $scheme = '';
  336. if ($this->scheme) {
  337. $scheme = $this->scheme . '://';
  338. } elseif ($this->host) {
  339. $scheme = '//';
  340. }
  341. return $scheme;
  342. }
  343. return $this->scheme;
  344. }
  345. /**
  346. * Return the host of the URI
  347. *
  348. * @return string|null The host of the URI
  349. */
  350. public function host()
  351. {
  352. return $this->host;
  353. }
  354. /**
  355. * Return the port number if it can be figured out
  356. *
  357. * @param bool $raw
  358. * @return int|null
  359. */
  360. public function port($raw = false)
  361. {
  362. $port = $this->port;
  363. // If not in raw mode and port is not set, figure it out from scheme.
  364. if (!$raw && $port === null) {
  365. if ($this->scheme === 'http') {
  366. $this->port = 80;
  367. } elseif ($this->scheme === 'https') {
  368. $this->port = 443;
  369. }
  370. }
  371. return $this->port;
  372. }
  373. /**
  374. * Return user
  375. *
  376. * @return string|null
  377. */
  378. public function user()
  379. {
  380. return $this->user;
  381. }
  382. /**
  383. * Return password
  384. *
  385. * @return string|null
  386. */
  387. public function password()
  388. {
  389. return $this->password;
  390. }
  391. /**
  392. * Gets the environment name
  393. *
  394. * @return String
  395. */
  396. public function environment()
  397. {
  398. return $this->env;
  399. }
  400. /**
  401. * Return the basename of the URI
  402. *
  403. * @return String The basename of the URI
  404. */
  405. public function basename()
  406. {
  407. return $this->basename;
  408. }
  409. /**
  410. * Return the full uri
  411. *
  412. * @param bool $include_root
  413. * @return mixed
  414. */
  415. public function uri($include_root = true)
  416. {
  417. if ($include_root) {
  418. return $this->uri;
  419. }
  420. return str_replace($this->root_path, '', $this->uri);
  421. }
  422. /**
  423. * Return the base of the URI
  424. *
  425. * @return String The base of the URI
  426. */
  427. public function base()
  428. {
  429. return $this->base;
  430. }
  431. /**
  432. * Return the base relative URL including the language prefix
  433. * or the base relative url if multi-language is not enabled
  434. *
  435. * @return String The base of the URI
  436. */
  437. public function baseIncludingLanguage()
  438. {
  439. $grav = Grav::instance();
  440. /** @var Pages $pages */
  441. $pages = $grav['pages'];
  442. return $pages->baseUrl(null, false);
  443. }
  444. /**
  445. * Return root URL to the site.
  446. *
  447. * @param bool $include_host Include hostname.
  448. *
  449. * @return mixed
  450. */
  451. public function rootUrl($include_host = false)
  452. {
  453. if ($include_host) {
  454. return $this->root;
  455. }
  456. return str_replace($this->base, '', $this->root);
  457. }
  458. /**
  459. * Return current page number.
  460. *
  461. * @return int
  462. */
  463. public function currentPage()
  464. {
  465. return isset($this->params['page']) ? $this->params['page'] : 1;
  466. }
  467. /**
  468. * Return relative path to the referrer defaulting to current or given page.
  469. *
  470. * @param string $default
  471. * @param string $attributes
  472. *
  473. * @return string
  474. */
  475. public function referrer($default = null, $attributes = null)
  476. {
  477. $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  478. // Check that referrer came from our site.
  479. $root = $this->rootUrl(true);
  480. if ($referrer) {
  481. // Referrer should always have host set and it should come from the same base address.
  482. if (stripos($referrer, $root) !== 0) {
  483. $referrer = null;
  484. }
  485. }
  486. if (!$referrer) {
  487. $referrer = $default ?: $this->route(true, true);
  488. }
  489. if ($attributes) {
  490. $referrer .= $attributes;
  491. }
  492. // Return relative path.
  493. return substr($referrer, strlen($root));
  494. }
  495. public function __toString()
  496. {
  497. return static::buildUrl($this->toArray());
  498. }
  499. public function toArray()
  500. {
  501. return [
  502. 'scheme' => $this->scheme,
  503. 'host' => $this->host,
  504. 'port' => $this->port,
  505. 'user' => $this->user,
  506. 'pass' => $this->password,
  507. 'path' => $this->path,
  508. 'params' => $this->params,
  509. 'query' => $this->query,
  510. 'fragment' => $this->fragment
  511. ];
  512. }
  513. /**
  514. * Calculate the parameter regex based on the param_sep setting
  515. *
  516. * @return string
  517. */
  518. public static function paramsRegex()
  519. {
  520. return '/\/([^\:\#\/\?]*' . Grav::instance()['config']->get('system.param_sep') . '[^\:\#\/\?]*)/';
  521. }
  522. /**
  523. * Return the IP address of the current user
  524. *
  525. * @return string ip address
  526. */
  527. public static function ip()
  528. {
  529. if (getenv('HTTP_CLIENT_IP')) {
  530. $ip = getenv('HTTP_CLIENT_IP');
  531. } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
  532. $ip = getenv('HTTP_X_FORWARDED_FOR');
  533. } elseif (getenv('HTTP_X_FORWARDED')) {
  534. $ip = getenv('HTTP_X_FORWARDED');
  535. } elseif (getenv('HTTP_FORWARDED_FOR')) {
  536. $ip = getenv('HTTP_FORWARDED_FOR');
  537. } elseif (getenv('HTTP_FORWARDED')) {
  538. $ip = getenv('HTTP_FORWARDED');
  539. } elseif (getenv('REMOTE_ADDR')){
  540. $ip = getenv('REMOTE_ADDR');
  541. } else {
  542. $ip = 'UNKNOWN';
  543. }
  544. return $ip;
  545. }
  546. /**
  547. * Returns current Uri.
  548. *
  549. * @return \Grav\Framework\Uri\Uri
  550. */
  551. public static function getCurrentUri()
  552. {
  553. if (!static::$currentUri) {
  554. static::$currentUri = UriFactory::createFromEnvironment($_SERVER);
  555. }
  556. return static::$currentUri;
  557. }
  558. /**
  559. * Returns current route.
  560. *
  561. * @return \Grav\Framework\Route\Route
  562. */
  563. public static function getCurrentRoute()
  564. {
  565. if (!static::$currentRoute) {
  566. $uri = Grav::instance()['uri'];
  567. static::$currentRoute = RouteFactory::createFromParts($uri->toArray());
  568. }
  569. return static::$currentRoute;
  570. }
  571. /**
  572. * Is this an external URL? if it starts with `http` then yes, else false
  573. *
  574. * @param string $url the URL in question
  575. *
  576. * @return boolean is eternal state
  577. */
  578. public static function isExternal($url)
  579. {
  580. return Utils::startsWith($url, 'http');
  581. }
  582. /**
  583. * The opposite of built-in PHP method parse_url()
  584. *
  585. * @param array $parsed_url
  586. *
  587. * @return string
  588. */
  589. public static function buildUrl($parsed_url)
  590. {
  591. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . ':' : '';
  592. $authority = isset($parsed_url['host']) ? '//' : '';
  593. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  594. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  595. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  596. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  597. $pass = ($user || $pass) ? "{$pass}@" : '';
  598. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  599. $path = !empty($parsed_url['params']) ? rtrim($path, '/') . static::buildParams($parsed_url['params']) : $path;
  600. $query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  601. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  602. return "{$scheme}{$authority}{$user}{$pass}{$host}{$port}{$path}{$query}{$fragment}";
  603. }
  604. /**
  605. * @param array $params
  606. * @return string
  607. */
  608. public static function buildParams(array $params)
  609. {
  610. if (!$params) {
  611. return '';
  612. }
  613. $grav = Grav::instance();
  614. $sep = $grav['config']->get('system.param_sep');
  615. $output = [];
  616. foreach ($params as $key => $value) {
  617. $output[] = "{$key}{$sep}{$value}";
  618. }
  619. return '/' . implode('/', $output);
  620. }
  621. /**
  622. * Converts links from absolute '/' or relative (../..) to a Grav friendly format
  623. *
  624. * @param Page $page the current page to use as reference
  625. * @param string|array $url the URL as it was written in the markdown
  626. * @param string $type the type of URL, image | link
  627. * @param bool $absolute if null, will use system default, if true will use absolute links internally
  628. * @param bool $route_only only return the route, not full URL path
  629. * @return string the more friendly formatted url
  630. */
  631. public static function convertUrl(Page $page, $url, $type = 'link', $absolute = false, $route_only = false)
  632. {
  633. $grav = Grav::instance();
  634. $uri = $grav['uri'];
  635. // Link processing should prepend language
  636. $language = $grav['language'];
  637. $language_append = '';
  638. if ($type === 'link' && $language->enabled()) {
  639. $language_append = $language->getLanguageURLPrefix();
  640. }
  641. // Handle Excerpt style $url array
  642. $url_path = is_array($url) ? $url['path'] : $url;
  643. $external = false;
  644. $base = $grav['base_url_relative'];
  645. $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
  646. $pages_dir = $grav['locator']->findResource('page://');
  647. // if absolute and starts with a base_url move on
  648. if (isset($url['scheme']) && Utils::startsWith($url['scheme'], 'http')) {
  649. $external = true;
  650. } elseif ($url_path === '' && isset($url['fragment'])) {
  651. $external = true;
  652. } elseif ($url_path === '/' || ($base_url !== '' && Utils::startsWith($url_path, $base_url))) {
  653. $url_path = $base_url . $url_path;
  654. } else {
  655. // see if page is relative to this or absolute
  656. if (Utils::startsWith($url_path, '/')) {
  657. $normalized_url = Utils::normalizePath($base_url . $url_path);
  658. $normalized_path = Utils::normalizePath($pages_dir . $url_path);
  659. } else {
  660. $page_route = ($page->home() && !empty($url_path)) ? $page->rawRoute() : $page->route();
  661. $normalized_url = $base_url . Utils::normalizePath($page_route . '/' . $url_path);
  662. $normalized_path = Utils::normalizePath($page->path() . '/' . $url_path);
  663. }
  664. // special check to see if path checking is required.
  665. $just_path = str_replace($normalized_url, '', $normalized_path);
  666. if ($normalized_url === '/' || $just_path === $page->path()) {
  667. $url_path = $normalized_url;
  668. } else {
  669. $url_bits = static::parseUrl($normalized_path);
  670. $full_path = $url_bits['path'];
  671. $raw_full_path = rawurldecode($full_path);
  672. if (file_exists($raw_full_path)) {
  673. $full_path = $raw_full_path;
  674. } elseif (!file_exists($full_path)) {
  675. $full_path = false;
  676. }
  677. if ($full_path) {
  678. $path_info = pathinfo($full_path);
  679. $page_path = $path_info['dirname'];
  680. $filename = '';
  681. if ($url_path === '..') {
  682. $page_path = $full_path;
  683. } else {
  684. // save the filename if a file is part of the path
  685. if (is_file($full_path)) {
  686. if ($path_info['extension'] !== 'md') {
  687. $filename = '/' . $path_info['basename'];
  688. }
  689. } else {
  690. $page_path = $full_path;
  691. }
  692. }
  693. // get page instances and try to find one that fits
  694. $instances = $grav['pages']->instances();
  695. if (isset($instances[$page_path])) {
  696. /** @var Page $target */
  697. $target = $instances[$page_path];
  698. $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
  699. $url_path = Uri::buildUrl($url_bits);
  700. } else {
  701. $url_path = $normalized_url;
  702. }
  703. } else {
  704. $url_path = $normalized_url;
  705. }
  706. }
  707. }
  708. // handle absolute URLs
  709. if (is_array($url) && !$external && ($absolute === true || $grav['config']->get('system.absolute_urls', false))) {
  710. $url['scheme'] = $uri->scheme(true);
  711. $url['host'] = $uri->host();
  712. $url['port'] = $uri->port(true);
  713. // check if page exists for this route, and if so, check if it has SSL enabled
  714. $pages = $grav['pages'];
  715. $routes = $pages->routes();
  716. // if this is an image, get the proper path
  717. $url_bits = pathinfo($url_path);
  718. if (isset($url_bits['extension'])) {
  719. $target_path = $url_bits['dirname'];
  720. } else {
  721. $target_path = $url_path;
  722. }
  723. // strip base from this path
  724. $target_path = str_replace($uri->rootUrl(), '', $target_path);
  725. // set to / if root
  726. if (empty($target_path)) {
  727. $target_path = '/';
  728. }
  729. // look to see if this page exists and has ssl enabled
  730. if (isset($routes[$target_path])) {
  731. $target_page = $pages->get($routes[$target_path]);
  732. if ($target_page) {
  733. $ssl_enabled = $target_page->ssl();
  734. if ($ssl_enabled !== null) {
  735. if ($ssl_enabled) {
  736. $url['scheme'] = 'https';
  737. } else {
  738. $url['scheme'] = 'http';
  739. }
  740. }
  741. }
  742. }
  743. }
  744. // Handle route only
  745. if ($route_only) {
  746. $url_path = str_replace(static::filterPath($base_url), '', $url_path);
  747. }
  748. // transform back to string/array as needed
  749. if (is_array($url)) {
  750. $url['path'] = $url_path;
  751. } else {
  752. $url = $url_path;
  753. }
  754. return $url;
  755. }
  756. public static function parseUrl($url)
  757. {
  758. $grav = Grav::instance();
  759. $encodedUrl = preg_replace_callback(
  760. '%[^:/@?&=#]+%usD',
  761. function ($matches) { return rawurlencode($matches[0]); },
  762. $url
  763. );
  764. $parts = parse_url($encodedUrl);
  765. if (false === $parts) {
  766. return false;
  767. }
  768. foreach($parts as $name => $value) {
  769. $parts[$name] = rawurldecode($value);
  770. }
  771. if (!isset($parts['path'])) {
  772. $parts['path'] = '';
  773. }
  774. list($stripped_path, $params) = static::extractParams($parts['path'], $grav['config']->get('system.param_sep'));
  775. if (!empty($params)) {
  776. $parts['path'] = $stripped_path;
  777. $parts['params'] = $params;
  778. }
  779. return $parts;
  780. }
  781. public static function extractParams($uri, $delimiter)
  782. {
  783. $params = [];
  784. if (strpos($uri, $delimiter) !== false) {
  785. preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
  786. foreach ($matches as $match) {
  787. $param = explode($delimiter, $match[1]);
  788. if (count($param) === 2) {
  789. $plain_var = filter_var(rawurldecode($param[1]), FILTER_SANITIZE_STRING);
  790. $params[$param[0]] = $plain_var;
  791. $uri = str_replace($match[0], '', $uri);
  792. }
  793. }
  794. }
  795. return [$uri, $params];
  796. }
  797. /**
  798. * Converts links from absolute '/' or relative (../..) to a Grav friendly format
  799. *
  800. * @param Page $page the current page to use as reference
  801. * @param string $markdown_url the URL as it was written in the markdown
  802. * @param string $type the type of URL, image | link
  803. * @param null $relative if null, will use system default, if true will use relative links internally
  804. *
  805. * @return string the more friendly formatted url
  806. */
  807. public static function convertUrlOld(Page $page, $markdown_url, $type = 'link', $relative = null)
  808. {
  809. $grav = Grav::instance();
  810. $language = $grav['language'];
  811. // Link processing should prepend language
  812. $language_append = '';
  813. if ($type === 'link' && $language->enabled()) {
  814. $language_append = $language->getLanguageURLPrefix();
  815. }
  816. $pages_dir = $grav['locator']->findResource('page://');
  817. if ($relative === null) {
  818. $base = $grav['base_url'];
  819. } else {
  820. $base = $relative ? $grav['base_url_relative'] : $grav['base_url_absolute'];
  821. }
  822. $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
  823. // if absolute and starts with a base_url move on
  824. if (pathinfo($markdown_url, PATHINFO_DIRNAME) === '.' && $page->url() === '/') {
  825. return '/' . $markdown_url;
  826. }
  827. // no path to convert
  828. if ($base_url !== '' && Utils::startsWith($markdown_url, $base_url)) {
  829. return $markdown_url;
  830. }
  831. // if contains only a fragment
  832. if (Utils::startsWith($markdown_url, '#')) {
  833. return $markdown_url;
  834. }
  835. $target = null;
  836. // see if page is relative to this or absolute
  837. if (Utils::startsWith($markdown_url, '/')) {
  838. $normalized_url = Utils::normalizePath($base_url . $markdown_url);
  839. $normalized_path = Utils::normalizePath($pages_dir . $markdown_url);
  840. } else {
  841. $normalized_url = $base_url . Utils::normalizePath($page->route() . '/' . $markdown_url);
  842. $normalized_path = Utils::normalizePath($page->path() . '/' . $markdown_url);
  843. }
  844. // special check to see if path checking is required.
  845. $just_path = str_replace($normalized_url, '', $normalized_path);
  846. if ($just_path === $page->path()) {
  847. return $normalized_url;
  848. }
  849. $url_bits = parse_url($normalized_path);
  850. $full_path = $url_bits['path'];
  851. if (file_exists($full_path)) {
  852. // do nothing
  853. } elseif (file_exists(rawurldecode($full_path))) {
  854. $full_path = rawurldecode($full_path);
  855. } else {
  856. return $normalized_url;
  857. }
  858. $path_info = pathinfo($full_path);
  859. $page_path = $path_info['dirname'];
  860. $filename = '';
  861. if ($markdown_url === '..') {
  862. $page_path = $full_path;
  863. } else {
  864. // save the filename if a file is part of the path
  865. if (is_file($full_path)) {
  866. if ($path_info['extension'] !== 'md') {
  867. $filename = '/' . $path_info['basename'];
  868. }
  869. } else {
  870. $page_path = $full_path;
  871. }
  872. }
  873. // get page instances and try to find one that fits
  874. $instances = $grav['pages']->instances();
  875. if (isset($instances[$page_path])) {
  876. /** @var Page $target */
  877. $target = $instances[$page_path];
  878. $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
  879. return static::buildUrl($url_bits);
  880. }
  881. return $normalized_url;
  882. }
  883. /**
  884. * Adds the nonce to a URL for a specific action
  885. *
  886. * @param string $url the url
  887. * @param string $action the action
  888. * @param string $nonceParamName the param name to use
  889. *
  890. * @return string the url with the nonce
  891. */
  892. public static function addNonce($url, $action, $nonceParamName = 'nonce')
  893. {
  894. $fake = $url && $url[0] === '/';
  895. if ($fake) {
  896. $url = 'http://domain.com' . $url;
  897. }
  898. $uri = new static($url);
  899. $parts = $uri->toArray();
  900. $nonce = Utils::getNonce($action);
  901. $parts['params'] = (isset($parts['params']) ? $parts['params'] : []) + [$nonceParamName => $nonce];
  902. if ($fake) {
  903. unset($parts['scheme'], $parts['host']);
  904. }
  905. return static::buildUrl($parts);
  906. }
  907. /**
  908. * Is the passed in URL a valid URL?
  909. *
  910. * @param $url
  911. * @return bool
  912. */
  913. public static function isValidUrl($url)
  914. {
  915. $regex = '/^(?:(https?|ftp|telnet):)?\/\/((?:[a-z0-9@:.-]|%[0-9A-F]{2}){3,})(?::(\d+))?((?:\/(?:[a-z0-9-._~!$&\'\(\)\*\+\,\;\=\:\@]|%[0-9A-F]{2})*)*)(?:\?((?:[a-z0-9-._~!$&\'\(\)\*\+\,\;\=\:\/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&\'\(\)\*\+\,\;\=\:\/?@]|%[0-9A-F]{2})*))?/';
  916. if (preg_match($regex, $url)) {
  917. return true;
  918. }
  919. return false;
  920. }
  921. /**
  922. * Removes extra double slashes and fixes back-slashes
  923. *
  924. * @param $path
  925. * @return mixed|string
  926. */
  927. public static function cleanPath($path)
  928. {
  929. $regex = '/(\/)\/+/';
  930. $path = str_replace(['\\', '/ /'], '/', $path);
  931. $path = preg_replace($regex,'$1',$path);
  932. return $path;
  933. }
  934. /**
  935. * Filters the user info string.
  936. *
  937. * @param string $info The raw user or password.
  938. * @return string The percent-encoded user or password string.
  939. */
  940. public static function filterUserInfo($info)
  941. {
  942. return $info !== null ? UriPartsFilter::filterUserInfo($info) : '';
  943. }
  944. /**
  945. * Filter Uri path.
  946. *
  947. * This method percent-encodes all reserved
  948. * characters in the provided path string. This method
  949. * will NOT double-encode characters that are already
  950. * percent-encoded.
  951. *
  952. * @param string $path The raw uri path.
  953. * @return string The RFC 3986 percent-encoded uri path.
  954. * @link http://www.faqs.org/rfcs/rfc3986.html
  955. */
  956. public static function filterPath($path)
  957. {
  958. return $path !== null ? UriPartsFilter::filterPath($path) : '';
  959. }
  960. /**
  961. * Filters the query string or fragment of a URI.
  962. *
  963. * @param string $query The raw uri query string.
  964. * @return string The percent-encoded query string.
  965. */
  966. public static function filterQuery($query)
  967. {
  968. return $query !== null ? UriPartsFilter::filterQueryOrFragment($query) : '';
  969. }
  970. /**
  971. * @param array $env
  972. */
  973. protected function createFromEnvironment(array $env)
  974. {
  975. // Build scheme.
  976. if (isset($env['HTTP_X_FORWARDED_PROTO'])) {
  977. $this->scheme = $env['HTTP_X_FORWARDED_PROTO'];
  978. } elseif (isset($env['X-FORWARDED-PROTO'])) {
  979. $this->scheme = $env['X-FORWARDED-PROTO'];
  980. } elseif (isset($env['REQUEST_SCHEME'])) {
  981. $this->scheme = $env['REQUEST_SCHEME'];
  982. } else {
  983. $https = isset($env['HTTPS']) ? $env['HTTPS'] : '';
  984. $this->scheme = (empty($https) || strtolower($https) === 'off') ? 'http' : 'https';
  985. }
  986. // Build user and password.
  987. $this->user = isset($env['PHP_AUTH_USER']) ? $env['PHP_AUTH_USER'] : null;
  988. $this->password = isset($env['PHP_AUTH_PW']) ? $env['PHP_AUTH_PW'] : null;
  989. // Build host.
  990. $hostname = 'localhost';
  991. if (isset($env['HTTP_HOST'])) {
  992. $hostname = $env['HTTP_HOST'];
  993. } elseif (isset($env['SERVER_NAME'])) {
  994. $hostname = $env['SERVER_NAME'];
  995. }
  996. // Remove port from HTTP_HOST generated $hostname
  997. $hostname = Utils::substrToString($hostname, ':');
  998. // Validate the hostname
  999. $this->host = $this->validateHostname($hostname) ? $hostname : 'unknown';
  1000. // Build port.
  1001. if (isset($env['HTTP_X_FORWARDED_PORT'])) {
  1002. $this->port = (int)$env['HTTP_X_FORWARDED_PORT'];
  1003. } elseif (isset($env['X-FORWARDED-PORT'])) {
  1004. $this->port = (int)$env['X-FORWARDED-PORT'];
  1005. } elseif (isset($env['SERVER_PORT'])) {
  1006. $this->port = (int)$env['SERVER_PORT'];
  1007. } else {
  1008. $this->port = null;
  1009. }
  1010. if ($this->hasStandardPort()) {
  1011. $this->port = null;
  1012. }
  1013. // Build path.
  1014. $request_uri = isset($env['REQUEST_URI']) ? $env['REQUEST_URI'] : '';
  1015. $this->path = rawurldecode(parse_url('http://example.com' . $request_uri, PHP_URL_PATH));
  1016. // Build query string.
  1017. $this->query = isset($env['QUERY_STRING']) ? $env['QUERY_STRING'] : '';
  1018. if ($this->query === '') {
  1019. $this->query = parse_url('http://example.com' . $request_uri, PHP_URL_QUERY);
  1020. }
  1021. // Support ngnix routes.
  1022. if (strpos($this->query, '_url=') === 0) {
  1023. parse_str($this->query, $query);
  1024. unset($query['_url']);
  1025. $this->query = http_build_query($query);
  1026. }
  1027. // Build fragment.
  1028. $this->fragment = null;
  1029. // Filter userinfo, path and query string.
  1030. $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null;
  1031. $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null;
  1032. $this->path = empty($this->path) ? '/' : static::filterPath($this->path);
  1033. $this->query = static::filterQuery($this->query);
  1034. $this->reset();
  1035. }
  1036. /**
  1037. * Does this Uri use a standard port?
  1038. *
  1039. * @return bool
  1040. */
  1041. protected function hasStandardPort()
  1042. {
  1043. return ($this->scheme === 'http' && $this->port === 80) || ($this->scheme === 'https' && $this->port === 443);
  1044. }
  1045. /**
  1046. * @param string $url
  1047. */
  1048. protected function createFromString($url)
  1049. {
  1050. // Set Uri parts.
  1051. $parts = parse_url($url);
  1052. if ($parts === false) {
  1053. throw new \RuntimeException('Malformed URL: ' . $url);
  1054. }
  1055. $this->scheme = isset($parts['scheme']) ? $parts['scheme'] : null;
  1056. $this->user = isset($parts['user']) ? $parts['user'] : null;
  1057. $this->password = isset($parts['pass']) ? $parts['pass'] : null;
  1058. $this->host = isset($parts['host']) ? $parts['host'] : null;
  1059. $this->port = isset($parts['port']) ? (int)$parts['port'] : null;
  1060. $this->path = isset($parts['path']) ? $parts['path'] : '';
  1061. $this->query = isset($parts['query']) ? $parts['query'] : '';
  1062. $this->fragment = isset($parts['fragment']) ? $parts['fragment'] : null;
  1063. // Validate the hostname
  1064. if ($this->host) {
  1065. $this->host = $this->validateHostname($this->host) ? $this->host : 'unknown';
  1066. }
  1067. // Filter userinfo, path, query string and fragment.
  1068. $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null;
  1069. $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null;
  1070. $this->path = empty($this->path) ? '/' : static::filterPath($this->path);
  1071. $this->query = static::filterQuery($this->query);
  1072. $this->fragment = $this->fragment !== null ? static::filterQuery($this->fragment) : null;
  1073. $this->reset();
  1074. }
  1075. protected function reset()
  1076. {
  1077. // resets
  1078. parse_str($this->query, $this->queries);
  1079. $this->extension = null;
  1080. $this->basename = null;
  1081. $this->paths = [];
  1082. $this->params = [];
  1083. $this->env = $this->buildEnvironment();
  1084. $this->uri = $this->path . (!empty($this->query) ? '?' . $this->query : '');
  1085. $this->base = $this->buildBaseUrl();
  1086. $this->root_path = $this->buildRootPath();
  1087. $this->root = $this->base . $this->root_path;
  1088. $this->url = $this->base . $this->uri;
  1089. }
  1090. /**
  1091. * Get's post from either $_POST or JSON response object
  1092. * By default returns all data, or can return a single item
  1093. *
  1094. * @param string $element
  1095. * @param string $filter_type
  1096. * @return array|mixed|null
  1097. */
  1098. public function post($element = null, $filter_type = null)
  1099. {
  1100. if (!$this->post) {
  1101. $content_type = $this->getContentType();
  1102. if ($content_type === 'application/json') {
  1103. $json = file_get_contents('php://input');
  1104. $this->post = json_decode($json, true);
  1105. } elseif (!empty($_POST)) {
  1106. $this->post = (array)$_POST;
  1107. }
  1108. }
  1109. if ($this->post && null !== $element) {
  1110. $item = Utils::getDotNotation($this->post, $element);
  1111. if ($filter_type) {
  1112. $item = filter_var($item, $filter_type);
  1113. }
  1114. return $item;
  1115. }
  1116. return $this->post;
  1117. }
  1118. /**
  1119. * Get content type from request
  1120. *
  1121. * @param bool $short
  1122. * @return null|string
  1123. */
  1124. private function getContentType($short = true)
  1125. {
  1126. if (isset($_SERVER['CONTENT_TYPE'])) {
  1127. $content_type = $_SERVER['CONTENT_TYPE'];
  1128. if ($short) {
  1129. return Utils::substrToString($content_type,';');
  1130. }
  1131. return $content_type;
  1132. }
  1133. return null;
  1134. }
  1135. /**
  1136. * Get the base URI with port if needed
  1137. *
  1138. * @return string
  1139. */
  1140. private function buildBaseUrl()
  1141. {
  1142. return $this->scheme() . $this->host;
  1143. }
  1144. /**
  1145. * Get the Grav Root Path
  1146. *
  1147. * @return string
  1148. */
  1149. private function buildRootPath()
  1150. {
  1151. // In Windows script path uses backslash, convert it:
  1152. $scriptPath = str_replace('\\', '/', $_SERVER['PHP_SELF']);
  1153. $rootPath = str_replace(' ', '%20', rtrim(substr($scriptPath, 0, strpos($scriptPath, 'index.php')), '/'));
  1154. return $rootPath;
  1155. }
  1156. private function buildEnvironment()
  1157. {
  1158. // check for localhost variations
  1159. if ($this->host === '127.0.0.1' || $this->host === '::1') {
  1160. return 'localhost';
  1161. }
  1162. return $this->host ?: 'unknown';
  1163. }
  1164. /**
  1165. * Process any params based in this URL, supports any valid delimiter
  1166. *
  1167. * @param $uri
  1168. * @param string $delimiter
  1169. *
  1170. * @return string
  1171. */
  1172. private function processParams($uri, $delimiter = ':')
  1173. {
  1174. if (strpos($uri, $delimiter) !== false) {
  1175. preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
  1176. foreach ($matches as $match) {
  1177. $param = explode($delimiter, $match[1]);
  1178. if (count($param) === 2) {
  1179. $plain_var = filter_var($param[1], FILTER_SANITIZE_STRING);
  1180. $this->params[$param[0]] = $plain_var;
  1181. $uri = str_replace($match[0], '', $uri);
  1182. }
  1183. }
  1184. }
  1185. return $uri;
  1186. }
  1187. }