Uri.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 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 && $config->get('system.reverse_proxy_setup') === false) {
  145. $this->base .= ':' . $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 && $config->get('system.reverse_proxy_setup') === false) {
  160. $this->base .= ':' . $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 (and make sure that the path isn't seen as domain)
  183. $bits = parse_url('http://domain.com' . $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 = Utils::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 $id
  295. * @param string|false|null $default
  296. * @return string|false|null
  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 or is 0, figure it out from scheme.
  403. if (!$raw && !$port) {
  404. if ($this->scheme === 'http') {
  405. $this->port = 80;
  406. } elseif ($this->scheme === 'https') {
  407. $this->port = 443;
  408. }
  409. }
  410. return $this->port ?: null;
  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 string
  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. * You should set the third parameter to `true` for redirects as long as you came from the same sub-site and language.
  510. *
  511. * @param string|null $default
  512. * @param string|null $attributes
  513. * @param bool $withoutBaseRoute
  514. * @return string
  515. */
  516. public function referrer($default = null, $attributes = null, bool $withoutBaseRoute = false)
  517. {
  518. $referrer = $_SERVER['HTTP_REFERER'] ?? null;
  519. // Check that referrer came from our site.
  520. if ($withoutBaseRoute) {
  521. /** @var Pages $pages */
  522. $pages = Grav::instance()['pages'];
  523. $base = $pages->baseUrl(null, true);
  524. } else {
  525. $base = $this->rootUrl(true);
  526. }
  527. // Referrer should always have host set and it should come from the same base address.
  528. if (!is_string($referrer) || !str_starts_with($referrer, $base)) {
  529. $referrer = $default ?: $this->route(true, true);
  530. }
  531. // Relative path from grav root.
  532. $referrer = substr($referrer, strlen($base));
  533. if ($attributes) {
  534. $referrer .= $attributes;
  535. }
  536. return $referrer;
  537. }
  538. /**
  539. * @return string
  540. */
  541. #[\ReturnTypeWillChange]
  542. public function __toString()
  543. {
  544. return static::buildUrl($this->toArray());
  545. }
  546. /**
  547. * @return string
  548. */
  549. public function toOriginalString()
  550. {
  551. return static::buildUrl($this->toArray(true));
  552. }
  553. /**
  554. * @param bool $full
  555. * @return array
  556. */
  557. public function toArray($full = false)
  558. {
  559. if ($full === true) {
  560. $root_path = $this->root_path ?? '';
  561. $extension = isset($this->extension) && $this->isValidExtension($this->extension) ? '.' . $this->extension : '';
  562. $path = $root_path . $this->path . $extension;
  563. } else {
  564. $path = $this->path;
  565. }
  566. return [
  567. 'scheme' => $this->scheme,
  568. 'host' => $this->host,
  569. 'port' => $this->port ?: null,
  570. 'user' => $this->user,
  571. 'pass' => $this->password,
  572. 'path' => $path,
  573. 'params' => $this->params,
  574. 'query' => $this->query,
  575. 'fragment' => $this->fragment
  576. ];
  577. }
  578. /**
  579. * Calculate the parameter regex based on the param_sep setting
  580. *
  581. * @return string
  582. */
  583. public static function paramsRegex()
  584. {
  585. return '/\/{1,}([^\:\#\/\?]*' . Grav::instance()['config']->get('system.param_sep') . '[^\:\#\/\?]*)/';
  586. }
  587. /**
  588. * Return the IP address of the current user
  589. *
  590. * @return string ip address
  591. */
  592. public static function ip()
  593. {
  594. $ip = 'UNKNOWN';
  595. if (getenv('HTTP_CLIENT_IP')) {
  596. $ip = getenv('HTTP_CLIENT_IP');
  597. } elseif (getenv('HTTP_CF_CONNECTING_IP')) {
  598. $ip = getenv('HTTP_CF_CONNECTING_IP');
  599. } elseif (getenv('HTTP_X_FORWARDED_FOR') && Grav::instance()['config']->get('system.http_x_forwarded.ip')) {
  600. $ips = array_map('trim', explode(',', getenv('HTTP_X_FORWARDED_FOR')));
  601. $ip = array_shift($ips);
  602. } elseif (getenv('HTTP_X_FORWARDED') && Grav::instance()['config']->get('system.http_x_forwarded.ip')) {
  603. $ip = getenv('HTTP_X_FORWARDED');
  604. } elseif (getenv('HTTP_FORWARDED_FOR')) {
  605. $ip = getenv('HTTP_FORWARDED_FOR');
  606. } elseif (getenv('HTTP_FORWARDED')) {
  607. $ip = getenv('HTTP_FORWARDED');
  608. } elseif (getenv('REMOTE_ADDR')) {
  609. $ip = getenv('REMOTE_ADDR');
  610. }
  611. return $ip;
  612. }
  613. /**
  614. * Returns current Uri.
  615. *
  616. * @return \Grav\Framework\Uri\Uri
  617. */
  618. public static function getCurrentUri()
  619. {
  620. if (!static::$currentUri) {
  621. static::$currentUri = UriFactory::createFromEnvironment($_SERVER);
  622. }
  623. return static::$currentUri;
  624. }
  625. /**
  626. * Returns current route.
  627. *
  628. * @return Route
  629. */
  630. public static function getCurrentRoute()
  631. {
  632. if (!static::$currentRoute) {
  633. /** @var Uri $uri */
  634. $uri = Grav::instance()['uri'];
  635. static::$currentRoute = RouteFactory::createFromLegacyUri($uri);
  636. }
  637. return static::$currentRoute;
  638. }
  639. /**
  640. * Is this an external URL? if it starts with `http` then yes, else false
  641. *
  642. * @param string $url the URL in question
  643. * @return bool is eternal state
  644. */
  645. public static function isExternal($url)
  646. {
  647. return (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://') || 0 === strpos($url, '//'));
  648. }
  649. /**
  650. * The opposite of built-in PHP method parse_url()
  651. *
  652. * @param array $parsed_url
  653. * @return string
  654. */
  655. public static function buildUrl($parsed_url)
  656. {
  657. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . ':' : '';
  658. $authority = isset($parsed_url['host']) ? '//' : '';
  659. $host = $parsed_url['host'] ?? '';
  660. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  661. $user = $parsed_url['user'] ?? '';
  662. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  663. $pass = ($user || $pass) ? "{$pass}@" : '';
  664. $path = $parsed_url['path'] ?? '';
  665. $path = !empty($parsed_url['params']) ? rtrim($path, '/') . static::buildParams($parsed_url['params']) : $path;
  666. $query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  667. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  668. return "{$scheme}{$authority}{$user}{$pass}{$host}{$port}{$path}{$query}{$fragment}";
  669. }
  670. /**
  671. * @param array $params
  672. * @return string
  673. */
  674. public static function buildParams(array $params)
  675. {
  676. if (!$params) {
  677. return '';
  678. }
  679. $grav = Grav::instance();
  680. $sep = $grav['config']->get('system.param_sep');
  681. $output = [];
  682. foreach ($params as $key => $value) {
  683. $output[] = "{$key}{$sep}{$value}";
  684. }
  685. return '/' . implode('/', $output);
  686. }
  687. /**
  688. * Converts links from absolute '/' or relative (../..) to a Grav friendly format
  689. *
  690. * @param PageInterface $page the current page to use as reference
  691. * @param string|array $url the URL as it was written in the markdown
  692. * @param string $type the type of URL, image | link
  693. * @param bool $absolute if null, will use system default, if true will use absolute links internally
  694. * @param bool $route_only only return the route, not full URL path
  695. * @return string|array the more friendly formatted url
  696. */
  697. public static function convertUrl(PageInterface $page, $url, $type = 'link', $absolute = false, $route_only = false)
  698. {
  699. $grav = Grav::instance();
  700. $uri = $grav['uri'];
  701. // Link processing should prepend language
  702. $language = $grav['language'];
  703. $language_append = '';
  704. if ($type === 'link' && $language->enabled()) {
  705. $language_append = $language->getLanguageURLPrefix();
  706. }
  707. // Handle Excerpt style $url array
  708. $url_path = is_array($url) ? $url['path'] : $url;
  709. $external = false;
  710. $base = $grav['base_url_relative'];
  711. $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
  712. $pages_dir = $grav['locator']->findResource('page://');
  713. // if absolute and starts with a base_url move on
  714. if (isset($url['scheme']) && Utils::startsWith($url['scheme'], 'http')) {
  715. $external = true;
  716. } elseif ($url_path === '' && isset($url['fragment'])) {
  717. $external = true;
  718. } elseif ($url_path === '/' || ($base_url !== '' && Utils::startsWith($url_path, $base_url))) {
  719. $url_path = $base_url . $url_path;
  720. } else {
  721. // see if page is relative to this or absolute
  722. if (Utils::startsWith($url_path, '/')) {
  723. $normalized_url = Utils::normalizePath($base_url . $url_path);
  724. $normalized_path = Utils::normalizePath($pages_dir . $url_path);
  725. } else {
  726. $page_route = ($page->home() && !empty($url_path)) ? $page->rawRoute() : $page->route();
  727. $normalized_url = $base_url . Utils::normalizePath(rtrim($page_route, '/') . '/' . $url_path);
  728. $normalized_path = Utils::normalizePath($page->path() . '/' . $url_path);
  729. }
  730. // special check to see if path checking is required.
  731. $just_path = Utils::replaceFirstOccurrence($normalized_url, '', $normalized_path);
  732. if ($normalized_url === '/' || $just_path === $page->path()) {
  733. $url_path = $normalized_url;
  734. } else {
  735. $url_bits = static::parseUrl($normalized_path);
  736. $full_path = $url_bits['path'];
  737. $raw_full_path = rawurldecode($full_path);
  738. if (file_exists($raw_full_path)) {
  739. $full_path = $raw_full_path;
  740. } elseif (!file_exists($full_path)) {
  741. $full_path = false;
  742. }
  743. if ($full_path) {
  744. $path_info = Utils::pathinfo($full_path);
  745. $page_path = $path_info['dirname'];
  746. $filename = '';
  747. if ($url_path === '..') {
  748. $page_path = $full_path;
  749. } else {
  750. // save the filename if a file is part of the path
  751. if (is_file($full_path)) {
  752. if ($path_info['extension'] !== 'md') {
  753. $filename = '/' . $path_info['basename'];
  754. }
  755. } else {
  756. $page_path = $full_path;
  757. }
  758. }
  759. // get page instances and try to find one that fits
  760. $instances = $grav['pages']->instances();
  761. if (isset($instances[$page_path])) {
  762. /** @var PageInterface $target */
  763. $target = $instances[$page_path];
  764. $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
  765. $url_path = Uri::buildUrl($url_bits);
  766. } else {
  767. $url_path = $normalized_url;
  768. }
  769. } else {
  770. $url_path = $normalized_url;
  771. }
  772. }
  773. }
  774. // handle absolute URLs
  775. if (is_array($url) && !$external && ($absolute === true || $grav['config']->get('system.absolute_urls', false))) {
  776. $url['scheme'] = $uri->scheme(true);
  777. $url['host'] = $uri->host();
  778. $url['port'] = $uri->port(true);
  779. // check if page exists for this route, and if so, check if it has SSL enabled
  780. $pages = $grav['pages'];
  781. $routes = $pages->routes();
  782. // if this is an image, get the proper path
  783. $url_bits = Utils::pathinfo($url_path);
  784. if (isset($url_bits['extension'])) {
  785. $target_path = $url_bits['dirname'];
  786. } else {
  787. $target_path = $url_path;
  788. }
  789. // strip base from this path
  790. $target_path = Utils::replaceFirstOccurrence($uri->rootUrl(), '', $target_path);
  791. // set to / if root
  792. if (empty($target_path)) {
  793. $target_path = '/';
  794. }
  795. // look to see if this page exists and has ssl enabled
  796. if (isset($routes[$target_path])) {
  797. $target_page = $pages->get($routes[$target_path]);
  798. if ($target_page) {
  799. $ssl_enabled = $target_page->ssl();
  800. if ($ssl_enabled !== null) {
  801. if ($ssl_enabled) {
  802. $url['scheme'] = 'https';
  803. } else {
  804. $url['scheme'] = 'http';
  805. }
  806. }
  807. }
  808. }
  809. }
  810. // Handle route only
  811. if ($route_only) {
  812. $url_path = Utils::replaceFirstOccurrence(static::filterPath($base_url), '', $url_path);
  813. }
  814. // transform back to string/array as needed
  815. if (is_array($url)) {
  816. $url['path'] = $url_path;
  817. } else {
  818. $url = $url_path;
  819. }
  820. return $url;
  821. }
  822. /**
  823. * @param string $url
  824. * @return array|false
  825. */
  826. public static function parseUrl($url)
  827. {
  828. $grav = Grav::instance();
  829. // Remove extra slash from streams, parse_url() doesn't like it.
  830. if ($pos = strpos($url, ':///')) {
  831. $url = substr_replace($url, '://', $pos, 4);
  832. }
  833. $encodedUrl = preg_replace_callback(
  834. '%[^:/@?&=#]+%usD',
  835. static function ($matches) {
  836. return rawurlencode($matches[0]);
  837. },
  838. $url
  839. );
  840. $parts = parse_url($encodedUrl);
  841. if (false === $parts) {
  842. return false;
  843. }
  844. foreach ($parts as $name => $value) {
  845. $parts[$name] = rawurldecode($value);
  846. }
  847. if (!isset($parts['path'])) {
  848. $parts['path'] = '';
  849. }
  850. [$stripped_path, $params] = static::extractParams($parts['path'], $grav['config']->get('system.param_sep'));
  851. if (!empty($params)) {
  852. $parts['path'] = $stripped_path;
  853. $parts['params'] = $params;
  854. }
  855. return $parts;
  856. }
  857. /**
  858. * @param string $uri
  859. * @param string $delimiter
  860. * @return array
  861. */
  862. public static function extractParams($uri, $delimiter)
  863. {
  864. $params = [];
  865. if (strpos($uri, $delimiter) !== false) {
  866. preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
  867. foreach ($matches as $match) {
  868. $param = explode($delimiter, $match[1]);
  869. if (count($param) === 2) {
  870. $plain_var = htmlspecialchars(strip_tags(rawurldecode($param[1])), ENT_QUOTES, 'UTF-8');
  871. $params[$param[0]] = $plain_var;
  872. $uri = str_replace($match[0], '', $uri);
  873. }
  874. }
  875. }
  876. return [$uri, $params];
  877. }
  878. /**
  879. * Converts links from absolute '/' or relative (../..) to a Grav friendly format
  880. *
  881. * @param PageInterface $page the current page to use as reference
  882. * @param string $markdown_url the URL as it was written in the markdown
  883. * @param string $type the type of URL, image | link
  884. * @param bool|null $relative if null, will use system default, if true will use relative links internally
  885. *
  886. * @return string the more friendly formatted url
  887. */
  888. public static function convertUrlOld(PageInterface $page, $markdown_url, $type = 'link', $relative = null)
  889. {
  890. $grav = Grav::instance();
  891. $language = $grav['language'];
  892. // Link processing should prepend language
  893. $language_append = '';
  894. if ($type === 'link' && $language->enabled()) {
  895. $language_append = $language->getLanguageURLPrefix();
  896. }
  897. $pages_dir = $grav['locator']->findResource('page://');
  898. if ($relative === null) {
  899. $base = $grav['base_url'];
  900. } else {
  901. $base = $relative ? $grav['base_url_relative'] : $grav['base_url_absolute'];
  902. }
  903. $base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
  904. // if absolute and starts with a base_url move on
  905. if (Utils::pathinfo($markdown_url, PATHINFO_DIRNAME) === '.' && $page->url() === '/') {
  906. return '/' . $markdown_url;
  907. }
  908. // no path to convert
  909. if ($base_url !== '' && Utils::startsWith($markdown_url, $base_url)) {
  910. return $markdown_url;
  911. }
  912. // if contains only a fragment
  913. if (Utils::startsWith($markdown_url, '#')) {
  914. return $markdown_url;
  915. }
  916. $target = null;
  917. // see if page is relative to this or absolute
  918. if (Utils::startsWith($markdown_url, '/')) {
  919. $normalized_url = Utils::normalizePath($base_url . $markdown_url);
  920. $normalized_path = Utils::normalizePath($pages_dir . $markdown_url);
  921. } else {
  922. $normalized_url = $base_url . Utils::normalizePath($page->route() . '/' . $markdown_url);
  923. $normalized_path = Utils::normalizePath($page->path() . '/' . $markdown_url);
  924. }
  925. // special check to see if path checking is required.
  926. $just_path = Utils::replaceFirstOccurrence($normalized_url, '', $normalized_path);
  927. if ($just_path === $page->path()) {
  928. return $normalized_url;
  929. }
  930. $url_bits = parse_url($normalized_path);
  931. $full_path = $url_bits['path'];
  932. if (file_exists($full_path)) {
  933. // do nothing
  934. } elseif (file_exists(rawurldecode($full_path))) {
  935. $full_path = rawurldecode($full_path);
  936. } else {
  937. return $normalized_url;
  938. }
  939. $path_info = Utils::pathinfo($full_path);
  940. $page_path = $path_info['dirname'];
  941. $filename = '';
  942. if ($markdown_url === '..') {
  943. $page_path = $full_path;
  944. } else {
  945. // save the filename if a file is part of the path
  946. if (is_file($full_path)) {
  947. if ($path_info['extension'] !== 'md') {
  948. $filename = '/' . $path_info['basename'];
  949. }
  950. } else {
  951. $page_path = $full_path;
  952. }
  953. }
  954. // get page instances and try to find one that fits
  955. $instances = $grav['pages']->instances();
  956. if (isset($instances[$page_path])) {
  957. /** @var PageInterface $target */
  958. $target = $instances[$page_path];
  959. $url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
  960. return static::buildUrl($url_bits);
  961. }
  962. return $normalized_url;
  963. }
  964. /**
  965. * Adds the nonce to a URL for a specific action
  966. *
  967. * @param string $url the url
  968. * @param string $action the action
  969. * @param string $nonceParamName the param name to use
  970. *
  971. * @return string the url with the nonce
  972. */
  973. public static function addNonce($url, $action, $nonceParamName = 'nonce')
  974. {
  975. $fake = $url && strpos($url, '/') === 0;
  976. if ($fake) {
  977. $url = 'http://domain.com' . $url;
  978. }
  979. $uri = new static($url);
  980. $parts = $uri->toArray();
  981. $nonce = Utils::getNonce($action);
  982. $parts['params'] = ($parts['params'] ?? []) + [$nonceParamName => $nonce];
  983. if ($fake) {
  984. unset($parts['scheme'], $parts['host']);
  985. }
  986. return static::buildUrl($parts);
  987. }
  988. /**
  989. * Is the passed in URL a valid URL?
  990. *
  991. * @param string $url
  992. * @return bool
  993. */
  994. public static function isValidUrl($url)
  995. {
  996. $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})*))?/';
  997. return (bool)preg_match($regex, $url);
  998. }
  999. /**
  1000. * Removes extra double slashes and fixes back-slashes
  1001. *
  1002. * @param string $path
  1003. * @return string
  1004. */
  1005. public static function cleanPath($path)
  1006. {
  1007. $regex = '/(\/)\/+/';
  1008. $path = str_replace(['\\', '/ /'], '/', $path);
  1009. $path = preg_replace($regex, '$1', $path);
  1010. return $path;
  1011. }
  1012. /**
  1013. * Filters the user info string.
  1014. *
  1015. * @param string|null $info The raw user or password.
  1016. * @return string The percent-encoded user or password string.
  1017. */
  1018. public static function filterUserInfo($info)
  1019. {
  1020. return $info !== null ? UriPartsFilter::filterUserInfo($info) : '';
  1021. }
  1022. /**
  1023. * Filter Uri path.
  1024. *
  1025. * This method percent-encodes all reserved
  1026. * characters in the provided path string. This method
  1027. * will NOT double-encode characters that are already
  1028. * percent-encoded.
  1029. *
  1030. * @param string|null $path The raw uri path.
  1031. * @return string The RFC 3986 percent-encoded uri path.
  1032. * @link http://www.faqs.org/rfcs/rfc3986.html
  1033. */
  1034. public static function filterPath($path)
  1035. {
  1036. return $path !== null ? UriPartsFilter::filterPath($path) : '';
  1037. }
  1038. /**
  1039. * Filters the query string or fragment of a URI.
  1040. *
  1041. * @param string|null $query The raw uri query string.
  1042. * @return string The percent-encoded query string.
  1043. */
  1044. public static function filterQuery($query)
  1045. {
  1046. return $query !== null ? UriPartsFilter::filterQueryOrFragment($query) : '';
  1047. }
  1048. /**
  1049. * @param array $env
  1050. * @return void
  1051. */
  1052. protected function createFromEnvironment(array $env)
  1053. {
  1054. // Build scheme.
  1055. if (isset($env['HTTP_X_FORWARDED_PROTO']) && Grav::instance()['config']->get('system.http_x_forwarded.protocol')) {
  1056. $this->scheme = $env['HTTP_X_FORWARDED_PROTO'];
  1057. } elseif (isset($env['X-FORWARDED-PROTO'])) {
  1058. $this->scheme = $env['X-FORWARDED-PROTO'];
  1059. } elseif (isset($env['HTTP_CLOUDFRONT_FORWARDED_PROTO'])) {
  1060. $this->scheme = $env['HTTP_CLOUDFRONT_FORWARDED_PROTO'];
  1061. } elseif (isset($env['REQUEST_SCHEME']) && empty($env['HTTPS'])) {
  1062. $this->scheme = $env['REQUEST_SCHEME'];
  1063. } else {
  1064. $https = $env['HTTPS'] ?? '';
  1065. $this->scheme = (empty($https) || strtolower($https) === 'off') ? 'http' : 'https';
  1066. }
  1067. // Build user and password.
  1068. $this->user = $env['PHP_AUTH_USER'] ?? null;
  1069. $this->password = $env['PHP_AUTH_PW'] ?? null;
  1070. // Build host.
  1071. if (isset($env['HTTP_X_FORWARDED_HOST']) && Grav::instance()['config']->get('system.http_x_forwarded.host')) {
  1072. $hostname = $env['HTTP_X_FORWARDED_HOST'];
  1073. } else if (isset($env['HTTP_HOST'])) {
  1074. $hostname = $env['HTTP_HOST'];
  1075. } elseif (isset($env['SERVER_NAME'])) {
  1076. $hostname = $env['SERVER_NAME'];
  1077. } else {
  1078. $hostname = 'localhost';
  1079. }
  1080. // Remove port from HTTP_HOST generated $hostname
  1081. $hostname = Utils::substrToString($hostname, ':');
  1082. // Validate the hostname
  1083. $this->host = $this->validateHostname($hostname) ? $hostname : 'unknown';
  1084. // Build port.
  1085. if (isset($env['HTTP_X_FORWARDED_PORT']) && Grav::instance()['config']->get('system.http_x_forwarded.port')) {
  1086. $this->port = (int)$env['HTTP_X_FORWARDED_PORT'];
  1087. } elseif (isset($env['X-FORWARDED-PORT'])) {
  1088. $this->port = (int)$env['X-FORWARDED-PORT'];
  1089. } elseif (isset($env['HTTP_CLOUDFRONT_FORWARDED_PROTO'])) {
  1090. // Since AWS Cloudfront does not provide a forwarded port header,
  1091. // we have to build the port using the scheme.
  1092. $this->port = $this->port();
  1093. } elseif (isset($env['SERVER_PORT'])) {
  1094. $this->port = (int)$env['SERVER_PORT'];
  1095. } else {
  1096. $this->port = null;
  1097. }
  1098. if ($this->port === 0 || $this->hasStandardPort()) {
  1099. $this->port = null;
  1100. }
  1101. // Build path.
  1102. $request_uri = $env['REQUEST_URI'] ?? '';
  1103. $this->path = rawurldecode(parse_url('http://example.com' . $request_uri, PHP_URL_PATH));
  1104. // Build query string.
  1105. $this->query = $env['QUERY_STRING'] ?? '';
  1106. if ($this->query === '') {
  1107. $this->query = parse_url('http://example.com' . $request_uri, PHP_URL_QUERY) ?? '';
  1108. }
  1109. // Support ngnix routes.
  1110. if (strpos($this->query, '_url=') === 0) {
  1111. parse_str($this->query, $query);
  1112. unset($query['_url']);
  1113. $this->query = http_build_query($query);
  1114. }
  1115. // Build fragment.
  1116. $this->fragment = null;
  1117. // Filter userinfo, path and query string.
  1118. $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null;
  1119. $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null;
  1120. $this->path = empty($this->path) ? '/' : static::filterPath($this->path);
  1121. $this->query = static::filterQuery($this->query);
  1122. $this->reset();
  1123. }
  1124. /**
  1125. * Does this Uri use a standard port?
  1126. *
  1127. * @return bool
  1128. */
  1129. protected function hasStandardPort()
  1130. {
  1131. return (!$this->port || $this->port === 80 || $this->port === 443);
  1132. }
  1133. /**
  1134. * @param string $url
  1135. */
  1136. protected function createFromString($url)
  1137. {
  1138. // Set Uri parts.
  1139. $parts = parse_url($url);
  1140. if ($parts === false) {
  1141. throw new RuntimeException('Malformed URL: ' . $url);
  1142. }
  1143. $port = (int)($parts['port'] ?? 0);
  1144. $this->scheme = $parts['scheme'] ?? null;
  1145. $this->user = $parts['user'] ?? null;
  1146. $this->password = $parts['pass'] ?? null;
  1147. $this->host = $parts['host'] ?? null;
  1148. $this->port = $port ?: null;
  1149. $this->path = $parts['path'] ?? '';
  1150. $this->query = $parts['query'] ?? '';
  1151. $this->fragment = $parts['fragment'] ?? null;
  1152. // Validate the hostname
  1153. if ($this->host) {
  1154. $this->host = $this->validateHostname($this->host) ? $this->host : 'unknown';
  1155. }
  1156. // Filter userinfo, path, query string and fragment.
  1157. $this->user = $this->user !== null ? static::filterUserInfo($this->user) : null;
  1158. $this->password = $this->password !== null ? static::filterUserInfo($this->password) : null;
  1159. $this->path = empty($this->path) ? '/' : static::filterPath($this->path);
  1160. $this->query = static::filterQuery($this->query);
  1161. $this->fragment = $this->fragment !== null ? static::filterQuery($this->fragment) : null;
  1162. $this->reset();
  1163. }
  1164. /**
  1165. * @return void
  1166. */
  1167. protected function reset()
  1168. {
  1169. // resets
  1170. parse_str($this->query, $this->queries);
  1171. $this->extension = null;
  1172. $this->basename = null;
  1173. $this->paths = [];
  1174. $this->params = [];
  1175. $this->env = $this->buildEnvironment();
  1176. $this->uri = $this->path . (!empty($this->query) ? '?' . $this->query : '');
  1177. $this->base = $this->buildBaseUrl();
  1178. $this->root_path = $this->buildRootPath();
  1179. $this->root = $this->base . $this->root_path;
  1180. $this->url = $this->base . $this->uri;
  1181. }
  1182. /**
  1183. * Get post from either $_POST or JSON response object
  1184. * By default returns all data, or can return a single item
  1185. *
  1186. * @param string|null $element
  1187. * @param string|null $filter_type
  1188. * @return array|null
  1189. */
  1190. public function post($element = null, $filter_type = null)
  1191. {
  1192. if (!$this->post) {
  1193. $content_type = $this->getContentType();
  1194. if ($content_type === 'application/json') {
  1195. $json = file_get_contents('php://input');
  1196. $this->post = json_decode($json, true);
  1197. } elseif (!empty($_POST)) {
  1198. $this->post = (array)$_POST;
  1199. }
  1200. $event = new Event(['post' => &$this->post]);
  1201. Grav::instance()->fireEvent('onHttpPostFilter', $event);
  1202. }
  1203. if ($this->post && null !== $element) {
  1204. $item = Utils::getDotNotation($this->post, $element);
  1205. if ($filter_type) {
  1206. if ($filter_type === FILTER_SANITIZE_STRING || $filter_type === GRAV_SANITIZE_STRING) {
  1207. $item = htmlspecialchars(strip_tags($item), ENT_QUOTES, 'UTF-8');
  1208. } else {
  1209. $item = filter_var($item, $filter_type);
  1210. }
  1211. }
  1212. return $item;
  1213. }
  1214. return $this->post;
  1215. }
  1216. /**
  1217. * Get content type from request
  1218. *
  1219. * @param bool $short
  1220. * @return null|string
  1221. */
  1222. public function getContentType($short = true)
  1223. {
  1224. if (isset($_SERVER['CONTENT_TYPE'])) {
  1225. $content_type = $_SERVER['CONTENT_TYPE'];
  1226. if ($short) {
  1227. return Utils::substrToString($content_type, ';');
  1228. }
  1229. return $content_type;
  1230. }
  1231. return null;
  1232. }
  1233. /**
  1234. * Check if this is a valid Grav extension
  1235. *
  1236. * @param string|null $extension
  1237. * @return bool
  1238. */
  1239. public function isValidExtension($extension): bool
  1240. {
  1241. $extension = (string)$extension;
  1242. return $extension !== '' && in_array($extension, Utils::getSupportPageTypes(), true);
  1243. }
  1244. /**
  1245. * Allow overriding of any element (be careful!)
  1246. *
  1247. * @param array $data
  1248. * @return Uri
  1249. */
  1250. public function setUriProperties($data)
  1251. {
  1252. foreach (get_object_vars($this) as $property => $default) {
  1253. if (!array_key_exists($property, $data)) {
  1254. continue;
  1255. }
  1256. $this->{$property} = $data[$property]; // assign value to object
  1257. }
  1258. return $this;
  1259. }
  1260. /**
  1261. * Compatibility in case getallheaders() is not available on platform
  1262. */
  1263. public static function getAllHeaders()
  1264. {
  1265. if (!function_exists('getallheaders')) {
  1266. $headers = [];
  1267. foreach ($_SERVER as $name => $value) {
  1268. if (substr($name, 0, 5) == 'HTTP_') {
  1269. $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  1270. }
  1271. }
  1272. return $headers;
  1273. }
  1274. return getallheaders();
  1275. }
  1276. /**
  1277. * Get the base URI with port if needed
  1278. *
  1279. * @return string
  1280. */
  1281. private function buildBaseUrl()
  1282. {
  1283. return $this->scheme() . $this->host;
  1284. }
  1285. /**
  1286. * Get the Grav Root Path
  1287. *
  1288. * @return string
  1289. */
  1290. private function buildRootPath()
  1291. {
  1292. // In Windows script path uses backslash, convert it:
  1293. $scriptPath = str_replace('\\', '/', $_SERVER['PHP_SELF']);
  1294. $rootPath = str_replace(' ', '%20', rtrim(substr($scriptPath, 0, strpos($scriptPath, 'index.php')), '/'));
  1295. return $rootPath;
  1296. }
  1297. /**
  1298. * @return string
  1299. */
  1300. private function buildEnvironment()
  1301. {
  1302. // check for localhost variations
  1303. if ($this->host === '127.0.0.1' || $this->host === '::1') {
  1304. return 'localhost';
  1305. }
  1306. return $this->host ?: 'unknown';
  1307. }
  1308. /**
  1309. * Process any params based in this URL, supports any valid delimiter
  1310. *
  1311. * @param string $uri
  1312. * @param string $delimiter
  1313. * @return string
  1314. */
  1315. private function processParams(string $uri, string $delimiter = ':'): string
  1316. {
  1317. if (strpos($uri, $delimiter) !== false) {
  1318. preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
  1319. foreach ($matches as $match) {
  1320. $param = explode($delimiter, $match[1]);
  1321. if (count($param) === 2) {
  1322. $plain_var = htmlspecialchars(strip_tags($param[1]), ENT_QUOTES, 'UTF-8');
  1323. $this->params[$param[0]] = $plain_var;
  1324. $uri = str_replace($match[0], '', $uri);
  1325. }
  1326. }
  1327. }
  1328. return $uri;
  1329. }
  1330. }