-
-
Notifications
You must be signed in to change notification settings - Fork 528
/
Copy pathmodParser.php
625 lines (590 loc) · 25 KB
/
modParser.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
<?php
/*
* This file is part of the MODX Revolution package.
*
* Copyright (c) MODX, LLC
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace MODX\Revolution;
use MODX\Revolution\Sources\modMediaSource;
use xPDO\xPDO;
/**
* Represents the MODX parser responsible for processing MODX tags.
*
* This class encapsulates all of the functions for collecting and evaluating
* element tags embedded in text content.
*
* @package MODX\Revolution
*/
class modParser
{
/**
* A reference to the modX instance
* @var modX $modx
*/
public $modx= null;
/**
* If the parser is currently processing a tag
* @var bool $_processingTag
*/
protected $_processingTag = false;
/**
* If the parser is currently processing an element
* @var bool $_processingElement
*/
protected $_processingElement = false;
/**
* If the parser is currently processing an uncacheable tag
* @var bool $_processingUncacheable
*/
protected $_processingUncacheable = false;
/**
* If the parser is currently removing all unprocessed tags
* @var bool $_removingUnprocessed
*/
protected $_removingUnprocessed = false;
/**
* If the parser has ever processed uncacheable
*
* @var bool $_startedProcessingUncacheable
*/
protected $_startedProcessingUncacheable = false;
/**
* @param xPDO $modx A reference to the modX|xPDO instance
*/
function __construct(xPDO &$modx) {
$this->modx =& $modx;
}
/**
* Returns true if the parser is currently processing an uncacheable tag
* @return bool
*/
public function isProcessingUncacheable() {
$result = false;
if ($this->isProcessingTag() || $this->isProcessingElement()) $result = (boolean) $this->_processingUncacheable;
return $result;
}
/**
* Returns true if the parser has ever processed an uncacheable tag
* @return bool
*/
public function startedProcessingUncacheable() {
return $this->_startedProcessingUncacheable;
}
/**
* Returns true if the parser is currently removing any unprocessed tags
* @return bool
*/
public function isRemovingUnprocessed() {
$result = false;
if ($this->isProcessingTag() || $this->isProcessingElement()) $result = (boolean) $this->_removingUnprocessed;
return $result;
}
/**
* Returns true if the parser is currently processing a tag
* @return bool
*/
public function isProcessingTag() {
return (boolean) $this->_processingTag;
}
/**
* Returns true if the parser is currently processing an element
* @return bool
*/
public function isProcessingElement() {
return (boolean) $this->_processingElement;
}
public function setProcessingElement($arg = null) {
if (is_bool($arg)) {
$this->_processingElement = $arg;
} elseif ($arg === null) {
$this->_processingElement = !$this->_processingElement ? true : false;
} else {
$this->_processingElement = (boolean)$arg;
}
}
/**
* Collects element tags in a string and injects them into an array.
*
* @param string $origContent The content to collect tags from.
* @param array &$matches An array in which the collected tags will be
* stored (by reference)
* @param string $prefix The characters that define the start of a tag
* (default= "[[").
* @param string $suffix The characters that define the end of a tag
* (default= "]]").
* @return integer The number of tags collected from the content.
*/
public function collectElementTags($origContent, array &$matches, $prefix= '[[', $suffix= ']]') {
$subPrefix = $prefix;
$subSuffix = $suffix;
if (strlen($prefix) % 2 === 0) {
$uniqueCharactersPrefix = count_chars($prefix, 3);
if (strlen($uniqueCharactersPrefix) === 1) {
$subPrefix = substr($prefix, 0, 1);
}
}
if (strlen($suffix) % 2 === 0) {
$uniqueCharactersSuffix = count_chars($suffix, 3);
if (strlen($uniqueCharactersSuffix) === 1) {
$subSuffix = substr($suffix, 0, 1);
}
}
$pattern = '/\Q'.$prefix.'\E((?:(?:[^'.$subSuffix.$subPrefix.'][\s\S]*?|(?R))*?))\Q'.$suffix.'\E/x';
preg_match_all($pattern, $origContent, $matches, PREG_SET_ORDER);
$matchCount = count($matches);
if ($this->modx->getDebug() === true && !empty($matches)) {
$this->modx->log(modX::LOG_LEVEL_DEBUG, "modParser::collectElementTags \$matches = " . print_r($matches, 1) . "\n");
/* $this->modx->cacheManager->writeFile(MODX_CORE_PATH . 'logs/parser.log', print_r($matches, 1) . "\n", 'a'); */
}
return $matchCount;
}
/**
* Collects and processes any set of tags as defined by a prefix and suffix.
*
* @param string $parentTag The tag representing the element processing this
* tag. Pass an empty string to allow parsing without this recursion check.
* @param string $content The content to process and act on (by reference).
* @param boolean $processUncacheable Determines if noncacheable tags are to
* be processed (default= false).
* @param boolean $removeUnprocessed Determines if unprocessed tags should
* be left in place in the content, or stripped out (default= false).
* @param string $prefix The characters that define the start of a tag
* (default= "[[").
* @param string $suffix The characters that define the end of a tag
* (default= "]]").
* @param array $tokens Indicates that the parser should only process tags
* with the tokens included in this array.
* @param integer $depth The maximum iterations to recursively process tags
* returned by prior passes, 0 by default.
* @return int The number of processed tags
*/
public function processElementTags($parentTag, & $content, $processUncacheable= false, $removeUnprocessed= false, $prefix= "[[", $suffix= "]]", $tokens= [], $depth= 0) {
if ($processUncacheable) {
$this->_startedProcessingUncacheable = true;
}
$_processingTag = $this->_processingTag;
$_processingUncacheable = $this->_processingUncacheable;
$_removingUnprocessed = $this->_removingUnprocessed;
$this->_processingTag = true;
$this->_processingUncacheable = (boolean) $processUncacheable;
$this->_removingUnprocessed = (boolean) $removeUnprocessed;
$depth = $depth > 0 ? $depth - 1 : 0;
$processed= 0;
$tags= [];
/* invoke OnParseDocument event */
$this->modx->documentOutput = $content;
$this->modx->invokeEvent('OnParseDocument', ['content' => &$content]);
$content = $this->modx->documentOutput;
unset($this->modx->documentOutput);
if ($collected= $this->collectElementTags($content, $tags, $prefix, $suffix, $tokens)) {
$tagMap= [];
foreach ($tags as $tag) {
$token= substr($tag[1], 0, 1);
if (!$processUncacheable && $token === '!') {
if ($removeUnprocessed) {
$tagMap[$tag[0]]= '';
}
}
elseif (!empty ($tokens) && !in_array($token, $tokens)) {
$collected--;
continue;
}
if ($tag[0] === $parentTag) {
$tagMap[$tag[0]]= '';
$processed++;
continue;
}
$tagOutput= $this->processTag($tag, $processUncacheable);
if (($tagOutput === null || $tagOutput === false) && $removeUnprocessed) {
$tagMap[$tag[0]]= '';
$processed++;
}
elseif ($tagOutput !== null && $tagOutput !== false) {
$tagMap[$tag[0]]= $tagOutput;
if ($tag[0] !== $tagOutput) $processed++;
}
}
$this->mergeTagOutput($tagMap, $content);
if ($processed > 0 && $depth > 0) {
$processed+= $this->processElementTags($parentTag, $content, $processUncacheable, $removeUnprocessed, $prefix, $suffix, $tokens, $depth);
}
}
$this->_removingUnprocessed = $_removingUnprocessed;
$this->_processingUncacheable = $_processingUncacheable;
$this->_processingTag = $_processingTag;
return $processed;
}
/**
* Merges processed tag output into provided content string.
*
* @param array $tagMap An array with full tags as keys and processed output
* as the values.
* @param string $content The content to merge the tag output with (passed by
* reference).
*/
public function mergeTagOutput(array $tagMap, & $content) {
if (!empty ($content) && is_array($tagMap) && !empty ($tagMap)) {
$content= str_replace(array_keys($tagMap), array_values($tagMap), $content);
}
}
/**
* Parses an element/tag property string or array definition.
*
* @param string $propSource A valid property string or array source to
* parse.
* @return array An associative array of property values parsed from
* the property string or array definition.
*/
public function parseProperties($propSource) {
$properties= [];
if (!empty ($propSource)) {
if (is_string($propSource)) {
$properties = $this->parsePropertyString($propSource, true);
} elseif (is_array($propSource)) {
foreach ($propSource as $propName => &$property) {
if (is_array($property) && array_key_exists('value', $property)) {
$properties[$propName]= $property['value'];
} else {
$properties[$propName]= &$property;
}
}
}
}
return $properties;
}
/**
* Parses an element/tag property string and returns an array of properties.
*
* @param string $string The property string to parse.
* @param boolean $valuesOnly Indicates only the property value should be
* returned.
* @return array The processed properties in array format
*/
public function parsePropertyString($string, $valuesOnly = false) {
$properties = [];
$tagProps= xPDO :: escSplit("&", $string);
foreach ($tagProps as $prop) {
$property= xPDO :: escSplit('=', $prop);
if (count($property) == 2) {
$propName= $property[0];
if (substr($propName, 0, 4) == "amp;") {
$propName= substr($propName, 4);
}
$propValue= $property[1];
$propType= 'textfield';
$propDesc= '';
$propOptions= [];
$pvTmp= xPDO :: escSplit(';', $propValue);
if ($pvTmp && isset ($pvTmp[1])) {
$propDesc= $pvTmp[0];
if (($pvTmp[1]=='list' || $pvTmp[1]=='combo') && isset($pvTmp[3]) && $pvTmp[3]) {
if (!$valuesOnly) {
$propType = modParser::_XType($pvTmp[1]);
$options = explode(',', $pvTmp[2]);
if ($options) {
foreach ($options as $option) $propOptions[] = ['name' => ucfirst($option), 'value' => $option];
}
}
$propValue = $pvTmp[3];
}
elseif ($pvTmp[1]!='list' && $pvTmp[1]!='combo' && isset($pvTmp[2]) && $pvTmp[2]) {
if (!$valuesOnly) {
$propType = modParser::_XType($pvTmp[1]);
}
$propValue = $pvTmp[2];
} else {
$propValue = $pvTmp[0];
}
}
if ($propValue[0] == '`' && $propValue[strlen($propValue) - 1] == '`') {
$propValue= substr($propValue, 1, strlen($propValue) - 2);
}
$propValue= str_replace("``", "`", $propValue);
if ($valuesOnly) {
$properties[$propName]= $propValue;
} else {
$properties[$propName]= [
'name' => $propName,
'desc' => $propDesc,
'type' => $propType,
'options' => $propOptions,
'value' => $propValue
];
}
}
}
return $properties;
}
/**
* Converts legacy property string types to xtypes.
*
* @access protected
* @param string $type A property type string.
* @return string A valid xtype.
*/
protected function _XType($type) {
$xtype = $type;
switch ($type) {
case 'string':
$xtype = 'textfield';
break;
case 'int':
case 'integer':
case 'float':
$xtype = 'numberfield';
break;
case 'bool':
case 'boolean':
$xtype = 'checkbox';
break;
case 'list':
break;
default:
if (!in_array($xtype, ['checkbox', 'combo', 'datefield', 'numberfield', 'radio', 'textarea', 'textfield', 'timefield']
)) {
$xtype = 'textfield';
}
break;
}
return $xtype;
}
/**
* Processes a modElement tag and returns the result.
*
* @param string $tag A full tag string parsed from content.
* @param boolean $processUncacheable
* @return mixed The output of the processed element represented by the
* specified tag.
*/
public function processTag($tag, $processUncacheable = true) {
$this->_processingTag = true;
$element= null;
$elementOutput= null;
$outerTag= $tag[0];
$innerTag= $tag[1];
/* Avoid all processing for comment tags, e.g. [[- comments here]] */
if (substr($innerTag, 0, 1) === '-') {
return "";
}
/* collect any nested element tags in the innerTag and process them */
$this->processElementTags($outerTag, $innerTag, $processUncacheable);
$this->_processingTag = true;
$outerTag= '[[' . $innerTag . ']]';
$tagParts= xPDO :: escSplit('?', $innerTag, '`', 2);
$tagName= trim($tagParts[0]);
$tagPropString= null;
if (isset ($tagParts[1])) {
$tagPropString= trim($tagParts[1]);
}
$token= substr($tagName, 0, 1);
$tokenOffset= 0;
$cacheable= true;
if ($token === '!') {
if (!$processUncacheable) {
$this->_processingTag = false;
return $outerTag;
}
$cacheable= false;
$tokenOffset++;
$token= substr($tagName, $tokenOffset, 1);
} elseif (!$processUncacheable && strpos($tagPropString, '[[!') !== false) {
$this->modx->log(xPDO::LOG_LEVEL_WARN, "You should not call uncached elements inside cached!\nOuter tag: {$tag[0]}\nInner tag {$innerTag}");
$this->_processingTag = false;
return $outerTag;
}
if ($cacheable && $token !== '+') {
$elementOutput= $this->loadFromCache($outerTag);
}
$_restoreProcessingUncacheable = $this->_processingUncacheable;
/* stop processing uncacheable tags so they are not cached in the cacheable content */
if ($this->_processingUncacheable && $cacheable && $this->modx->getOption('parser_recurse_uncacheable', null, true)) {
$this->_processingUncacheable = false;
}
if ($elementOutput === null) {
switch ($token) {
case '-':
$elementOutput = '';
break;
case '+':
$tagName= substr($tagName, 1 + $tokenOffset);
$element= new modPlaceholderTag($this->modx);
$element->set('name', $tagName);
$element->setTag($outerTag);
$elementOutput= $element->process($tagPropString);
break;
case '%':
$tagName= substr($tagName, 1 + $tokenOffset);
$element= new modLexiconTag($this->modx);
$element->set('name', $tagName);
$element->setTag($outerTag);
$element->setCacheable($cacheable);
$elementOutput= $element->process($tagPropString);
break;
case '~':
$tagName= substr($tagName, 1 + $tokenOffset);
$element= new modLinkTag($this->modx);
$element->set('name', $tagName);
$element->setTag($outerTag);
$element->setCacheable($cacheable);
$elementOutput= $element->process($tagPropString);
break;
case '$':
$tagName= substr($tagName, 1 + $tokenOffset);
if ($element= $this->getElement(modChunk::class, $tagName)) {
$element->set('name', $tagName);
$element->setTag($outerTag);
$element->setCacheable($cacheable);
$elementOutput= $element->process($tagPropString);
}
break;
case '*':
$tagName= substr($tagName, 1 + $tokenOffset);
$nextToken= substr($tagName, 0, 1);
if ($nextToken === '#') {
$tagName= substr($tagName, 1);
}
if (is_array($this->modx->resource->_fieldMeta) && in_array($this->realname($tagName), array_keys($this->modx->resource->_fieldMeta))) {
$element= new modFieldTag($this->modx);
$element->set('name', $tagName);
$element->setTag($outerTag);
$element->setCacheable($cacheable);
$elementOutput= $element->process($tagPropString);
}
else {
$element = $this->getElement(modTemplateVar::class, $tagName);
// If our element tag was not found (e.i. not an existing TV), create a new instance of
// modFieldTag. We do this to make it possible to use output modifiers such as default. This
// mirrors the behavior of placeholders.
if ($element === false) {
$element = new modFieldTag($this->modx);
}
$element->set('name', $tagName);
$element->setTag($outerTag);
$element->setCacheable($cacheable);
$elementOutput= $element->process($tagPropString);
}
break;
default:
$tagName= substr($tagName, $tokenOffset);
if ($element= $this->getElement(modSnippet::class, $tagName)) {
$element->set('name', $tagName);
$element->setTag($outerTag);
$element->setCacheable($cacheable);
$elementOutput= $element->process($tagPropString);
}
elseif(!empty($tagName)) {
if ($this->modx->getOption('log_snippet_not_found', null, false)) {
$this->modx->log(xPDO::LOG_LEVEL_ERROR, "Could not find snippet with name {$tagName}.");
}
}
}
}
if (($elementOutput === null || $elementOutput === false) && $outerTag !== $tag[0]) {
$elementOutput = $outerTag;
}
if ($this->modx->getDebug() === true) {
$this->modx->log(xPDO::LOG_LEVEL_DEBUG, "Processing {$outerTag} as {$innerTag} using tagname {$tagName}:\n" . print_r($elementOutput, 1) . "\n\n");
/* $this->modx->cacheManager->writeFile(MODX_BASE_PATH . 'parser.log', "Processing {$outerTag} as {$innerTag}:\n" . print_r($elementOutput, 1) . "\n\n", 'a'); */
}
$this->_processingTag = false;
$this->_processingUncacheable = $_restoreProcessingUncacheable;
return $elementOutput;
}
/**
* Get a modElement instance taking advantage of the modX::$sourceCache.
*
* @param string $class The modElement derivative class to load.
* @param string $name An element name or raw tagName to identify the modElement instance.
* @return modElement|null An instance of the specified modElement derivative class.
*/
public function getElement($class, $name) {
$realname = $this->realname($name);
$class = $this->modx->loadClass($class);
if (array_key_exists($class, $this->modx->sourceCache) && array_key_exists($realname, $this->modx->sourceCache[$class])) {
/** @var modElement $element */
$element = $this->modx->newObject($class);
$element->fromArray($this->modx->sourceCache[$class][$realname]['fields'], '', true, true);
$element->setPolicies($this->modx->sourceCache[$class][$realname]['policies']);
if (!empty($this->modx->sourceCache[$class][$realname]['source'])) {
if (!empty($this->modx->sourceCache[$class][$realname]['source']['class_key'])) {
$sourceClassKey = $this->modx->sourceCache[$class][$realname]['source']['class_key'];
/* @var modMediaSource $source */
$source = $this->modx->newObject($sourceClassKey);
$source->fromArray($this->modx->sourceCache[$class][$realname]['source'],'',true,true);
$element->addOne($source,'Source');
}
}
} else {
/** @var modElement $element */
$element = $this->modx->getObjectGraph($class, ['Source' => []], ['name' => $realname], true);
if ($element && array_key_exists($class, $this->modx->sourceCache)) {
$this->modx->sourceCache[$class][$realname] = [
'fields' => $element->toArray(),
'policies' => $element->getPolicies(),
'source' => $element->Source ? $element->Source->toArray() : [],
];
}
elseif(!$element) {
$evtOutput = $this->modx->invokeEvent('OnElementNotFound', ['class' => $class, 'name' => $realname]);
$element = false;
if ($evtOutput != false) {
foreach ((array) $evtOutput as $elm) {
if (!empty($elm) && is_string($elm)) {
$element = $this->modx->newObject($class, [
'name' => $realname,
'snippet' => $elm
]
);
}
elseif ($elm instanceof modElement ) {
$element = $elm;
}
if ($element) {
break;
}
}
}
}
}
if ($element instanceof modElement) {
$element->set('name', $name);
}
return $element;
}
/**
* Gets the real name of an element containing filter modifiers.
*
* @param string $unfiltered The unfiltered name of a {@link modElement}.
* @return string The name minus any filter modifiers.
*/
public function realname($unfiltered) {
$filtered= $unfiltered;
$split= xPDO :: escSplit(':', $filtered);
if ($split && isset($split[0])) {
$filtered= $split[0];
$propsetSplit = xPDO :: escSplit('@', $filtered);
if ($propsetSplit && isset($propsetSplit[0])) {
$filtered= $propsetSplit[0];
}
}
return $filtered;
}
/**
* Loads output cached by complete tag signature from the elementCache.
*
* @uses modX::$_elementCache Stores all cacheable content from processed
* elements.
* @param string $tag The tag signature representing the element instance.
* @return string The cached output from the element instance.
*/
public function loadFromCache($tag) {
$elementOutput= null;
if (isset ($this->modx->elementCache[$tag])) {
$elementOutput= (string) $this->modx->elementCache[$tag];
}
return $elementOutput;
}
}