Uri.php 45 KB

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