Uri.php 43 KB

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