Uri.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 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\Interfaces\PageInterface;
  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. use RocketTheme\Toolbox\Event\Event;
  17. class Uri
  18. {
  19. 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])$/';
  20. /** @var \Grav\Framework\Uri\Uri */
  21. protected static $currentUri;
  22. /** @var \Grav\Framework\Route\Route */
  23. protected static $currentRoute;
  24. public $url;
  25. // Uri parts.
  26. protected $scheme;
  27. protected $user;
  28. protected $password;
  29. protected $host;
  30. protected $port;
  31. protected $path;
  32. protected $query;
  33. protected $fragment;
  34. // Internal stuff.
  35. protected $base;
  36. protected $basename;
  37. protected $content_path;
  38. protected $extension;
  39. protected $env;
  40. protected $paths;
  41. protected $queries;
  42. protected $params;
  43. protected $root;
  44. protected $root_path;
  45. protected $uri;
  46. protected $content_type;
  47. protected $post;
  48. /**
  49. * Uri constructor.
  50. * @param string|array $env
  51. */
  52. public function __construct($env = null)
  53. {
  54. if (is_string($env)) {
  55. $this->createFromString($env);
  56. } else {
  57. $this->createFromEnvironment(\is_array($env) ? $env : $_SERVER);
  58. }
  59. }
  60. /**
  61. * Initialize the URI class with a url passed via parameter.
  62. * Used for testing purposes.
  63. *
  64. * @param string $url the URL to use in the class
  65. *
  66. * @return $this
  67. */
  68. public function initializeWithUrl($url = '')
  69. {
  70. if ($url) {
  71. $this->createFromString($url);
  72. }
  73. return $this;
  74. }
  75. /**
  76. * Initialize the URI class by providing url and root_path arguments
  77. *
  78. * @param string $url
  79. * @param string $root_path
  80. *
  81. * @return $this
  82. */
  83. public function initializeWithUrlAndRootPath($url, $root_path)
  84. {
  85. $this->initializeWithUrl($url);
  86. $this->root_path = $root_path;
  87. return $this;
  88. }
  89. /**
  90. * Validate a hostname
  91. *
  92. * @param string $hostname The hostname
  93. *
  94. * @return boolean
  95. */
  96. public function validateHostname($hostname)
  97. {
  98. return (bool)preg_match(static::HOSTNAME_REGEX, $hostname);
  99. }
  100. /**
  101. * Initializes the URI object based on the url set on the object
  102. */
  103. public function init()
  104. {
  105. $grav = Grav::instance();
  106. /** @var Config $config */
  107. $config = $grav['config'];
  108. /** @var Language $language */
  109. $language = $grav['language'];
  110. // add the port to the base for non-standard ports
  111. if ($this->port !== null && $config->get('system.reverse_proxy_setup') === false) {
  112. $this->base .= ':' . (string)$this->port;
  113. }
  114. // Handle custom base
  115. $custom_base = rtrim($grav['config']->get('system.custom_base_url'), '/');
  116. if ($custom_base) {
  117. $custom_parts = parse_url($custom_base);
  118. $orig_root_path = $this->root_path;
  119. $this->root_path = isset($custom_parts['path']) ? rtrim($custom_parts['path'], '/') : '';
  120. if (isset($custom_parts['scheme'])) {
  121. $this->base = $custom_parts['scheme'] . '://' . $custom_parts['host'];
  122. $this->root = $custom_base;
  123. } else {
  124. $this->root = $this->base . $this->root_path;
  125. }
  126. $this->uri = Utils::replaceFirstOccurrence($orig_root_path, $this->root_path, $this->uri);
  127. } else {
  128. $this->root = $this->base . $this->root_path;
  129. }
  130. $this->url = $this->base . $this->uri;
  131. $uri = str_replace(static::filterPath($this->root), '', $this->url);
  132. // remove the setup.php based base if set:
  133. $setup_base = $grav['pages']->base();
  134. if ($setup_base) {
  135. $uri = preg_replace('|^' . preg_quote($setup_base, '|') . '|', '', $uri);
  136. }
  137. // process params
  138. $uri = $this->processParams($uri, $config->get('system.param_sep'));
  139. // set active language
  140. $uri = $language->setActiveFromUri($uri);
  141. // split the URL and params
  142. $bits = parse_url($uri);
  143. //process fragment
  144. if (isset($bits['fragment'])) {
  145. $this->fragment = $bits['fragment'];
  146. }
  147. // Get the path. If there's no path, make sure pathinfo() still returns dirname variable
  148. $path = $bits['path'] ?? '/';
  149. // remove the extension if there is one set
  150. $parts = pathinfo($path);
  151. // set the original basename
  152. $this->basename = $parts['basename'];
  153. // set the extension
  154. if (isset($parts['extension'])) {
  155. $this->extension = $parts['extension'];
  156. }
  157. // Strip the file extension for valid page types
  158. if ($this->isValidExtension($this->extension)) {
  159. $path = Utils::replaceLastOccurrence(".{$this->extension}", '', $path);
  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 $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 $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 = $_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 toOriginalString()
  500. {
  501. return static::buildUrl($this->toArray(true));
  502. }
  503. public function toArray($full = false)
  504. {
  505. if ($full === true) {
  506. $root_path = $this->root_path ?? '';
  507. $extension = isset($this->extension) && $this->isValidExtension($this->extension) ? '.' . $this->extension : '';
  508. $path = $root_path . $this->path . $extension;
  509. } else {
  510. $path = $this->path;
  511. }
  512. return [
  513. 'scheme' => $this->scheme,
  514. 'host' => $this->host,
  515. 'port' => $this->port,
  516. 'user' => $this->user,
  517. 'pass' => $this->password,
  518. 'path' => $path,
  519. 'params' => $this->params,
  520. 'query' => $this->query,
  521. 'fragment' => $this->fragment
  522. ];
  523. }
  524. /**
  525. * Calculate the parameter regex based on the param_sep setting
  526. *
  527. * @return string
  528. */
  529. public static function paramsRegex()
  530. {
  531. return '/\/([^\:\#\/\?]*' . Grav::instance()['config']->get('system.param_sep') . '[^\:\#\/\?]*)/';
  532. }
  533. /**
  534. * Return the IP address of the current user
  535. *
  536. * @return string ip address
  537. */
  538. public static function ip()
  539. {
  540. if (getenv('HTTP_CLIENT_IP')) {
  541. $ip = getenv('HTTP_CLIENT_IP');
  542. } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
  543. $ip = getenv('HTTP_X_FORWARDED_FOR');
  544. } elseif (getenv('HTTP_X_FORWARDED')) {
  545. $ip = getenv('HTTP_X_FORWARDED');
  546. } elseif (getenv('HTTP_FORWARDED_FOR')) {
  547. $ip = getenv('HTTP_FORWARDED_FOR');
  548. } elseif (getenv('HTTP_FORWARDED')) {
  549. $ip = getenv('HTTP_FORWARDED');
  550. } elseif (getenv('REMOTE_ADDR')){
  551. $ip = getenv('REMOTE_ADDR');
  552. } else {
  553. $ip = 'UNKNOWN';
  554. }
  555. return $ip;
  556. }
  557. /**
  558. * Returns current Uri.
  559. *
  560. * @return \Grav\Framework\Uri\Uri
  561. */
  562. public static function getCurrentUri()
  563. {
  564. if (!static::$currentUri) {
  565. static::$currentUri = UriFactory::createFromEnvironment($_SERVER);
  566. }
  567. return static::$currentUri;
  568. }
  569. /**
  570. * Returns current route.
  571. *
  572. * @return \Grav\Framework\Route\Route
  573. */
  574. public static function getCurrentRoute()
  575. {
  576. if (!static::$currentRoute) {
  577. $uri = Grav::instance()['uri'];
  578. static::$currentRoute = RouteFactory::createFromParts($uri->toArray());
  579. }
  580. return static::$currentRoute;
  581. }
  582. /**
  583. * Is this an external URL? if it starts with `http` then yes, else false
  584. *
  585. * @param string $url the URL in question
  586. *
  587. * @return boolean is eternal state
  588. */
  589. public static function isExternal($url)
  590. {
  591. return (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://') || 0 === strpos($url, '//'));
  592. }
  593. /**
  594. * The opposite of built-in PHP method parse_url()
  595. *
  596. * @param array $parsed_url
  597. *
  598. * @return string
  599. */
  600. public static function buildUrl($parsed_url)
  601. {
  602. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . ':' : '';
  603. $authority = isset($parsed_url['host']) ? '//' : '';
  604. $host = $parsed_url['host'] ?? '';
  605. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  606. $user = $parsed_url['user'] ?? '';
  607. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  608. $pass = ($user || $pass) ? "{$pass}@" : '';
  609. $path = $parsed_url['path'] ?? '';
  610. $path = !empty($parsed_url['params']) ? rtrim($path, '/') . static::buildParams($parsed_url['params']) : $path;
  611. $query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  612. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  613. return "{$scheme}{$authority}{$user}{$pass}{$host}{$port}{$path}{$query}{$fragment}";
  614. }
  615. /**
  616. * @param array $params
  617. * @return string
  618. */
  619. public static function buildParams(array $params)
  620. {
  621. if (!$params) {
  622. return '';
  623. }
  624. $grav = Grav::instance();
  625. $sep = $grav['config']->get('system.param_sep');
  626. $output = [];
  627. foreach ($params as $key => $value) {
  628. $output[] = "{$key}{$sep}{$value}";
  629. }
  630. return '/' . implode('/', $output);
  631. }
  632. /**
  633. * Converts links from absolute '/' or relative (../..) to a Grav friendly format
  634. *
  635. * @param PageInterface $page the current page to use as reference
  636. * @param string|array $url the URL as it was written in the markdown
  637. * @param string $type the type of URL, image | link
  638. * @param bool $absolute if null, will use system default, if true will use absolute links internally
  639. * @param bool $route_only only return the route, not full URL path
  640. * @return string|array the more friendly formatted url
  641. */
  642. public static function convertUrl(PageInterface $page, $url, $type = 'link', $absolute = false, $route_only = false)
  643. {
  644. $grav = Grav::instance();
  645. $uri = $grav['uri'];
  646. // Link processing should prepend language
  647. $language = $grav['language'];
  648. $language_append = '';
  649. if ($type === 'link' && $language->enabled()) {
  650. $language_append = $language->getLanguageURLPrefix();
  651. }
  652. // Handle Excerpt style $url array
  653. $url_path = is_array($url) ? $url['path'] : $url;
  654. $external = false;
  655. $base = $grav['base_url_relative'];
  656. $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
  657. $pages_dir = $grav['locator']->findResource('page://');
  658. // if absolute and starts with a base_url move on
  659. if (isset($url['scheme']) && Utils::startsWith($url['scheme'], 'http')) {
  660. $external = true;
  661. } elseif ($url_path === '' && isset($url['fragment'])) {
  662. $external = true;
  663. } elseif ($url_path === '/' || ($base_url !== '' && Utils::startsWith($url_path, $base_url))) {
  664. $url_path = $base_url . $url_path;
  665. } else {
  666. // see if page is relative to this or absolute
  667. if (Utils::startsWith($url_path, '/')) {
  668. $normalized_url = Utils::normalizePath($base_url . $url_path);
  669. $normalized_path = Utils::normalizePath($pages_dir . $url_path);
  670. } else {
  671. $page_route = ($page->home() && !empty($url_path)) ? $page->rawRoute() : $page->route();
  672. $normalized_url = $base_url . Utils::normalizePath(rtrim($page_route, '/') . '/' . $url_path);
  673. $normalized_path = Utils::normalizePath($page->path() . '/' . $url_path);
  674. }
  675. // special check to see if path checking is required.
  676. $just_path = str_replace($normalized_url, '', $normalized_path);
  677. if ($normalized_url === '/' || $just_path === $page->path()) {
  678. $url_path = $normalized_url;
  679. } else {
  680. $url_bits = static::parseUrl($normalized_path);
  681. $full_path = $url_bits['path'];
  682. $raw_full_path = rawurldecode($full_path);
  683. if (file_exists($raw_full_path)) {
  684. $full_path = $raw_full_path;
  685. } elseif (!file_exists($full_path)) {
  686. $full_path = false;
  687. }
  688. if ($full_path) {
  689. $path_info = pathinfo($full_path);
  690. $page_path = $path_info['dirname'];
  691. $filename = '';
  692. if ($url_path === '..') {
  693. $page_path = $full_path;
  694. } else {
  695. // save the filename if a file is part of the path
  696. if (is_file($full_path)) {
  697. if ($path_info['extension'] !== 'md') {
  698. $filename = '/' . $path_info['basename'];
  699. }
  700. } else {
  701. $page_path = $full_path;
  702. }
  703. }
  704. // get page instances and try to find one that fits
  705. $instances = $grav['pages']->instances();
  706. if (isset($instances[$page_path])) {
  707. /** @var PageInterface $target */
  708. $target = $instances[$page_path];
  709. $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
  710. $url_path = Uri::buildUrl($url_bits);
  711. } else {
  712. $url_path = $normalized_url;
  713. }
  714. } else {
  715. $url_path = $normalized_url;
  716. }
  717. }
  718. }
  719. // handle absolute URLs
  720. if (\is_array($url) && !$external && ($absolute === true || $grav['config']->get('system.absolute_urls', false))) {
  721. $url['scheme'] = $uri->scheme(true);
  722. $url['host'] = $uri->host();
  723. $url['port'] = $uri->port(true);
  724. // check if page exists for this route, and if so, check if it has SSL enabled
  725. $pages = $grav['pages'];
  726. $routes = $pages->routes();
  727. // if this is an image, get the proper path
  728. $url_bits = pathinfo($url_path);
  729. if (isset($url_bits['extension'])) {
  730. $target_path = $url_bits['dirname'];
  731. } else {
  732. $target_path = $url_path;
  733. }
  734. // strip base from this path
  735. $target_path = str_replace($uri->rootUrl(), '', $target_path);
  736. // set to / if root
  737. if (empty($target_path)) {
  738. $target_path = '/';
  739. }
  740. // look to see if this page exists and has ssl enabled
  741. if (isset($routes[$target_path])) {
  742. $target_page = $pages->get($routes[$target_path]);
  743. if ($target_page) {
  744. $ssl_enabled = $target_page->ssl();
  745. if ($ssl_enabled !== null) {
  746. if ($ssl_enabled) {
  747. $url['scheme'] = 'https';
  748. } else {
  749. $url['scheme'] = 'http';
  750. }
  751. }
  752. }
  753. }
  754. }
  755. // Handle route only
  756. if ($route_only) {
  757. $url_path = str_replace(static::filterPath($base_url), '', $url_path);
  758. }
  759. // transform back to string/array as needed
  760. if (is_array($url)) {
  761. $url['path'] = $url_path;
  762. } else {
  763. $url = $url_path;
  764. }
  765. return $url;
  766. }
  767. public static function parseUrl($url)
  768. {
  769. $grav = Grav::instance();
  770. $encodedUrl = preg_replace_callback(
  771. '%[^:/@?&=#]+%usD',
  772. function ($matches) { return rawurlencode($matches[0]); },
  773. $url
  774. );
  775. $parts = parse_url($encodedUrl);
  776. if (false === $parts) {
  777. return false;
  778. }
  779. foreach($parts as $name => $value) {
  780. $parts[$name] = rawurldecode($value);
  781. }
  782. if (!isset($parts['path'])) {
  783. $parts['path'] = '';
  784. }
  785. list($stripped_path, $params) = static::extractParams($parts['path'], $grav['config']->get('system.param_sep'));
  786. if (!empty($params)) {
  787. $parts['path'] = $stripped_path;
  788. $parts['params'] = $params;
  789. }
  790. return $parts;
  791. }
  792. public static function extractParams($uri, $delimiter)
  793. {
  794. $params = [];
  795. if (strpos($uri, $delimiter) !== false) {
  796. preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
  797. foreach ($matches as $match) {
  798. $param = explode($delimiter, $match[1]);
  799. if (\count($param) === 2) {
  800. $plain_var = filter_var(rawurldecode($param[1]), FILTER_SANITIZE_STRING);
  801. $params[$param[0]] = $plain_var;
  802. $uri = str_replace($match[0], '', $uri);
  803. }
  804. }
  805. }
  806. return [$uri, $params];
  807. }
  808. /**
  809. * Converts links from absolute '/' or relative (../..) to a Grav friendly format
  810. *
  811. * @param PageInterface $page the current page to use as reference
  812. * @param string $markdown_url the URL as it was written in the markdown
  813. * @param string $type the type of URL, image | link
  814. * @param null $relative if null, will use system default, if true will use relative links internally
  815. *
  816. * @return string the more friendly formatted url
  817. */
  818. public static function convertUrlOld(PageInterface $page, $markdown_url, $type = 'link', $relative = null)
  819. {
  820. $grav = Grav::instance();
  821. $language = $grav['language'];
  822. // Link processing should prepend language
  823. $language_append = '';
  824. if ($type === 'link' && $language->enabled()) {
  825. $language_append = $language->getLanguageURLPrefix();
  826. }
  827. $pages_dir = $grav['locator']->findResource('page://');
  828. if ($relative === null) {
  829. $base = $grav['base_url'];
  830. } else {
  831. $base = $relative ? $grav['base_url_relative'] : $grav['base_url_absolute'];
  832. }
  833. $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
  834. // if absolute and starts with a base_url move on
  835. if (pathinfo($markdown_url, PATHINFO_DIRNAME) === '.' && $page->url() === '/') {
  836. return '/' . $markdown_url;
  837. }
  838. // no path to convert
  839. if ($base_url !== '' && Utils::startsWith($markdown_url, $base_url)) {
  840. return $markdown_url;
  841. }
  842. // if contains only a fragment
  843. if (Utils::startsWith($markdown_url, '#')) {
  844. return $markdown_url;
  845. }
  846. $target = null;
  847. // see if page is relative to this or absolute
  848. if (Utils::startsWith($markdown_url, '/')) {
  849. $normalized_url = Utils::normalizePath($base_url . $markdown_url);
  850. $normalized_path = Utils::normalizePath($pages_dir . $markdown_url);
  851. } else {
  852. $normalized_url = $base_url . Utils::normalizePath($page->route() . '/' . $markdown_url);
  853. $normalized_path = Utils::normalizePath($page->path() . '/' . $markdown_url);
  854. }
  855. // special check to see if path checking is required.
  856. $just_path = str_replace($normalized_url, '', $normalized_path);
  857. if ($just_path === $page->path()) {
  858. return $normalized_url;
  859. }
  860. $url_bits = parse_url($normalized_path);
  861. $full_path = $url_bits['path'];
  862. if (file_exists($full_path)) {
  863. // do nothing
  864. } elseif (file_exists(rawurldecode($full_path))) {
  865. $full_path = rawurldecode($full_path);
  866. } else {
  867. return $normalized_url;
  868. }
  869. $path_info = pathinfo($full_path);
  870. $page_path = $path_info['dirname'];
  871. $filename = '';
  872. if ($markdown_url === '..') {
  873. $page_path = $full_path;
  874. } else {
  875. // save the filename if a file is part of the path
  876. if (is_file($full_path)) {
  877. if ($path_info['extension'] !== 'md') {
  878. $filename = '/' . $path_info['basename'];
  879. }
  880. } else {
  881. $page_path = $full_path;
  882. }
  883. }
  884. // get page instances and try to find one that fits
  885. $instances = $grav['pages']->instances();
  886. if (isset($instances[$page_path])) {
  887. /** @var PageInterface $target */
  888. $target = $instances[$page_path];
  889. $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
  890. return static::buildUrl($url_bits);
  891. }
  892. return $normalized_url;
  893. }
  894. /**
  895. * Adds the nonce to a URL for a specific action
  896. *
  897. * @param string $url the url
  898. * @param string $action the action
  899. * @param string $nonceParamName the param name to use
  900. *
  901. * @return string the url with the nonce
  902. */
  903. public static function addNonce($url, $action, $nonceParamName = 'nonce')
  904. {
  905. $fake = $url && strpos($url, '/') === 0;
  906. if ($fake) {
  907. $url = 'http://domain.com' . $url;
  908. }
  909. $uri = new static($url);
  910. $parts = $uri->toArray();
  911. $nonce = Utils::getNonce($action);
  912. $parts['params'] = ($parts['params'] ?? []) + [$nonceParamName => $nonce];
  913. if ($fake) {
  914. unset($parts['scheme'], $parts['host']);
  915. }
  916. return static::buildUrl($parts);
  917. }
  918. /**
  919. * Is the passed in URL a valid URL?
  920. *
  921. * @param string $url
  922. * @return bool
  923. */
  924. public static function isValidUrl($url)
  925. {
  926. $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})*))?/';
  927. if (preg_match($regex, $url)) {
  928. return true;
  929. }
  930. return false;
  931. }
  932. /**
  933. * Removes extra double slashes and fixes back-slashes
  934. *
  935. * @param string $path
  936. * @return mixed|string
  937. */
  938. public static function cleanPath($path)
  939. {
  940. $regex = '/(\/)\/+/';
  941. $path = str_replace(['\\', '/ /'], '/', $path);
  942. $path = preg_replace($regex,'$1',$path);
  943. return $path;
  944. }
  945. /**
  946. * Filters the user info string.
  947. *
  948. * @param string $info The raw user or password.
  949. * @return string The percent-encoded user or password string.
  950. */
  951. public static function filterUserInfo($info)
  952. {
  953. return $info !== null ? UriPartsFilter::filterUserInfo($info) : '';
  954. }
  955. /**
  956. * Filter Uri path.
  957. *
  958. * This method percent-encodes all reserved
  959. * characters in the provided path string. This method
  960. * will NOT double-encode characters that are already
  961. * percent-encoded.
  962. *
  963. * @param string $path The raw uri path.
  964. * @return string The RFC 3986 percent-encoded uri path.
  965. * @link http://www.faqs.org/rfcs/rfc3986.html
  966. */
  967. public static function filterPath($path)
  968. {
  969. return $path !== null ? UriPartsFilter::filterPath($path) : '';
  970. }
  971. /**
  972. * Filters the query string or fragment of a URI.
  973. *
  974. * @param string $query The raw uri query string.
  975. * @return string The percent-encoded query string.
  976. */
  977. public static function filterQuery($query)
  978. {
  979. return $query !== null ? UriPartsFilter::filterQueryOrFragment($query) : '';
  980. }
  981. /**
  982. * @param array $env
  983. */
  984. protected function createFromEnvironment(array $env)
  985. {
  986. // Build scheme.
  987. if (isset($env['HTTP_X_FORWARDED_PROTO'])) {
  988. $this->scheme = $env['HTTP_X_FORWARDED_PROTO'];
  989. } elseif (isset($env['X-FORWARDED-PROTO'])) {
  990. $this->scheme = $env['X-FORWARDED-PROTO'];
  991. } elseif (isset($env['HTTP_CLOUDFRONT_FORWARDED_PROTO'])) {
  992. $this->scheme = $env['HTTP_CLOUDFRONT_FORWARDED_PROTO'];
  993. } elseif (isset($env['REQUEST_SCHEME']) && empty($env['HTTPS'])) {
  994. $this->scheme = $env['REQUEST_SCHEME'];
  995. } else {
  996. $https = $env['HTTPS'] ?? '';
  997. $this->scheme = (empty($https) || strtolower($https) === 'off') ? 'http' : 'https';
  998. }
  999. // Build user and password.
  1000. $this->user = $env['PHP_AUTH_USER'] ?? null;
  1001. $this->password = $env['PHP_AUTH_PW'] ?? null;
  1002. // Build host.
  1003. $hostname = 'localhost';
  1004. if (isset($env['HTTP_HOST'])) {
  1005. $hostname = $env['HTTP_HOST'];
  1006. } elseif (isset($env['SERVER_NAME'])) {
  1007. $hostname = $env['SERVER_NAME'];
  1008. }
  1009. // Remove port from HTTP_HOST generated $hostname
  1010. $hostname = Utils::substrToString($hostname, ':');
  1011. // Validate the hostname
  1012. $this->host = $this->validateHostname($hostname) ? $hostname : 'unknown';
  1013. // Build port.
  1014. if (isset($env['HTTP_X_FORWARDED_PORT'])) {
  1015. $this->port = (int)$env['HTTP_X_FORWARDED_PORT'];
  1016. } elseif (isset($env['X-FORWARDED-PORT'])) {
  1017. $this->port = (int)$env['X-FORWARDED-PORT'];
  1018. } elseif (isset($env['HTTP_CLOUDFRONT_FORWARDED_PROTO'])) {
  1019. // Since AWS Cloudfront does not provide a forwarded port header,
  1020. // we have to build the port using the scheme.
  1021. $this->port = $this->port();
  1022. } elseif (isset($env['SERVER_PORT'])) {
  1023. $this->port = (int)$env['SERVER_PORT'];
  1024. } else {
  1025. $this->port = null;
  1026. }
  1027. if ($this->hasStandardPort()) {
  1028. $this->port = null;
  1029. }
  1030. // Build path.
  1031. $request_uri = $env['REQUEST_URI'] ?? '';
  1032. $this->path = rawurldecode(parse_url('http://example.com' . $request_uri, PHP_URL_PATH));
  1033. // Build query string.
  1034. $this->query = $env['QUERY_STRING'] ?? '';
  1035. if ($this->query === '') {
  1036. $this->query = parse_url('http://example.com' . $request_uri, PHP_URL_QUERY);
  1037. }
  1038. // Support ngnix routes.
  1039. if (strpos($this->query, '_url=') === 0) {
  1040. parse_str($this->query, $query);
  1041. unset($query['_url']);
  1042. $this->query = http_build_query($query);
  1043. }
  1044. // Build fragment.
  1045. $this->fragment = null;
  1046. // Filter userinfo, path and query string.
  1047. $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null;
  1048. $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null;
  1049. $this->path = empty($this->path) ? '/' : static::filterPath($this->path);
  1050. $this->query = static::filterQuery($this->query);
  1051. $this->reset();
  1052. }
  1053. /**
  1054. * Does this Uri use a standard port?
  1055. *
  1056. * @return bool
  1057. */
  1058. protected function hasStandardPort()
  1059. {
  1060. return ($this->port === 80 || $this->port === 443);
  1061. }
  1062. /**
  1063. * @param string $url
  1064. */
  1065. protected function createFromString($url)
  1066. {
  1067. // Set Uri parts.
  1068. $parts = parse_url($url);
  1069. if ($parts === false) {
  1070. throw new \RuntimeException('Malformed URL: ' . $url);
  1071. }
  1072. $this->scheme = $parts['scheme'] ?? null;
  1073. $this->user = $parts['user'] ?? null;
  1074. $this->password = $parts['pass'] ?? null;
  1075. $this->host = $parts['host'] ?? null;
  1076. $this->port = isset($parts['port']) ? (int)$parts['port'] : null;
  1077. $this->path = $parts['path'] ?? '';
  1078. $this->query = $parts['query'] ?? '';
  1079. $this->fragment = $parts['fragment'] ?? null;
  1080. // Validate the hostname
  1081. if ($this->host) {
  1082. $this->host = $this->validateHostname($this->host) ? $this->host : 'unknown';
  1083. }
  1084. // Filter userinfo, path, query string and fragment.
  1085. $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null;
  1086. $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null;
  1087. $this->path = empty($this->path) ? '/' : static::filterPath($this->path);
  1088. $this->query = static::filterQuery($this->query);
  1089. $this->fragment = $this->fragment !== null ? static::filterQuery($this->fragment) : null;
  1090. $this->reset();
  1091. }
  1092. protected function reset()
  1093. {
  1094. // resets
  1095. parse_str($this->query, $this->queries);
  1096. $this->extension = null;
  1097. $this->basename = null;
  1098. $this->paths = [];
  1099. $this->params = [];
  1100. $this->env = $this->buildEnvironment();
  1101. $this->uri = $this->path . (!empty($this->query) ? '?' . $this->query : '');
  1102. $this->base = $this->buildBaseUrl();
  1103. $this->root_path = $this->buildRootPath();
  1104. $this->root = $this->base . $this->root_path;
  1105. $this->url = $this->base . $this->uri;
  1106. }
  1107. /**
  1108. * Get post from either $_POST or JSON response object
  1109. * By default returns all data, or can return a single item
  1110. *
  1111. * @param string $element
  1112. * @param string $filter_type
  1113. * @return array|mixed|null
  1114. */
  1115. public function post($element = null, $filter_type = null)
  1116. {
  1117. if (!$this->post) {
  1118. $content_type = $this->getContentType();
  1119. if ($content_type === 'application/json') {
  1120. $json = file_get_contents('php://input');
  1121. $this->post = json_decode($json, true);
  1122. } elseif (!empty($_POST)) {
  1123. $this->post = (array)$_POST;
  1124. }
  1125. $event = new Event(['post' => &$this->post]);
  1126. Grav::instance()->fireEvent('onHttpPostFilter', $event);
  1127. }
  1128. if ($this->post && null !== $element) {
  1129. $item = Utils::getDotNotation($this->post, $element);
  1130. if ($filter_type) {
  1131. $item = filter_var($item, $filter_type);
  1132. }
  1133. return $item;
  1134. }
  1135. return $this->post;
  1136. }
  1137. /**
  1138. * Get content type from request
  1139. *
  1140. * @param bool $short
  1141. * @return null|string
  1142. */
  1143. public function getContentType($short = true)
  1144. {
  1145. if (isset($_SERVER['CONTENT_TYPE'])) {
  1146. $content_type = $_SERVER['CONTENT_TYPE'];
  1147. if ($short) {
  1148. return Utils::substrToString($content_type,';');
  1149. }
  1150. return $content_type;
  1151. }
  1152. return null;
  1153. }
  1154. /**
  1155. * Check if this is a valid Grav extension
  1156. *
  1157. * @param $extension
  1158. * @return bool
  1159. */
  1160. public function isValidExtension($extension)
  1161. {
  1162. $valid_page_types = implode('|', Utils::getSupportPageTypes());
  1163. // Strip the file extension for valid page types
  1164. if (preg_match('/(' . $valid_page_types . ')/', $extension)) {
  1165. return true;
  1166. }
  1167. return false;
  1168. }
  1169. /**
  1170. * Allow overriding of any element (be careful!)
  1171. *
  1172. * @param $data
  1173. * @return Uri
  1174. */
  1175. public function setUriProperties($data)
  1176. {
  1177. foreach (get_object_vars($this) as $property => $default) {
  1178. if (!array_key_exists($property, $data)) continue;
  1179. $this->{$property} = $data[$property]; // assign value to object
  1180. }
  1181. return $this;
  1182. }
  1183. /**
  1184. * Get the base URI with port if needed
  1185. *
  1186. * @return string
  1187. */
  1188. private function buildBaseUrl()
  1189. {
  1190. return $this->scheme() . $this->host;
  1191. }
  1192. /**
  1193. * Get the Grav Root Path
  1194. *
  1195. * @return string
  1196. */
  1197. private function buildRootPath()
  1198. {
  1199. // In Windows script path uses backslash, convert it:
  1200. $scriptPath = str_replace('\\', '/', $_SERVER['PHP_SELF']);
  1201. $rootPath = str_replace(' ', '%20', rtrim(substr($scriptPath, 0, strpos($scriptPath, 'index.php')), '/'));
  1202. return $rootPath;
  1203. }
  1204. private function buildEnvironment()
  1205. {
  1206. // check for localhost variations
  1207. if ($this->host === '127.0.0.1' || $this->host === '::1') {
  1208. return 'localhost';
  1209. }
  1210. return $this->host ?: 'unknown';
  1211. }
  1212. /**
  1213. * Process any params based in this URL, supports any valid delimiter
  1214. *
  1215. * @param string $uri
  1216. * @param string $delimiter
  1217. *
  1218. * @return string
  1219. */
  1220. private function processParams($uri, $delimiter = ':')
  1221. {
  1222. if (strpos($uri, $delimiter) !== false) {
  1223. preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
  1224. foreach ($matches as $match) {
  1225. $param = explode($delimiter, $match[1]);
  1226. if (count($param) === 2) {
  1227. $plain_var = filter_var($param[1], FILTER_SANITIZE_STRING);
  1228. $this->params[$param[0]] = $plain_var;
  1229. $uri = str_replace($match[0], '', $uri);
  1230. }
  1231. }
  1232. }
  1233. return $uri;
  1234. }
  1235. }