-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Page.php
2935 lines (2557 loc) · 84.6 KB
/
Page.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 Grav\Common\Cache;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Markdown\ParsedownExtra;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Media\Traits\MediaTrait;
use Grav\Common\Page\Markdown\Excerpts;
use Grav\Common\Page\Traits\PageFormTrait;
use Grav\Common\Twig\Twig;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Common\Yaml;
use Grav\Framework\Flex\Flex;
use InvalidArgumentException;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\MarkdownFile;
use RuntimeException;
use SplFileInfo;
use function dirname;
use function in_array;
use function is_array;
use function is_object;
use function is_string;
use function strlen;
define('PAGE_ORDER_PREFIX_REGEX', '/^[0-9]+\./u');
/**
* Class Page
* @package Grav\Common\Page
*/
class Page implements PageInterface
{
use PageFormTrait;
use MediaTrait;
/** @var string|null Filename. Leave as null if page is folder. */
protected $name;
/** @var bool */
protected $initialized = false;
/** @var string */
protected $folder;
/** @var string */
protected $path;
/** @var string */
protected $extension;
/** @var string */
protected $url_extension;
/** @var string */
protected $id;
/** @var string */
protected $parent;
/** @var string */
protected $template;
/** @var int */
protected $expires;
/** @var string */
protected $cache_control;
/** @var bool */
protected $visible;
/** @var bool */
protected $published;
/** @var int */
protected $publish_date;
/** @var int|null */
protected $unpublish_date;
/** @var string */
protected $slug;
/** @var string|null */
protected $route;
/** @var string|null */
protected $raw_route;
/** @var string */
protected $url;
/** @var array */
protected $routes;
/** @var bool */
protected $routable;
/** @var int */
protected $modified;
/** @var string */
protected $redirect;
/** @var string */
protected $external_url;
/** @var object|null */
protected $header;
/** @var string */
protected $frontmatter;
/** @var string */
protected $language;
/** @var string|null */
protected $content;
/** @var array */
protected $content_meta;
/** @var string|null */
protected $summary;
/** @var string */
protected $raw_content;
/** @var array|null */
protected $metadata;
/** @var string */
protected $title;
/** @var int */
protected $max_count;
/** @var string */
protected $menu;
/** @var int */
protected $date;
/** @var string */
protected $dateformat;
/** @var array */
protected $taxonomy;
/** @var string */
protected $order_by;
/** @var string */
protected $order_dir;
/** @var array|string|null */
protected $order_manual;
/** @var bool */
protected $modular_twig;
/** @var array */
protected $process;
/** @var int|null */
protected $summary_size;
/** @var bool */
protected $markdown_extra;
/** @var bool */
protected $etag;
/** @var bool */
protected $last_modified;
/** @var string */
protected $home_route;
/** @var bool */
protected $hide_home_route;
/** @var bool */
protected $ssl;
/** @var string */
protected $template_format;
/** @var bool */
protected $debugger;
/** @var PageInterface|null Unmodified (original) version of the page. Used for copying and moving the page. */
private $_original;
/** @var string Action */
private $_action;
/**
* Page Object Constructor
*/
public function __construct()
{
/** @var Config $config */
$config = Grav::instance()['config'];
$this->taxonomy = [];
$this->process = $config->get('system.pages.process');
$this->published = true;
}
/**
* Initializes the page instance variables based on a file
*
* @param SplFileInfo $file The file information for the .md file that the page represents
* @param string|null $extension
* @return $this
*/
public function init(SplFileInfo $file, $extension = null)
{
$config = Grav::instance()['config'];
$this->initialized = true;
// some extension logic
if (empty($extension)) {
$this->extension('.' . $file->getExtension());
} else {
$this->extension($extension);
}
// extract page language from page extension
$language = trim(Utils::basename($this->extension(), 'md'), '.') ?: null;
$this->language($language);
$this->hide_home_route = $config->get('system.home.hide_in_urls', false);
$this->home_route = $this->adjustRouteCase($config->get('system.home.alias'));
$this->filePath($file->getPathname());
$this->modified($file->getMTime());
$this->id($this->modified() . md5($this->filePath()));
$this->routable(true);
$this->header();
$this->date();
$this->metadata();
$this->url();
$this->visible();
$this->modularTwig(strpos($this->slug(), '_') === 0);
$this->setPublishState();
$this->published();
$this->urlExtension();
return $this;
}
#[\ReturnTypeWillChange]
public function __clone()
{
$this->initialized = false;
$this->header = $this->header ? clone $this->header : null;
}
/**
* @return void
*/
public function initialize(): void
{
if (!$this->initialized) {
$this->initialized = true;
$this->route = null;
$this->raw_route = null;
$this->_forms = null;
}
}
/**
* @return void
*/
protected function processFrontmatter()
{
// Quick check for twig output tags in frontmatter if enabled
$process_fields = (array)$this->header();
if (Utils::contains(json_encode(array_values($process_fields)), '{{')) {
$ignored_fields = [];
foreach ((array)Grav::instance()['config']->get('system.pages.frontmatter.ignore_fields') as $field) {
if (isset($process_fields[$field])) {
$ignored_fields[$field] = $process_fields[$field];
unset($process_fields[$field]);
}
}
$text_header = Grav::instance()['twig']->processString(json_encode($process_fields, JSON_UNESCAPED_UNICODE), ['page' => $this]);
$this->header((object)(json_decode($text_header, true) + $ignored_fields));
}
}
/**
* Return an array with the routes of other translated languages
*
* @param bool $onlyPublished only return published translations
* @return array the page translated languages
*/
public function translatedLanguages($onlyPublished = false)
{
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languages = $language->getLanguages();
$defaultCode = $language->getDefault();
$name = substr($this->name, 0, -strlen($this->extension()));
$translatedLanguages = [];
foreach ($languages as $languageCode) {
$languageExtension = ".{$languageCode}.md";
$path = $this->path . DS . $this->folder . DS . $name . $languageExtension;
$exists = file_exists($path);
// Default language may be saved without language file location.
if (!$exists && $languageCode === $defaultCode) {
$languageExtension = '.md';
$path = $this->path . DS . $this->folder . DS . $name . $languageExtension;
$exists = file_exists($path);
}
if ($exists) {
$aPage = new Page();
$aPage->init(new SplFileInfo($path), $languageExtension);
$aPage->route($this->route());
$aPage->rawRoute($this->rawRoute());
$route = $aPage->header()->routes['default'] ?? $aPage->rawRoute();
if (!$route) {
$route = $aPage->route();
}
if ($onlyPublished && !$aPage->published()) {
continue;
}
$translatedLanguages[$languageCode] = $route;
}
}
return $translatedLanguages;
}
/**
* Return an array listing untranslated languages available
*
* @param bool $includeUnpublished also list unpublished translations
* @return array the page untranslated languages
*/
public function untranslatedLanguages($includeUnpublished = false)
{
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languages = $language->getLanguages();
$translated = array_keys($this->translatedLanguages(!$includeUnpublished));
return array_values(array_diff($languages, $translated));
}
/**
* Gets and Sets the raw data
*
* @param string|null $var Raw content string
* @return string Raw content string
*/
public function raw($var = null)
{
$file = $this->file();
if ($var) {
// First update file object.
if ($file) {
$file->raw($var);
}
// Reset header and content.
$this->modified = time();
$this->id($this->modified() . md5($this->filePath()));
$this->header = null;
$this->content = null;
$this->summary = null;
}
return $file ? $file->raw() : '';
}
/**
* Gets and Sets the page frontmatter
*
* @param string|null $var
*
* @return string
*/
public function frontmatter($var = null)
{
if ($var) {
$this->frontmatter = (string)$var;
// Update also file object.
$file = $this->file();
if ($file) {
$file->frontmatter((string)$var);
}
// Force content re-processing.
$this->id(time() . md5($this->filePath()));
}
if (!$this->frontmatter) {
$this->header();
}
return $this->frontmatter;
}
/**
* Gets and Sets the header based on the YAML configuration at the top of the .md file
*
* @param object|array|null $var a YAML object representing the configuration for the file
* @return \stdClass the current YAML configuration
*/
public function header($var = null)
{
if ($var) {
$this->header = (object)$var;
// Update also file object.
$file = $this->file();
if ($file) {
$file->header((array)$var);
}
// Force content re-processing.
$this->id(time() . md5($this->filePath()));
}
if (!$this->header) {
$file = $this->file();
if ($file) {
try {
$this->raw_content = $file->markdown();
$this->frontmatter = $file->frontmatter();
$this->header = (object)$file->header();
if (!Utils::isAdminPlugin()) {
// If there's a `frontmatter.yaml` file merge that in with the page header
// note page's own frontmatter has precedence and will overwrite any defaults
$frontmatter_filename = $this->path . '/' . $this->folder . '/frontmatter.yaml';
if (file_exists($frontmatter_filename)) {
$frontmatter_file = CompiledYamlFile::instance($frontmatter_filename);
$frontmatter_data = $frontmatter_file->content();
$this->header = (object)array_replace_recursive(
$frontmatter_data,
(array)$this->header
);
$frontmatter_file->free();
}
// Process frontmatter with Twig if enabled
if (Grav::instance()['config']->get('system.pages.frontmatter.process_twig') === true) {
$this->processFrontmatter();
}
}
} catch (Exception $e) {
$file->raw(Grav::instance()['language']->translate([
'GRAV.FRONTMATTER_ERROR_PAGE',
$this->slug(),
$file->filename(),
$e->getMessage(),
$file->raw()
]));
$this->raw_content = $file->markdown();
$this->frontmatter = $file->frontmatter();
$this->header = (object)$file->header();
}
$var = true;
}
}
if ($var) {
if (isset($this->header->modified)) {
$this->modified($this->header->modified);
}
if (isset($this->header->slug)) {
$this->slug($this->header->slug);
}
if (isset($this->header->routes)) {
$this->routes = (array)$this->header->routes;
}
if (isset($this->header->title)) {
$this->title = trim($this->header->title);
}
if (isset($this->header->language)) {
$this->language = trim($this->header->language);
}
if (isset($this->header->template)) {
$this->template = trim($this->header->template);
}
if (isset($this->header->menu)) {
$this->menu = trim($this->header->menu);
}
if (isset($this->header->routable)) {
$this->routable = (bool)$this->header->routable;
}
if (isset($this->header->visible)) {
$this->visible = (bool)$this->header->visible;
}
if (isset($this->header->redirect)) {
$this->redirect = trim($this->header->redirect);
}
if (isset($this->header->external_url)) {
$this->external_url = trim($this->header->external_url);
}
if (isset($this->header->order_dir)) {
$this->order_dir = trim($this->header->order_dir);
}
if (isset($this->header->order_by)) {
$this->order_by = trim($this->header->order_by);
}
if (isset($this->header->order_manual)) {
$this->order_manual = (array)$this->header->order_manual;
}
if (isset($this->header->dateformat)) {
$this->dateformat($this->header->dateformat);
}
if (isset($this->header->date)) {
$this->date($this->header->date);
}
if (isset($this->header->markdown_extra)) {
$this->markdown_extra = (bool)$this->header->markdown_extra;
}
if (isset($this->header->taxonomy)) {
$this->taxonomy($this->header->taxonomy);
}
if (isset($this->header->max_count)) {
$this->max_count = (int)$this->header->max_count;
}
if (isset($this->header->process)) {
foreach ((array)$this->header->process as $process => $status) {
$this->process[$process] = (bool)$status;
}
}
if (isset($this->header->published)) {
$this->published = (bool)$this->header->published;
}
if (isset($this->header->publish_date)) {
$this->publishDate($this->header->publish_date);
}
if (isset($this->header->unpublish_date)) {
$this->unpublishDate($this->header->unpublish_date);
}
if (isset($this->header->expires)) {
$this->expires = (int)$this->header->expires;
}
if (isset($this->header->cache_control)) {
$this->cache_control = $this->header->cache_control;
}
if (isset($this->header->etag)) {
$this->etag = (bool)$this->header->etag;
}
if (isset($this->header->last_modified)) {
$this->last_modified = (bool)$this->header->last_modified;
}
if (isset($this->header->ssl)) {
$this->ssl = (bool)$this->header->ssl;
}
if (isset($this->header->template_format)) {
$this->template_format = $this->header->template_format;
}
if (isset($this->header->debugger)) {
$this->debugger = (bool)$this->header->debugger;
}
if (isset($this->header->append_url_extension)) {
$this->url_extension = $this->header->append_url_extension;
}
}
return $this->header;
}
/**
* Get page language
*
* @param string|null $var
* @return mixed
*/
public function language($var = null)
{
if ($var !== null) {
$this->language = $var;
}
return $this->language;
}
/**
* Modify a header value directly
*
* @param string $key
* @param mixed $value
*/
public function modifyHeader($key, $value)
{
$this->header->{$key} = $value;
}
/**
* @return int
*/
public function httpResponseCode()
{
return (int)($this->header()->http_response_code ?? 200);
}
/**
* @return array
*/
public function httpHeaders()
{
$headers = [];
$grav = Grav::instance();
$format = $this->templateFormat();
$cache_control = $this->cacheControl();
$expires = $this->expires();
// Set Content-Type header
$headers['Content-Type'] = Utils::getMimeByExtension($format, 'text/html');
// Calculate Expires Headers if set to > 0
if ($expires > 0) {
$expires_date = gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT';
if (!$cache_control) {
$headers['Cache-Control'] = 'max-age=' . $expires;
}
$headers['Expires'] = $expires_date;
}
// Set Cache-Control header
if ($cache_control) {
$headers['Cache-Control'] = strtolower($cache_control);
}
// Set Last-Modified header
if ($this->lastModified()) {
$last_modified = $this->modified();
foreach ($this->children()->modular() as $cpage) {
$modular_mtime = $cpage->modified();
if ($modular_mtime > $last_modified) {
$last_modified = $modular_mtime;
}
}
$last_modified_date = gmdate('D, d M Y H:i:s', $last_modified) . ' GMT';
$headers['Last-Modified'] = $last_modified_date;
}
// Ask Grav to calculate ETag from the final content.
if ($this->eTag()) {
$headers['ETag'] = '1';
}
// Set Vary: Accept-Encoding header
if ($grav['config']->get('system.pages.vary_accept_encoding', false)) {
$headers['Vary'] = 'Accept-Encoding';
}
// Added new Headers event
$headers_obj = (object) $headers;
Grav::instance()->fireEvent('onPageHeaders', new Event(['headers' => $headers_obj]));
return (array)$headers_obj;
}
/**
* Get the summary.
*
* @param int|null $size Max summary size.
* @param bool $textOnly Only count text size.
* @return string
*/
public function summary($size = null, $textOnly = false)
{
$config = (array)Grav::instance()['config']->get('site.summary');
if (isset($this->header->summary)) {
$config = array_merge($config, $this->header->summary);
}
// Return summary based on settings in site config file
if (!$config['enabled']) {
return $this->content();
}
// Set up variables to process summary from page or from custom summary
if ($this->summary === null) {
$content = $textOnly ? strip_tags($this->content()) : $this->content();
$summary_size = $this->summary_size;
} else {
$content = $textOnly ? strip_tags($this->summary) : $this->summary;
$summary_size = mb_strwidth($content, 'utf-8');
}
// Return calculated summary based on summary divider's position
$format = $config['format'];
// Return entire page content on wrong/ unknown format
if (!in_array($format, ['short', 'long'])) {
return $content;
}
if (($format === 'short') && isset($summary_size)) {
// Slice the string
if (mb_strwidth($content, 'utf8') > $summary_size) {
return mb_substr($content, 0, $summary_size);
}
return $content;
}
// Get summary size from site config's file
if ($size === null) {
$size = $config['size'];
}
// If the size is zero, return the entire page content
if ($size === 0) {
return $content;
// Return calculated summary based on defaults
}
if (!is_numeric($size) || ($size < 0)) {
$size = 300;
}
// Only return string but not html, wrap whatever html tag you want when using
if ($textOnly) {
if (mb_strwidth($content, 'utf-8') <= $size) {
return $content;
}
return mb_strimwidth($content, 0, $size, '…', 'UTF-8');
}
$summary = Utils::truncateHtml($content, $size);
return html_entity_decode($summary, ENT_COMPAT | ENT_HTML401, 'UTF-8');
}
/**
* Sets the summary of the page
*
* @param string $summary Summary
*/
public function setSummary($summary)
{
$this->summary = $summary;
}
/**
* Gets and Sets the content based on content portion of the .md file
*
* @param string|null $var Content
* @return string Content
*/
public function content($var = null)
{
if ($var !== null) {
$this->raw_content = $var;
// Update file object.
$file = $this->file();
if ($file) {
$file->markdown($var);
}
// Force re-processing.
$this->id(time() . md5($this->filePath()));
$this->content = null;
}
// If no content, process it
if ($this->content === null) {
// Get media
$this->media();
/** @var Config $config */
$config = Grav::instance()['config'];
// Load cached content
/** @var Cache $cache */
$cache = Grav::instance()['cache'];
$cache_id = md5('page' . $this->getCacheKey());
$content_obj = $cache->fetch($cache_id);
if (is_array($content_obj)) {
$this->content = $content_obj['content'];
$this->content_meta = $content_obj['content_meta'];
} else {
$this->content = $content_obj;
}
$process_markdown = $this->shouldProcess('markdown');
$process_twig = $this->shouldProcess('twig') || $this->modularTwig();
$cache_enable = $this->header->cache_enable ?? $config->get(
'system.cache.enabled',
true
);
$twig_first = $this->header->twig_first ?? $config->get(
'system.pages.twig_first',
false
);
// never cache twig means it's always run after content
$never_cache_twig = $this->header->never_cache_twig ?? $config->get(
'system.pages.never_cache_twig',
true
);
// if no cached-content run everything
if ($never_cache_twig) {
if ($this->content === false || $cache_enable === false) {
$this->content = $this->raw_content;
Grav::instance()->fireEvent('onPageContentRaw', new Event(['page' => $this]));
if ($process_markdown) {
$this->processMarkdown();
}
// Content Processed but not cached yet
Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
if ($cache_enable) {
$this->cachePageContent();
}
}
if ($process_twig) {
$this->processTwig();
}
} else {
if ($this->content === false || $cache_enable === false) {
$this->content = $this->raw_content;
Grav::instance()->fireEvent('onPageContentRaw', new Event(['page' => $this]));
if ($twig_first) {
if ($process_twig) {
$this->processTwig();
}
if ($process_markdown) {
$this->processMarkdown();
}
// Content Processed but not cached yet
Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
} else {
if ($process_markdown) {
$this->processMarkdown($process_twig);
}
// Content Processed but not cached yet
Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
if ($process_twig) {
$this->processTwig();
}
}
if ($cache_enable) {
$this->cachePageContent();
}
}
}
// Handle summary divider
$delimiter = $config->get('site.summary.delimiter', '===');
$divider_pos = mb_strpos($this->content, "<p>{$delimiter}</p>");
if ($divider_pos !== false) {
$this->summary_size = $divider_pos;
$this->content = str_replace("<p>{$delimiter}</p>", '', $this->content);
}
// Fire event when Page::content() is called
Grav::instance()->fireEvent('onPageContent', new Event(['page' => $this]));
}
return $this->content;
}
/**
* Get the contentMeta array and initialize content first if it's not already
*
* @return mixed
*/
public function contentMeta()
{
if ($this->content === null) {
$this->content();
}
return $this->getContentMeta();
}
/**
* Add an entry to the page's contentMeta array
*
* @param string $name
* @param mixed $value
*/
public function addContentMeta($name, $value)
{
$this->content_meta[$name] = $value;
}
/**
* Return the whole contentMeta array as it currently stands
*
* @param string|null $name
*
* @return mixed|null
*/
public function getContentMeta($name = null)
{
if ($name) {
return $this->content_meta[$name] ?? null;
}
return $this->content_meta;
}
/**
* Sets the whole content meta array in one shot
*
* @param array $content_meta
*
* @return array
*/
public function setContentMeta($content_meta)
{
return $this->content_meta = $content_meta;
}
/**
* Process the Markdown content. Uses Parsedown or Parsedown Extra depending on configuration
*
* @param bool $keepTwig If true, content between twig tags will not be processed.
* @return void
*/
protected function processMarkdown(bool $keepTwig = false)
{
/** @var Config $config */
$config = Grav::instance()['config'];
$markdownDefaults = (array)$config->get('system.pages.markdown');
if (isset($this->header()->markdown)) {
$markdownDefaults = array_merge($markdownDefaults, $this->header()->markdown);
}
// pages.markdown_extra is deprecated, but still check it...
if (!isset($markdownDefaults['extra']) && (isset($this->markdown_extra) || $config->get('system.pages.markdown_extra') !== null)) {
user_error('Configuration option \'system.pages.markdown_extra\' is deprecated since Grav 1.5, use \'system.pages.markdown.extra\' instead', E_USER_DEPRECATED);
$markdownDefaults['extra'] = $this->markdown_extra ?: $config->get('system.pages.markdown_extra');
}
$extra = $markdownDefaults['extra'] ?? false;
$defaults = [
'markdown' => $markdownDefaults,
'images' => $config->get('system.images', [])
];
$excerpts = new Excerpts($this, $defaults);
// Initialize the preferred variant of Parsedown
if ($extra) {
$parsedown = new ParsedownExtra($excerpts);
} else {
$parsedown = new Parsedown($excerpts);
}
$content = $this->content;
if ($keepTwig) {
$token = [
'/' . Utils::generateRandomString(3),
Utils::generateRandomString(3) . '/'
];
// Base64 encode any twig.
$content = preg_replace_callback(
['/({#.*?#})/mu', '/({{.*?}})/mu', '/({%.*?%})/mu'],
static function ($matches) use ($token) { return $token[0] . base64_encode($matches[1]) . $token[1]; },
$content
);
}
$content = $parsedown->text($content);
if ($keepTwig) {
// Base64 decode the encoded twig.
$content = preg_replace_callback(
['`' . $token[0] . '([A-Za-z0-9+/]+={0,2})' . $token[1] . '`mu'],
static function ($matches) { return base64_decode($matches[1]); },
$content
);
}
$this->content = $content;
}
/**
* Process the Twig page content.
*
* @return void
*/
private function processTwig()
{
/** @var Twig $twig */
$twig = Grav::instance()['twig'];
$this->content = $twig->processPage($this, $this->content);
}
/**
* Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
*
* @return void
*/
public function cachePageContent()
{
/** @var Cache $cache */
$cache = Grav::instance()['cache'];
$cache_id = md5('page' . $this->getCacheKey());
$cache->save($cache_id, ['content' => $this->content, 'content_meta' => $this->content_meta]);