-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Pages.php
2258 lines (1930 loc) · 69.8 KB
/
Pages.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\Page
*
* @copyright Copyright (c) 2015 - 2024 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page;
use Exception;
use FilesystemIterator;
use Grav\Common\Cache;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Blueprints;
use Grav\Common\Debugger;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Flex\Types\Pages\PageCollection;
use Grav\Common\Flex\Types\Pages\PageIndex;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Taxonomy;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Events\TypesEvent;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Interfaces\FlexTranslateInterface;
use Grav\Framework\Flex\Pages\FlexPageObject;
use Grav\Plugin\Admin;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use SplFileInfo;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Whoops\Exception\ErrorException;
use Collator;
use function array_key_exists;
use function array_search;
use function count;
use function dirname;
use function extension_loaded;
use function in_array;
use function is_array;
use function is_int;
use function is_string;
/**
* Class Pages
* @package Grav\Common\Page
*/
class Pages
{
/** @var FlexDirectory|null */
private $directory;
/** @var Grav */
protected $grav;
/** @var array<PageInterface> */
protected $instances = [];
/** @var array<PageInterface|string> */
protected $index = [];
/** @var array */
protected $children;
/** @var string */
protected $base = '';
/** @var string[] */
protected $baseRoute = [];
/** @var string[] */
protected $routes = [];
/** @var array */
protected $sort;
/** @var Blueprints */
protected $blueprints;
/** @var bool */
protected $enable_pages = true;
/** @var int */
protected $last_modified;
/** @var string[] */
protected $ignore_files;
/** @var string[] */
protected $ignore_folders;
/** @var bool */
protected $ignore_hidden;
/** @var string */
protected $check_method;
/** @var string */
protected $simple_pages_hash;
/** @var string */
protected $pages_cache_id;
/** @var bool */
protected $initialized = false;
/** @var string */
protected $active_lang;
/** @var bool */
protected $fire_events = false;
/** @var Types|null */
protected static $types;
/** @var string|null */
protected static $home_route;
/**
* Constructor
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
$this->grav = $grav;
}
/**
* @return FlexDirectory|null
*/
public function getDirectory(): ?FlexDirectory
{
return $this->directory;
}
/**
* Method used in admin to disable frontend pages from being initialized.
*/
public function disablePages(): void
{
$this->enable_pages = false;
}
/**
* Method used in admin to later load frontend pages.
*/
public function enablePages(): void
{
if (!$this->enable_pages) {
$this->enable_pages = true;
$this->init();
}
}
/**
* Get or set base path for the pages.
*
* @param string|null $path
* @return string
*/
public function base($path = null)
{
if ($path !== null) {
$path = trim($path, '/');
$this->base = $path ? '/' . $path : '';
$this->baseRoute = [];
}
return $this->base;
}
/**
*
* Get base route for Grav pages.
*
* @param string|null $lang Optional language code for multilingual routes.
* @return string
*/
public function baseRoute($lang = null)
{
$key = $lang ?: $this->active_lang ?: 'default';
if (!isset($this->baseRoute[$key])) {
/** @var Language $language */
$language = $this->grav['language'];
$path_base = rtrim($this->base(), '/');
$path_lang = $language->enabled() ? $language->getLanguageURLPrefix($lang) : '';
$this->baseRoute[$key] = $path_base . $path_lang;
}
return $this->baseRoute[$key];
}
/**
*
* Get route for Grav site.
*
* @param string $route Optional route to the page.
* @param string|null $lang Optional language code for multilingual links.
* @return string
*/
public function route($route = '/', $lang = null)
{
if (!$route || $route === '/') {
return $this->baseRoute($lang) ?: '/';
}
return $this->baseRoute($lang) . $route;
}
/**
* Get relative referrer route and language code. Returns null if the route isn't within the current base, language (if set) and route.
*
* @example `$langCode = null; $referrer = $pages->referrerRoute($langCode, '/admin');` returns relative referrer url within /admin and updates $langCode
* @example `$langCode = 'en'; $referrer = $pages->referrerRoute($langCode, '/admin');` returns relative referrer url within the /en/admin
*
* @param string|null $langCode Variable to store the language code. If already set, check only against that language.
* @param string $route Optional route within the site.
* @return string|null
* @since 1.7.23
*/
public function referrerRoute(?string &$langCode, string $route = '/'): ?string
{
$referrer = $_SERVER['HTTP_REFERER'] ?? null;
// Start by checking that referrer came from our site.
$root = $this->grav['base_url_absolute'];
if (!is_string($referrer) || !str_starts_with($referrer, $root)) {
return null;
}
/** @var Language $language */
$language = $this->grav['language'];
// Get all language codes and append no language.
if (null === $langCode) {
$languages = $language->enabled() ? $language->getLanguages() : [];
$languages[] = '';
} else {
$languages[] = $langCode;
}
$path_base = rtrim($this->base(), '/');
$path_route = rtrim($route, '/');
// Try to figure out the language code.
foreach ($languages as $code) {
$path_lang = $code ? "/{$code}" : '';
$base = $path_base . $path_lang . $path_route;
if ($referrer === $base || str_starts_with($referrer, "{$base}/")) {
if (null === $langCode) {
$langCode = $code;
}
return substr($referrer, \strlen($base));
}
}
return null;
}
/**
*
* Get base URL for Grav pages.
*
* @param string|null $lang Optional language code for multilingual links.
* @param bool|null $absolute If true, return absolute url, if false, return relative url. Otherwise return default.
* @return string
*/
public function baseUrl($lang = null, $absolute = null)
{
if ($absolute === null) {
$type = 'base_url';
} elseif ($absolute) {
$type = 'base_url_absolute';
} else {
$type = 'base_url_relative';
}
return $this->grav[$type] . $this->baseRoute($lang);
}
/**
*
* Get home URL for Grav site.
*
* @param string|null $lang Optional language code for multilingual links.
* @param bool|null $absolute If true, return absolute url, if false, return relative url. Otherwise return default.
* @return string
*/
public function homeUrl($lang = null, $absolute = null)
{
return $this->baseUrl($lang, $absolute) ?: '/';
}
/**
*
* Get URL for Grav site.
*
* @param string $route Optional route to the page.
* @param string|null $lang Optional language code for multilingual links.
* @param bool|null $absolute If true, return absolute url, if false, return relative url. Otherwise return default.
* @return string
*/
public function url($route = '/', $lang = null, $absolute = null)
{
if (!$route || $route === '/') {
return $this->homeUrl($lang, $absolute);
}
return $this->baseUrl($lang, $absolute) . Uri::filterPath($route);
}
/**
* @param string $method
* @return void
*/
public function setCheckMethod($method): void
{
$this->check_method = strtolower($method);
}
/**
* @return void
*/
public function register(): void
{
$config = $this->grav['config'];
$type = $config->get('system.pages.type');
if ($type === 'flex') {
$this->initFlexPages();
}
}
/**
* Reset pages (used in search indexing etc).
*
* @return void
*/
public function reset(): void
{
$this->initialized = false;
$this->init();
}
/**
* Class initialization. Must be called before using this class.
*/
public function init(): void
{
if ($this->initialized) {
return;
}
$config = $this->grav['config'];
$this->ignore_files = (array)$config->get('system.pages.ignore_files');
$this->ignore_folders = (array)$config->get('system.pages.ignore_folders');
$this->ignore_hidden = (bool)$config->get('system.pages.ignore_hidden');
$this->fire_events = (bool)$config->get('system.pages.events.page');
$this->instances = [];
$this->index = [];
$this->children = [];
$this->routes = [];
if (!$this->check_method) {
$this->setCheckMethod($config->get('system.cache.check.method', 'file'));
}
if ($this->enable_pages === false) {
$page = $this->buildRootPage();
$this->instances[$page->path()] = $page;
return;
}
$this->buildPages();
$this->initialized = true;
}
/**
* Get or set last modification time.
*
* @param int|null $modified
* @return int|null
*/
public function lastModified($modified = null)
{
if ($modified && $modified > $this->last_modified) {
$this->last_modified = $modified;
}
return $this->last_modified;
}
/**
* Returns a list of all pages.
*
* @return PageInterface[]
*/
public function instances()
{
$instances = [];
foreach ($this->index as $path => $instance) {
$page = $this->get($path);
if ($page) {
$instances[$path] = $page;
}
}
return $instances;
}
/**
* Returns a list of all routes.
*
* @return array
*/
public function routes()
{
return $this->routes;
}
/**
* Adds a page and assigns a route to it.
*
* @param PageInterface $page Page to be added.
* @param string|null $route Optional route (uses route from the object if not set).
*/
public function addPage(PageInterface $page, $route = null): void
{
$path = $page->path() ?? '';
if (!isset($this->index[$path])) {
$this->index[$path] = $page;
$this->instances[$path] = $page;
}
$route = $page->route($route);
$parent = $page->parent();
if ($parent) {
$this->children[$parent->path() ?? ''][$path] = ['slug' => $page->slug()];
}
$this->routes[$route] = $path;
$this->grav->fireEvent('onPageProcessed', new Event(['page' => $page]));
}
/**
* Get a collection of pages in the given context.
*
* @param array $params
* @param array $context
* @return PageCollectionInterface|Collection
*/
public function getCollection(array $params = [], array $context = [])
{
if (!isset($params['items'])) {
return new Collection();
}
/** @var Config $config */
$config = $this->grav['config'];
$context += [
'event' => true,
'pagination' => true,
'url_taxonomy_filters' => $config->get('system.pages.url_taxonomy_filters'),
'taxonomies' => (array)$config->get('site.taxonomies'),
'pagination_page' => 1,
'self' => null,
];
// Include taxonomies from the URL if requested.
$process_taxonomy = $params['url_taxonomy_filters'] ?? $context['url_taxonomy_filters'];
if ($process_taxonomy) {
/** @var Uri $uri */
$uri = $this->grav['uri'];
foreach ($context['taxonomies'] as $taxonomy) {
$param = $uri->param(rawurlencode($taxonomy));
$items = is_string($param) ? explode(',', $param) : [];
foreach ($items as $item) {
$params['taxonomies'][$taxonomy][] = htmlspecialchars_decode(rawurldecode($item), ENT_QUOTES);
}
}
}
$pagination = $params['pagination'] ?? $context['pagination'];
if ($pagination && !isset($params['page'], $params['start'])) {
/** @var Uri $uri */
$uri = $this->grav['uri'];
$context['current_page'] = $uri->currentPage();
}
$collection = $this->evaluate($params['items'], $context['self']);
$collection->setParams($params);
// Filter by taxonomies.
foreach ($params['taxonomies'] ?? [] as $taxonomy => $items) {
foreach ($collection as $page) {
// Don't include modules
if ($page->isModule()) {
continue;
}
$test = $page->taxonomy()[$taxonomy] ?? [];
foreach ($items as $item) {
if (!$test || !in_array($item, $test, true)) {
$collection->remove($page->path());
}
}
}
}
$filters = $params['filter'] ?? [];
// Assume published=true if not set.
if (!isset($filters['published']) && !isset($filters['non-published'])) {
$filters['published'] = true;
}
// Remove any inclusive sets from filter.
$sets = ['published', 'visible', 'modular', 'routable'];
foreach ($sets as $type) {
$nonType = "non-{$type}";
if (isset($filters[$type], $filters[$nonType]) && $filters[$type] === $filters[$nonType]) {
if (!$filters[$type]) {
// Both options are false, return empty collection as nothing can match the filters.
return new Collection();
}
// Both options are true, remove opposite filters as all pages will match the filters.
unset($filters[$type], $filters[$nonType]);
}
}
// Filter the collection
foreach ($filters as $type => $filter) {
if (null === $filter) {
continue;
}
// Convert non-type to type.
if (str_starts_with($type, 'non-')) {
$type = substr($type, 4);
$filter = !$filter;
}
switch ($type) {
case 'translated':
if ($filter) {
$collection = $collection->translated();
} else {
$collection = $collection->nonTranslated();
}
break;
case 'published':
if ($filter) {
$collection = $collection->published();
} else {
$collection = $collection->nonPublished();
}
break;
case 'visible':
if ($filter) {
$collection = $collection->visible();
} else {
$collection = $collection->nonVisible();
}
break;
case 'page':
if ($filter) {
$collection = $collection->pages();
} else {
$collection = $collection->modules();
}
break;
case 'module':
case 'modular':
if ($filter) {
$collection = $collection->modules();
} else {
$collection = $collection->pages();
}
break;
case 'routable':
if ($filter) {
$collection = $collection->routable();
} else {
$collection = $collection->nonRoutable();
}
break;
case 'type':
$collection = $collection->ofType($filter);
break;
case 'types':
$collection = $collection->ofOneOfTheseTypes($filter);
break;
case 'access':
$collection = $collection->ofOneOfTheseAccessLevels($filter);
break;
}
}
if (isset($params['dateRange'])) {
$start = $params['dateRange']['start'] ?? null;
$end = $params['dateRange']['end'] ?? null;
$field = $params['dateRange']['field'] ?? null;
$collection = $collection->dateRange($start, $end, $field);
}
if (isset($params['order'])) {
$by = $params['order']['by'] ?? 'default';
$dir = $params['order']['dir'] ?? 'asc';
$custom = $params['order']['custom'] ?? null;
$sort_flags = $params['order']['sort_flags'] ?? null;
if (is_array($sort_flags)) {
$sort_flags = array_map('constant', $sort_flags); //transform strings to constant value
$sort_flags = array_reduce($sort_flags, static function ($a, $b) {
return $a | $b;
}, 0); //merge constant values using bit or
}
$collection = $collection->order($by, $dir, $custom, $sort_flags);
}
// New Custom event to handle things like pagination.
if ($context['event']) {
$this->grav->fireEvent('onCollectionProcessed', new Event(['collection' => $collection, 'context' => $context]));
}
if ($context['pagination']) {
// Slice and dice the collection if pagination is required
$params = $collection->params();
$limit = (int)($params['limit'] ?? 0);
$page = (int)($params['page'] ?? $context['current_page'] ?? 0);
$start = (int)($params['start'] ?? 0);
$start = $limit > 0 && $page > 0 ? ($page - 1) * $limit : max(0, $start);
if ($start || ($limit && $collection->count() > $limit)) {
$collection->slice($start, $limit ?: null);
}
}
return $collection;
}
/**
* @param array|string $value
* @param PageInterface|null $self
* @return Collection
*/
protected function evaluate($value, PageInterface $self = null)
{
// Parse command.
if (is_string($value)) {
// Format: @command.param
$cmd = $value;
$params = [];
} elseif (is_array($value) && count($value) === 1 && !is_int(key($value))) {
// Format: @command.param: { attr1: value1, attr2: value2 }
$cmd = (string)key($value);
$params = (array)current($value);
} else {
$result = [];
foreach ((array)$value as $key => $val) {
if (is_int($key)) {
$result = $result + $this->evaluate($val, $self)->toArray();
} else {
$result = $result + $this->evaluate([$key => $val], $self)->toArray();
}
}
return new Collection($result);
}
$parts = explode('.', $cmd);
$scope = array_shift($parts);
$type = $parts[0] ?? null;
/** @var PageInterface|null $page */
$page = null;
switch ($scope) {
case 'self@':
case '@self':
$page = $self;
break;
case 'page@':
case '@page':
$page = isset($params[0]) ? $this->find($params[0]) : null;
break;
case 'root@':
case '@root':
$page = $this->root();
break;
case 'taxonomy@':
case '@taxonomy':
// Gets a collection of pages by using one of the following formats:
// @taxonomy.category: blog
// @taxonomy.category: [ blog, featured ]
// @taxonomy: { category: [ blog, featured ], level: 1 }
/** @var Taxonomy $taxonomy_map */
$taxonomy_map = Grav::instance()['taxonomy'];
if (!empty($parts)) {
$params = [implode('.', $parts) => $params];
}
return $taxonomy_map->findTaxonomy($params);
}
if (!$page) {
return new Collection();
}
// Handle '@page', '@page.modular: false', '@self' and '@self.modular: false'.
if (null === $type || (in_array($type, ['modular', 'modules']) && ($params[0] ?? null) === false)) {
$type = 'children';
}
switch ($type) {
case 'all':
$collection = $page->children();
break;
case 'modules':
case 'modular':
$collection = $page->children()->modules();
break;
case 'pages':
case 'children':
$collection = $page->children()->pages();
break;
case 'page':
case 'self':
$collection = !$page->root() ? (new Collection())->addPage($page) : new Collection();
break;
case 'parent':
$parent = $page->parent();
$collection = new Collection();
$collection = $parent ? $collection->addPage($parent) : $collection;
break;
case 'siblings':
$parent = $page->parent();
if ($parent) {
/** @var Collection $collection */
$collection = $parent->children();
$collection = $collection->remove($page->path());
} else {
$collection = new Collection();
}
break;
case 'descendants':
$collection = $this->all($page)->remove($page->path())->pages();
break;
default:
// Unknown type; return empty collection.
$collection = new Collection();
break;
}
return $collection;
}
/**
* Sort sub-pages in a page.
*
* @param PageInterface $page
* @param string|null $order_by
* @param string|null $order_dir
* @return array
*/
public function sort(PageInterface $page, $order_by = null, $order_dir = null, $sort_flags = null)
{
if ($order_by === null) {
$order_by = $page->orderBy();
}
if ($order_dir === null) {
$order_dir = $page->orderDir();
}
$path = $page->path();
if (null === $path) {
return [];
}
$children = $this->children[$path] ?? [];
if (!$children) {
return $children;
}
if (!isset($this->sort[$path][$order_by])) {
$this->buildSort($path, $children, $order_by, $page->orderManual(), $sort_flags);
}
$sort = $this->sort[$path][$order_by];
if ($order_dir !== 'asc') {
$sort = array_reverse($sort);
}
return $sort;
}
/**
* @param Collection $collection
* @param string $orderBy
* @param string $orderDir
* @param array|null $orderManual
* @param int|null $sort_flags
* @return array
* @internal
*/
public function sortCollection(Collection $collection, $orderBy, $orderDir = 'asc', $orderManual = null, $sort_flags = null)
{
$items = $collection->toArray();
if (!$items) {
return [];
}
$lookup = md5(json_encode($items) . json_encode($orderManual) . $orderBy . $orderDir);
if (!isset($this->sort[$lookup][$orderBy])) {
$this->buildSort($lookup, $items, $orderBy, $orderManual, $sort_flags);
}
$sort = $this->sort[$lookup][$orderBy];
if ($orderDir !== 'asc') {
$sort = array_reverse($sort);
}
return $sort;
}
/**
* Get a page instance.
*
* @param string $path The filesystem full path of the page
* @return PageInterface|null
* @throws RuntimeException
*/
public function get($path)
{
$path = (string)$path;
if ($path === '') {
return null;
}
// Check for local instances first.
if (array_key_exists($path, $this->instances)) {
return $this->instances[$path];
}
$instance = $this->index[$path] ?? null;
if (is_string($instance)) {
if ($this->directory) {
/** @var Language $language */
$language = $this->grav['language'];
$lang = $language->getActive();
if ($lang) {
$languages = $language->getFallbackLanguages($lang, true);
$key = $instance;
$instance = null;
foreach ($languages as $code) {
$test = $code ? $key . ':' . $code : $key;
if (($instance = $this->directory->getObject($test, 'flex_key')) !== null) {
break;
}
}
} else {
$instance = $this->directory->getObject($instance, 'flex_key');
}
}
if ($instance instanceof PageInterface) {
if ($this->fire_events && method_exists($instance, 'initialize')) {
$instance->initialize();
}
} else {
/** @var Debugger $debugger */
$debugger = $this->grav['debugger'];
$debugger->addMessage(sprintf('Flex page %s is missing or broken!', $instance), 'debug');
}
}
if ($instance) {
$this->instances[$path] = $instance;
}
return $instance;
}
/**
* Get children of the path.
*
* @param string $path
* @return Collection
*/
public function children($path)
{
$children = $this->children[(string)$path] ?? [];
return new Collection($children, [], $this);
}
/**
* Get a page ancestor.
*
* @param string $route The relative URL of the page
* @param string|null $path The relative path of the ancestor folder
* @return PageInterface|null
*/
public function ancestor($route, $path = null)
{
if ($path !== null) {
$page = $this->find($route, true);
if ($page && $page->path() === $path) {
return $page;
}
$parent = $page ? $page->parent() : null;
if ($parent && !$parent->root()) {
return $this->ancestor($parent->route(), $path);
}
}
return null;
}
/**
* Get a page ancestor trait.
*
* @param string $route The relative route of the page
* @param string|null $field The field name of the ancestor to query for
* @return PageInterface|null
*/
public function inherited($route, $field = null)
{
if ($field !== null) {
$page = $this->find($route, true);
$parent = $page ? $page->parent() : null;
if ($parent && $parent->value('header.' . $field) !== null) {
return $parent;
}
if ($parent && !$parent->root()) {
return $this->inherited($parent->route(), $field);
}
}
return null;
}
/**
* Find a page based on route.
*
* @param string $route The route of the page
* @param bool $all If true, return also non-routable pages, otherwise return null if page isn't routable
* @return PageInterface|null
*/
public function find($route, $all = false)
{
$route = urldecode((string)$route);
// Fetch page if there's a defined route to it.
$path = $this->routes[$route] ?? null;
$page = null !== $path ? $this->get($path) : null;
// Try without trailing slash
if (null === $page && Utils::endsWith($route, '/')) {
$path = $this->routes[rtrim($route, '/')] ?? null;
$page = null !== $path ? $this->get($path) : null;
}
if (!$all && !isset($this->grav['admin'])) {
if (null === $page || !$page->routable()) {
// If the page cannot be accessed, look for the site wide routes and wildcards.
$page = $this->findSiteBasedRoute($route) ?? $page;
}
}
return $page;
}
/**
* Check site based routes.
*
* @param string $route
* @return PageInterface|null
*/
protected function findSiteBasedRoute($route)
{
/** @var Config $config */
$config = $this->grav['config'];
$site_routes = $config->get('site.routes');
if (!is_array($site_routes)) {
return null;
}