-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Uri.php
1475 lines (1279 loc) · 43.9 KB
/
Uri.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @package Grav\Common
*
* @copyright Copyright (C) 2015 - 2020 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use Grav\Common\Config\Config;
use Grav\Common\Language\Language;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Framework\Route\RouteFactory;
use Grav\Framework\Uri\UriFactory;
use Grav\Framework\Uri\UriPartsFilter;
use RocketTheme\Toolbox\Event\Event;
class Uri
{
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])$/';
/** @var \Grav\Framework\Uri\Uri|null */
protected static $currentUri;
/** @var \Grav\Framework\Route\Route|null */
protected static $currentRoute;
/** @var string */
public $url;
// Uri parts.
/** @var string|null */
protected $scheme;
/** @var string|null */
protected $user;
/** @var string|null */
protected $password;
/** @var string|null */
protected $host;
/** @var int|null */
protected $port;
/** @var string */
protected $path;
/** @var string */
protected $query;
/** @var string|null */
protected $fragment;
// Internal stuff.
/** @var string */
protected $base;
/** @var string|null */
protected $basename;
/** @var string */
protected $content_path;
/** @var string|null */
protected $extension;
/** @var string */
protected $env;
/** @var array */
protected $paths;
/** @var array */
protected $queries;
/** @var array */
protected $params;
/** @var string */
protected $root;
/** @var string */
protected $setup_base;
/** @var string */
protected $root_path;
/** @var string */
protected $uri;
/** @var array */
protected $post;
/**
* Uri constructor.
* @param string|array $env
*/
public function __construct($env = null)
{
if (is_string($env)) {
$this->createFromString($env);
} else {
$this->createFromEnvironment(\is_array($env) ? $env : $_SERVER);
}
}
/**
* Initialize the URI class with a url passed via parameter.
* Used for testing purposes.
*
* @param string $url the URL to use in the class
*
* @return $this
*/
public function initializeWithUrl($url = '')
{
if ($url) {
$this->createFromString($url);
}
return $this;
}
/**
* Initialize the URI class by providing url and root_path arguments
*
* @param string $url
* @param string $root_path
*
* @return $this
*/
public function initializeWithUrlAndRootPath($url, $root_path)
{
$this->initializeWithUrl($url);
$this->root_path = $root_path;
return $this;
}
/**
* Validate a hostname
*
* @param string $hostname The hostname
*
* @return boolean
*/
public function validateHostname($hostname)
{
return (bool)preg_match(static::HOSTNAME_REGEX, $hostname);
}
/**
* Initializes the URI object based on the url set on the object
*/
public function init()
{
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
/** @var Language $language */
$language = $grav['language'];
// add the port to the base for non-standard ports
if ($this->port !== null && $config->get('system.reverse_proxy_setup') === false) {
$this->base .= ':' . (string)$this->port;
}
// Handle custom base
$custom_base = rtrim($grav['config']->get('system.custom_base_url'), '/');
if ($custom_base) {
$custom_parts = parse_url($custom_base);
if ($custom_parts === false) {
throw new \RuntimeException('Bad configuration: system.custom_base_url');
}
$orig_root_path = $this->root_path;
$this->root_path = isset($custom_parts['path']) ? rtrim($custom_parts['path'], '/') : '';
if (isset($custom_parts['scheme'])) {
$this->base = $custom_parts['scheme'] . '://' . $custom_parts['host'];
$this->root = $custom_base;
} else {
$this->root = $this->base . $this->root_path;
}
$this->uri = Utils::replaceFirstOccurrence($orig_root_path, $this->root_path, $this->uri);
} else {
$this->root = $this->base . $this->root_path;
}
$this->url = $this->base . $this->uri;
$uri = Utils::replaceFirstOccurrence(static::filterPath($this->root), '', $this->url);
// remove the setup.php based base if set:
$setup_base = $grav['pages']->base();
if ($setup_base) {
$uri = preg_replace('|^' . preg_quote($setup_base, '|') . '|', '', $uri);
}
$this->setup_base = $setup_base;
// process params
$uri = $this->processParams($uri, $config->get('system.param_sep'));
// set active language
$uri = $language->setActiveFromUri($uri);
// split the URL and params
$bits = parse_url($uri);
//process fragment
if (isset($bits['fragment'])) {
$this->fragment = $bits['fragment'];
}
// Get the path. If there's no path, make sure pathinfo() still returns dirname variable
$path = $bits['path'] ?? '/';
// remove the extension if there is one set
$parts = pathinfo($path);
// set the original basename
$this->basename = $parts['basename'];
// set the extension
if (isset($parts['extension'])) {
$this->extension = $parts['extension'];
}
// Strip the file extension for valid page types
if ($this->isValidExtension($this->extension)) {
$path = Utils::replaceLastOccurrence(".{$this->extension}", '', $path);
}
// set the new url
$this->url = $this->root . $path;
$this->path = static::cleanPath($path);
$this->content_path = trim(Utils::replaceFirstOccurrence($this->base, '', $this->path), '/');
if ($this->content_path !== '') {
$this->paths = explode('/', $this->content_path);
}
// Set some Grav stuff
$grav['base_url_absolute'] = $config->get('system.custom_base_url') ?: $this->rootUrl(true);
$grav['base_url_relative'] = $this->rootUrl(false);
$grav['base_url'] = $config->get('system.absolute_urls') ? $grav['base_url_absolute'] : $grav['base_url_relative'];
RouteFactory::setRoot($this->root_path . $setup_base);
RouteFactory::setLanguage($language->getLanguageURLPrefix());
RouteFactory::setParamValueDelimiter($config->get('system.param_sep'));
}
/**
* Return URI path.
*
* @param int $id
*
* @return string|string[]
*/
public function paths($id = null)
{
if ($id !== null) {
return $this->paths[$id];
}
return $this->paths;
}
/**
* Return route to the current URI. By default route doesn't include base path.
*
* @param bool $absolute True to include full path.
* @param bool $domain True to include domain. Works only if first parameter is also true.
*
* @return string
*/
public function route($absolute = false, $domain = false)
{
return ($absolute ? $this->rootUrl($domain) : '') . '/' . implode('/', $this->paths);
}
/**
* Return full query string or a single query attribute.
*
* @param string $id Optional attribute. Get a single query attribute if set
* @param bool $raw If true and $id is not set, return the full query array. Otherwise return the query string
*
* @return string|array Returns an array if $id = null and $raw = true
*/
public function query($id = null, $raw = false)
{
if ($id !== null) {
return $this->queries[$id] ?? null;
}
if ($raw) {
return $this->queries;
}
if (!$this->queries) {
return '';
}
return http_build_query($this->queries);
}
/**
* Return all or a single query parameter as a URI compatible string.
*
* @param string $id Optional parameter name.
* @param boolean $array return the array format or not
*
* @return null|string|array
*/
public function params($id = null, $array = false)
{
$config = Grav::instance()['config'];
$sep = $config->get('system.param_sep');
$params = null;
if ($id === null) {
if ($array) {
return $this->params;
}
$output = [];
foreach ($this->params as $key => $value) {
$output[] = "{$key}{$sep}{$value}";
$params = '/' . implode('/', $output);
}
} elseif (isset($this->params[$id])) {
if ($array) {
return $this->params[$id];
}
$params = "/{$id}{$sep}{$this->params[$id]}";
}
return $params;
}
/**
* Get URI parameter.
*
* @param string $id
* @param string|bool|null $default
*
* @return bool|string
*/
public function param($id, $default = false)
{
if (isset($this->params[$id])) {
return html_entity_decode(rawurldecode($this->params[$id]), ENT_COMPAT | ENT_HTML401, 'UTF-8');
}
return $default;
}
/**
* Gets the Fragment portion of a URI (eg #target)
*
* @param string $fragment
*
* @return string|null
*/
public function fragment($fragment = null)
{
if ($fragment !== null) {
$this->fragment = $fragment;
}
return $this->fragment;
}
/**
* Return URL.
*
* @param bool $include_host Include hostname.
*
* @return string
*/
public function url($include_host = false)
{
if ($include_host) {
return $this->url;
}
$url = Utils::replaceFirstOccurrence($this->base, '', rtrim($this->url, '/'));
return $url ?: '/';
}
/**
* Return the Path
*
* @return string The path of the URI
*/
public function path()
{
return $this->path;
}
/**
* Return the Extension of the URI
*
* @param string|null $default
*
* @return string The extension of the URI
*/
public function extension($default = null)
{
if (!$this->extension) {
$this->extension = $default;
}
return $this->extension;
}
public function method()
{
$method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';
if ($method === 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
}
return $method;
}
/**
* Return the scheme of the URI
*
* @param bool $raw
* @return string The scheme of the URI
*/
public function scheme($raw = false)
{
if (!$raw) {
$scheme = '';
if ($this->scheme) {
$scheme = $this->scheme . '://';
} elseif ($this->host) {
$scheme = '//';
}
return $scheme;
}
return $this->scheme;
}
/**
* Return the host of the URI
*
* @return string|null The host of the URI
*/
public function host()
{
return $this->host;
}
/**
* Return the port number if it can be figured out
*
* @param bool $raw
* @return int|null
*/
public function port($raw = false)
{
$port = $this->port;
// If not in raw mode and port is not set, figure it out from scheme.
if (!$raw && $port === null) {
if ($this->scheme === 'http') {
$this->port = 80;
} elseif ($this->scheme === 'https') {
$this->port = 443;
}
}
return $this->port;
}
/**
* Return user
*
* @return string|null
*/
public function user()
{
return $this->user;
}
/**
* Return password
*
* @return string|null
*/
public function password()
{
return $this->password;
}
/**
* Gets the environment name
*
* @return String
*/
public function environment()
{
return $this->env;
}
/**
* Return the basename of the URI
*
* @return String The basename of the URI
*/
public function basename()
{
return $this->basename;
}
/**
* Return the full uri
*
* @param bool $include_root
* @return mixed
*/
public function uri($include_root = true)
{
if ($include_root) {
return $this->uri;
}
return Utils::replaceFirstOccurrence($this->root_path, '', $this->uri);
}
/**
* Return the base of the URI
*
* @return String The base of the URI
*/
public function base()
{
return $this->base;
}
/**
* Return the base relative URL including the language prefix
* or the base relative url if multi-language is not enabled
*
* @return String The base of the URI
*/
public function baseIncludingLanguage()
{
$grav = Grav::instance();
/** @var Pages $pages */
$pages = $grav['pages'];
return $pages->baseUrl(null, false);
}
/**
* Return root URL to the site.
*
* @param bool $include_host Include hostname.
*
* @return mixed
*/
public function rootUrl($include_host = false)
{
if ($include_host) {
return $this->root;
}
return Utils::replaceFirstOccurrence($this->base, '', $this->root);
}
/**
* Return current page number.
*
* @return int
*/
public function currentPage()
{
$page = (int)($this->params['page'] ?? 1);
return max(1, $page);
}
/**
* Return relative path to the referrer defaulting to current or given page.
*
* @param string $default
* @param string $attributes
*
* @return string
*/
public function referrer($default = null, $attributes = null)
{
$referrer = $_SERVER['HTTP_REFERER'] ?? null;
// Check that referrer came from our site.
$root = $this->rootUrl(true);
if ($referrer) {
// Referrer should always have host set and it should come from the same base address.
if (stripos($referrer, $root) !== 0) {
$referrer = null;
}
}
if (!$referrer) {
$referrer = $default ?: $this->route(true, true);
}
if ($attributes) {
$referrer .= $attributes;
}
// Return relative path.
return substr($referrer, strlen($root));
}
public function __toString()
{
return static::buildUrl($this->toArray());
}
public function toOriginalString()
{
return static::buildUrl($this->toArray(true));
}
public function toArray($full = false)
{
if ($full === true) {
$root_path = $this->root_path ?? '';
$extension = isset($this->extension) && $this->isValidExtension($this->extension) ? '.' . $this->extension : '';
$path = $root_path . $this->path . $extension;
} else {
$path = $this->path;
}
return [
'scheme' => $this->scheme,
'host' => $this->host,
'port' => $this->port,
'user' => $this->user,
'pass' => $this->password,
'path' => $path,
'params' => $this->params,
'query' => $this->query,
'fragment' => $this->fragment
];
}
/**
* Calculate the parameter regex based on the param_sep setting
*
* @return string
*/
public static function paramsRegex()
{
return '/\/([^\:\#\/\?]*' . Grav::instance()['config']->get('system.param_sep') . '[^\:\#\/\?]*)/';
}
/**
* Return the IP address of the current user
*
* @return string ip address
*/
public static function ip()
{
if (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR') && Grav::instance()['config']->get('system.http_x_forwarded.ip')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_X_FORWARDED') && Grav::instance()['config']->get('system.http_x_forwarded.ip')) {
$ip = getenv('HTTP_X_FORWARDED');
} elseif (getenv('HTTP_FORWARDED_FOR')) {
$ip = getenv('HTTP_FORWARDED_FOR');
} elseif (getenv('HTTP_FORWARDED')) {
$ip = getenv('HTTP_FORWARDED');
} elseif (getenv('REMOTE_ADDR')) {
$ip = getenv('REMOTE_ADDR');
} else {
$ip = 'UNKNOWN';
}
return $ip;
}
/**
* Returns current Uri.
*
* @return \Grav\Framework\Uri\Uri
*/
public static function getCurrentUri()
{
if (!static::$currentUri) {
static::$currentUri = UriFactory::createFromEnvironment($_SERVER);
}
return static::$currentUri;
}
/**
* Returns current route.
*
* @return \Grav\Framework\Route\Route
*/
public static function getCurrentRoute()
{
if (!static::$currentRoute) {
/** @var Uri $uri */
$uri = Grav::instance()['uri'];
static::$currentRoute = RouteFactory::createFromLegacyUri($uri);
}
return static::$currentRoute;
}
/**
* Is this an external URL? if it starts with `http` then yes, else false
*
* @param string $url the URL in question
*
* @return boolean is eternal state
*/
public static function isExternal($url)
{
return (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://') || 0 === strpos($url, '//'));
}
/**
* The opposite of built-in PHP method parse_url()
*
* @param array $parsed_url
*
* @return string
*/
public static function buildUrl($parsed_url)
{
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . ':' : '';
$authority = isset($parsed_url['host']) ? '//' : '';
$host = $parsed_url['host'] ?? '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = $parsed_url['user'] ?? '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "{$pass}@" : '';
$path = $parsed_url['path'] ?? '';
$path = !empty($parsed_url['params']) ? rtrim($path, '/') . static::buildParams($parsed_url['params']) : $path;
$query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "{$scheme}{$authority}{$user}{$pass}{$host}{$port}{$path}{$query}{$fragment}";
}
/**
* @param array $params
* @return string
*/
public static function buildParams(array $params)
{
if (!$params) {
return '';
}
$grav = Grav::instance();
$sep = $grav['config']->get('system.param_sep');
$output = [];
foreach ($params as $key => $value) {
$output[] = "{$key}{$sep}{$value}";
}
return '/' . implode('/', $output);
}
/**
* Converts links from absolute '/' or relative (../..) to a Grav friendly format
*
* @param PageInterface $page the current page to use as reference
* @param string|array $url the URL as it was written in the markdown
* @param string $type the type of URL, image | link
* @param bool $absolute if null, will use system default, if true will use absolute links internally
* @param bool $route_only only return the route, not full URL path
* @return string|array the more friendly formatted url
*/
public static function convertUrl(PageInterface $page, $url, $type = 'link', $absolute = false, $route_only = false)
{
$grav = Grav::instance();
$uri = $grav['uri'];
// Link processing should prepend language
$language = $grav['language'];
$language_append = '';
if ($type === 'link' && $language->enabled()) {
$language_append = $language->getLanguageURLPrefix();
}
// Handle Excerpt style $url array
$url_path = is_array($url) ? $url['path'] : $url;
$external = false;
$base = $grav['base_url_relative'];
$base_url = rtrim($base . $grav['pages']->base(), '/') . $language_append;
$pages_dir = $grav['locator']->findResource('page://');
// if absolute and starts with a base_url move on
if (isset($url['scheme']) && Utils::startsWith($url['scheme'], 'http')) {
$external = true;
} elseif ($url_path === '' && isset($url['fragment'])) {
$external = true;
} elseif ($url_path === '/' || ($base_url !== '' && Utils::startsWith($url_path, $base_url))) {
$url_path = $base_url . $url_path;
} else {
// see if page is relative to this or absolute
if (Utils::startsWith($url_path, '/')) {
$normalized_url = Utils::normalizePath($base_url . $url_path);
$normalized_path = Utils::normalizePath($pages_dir . $url_path);
} else {
$page_route = ($page->home() && !empty($url_path)) ? $page->rawRoute() : $page->route();
$normalized_url = $base_url . Utils::normalizePath(rtrim($page_route, '/') . '/' . $url_path);
$normalized_path = Utils::normalizePath($page->path() . '/' . $url_path);
}
// special check to see if path checking is required.
$just_path = Utils::replaceFirstOccurrence($normalized_url, '', $normalized_path);
if ($normalized_url === '/' || $just_path === $page->path()) {
$url_path = $normalized_url;
} else {
$url_bits = static::parseUrl($normalized_path);
$full_path = $url_bits['path'];
$raw_full_path = rawurldecode($full_path);
if (file_exists($raw_full_path)) {
$full_path = $raw_full_path;
} elseif (!file_exists($full_path)) {
$full_path = false;
}
if ($full_path) {
$path_info = pathinfo($full_path);
$page_path = $path_info['dirname'];
$filename = '';
if ($url_path === '..') {
$page_path = $full_path;
} else {
// save the filename if a file is part of the path
if (is_file($full_path)) {
if ($path_info['extension'] !== 'md') {
$filename = '/' . $path_info['basename'];
}
} else {
$page_path = $full_path;
}
}
// get page instances and try to find one that fits
$instances = $grav['pages']->instances();
if (isset($instances[$page_path])) {
/** @var PageInterface $target */
$target = $instances[$page_path];
$url_bits['path'] = $base_url . rtrim($target->route(), '/') . $filename;
$url_path = Uri::buildUrl($url_bits);
} else {
$url_path = $normalized_url;
}
} else {
$url_path = $normalized_url;
}
}
}
// handle absolute URLs
if (\is_array($url) && !$external && ($absolute === true || $grav['config']->get('system.absolute_urls', false))) {
$url['scheme'] = $uri->scheme(true);
$url['host'] = $uri->host();
$url['port'] = $uri->port(true);
// check if page exists for this route, and if so, check if it has SSL enabled
$pages = $grav['pages'];
$routes = $pages->routes();
// if this is an image, get the proper path
$url_bits = pathinfo($url_path);
if (isset($url_bits['extension'])) {
$target_path = $url_bits['dirname'];
} else {
$target_path = $url_path;
}
// strip base from this path
$target_path = Utils::replaceFirstOccurrence($uri->rootUrl(), '', $target_path);
// set to / if root
if (empty($target_path)) {
$target_path = '/';
}
// look to see if this page exists and has ssl enabled
if (isset($routes[$target_path])) {
$target_page = $pages->get($routes[$target_path]);
if ($target_page) {
$ssl_enabled = $target_page->ssl();
if ($ssl_enabled !== null) {
if ($ssl_enabled) {
$url['scheme'] = 'https';
} else {
$url['scheme'] = 'http';
}
}
}
}
}
// Handle route only
if ($route_only) {
$url_path = Utils::replaceFirstOccurrence(static::filterPath($base_url), '', $url_path);
}
// transform back to string/array as needed
if (is_array($url)) {
$url['path'] = $url_path;
} else {
$url = $url_path;
}
return $url;
}
public static function parseUrl($url)
{
$grav = Grav::instance();
// Remove extra slash from streams, parse_url() doesn't like it.
if ($pos = strpos($url, ':///')) {
$url = substr_replace($url, '://', $pos, 4);
}
$encodedUrl = preg_replace_callback(
'%[^:/@?&=#]+%usD',
static function ($matches) {
return rawurlencode($matches[0]);
},
$url
);
$parts = parse_url($encodedUrl);
if (false === $parts) {
return false;
}
foreach ($parts as $name => $value) {
$parts[$name] = rawurldecode($value);
}
if (!isset($parts['path'])) {
$parts['path'] = '';
}
[$stripped_path, $params] = static::extractParams($parts['path'], $grav['config']->get('system.param_sep'));
if (!empty($params)) {
$parts['path'] = $stripped_path;
$parts['params'] = $params;
}
return $parts;
}
public static function extractParams($uri, $delimiter)
{
$params = [];
if (strpos($uri, $delimiter) !== false) {
preg_match_all(static::paramsRegex(), $uri, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$param = explode($delimiter, $match[1]);
if (\count($param) === 2) {
$plain_var = filter_var(rawurldecode($param[1]), FILTER_SANITIZE_STRING);
$params[$param[0]] = $plain_var;
$uri = str_replace($match[0], '', $uri);
}
}
}
return [$uri, $params];
}
/**
* Converts links from absolute '/' or relative (../..) to a Grav friendly format
*
* @param PageInterface $page the current page to use as reference
* @param string $markdown_url the URL as it was written in the markdown
* @param string $type the type of URL, image | link
* @param bool|null $relative if null, will use system default, if true will use relative links internally
*
* @return string the more friendly formatted url
*/
public static function convertUrlOld(PageInterface $page, $markdown_url, $type = 'link', $relative = null)
{
$grav = Grav::instance();
$language = $grav['language'];
// Link processing should prepend language