forked from ExpressionEngine/ExpressionEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemplate.php
More file actions
4606 lines (3767 loc) · 178 KB
/
Copy pathTemplate.php
File metadata and controls
4606 lines (3767 loc) · 178 KB
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
/**
* This source file is part of the open source project
* ExpressionEngine (https://expressionengine.com)
*
* @link https://expressionengine.com/
* @copyright Copyright (c) 2003-2023, Packet Tide, LLC (https://www.packettide.com)
* @license https://expressionengine.com/license Licensed under Apache License, Version 2.0
*/
use ExpressionEngine\Service\Template;
/**
* Template Parser
*/
class EE_Template
{
// bring in the :modifier methods
use Template\Variables\ModifiableTrait;
public $loop_count = 0; // Main loop counter.
public $depth = 0; // Sub-template loop depth
public $in_point = ''; // String position of matched opening tag
public $template = ''; // The requested template (page)
public $final_template = ''; // The finalized template
public $fl_tmpl = ''; // 'Floating' copy of the template. Used as a temporary "work area".
public $cache_hash = ''; // md5 checksum of the template name. Used as title of cache file.
public $cache_prefix = ''; // prefix for cache file. Defaults to current URL, but can be set to custom string for shared cache
public $cache_status = ''; // Status of page cache (NO_CACHE, CURRENT, EXPIRED)
public $tag_cache_status = ''; // Status of tag cache (NO_CACHE, CURRENT, EXPIRED)
public $cache_timestamp = '';
public $template_type = ''; // Type of template (webpage, rss)
public $template_engine = ''; // Engine for rendering Template
public $embed_type = ''; // Type of template for embedded template
public $template_hits = 0;
public $php_parse_location = 'output'; // Where in the chain the PHP gets parsed
public $template_edit_date = ''; // Template edit date
public $templates_sofar = ''; // Templates processed so far, subtemplate tracker
public $templates_loaded = array(); // Templates loaded so far (yes, redundant)
public $attempted_fetch = array(); // Templates attempted to fetch but may have bailed due to recursive embeds
public $encode_email = true; // Whether to use the email encoder. This is set automatically
public $hit_lock_override = false; // Set to TRUE if you want hits tracked on sub-templates
public $hit_lock = false; // Lets us lock the hit counter if sub-templates are contained in a template
public $parse_php = false; // Whether to parse PHP or not
public $strict_urls = false; // Whether to make URLs operate strictly or not. This is set via a template global pref
public $protect_javascript = false; // Protect js blocks from conditional parsing?
public $group_name = ''; // Group of template being parsed
public $template_group_id = 0;
public $template_name = ''; // Name of template being parsed
public $template_id = 0;
public $enable_frontedit = 'y';
public $tag_data = array(); // Data contained in tags
public $tagparams = array();
public $tagchunk = '';
public $modules = array(); // List of installed modules
public $module_data = array(); // Data for modules from exp_channels
public $plugins = array(); // List of installed plug-ins
public $var_single = array(); // "Single" variables
public $var_cond = array(); // "Conditional" variables
public $var_pair = array(); // "Paired" variables
public $global_vars = array(); // This array can be set via the assign_to_config
public $embed_vars = array(); // This array can be set via the {embed} tag
public $layout_vars = array(); // This array can be set via the {layout} tag
public $segment_vars = array(); // Array of segment variables
public $template_route_vars = array(); // Array of segment variables
public $consent_vars = []; // Array of consent variables
public $tagparts = array(); // The parts of the tag: {exp:comment:form}
public $tagdata = ''; // The chunk between tag pairs. This is what modules will utilize
public $tagproper = ''; // The full opening tag
public $no_results = ''; // The contents of the {if no_results}{/if} conditionals
public $no_results_block = ''; // The {if no_results}{/if} chunk
public $search_fields = array(); // Special array of tag parameters that begin with 'search:'
public $date_vars = array(); // Date variables found in the tagdata (FALSE if date variables do not exist in tagdata)
public $unfound_vars = array(); // These are variables that have not been found in the tagdata and can be ignored
public $conditional_vars = array(); // Used by the template variable parser to prep conditionals
public $layout_conditionals = array(); // Used for {if layout:variable conditionals
public $TYPE = false; // FALSE if Typography has not been instantiated, Typography Class object otherwise
public $related_data = array(); // A multi-dimensional array containing any related tags
public $related_id = ''; // Used temporarily for the related ID number
public $related_markers = array(); // Used temporarily
public $reverse_related_data = array(); // A multi-dimensional array containing any reverse related tags
public $site_ids = array(); // Site IDs for the Sites Request for a Tag
public $sites = array(); // Array of sites with site_id as key and site_name as value, used to determine site_ids for tag, above.
public $site_prefs_cache = array(); // Array of cached site prefs, to allow fetching of another site's template files
public $disable_caching = false;
public $debugging = false; // Template parser debugging on?
public $cease_processing = false; // Used with no_results() method.
public $log = array(); // Log of Template processing
public $start_microtime = 0; // For Logging (= microtime())
public $form_id = ''; // Form Id
public $form_class = ''; // Form Class
public $realm = 'Restricted Content'; // Localize?
public $marker = '0o93H7pQ09L8X1t49cHY01Z5j4TT91fGfr'; // Temporary marker used as a place-holder for template data
protected $_tag_cache_prefix = 'tag_cache'; // Tag cache key namespace
protected $_page_cache_prefix = 'page_cache'; // Page cache key namespace
private $layout_contents = '';
private $user_vars = array();
private $globals_regex = array();
protected $process_data = true;
protected $raw_data = null;
protected $modified_vars = false;
protected $mb_available;
protected $ignore_fetch = ['url_title'];
protected $tag_class_aliases = [
'low_search' => 'pro_search',
'low_variables' => 'pro_variables',
];
protected $annotations;
/**
* Constructor
*
* @return void
*/
public function __construct()
{
if (ee()->config->item('multiple_sites_enabled') != 'y') {
$this->sites[ee()->config->item('site_id')] = ee()->config->item('site_short_name');
}
if (ee()->config->item('show_profiler') === 'y') {
$this->debugging = true;
$this->start_microtime = microtime(true);
}
$this->user_vars = array(
'member_id', 'group_id', 'group_description', 'group_title', 'primary_role_id', 'primary_role_description', 'primary_role_name', 'primary_role_short_name',
'username', 'screen_name', 'avatar_filename', 'avatar_width', 'avatar_height',
'email', 'ip_address', 'total_entries', 'total_comments', 'private_messages',
'total_forum_posts', 'total_forum_topics', 'total_forum_replies', 'mfa_enabled',
);
$this->marker = md5(ee()->config->site_url() . $this->marker);
$this->mb_available = extension_loaded('mbstring');
}
/**
* Run Template Engine
*
* Upon a Page or a Preview, it Runs the Processing of a Template
* based on URI request or method arguments
*
* @param string
* @param string
* @return void
*/
public function run_template_engine($template_group = '', $template = '')
{
$this->log_item(" - Begin Template Processing - ");
// Run garbage collection about 10% of the time
if (rand(1, 10) == 1) {
$this->_garbage_collect_cache();
ee('ChannelSet')->garbageCollect();
}
$this->log_item("URI: " . ee()->uri->uri_string);
$this->log_item("Template: {$template_group}/{$template}");
$this->fetch_and_parse($template_group, $template, false);
$this->log_item(" - End Template Processing - ");
$this->log_item("Parse Global Variables");
if ($this->template_type == 'static') {
$this->final_template = $this->restore_xml_declaration($this->final_template);
} else {
$this->final_template = $this->parse_globals($this->final_template);
}
$this->final_template = $this->decode_channel_form_ee_tags($this->final_template);
$this->log_item("Template Parsing Finished");
ee()->output->out_type = $this->template_type;
ee()->output->set_output($this->final_template);
}
/**
* Fetch and Process Template
*
* Determines what template to process, fetches the template and its preferences, and then processes all of it
*
* @param string
* @param string
* @param bool
* @param int
* @return void
*/
public function fetch_and_parse($template_group = '', $template = '', $is_embed = false, $site_id = '', $is_layout = false)
{
// Set a default site_ID
$site_id = ($site_id) ?: ee()->config->item('site_id');
// add this template to our subtemplate tracker
$this->templates_sofar = $this->templates_sofar . '|' . $site_id . ':' . $template_group . '/' . $template . '|';
// Fetch the requested template
// The template can either come from the DB or a cache file
// Do not use a reference!
$this->cache_status = 'NO_CACHE';
//if the template is not embedded, ensure the cache is restricted to current URI
if (!$is_embed) {
$this->cache_prefix = '';
}
$this->template = ($template_group != '' and $template != '') ?
$this->fetch_template($template_group, $template, false, $site_id) :
$this->parse_template_uri();
// Add the template to our list of templates loaded
$this->templates_loaded[] = array(
'group_name' => $this->group_name,
'template_name' => $this->template_name,
'site_id' => $site_id
);
// Record the New Relic transaction. Use a constant so that separate instances of this
// class can't accidentally restart the transaction metrics
if (!defined('EECMS_NEW_RELIC_TRANS_NAME')) {
$templateLoaded = $this->templates_loaded[0];
define('EECMS_NEW_RELIC_TRANS_NAME', "{$templateLoaded['group_name']}/{$templateLoaded['template_name']}");
ee()->core->set_newrelic_transaction(EECMS_NEW_RELIC_TRANS_NAME);
}
$this->log_item("Template Type: " . $this->template_type);
$this->parse($this->template, $is_embed, $site_id, $is_layout);
// -------------------------------------------
// 'template_post_parse' hook.
// - Modify template after tag parsing
//
if (ee()->extensions->active_hook('template_post_parse') === true) {
// Populate the $currentTemplateInfo array
$currentTemplateInfo = array();
if (count($this->templates_loaded)) { // don't do this if we don't have any template info!
$currentTemplateInfo = array(
'template_name' => $template,
'template_group' => $template_group,
);
}
// Build a return packet since we don't know at this stage where we are returning it
$return = ee()->extensions->call(
'template_post_parse',
$is_embed || $is_layout ? $this->template : $this->final_template,
($is_embed || $is_layout), // $is_partial
$site_id,
$currentTemplateInfo
);
// Add a conditional to adjust what is updated by function depending on whether this is final template or not
if ($is_embed || $is_layout) {
$this->template = $return;
} else {
$this->final_template = $return;
}
}
//
// -------------------------------------------
}
/**
* Parse a string as a template
*
* @param string
* @param string
* @return void
*/
public function parse(&$str, $is_embed = false, $site_id = '', $is_layout = false)
{
if ($str != '') {
$this->template = &$str;
}
// Static Content, No Parsing
if ($this->template_type == 'static' or $this->embed_type == 'static') {
if ($is_embed == false && $is_layout == false) {
$this->final_template = $this->template;
}
return;
}
/* -------------------------------------
/* "Smart" Static Parsing
/*
/* Performed on embedded webpage templates only that do not have
/* ExpressionEngine tags or PHP in them.
/*
/* Hidden Configuration Variable
/* - smart_static_parsing => Bypass parsing of templates that could be
/* of the type 'static' but aren't? (y/n)
/* -------------------------------------*/
if (ee()->config->item('smart_static_parsing') !== 'n' && $this->embed_type == 'webpage' && !stristr($this->template, LD) && !stristr($this->template, '<?')) {
$this->log_item("Smart Static Parsing Triggered");
if ($is_embed == false && $is_layout == false) {
$this->final_template = $this->template;
}
return;
}
// Parse 'Site' variables
$this->log_item("Parsing Site Variables");
// load site variables into the global_vars array
foreach (
array(
'site_id',
'site_label',
'site_short_name',
'site_name',
'site_url',
'site_description',
'site_index',
'webmaster_email'
) as $site_var
) {
ee()->config->_global_vars[$site_var] = stripslashes(ee()->config->item($site_var));
}
$seg_array = ee()->uri->segment_array();
// Define some path and template related global variables
$added_globals = [
'last_segment' => end($seg_array),
'current_url' => ee()->functions->fetch_current_uri(),
'current_path' => (ee()->uri->uri_string) ? str_replace(array('"', "'"), array('%22', '%27'), ee()->uri->uri_string) : '/',
'current_query_string' => http_build_query($_GET), // GET has been sanitized!
'template_name' => $this->template_name,
'template_group' => $this->group_name,
'template_group_id' => $this->template_group_id,
'template_id' => $this->template_id,
'template_type' => $this->embed_type ?: $this->template_type,
'is_ajax_request' => AJAX_REQUEST,
'is_live_preview_request' => isset(ee()->session) ? ee('LivePreview')->hasEntryData() : false,
];
//Pro conditionals
$added_globals['frontedit'] = false;
if (
REQ == 'PAGE' &&
ee()->session->userdata('admin_sess') == 1 &&
(ee()->config->item('enable_frontedit') == 'y' || ee()->config->item('enable_frontedit') === false) &&
(isset(ee()->TMPL) && is_object(ee()->TMPL) && in_array(ee()->TMPL->template_type, ['webpage'])) &&
ee('pro:Access')->hasRequiredLicense() &&
ee('pro:Access')->hasDockPermission() &&
ee()->TMPL->enable_frontedit != 'n' &&
ee()->input->cookie('frontedit') != 'off'
) {
$added_globals['frontedit'] = true;
}
$added_globals = array_merge($added_globals, $this->getMemberVariables());
ee()->config->_global_vars = array_merge(ee()->config->_global_vars, $added_globals);
// retain in case templates contain is_core conditionals
ee()->config->_global_vars['is_core'] = false;
// Mark our template for better errors
$this->template = $this->markContext() . $this->template;
// Parse assign_to_config variables and Snippets
if (count(ee()->config->_global_vars) > 0) {
$this->log_item("Config Assignments & Template Partials");
// Only iterate over the partials present in the template
$regexes = $this->getGlobalsRegex();
foreach ($regexes as $regex) {
while (preg_match_all($regex, $this->template, $result)) {
foreach ($result[1] as $variable) {
// In case any of these variables have EE comments of their own,
// removing from the value makes snippets more usable in conditionals
$value = $this->remove_ee_comments(
ee()->config->_global_vars[$variable]
);
$replace = $this->wrapInContextAnnotations(
$value,
'Template Partial "' . $variable . '"'
);
$this->template = str_replace(LD . $variable . RD, $replace, $this->template);
}
}
}
}
// have to handle the silly in_group() conditionals before we
// get to a real prep_ponditionals which does not like these.
$this->template = $this->replace_special_group_conditional($this->template);
// Parse URI segments
// This code lets admins fetch URI segments which become
// available as: {segment_1} {segment_2}
for ($i = 1; $i < 10; $i++) {
$this->template = str_replace(LD . 'segment_' . $i . RD, ee()->uri->segment($i), $this->template);
$this->segment_vars['segment_' . $i] = ee()->uri->segment($i);
// apply modifiers to segments
if (strpos($this->template, LD . 'segment_' . $i . ':') !== false) {
if (preg_match_all('/{(segment_' . $i . ':(.*?))}/', $this->template, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$this->segment_vars[$match[1]] = ee()->uri->segment($i);
}
}
}
}
// Parse template route segments
foreach ($this->template_route_vars as $key => $var) {
$this->template = str_replace(LD . $key . RD, $var, $this->template);
}
$parse_embed_vars = ($is_embed === true && count($this->embed_vars) > 0);
$parse_layout_vars = ($is_layout === true && count($this->layout_vars) > 0);
// Match layout: or embed: vars with date parameters/modifiers
if ($parse_embed_vars or $parse_layout_vars) {
$this->date_vars = array();
$this->_match_date_vars($this->template);
}
// Parse {embed} tag variables
if ($parse_embed_vars) {
$this->log_item("Embed Variables:", $this->embed_vars);
foreach ($this->embed_vars as $key => $val) {
// add 'embed:' to the key for replacement and so these variables work in conditionals
$this->embed_vars['embed:' . $key] = $val;
unset($this->embed_vars[$key]);
$this->template = $this->_parse_var_single('embed:' . $key, $val, $this->template);
}
}
// Parse {layout} tag variables
if ($parse_layout_vars) {
$this->template = $this->parseLayoutVariables($str, $this->layout_vars);
}
// Cache the name of the layout. We do this here so that we can force
// layouts to be declared before module or plugin tags. That is the only
// reasonable way of using these - right at the top.
if ($is_layout === false && $is_embed === false) {
$layout = $this->_find_layout();
}
// Parse error conditinal tags
$errors = isset(ee()->session) ? ee()->session->flashdata('errors') : [];
// Make sure to age the flashdata so it doesn't appear on the next request accidentally.
// ee()->session->_age_flashdata();
// If we have any errors from the submit, display those inline.
if (strpos($this->template, "{if errors}") !== false) {
// If we have field errors, remove the template conditional and leave the error tags,
// otherwise, remove the conditional and error tags completely.
if (!empty($errors)) {
if (preg_match("/{if errors}(.+?){\/if}/s", $this->template, $match)) {
$this->template = preg_replace("/{if errors}.+?{\/if}/s", $match['1'], $this->template);
}
} else {
$this->template = preg_replace("/{if errors}.+?{\/if}/s", '', $this->template);
}
}
if (!empty($errors)) {
// Make sure our errors are an associative array so the {errors}{error}{/errors} field tags work properly.
$errors = array_map(function ($error) {
return array('error' => $error);
}, $errors);
$this->template = $this->parse_variables($this->template, array(array('errors' => $errors)));
}
// Parse date format string "constants"
foreach (ee()->localize->format as $date_key => $date_val) {
$this->template = str_replace(LD . $date_key . RD, $date_val, $this->template);
}
$dates = array();
// Template's Last Edit time {template_edit_date format="%Y %m %d %H:%i:%s"}
if (strpos($this->template, LD . 'template_edit_date') !== false) {
$dates['template_edit_date'] = $this->template_edit_date;
}
$this->log_item("Parse Current Time Variables");
// Current time {current_time format="%Y %m %d %H:%i:%s"}
if (strpos($this->template, LD . 'current_time') !== false) {
$dates['current_time'] = ee()->localize->now;
}
// variable_time {variable_time date="yesterday" format="%Y %m %d %H:%i:%s"}
if (strpos($this->template, LD . 'variable_time') !== false) {
$dates['variable_time'] = ee()->localize->now;
}
$this->template = $this->parse_date_variables($this->template, $dates);
unset($dates);
// Parse Consent variables. Since this adds a query or two, only do it if needed
if (strpos($this->template, LD . 'consent:') != false or strpos($this->template, ' consent:')) {
$requests = ee('Model')->get('ConsentRequest')
->with('CurrentVersion')
->all();
$this->consent_vars = [];
foreach ($requests as $request) {
$var_name = 'consent:' . $request->consent_name;
$responded_name = 'consent:has_responded:' . $request->consent_name;
$this->consent_vars[$var_name] = ee('Consent')->hasGranted($request->consent_name);
$this->consent_vars[$responded_name] = ee('Consent')->hasResponded($request->consent_name);
$this->template = str_replace(LD . $var_name . RD, $this->consent_vars[$var_name], $this->template);
$this->template = str_replace(LD . $responded_name . RD, $this->consent_vars[$responded_name], $this->template);
}
}
// Is the main template cached?
// If a cache file exists for the primary template
// there is no reason to go further.
// However we do need to fetch any subtemplates
if ($this->cache_status == 'CURRENT' and $is_embed == false && $is_layout == false) {
$this->log_item("Cached Template Used");
$this->template = $this->parse_nocache($this->template);
// Smite Our Enemies: Advanced Conditionals
if (stristr($this->template, LD . 'if')) {
$this->template = $this->advanced_conditionals($this->template);
}
$this->log_item("Conditionals Parsed, Processing Sub Templates");
$this->template = $this->process_layout_template($this->template, $layout);
$this->template = $this->process_sub_templates($this->template);
$this->final_template = $this->template;
$this->_cleanup_layout_tags();
return;
}
// Remove whitespace from variables.
// This helps prevent errors, particularly if PHP is used in a template
$this->template = preg_replace("/" . LD . "\s*(\S+)\s*" . RD . "/U", LD . "\\1" . RD, $this->template);
// Parse Input Stage PHP
if ($this->parse_php == true && $this->php_parse_location == 'input' && $this->cache_status != 'CURRENT') {
$this->log_item("Parsing PHP on Input");
$this->template = $this->parse_template_php($this->template);
}
// Set up logged_in_* variables for early conditional evaluation
$logged_in_user_cond = [];
if ($this->cache_status != 'EXPIRED') {
$logged_in_user_cond = $this->getMemberVariables();
}
// Smite Our Enemies: Conditionals & Modifiers
$this->log_item("Parsing Segment, Embed, Layout, logged_in_*, and Global Vars Conditionals");
$all_early_vars = array_merge(
$this->segment_vars,
$this->template_route_vars,
$this->embed_vars,
$this->layout_conditionals,
array('layout:contents' => $this->layout_contents),
$logged_in_user_cond,
ee()->config->_global_vars,
$this->consent_vars
);
$this->template = ee()->functions->prep_conditionals(
$this->template,
$all_early_vars
);
$this->template = ee('Variables/Parser')->parseModifiedVariables($this->template, $all_early_vars);
// cleanup of leftover/undeclared embed variables
// don't worry with undeclared embed: vars in conditionals as the conditionals processor will handle that adequately
if (strpos($this->template, LD . 'embed:') !== false) {
$this->template = preg_replace('/' . LD . 'embed:([^!]+?)' . RD . '/', '', $this->template);
}
// Preload Replacements
if (strpos($this->template, 'preload_replace') !== false) {
if (preg_match_all("/" . LD . "preload_replace:(.+?)=([\"\'])([^\\2]*?)\\2" . RD . "/i", $this->template, $matches)) {
$this->log_item("Processing Preload Text Replacements: " . trim(implode('|', $matches[1])));
for ($j = 0; $j < count($matches[0]); $j++) {
$this->template = str_replace($matches[0][$j], "", $this->template);
$this->template = str_replace(LD . $matches[1][$j] . RD, $matches[3][$j], $this->template);
}
}
}
// Parse Plugin and Module Tags
$this->tags();
if ($this->cease_processing === true) {
return;
}
// Parse Output Stage PHP
if ($this->parse_php == true and $this->php_parse_location == 'output' and $this->cache_status != 'CURRENT') {
$this->log_item("Parsing PHP on Output");
$this->template = $this->parse_template_php($this->template);
}
// Write the cache file if needed
if ($this->cache_status == 'EXPIRED') {
$cache_template = ee()->functions->insert_action_ids($this->template);
// we remove the layout name early to prevent nested tags, we need
// to reinsert that tag at the beginning of template before caching
if (!empty($layout)) {
$cache_template = $layout[0] . "\n" . $this->template;
}
//if the template is not embedded, ensure the cache is restricted to current URI
if (!$is_embed) {
$this->cache_prefix = '';
}
$this->write_cache_file($this->cache_hash, $cache_template, 'template');
}
// Parse Our Uncacheable Forms
$this->template = $this->parse_nocache($this->template);
// Smite Our Enemies: Advanced Conditionals
if (strpos($this->template, LD . 'if') !== false) {
$this->log_item("Processing Advanced Conditionals");
$this->template = $this->advanced_conditionals($this->template);
}
// Build finalized template
// We only do this on the first pass.
// The sub-template routine will insert embedded
// templates into the master template
if ($is_embed == false && $is_layout == false) {
$this->template = $this->process_layout_template($this->template, $layout);
$this->template = $this->process_sub_templates($this->template);
$this->final_template = $this->template;
$this->_cleanup_layout_tags();
}
}
/**
* Parse Layout variables
*
* Also sets the $layout_conditionals class property, which is used to handle conditionals
* for early parsed variables in one sweep
*
* @param string $str The template/string to parse
* @param array $layout_vars Layout variables to parser, 'variable_name' => 'content'
* @return string The parsed template/string
*/
private function parseLayoutVariables($str, $layout_vars)
{
$this->log_item("Layout Variables:", $layout_vars);
$this->layout_conditionals = [];
// get all the declared layout variables (excluding layout:contents)
if (preg_match_all('/' . LD . 'layout:(?!\bset|contents\b)([^!]+?)(' . RD . '|\s|:)/', $str, $matches)) {
$undefined_layout_vars = [];
foreach ($matches[1] as $key) {
// ignore if the variable is already defined
if (isset($layout_vars[$key])) {
continue;
}
// set the undefined (but declared) variable to an empty string
$layout_vars[$key] = '';
$undefined_layout_vars[] = $key;
}
if (count($undefined_layout_vars) > 0) {
$this->log_item(" -> Undefined Variables:", $undefined_layout_vars);
}
}
foreach ($layout_vars as $key => $val) {
if ($val === '' && strpos($str, LD . '/layout:' . $key . RD) !== false) {
$val = []; // undefined or empty value that is supposed to be an array
}
if (is_array($val)) {
$layout_conditionals['layout:' . $key] = !empty($val);
$total_items = count($val);
$variables = [];
$item = ''; // initial value for catch-all replacement
foreach ($val as $idx => $item) {
$variables[] = [
'index' => $idx,
'count' => $idx + 1,
'reverse_count' => $total_items - $idx,
'total_results' => $total_items,
'value' => $item,
];
}
$str = $this->_parse_var_pair('layout:' . $key, $variables, $str);
// catch-all, if a layout array is used as a single variable, output the last one in
if (strpos($str, 'layout:' . $key) !== false) {
$str = $this->_parse_var_single('layout:' . $key, $item, $str);
}
} else {
$layout_conditionals['layout:' . $key] = $val;
$str = $this->_parse_var_single('layout:' . $key, $val, $str);
}
}
// parse index-specified items, e.g.: {layout:titles index='4'}
if (strpos($str, LD . 'layout:') !== false) {
// prototype:
// array (size=1)
// 0 =>
// array (size=4)
// 0 => string '{layout:titles index='4'}' (length=25)
// 1 => string 'titles' (length=6)
// 2 => string ''' (length=1)
// 3 => string '4' (length=1)
preg_match_all("/" . LD . "layout:([^\s]+?)\s+index\s*=\s*(\042|\047)([^\\2]*?)\\2\s*" . RD . "/si", $str, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (isset($layout_vars[$match[1]])) {
$value = (isset($layout_vars[$match[1]][$match[3]])) ? $layout_vars[$match[1]][$match[3]] : '';
$str = str_replace($match[0], $value, $str);
} elseif (($prefix_pos = strpos($match[1], ':')) !== false) {
// check for :modifers
$var = substr($match[1], 0, $prefix_pos);
if (isset($layout_vars[$var])) {
// need to rewrite the variable internally, or multiple modified index='' vars will all have the same value
// {layout:titles[3]:length index='3'}
$idx = '[' . $match[3] . ']';
$rewritten_tag = substr_replace($match[0], $var . $idx, 8, $prefix_pos);
$str = str_replace($match[0], $rewritten_tag, $str);
$modified_vars['layout:' . $var . $idx] = (isset($layout_vars[$var][$match[3]])) ? $layout_vars[$var][$match[3]] : '';
}
}
}
if (!empty($modified_vars)) {
$str = ee('Variables/Parser')->parseModifiedVariables($str, $modified_vars);
}
}
$this->layout_conditionals = $layout_conditionals;
return $str;
}
/**
* Generates the regex needed to grab all global template
* partials/variables present on the page
*
* @return array Regexes to grab globals
*/
private function getGlobalsRegex()
{
$global_names = array_keys(ee()->config->_global_vars);
$cache_key = md5(serialize($global_names));
if (!isset($this->globals_regex[$cache_key])) {
$global_names = array_map(
function ($str) {
return preg_quote($str, '/');
},
$global_names
);
$global_names = $this->chunkGlobalsArray($global_names);
$this->globals_regex[$cache_key] = array_map(
function ($array) {
return '/' . LD . '(' . implode('|', $array) . ')' . RD . '/';
},
$global_names
);
}
return $this->globals_regex[$cache_key];
}
/**
* Chunks the globals array by groups to make sure their combined String
* lengths doesn't exceed a certain number to prevent a "Regular Expression
* too large" error in getGlobalsRegex() above
*
* @param array $globals Array of preg_quoted variable names
* @return array Chunked array of global variable names
*/
private function chunkGlobalsArray($globals)
{
$max_length = 30000;
$chunks = array(array());
$regex_length = 0;
$index = 0;
foreach ($globals as $variable) {
$regex_length += strlen($variable) + 1; // + 1 for pipe
$chunks[$index][] = $variable;
if ($regex_length > $max_length) {
$regex_length = 0;
$index++;
}
}
return $chunks;
}
/**
* Find the first layout tag.
*
* Error if any are found after the first exp: tag or if we find more
* than one.
*
* @return array $layout Layout tag information
* - 0: full tag
* - 1: {layout=
* - 2: "some/path" [param=value]*
*/
protected function _find_layout()
{
$layout = null;
$first_tag = strpos($this->template, LD . 'exp:');
if (strpos($this->template, LD . 'layout') !== false && preg_match('/(' . LD . 'layout\s*=)(.*?)' . RD . '/s', $this->template, $match)) {
$tag_pos = strpos($this->template, $match[0]);
$error = '';
// layout tag after exp tag? No good can come of this.
if ($tag_pos > $first_tag && $first_tag !== false) {
if (ee()->config->item('debug') >= 1) {
$error = ee()->lang->line('error_layout_too_late');
ee()->output->fatal_error($error);
}
exit;
} elseif (preg_match('/(' . LD . 'layout\s*=)(.*?)' . RD . '/s', $this->template, $bad_layout, 0, $tag_pos + 1)) {
// Is there another? We can't have that.
if (ee()->config->item('debug') >= 1) {
$error = ee()->lang->line('error_multiple_layouts');
$error .= '<br><br>';
$error .= htmlspecialchars($match[0]);
$error .= '<br><br>';
$error .= htmlspecialchars($bad_layout[0]);
ee()->output->fatal_error($error);
}
exit;
}
// save it
$layout = $match;
// remove the tag
$this->template = str_replace($match[0], '', $this->template);
}
return $layout;
}
/**
* Cleanup any leftover layout tags
*
* We need to do this at various steps of post parsing as doing it too early
* can result in accidental cleanup of the {layout:contents} variable.
*
* @return void
*/
protected function _cleanup_layout_tags()
{
// cleanup of leftover/undeclared layout variables
if (strpos($this->final_template, LD . 'layout:') !== false) {
$this->final_template = preg_replace('/' . LD . 'layout:([^!]+?)' . RD . '/', '', $this->final_template);
}
}
/**
* Processes Any Layout Templates
*
* If any {embed=} tags are found, it processes those templates and does a replacement.
*
* @param string $template Template string
* @param array $layout {layout tag match information from ``_find_layout``
* @return string Layout with embeded template string
*/
protected function process_layout_template($template, array $layout = null)
{
if (!isset($layout)) {
return $template;
}
$this->layout_contents = trim($this->remove_ee_comments($template)); // for use in conditionals
$this->log_item("Processing Layout Templates");
$this->depth++;
$layout[0] = ee('Variables/Parser')->getFullTag($template, $layout[0]);
$layout[2] = substr(str_replace($layout[1], '', $layout[0]), 0, -1);
$parts = preg_split("/\s+/", $layout[2], 2);
$layout_vars = (isset($parts[1])) ? ee('Variables/Parser')->parseTagParameters($parts[1]) : array();
if ($layout_vars === false) {
$layout_vars = array();
} elseif (isset($layout_vars['contents'])) {
show_error(lang('layout_contents_reserved'));
}
$this->layout_vars = array_merge($this->layout_vars, $layout_vars);
// Find the first open tag
$open_tag = LD . 'layout:set';
$close_tag = LD . '/layout:set' . RD;
$template = $this->decode_channel_form_ee_tags($template);
$open_tag_len = strlen($open_tag);
$close_tag_len = strlen($close_tag);
$pos = strpos($template, $open_tag);
// As long as we have opening tags we need to continue looking
while ($pos !== false) {
$tag = ee('Variables/Parser')->getFullTag($template, substr($template, $pos, $open_tag_len));
$params = ee('Variables/Parser')->parseTagParameters(substr($tag, $open_tag_len));
if ($params['name'] == 'contents') {
show_error(lang('layout_contents_reserved'));
}
// suss out if this was layout:set, layout:set:append, or layout:set:prepend
// first remove the parameters from the full tag so we can split by :
$args_str = trim((preg_match("/\s+.*/", $tag, $matches))) ? $matches[0] : '';
$setvar = trim(str_replace($args_str, '', $tag), '{}');
$setvar_parts = explode(':', $setvar);
$command = array_pop($setvar_parts);
$closing_tag = LD . '/layout:' . (($command == 'set') ? 'set' : 'set:' . $command) . RD;
$close_tag_len = strlen($closing_tag);
// If there is a closing tag and it's before the next open, then this will
// be treated as a tag pair.
$next = strpos($template, $open_tag, $pos + $open_tag_len);
$close = strpos($template, $closing_tag, $pos + $open_tag_len);
if ($close && (!$next || $close < $next)) {
// we have a pair
$start = $pos + strlen($tag);
$value = substr($template, $start, $close - $start);
$replace_len = $close + $close_tag_len - $pos;
} else {
$value = isset($params['value']) ? $params['value'] : '';
$replace_len = strlen($tag);
}
// Remove the setter from the template