[BUGFIX] INCLUDE_TYPOSCRIPT condition use correct ConditionMatcher
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / TypoScript / Parser / TypoScriptParser.php
1 <?php
2 namespace TYPO3\CMS\Core\TypoScript\Parser;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Configuration\TypoScript\ConditionMatching\ConditionMatcher as BackendConditionMatcher;
18 use TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher;
19 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
20 use TYPO3\CMS\Core\TypoScript\ExtendedTemplateService;
21 use TYPO3\CMS\Core\Utility\GeneralUtility;
22 use TYPO3\CMS\Core\Utility\MathUtility;
23 use TYPO3\CMS\Core\Utility\PathUtility;
24 use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher as FrontendConditionMatcher;
25
26 /**
27 * The TypoScript parser
28 */
29 class TypoScriptParser
30 {
31 /**
32 * TypoScript hierarchy being build during parsing.
33 *
34 * @var array
35 */
36 public $setup = [];
37
38 /**
39 * Raw data, the input string exploded by LF
40 *
41 * @var array
42 */
43 public $raw;
44
45 /**
46 * Pointer to entry in raw data array
47 *
48 * @var int
49 */
50 public $rawP;
51
52 /**
53 * Holding the value of the last comment
54 *
55 * @var string
56 */
57 public $lastComment = '';
58
59 /**
60 * Internally set, used as internal flag to create a multi-line comment (one of those like /* ... * /
61 *
62 * @var bool
63 */
64 public $commentSet = false;
65
66 /**
67 * Internally set, when multiline value is accumulated
68 *
69 * @var bool
70 */
71 public $multiLineEnabled = false;
72
73 /**
74 * Internally set, when multiline value is accumulated
75 *
76 * @var string
77 */
78 public $multiLineObject = '';
79
80 /**
81 * Internally set, when multiline value is accumulated
82 *
83 * @var array
84 */
85 public $multiLineValue = [];
86
87 /**
88 * Internally set, when in brace. Counter.
89 *
90 * @var int
91 */
92 public $inBrace = 0;
93
94 /**
95 * For each condition this flag is set, if the condition is TRUE,
96 * else it's cleared. Then it's used by the [ELSE] condition to determine if the next part should be parsed.
97 *
98 * @var bool
99 */
100 public $lastConditionTrue = true;
101
102 /**
103 * Tracking all conditions found
104 *
105 * @var array
106 */
107 public $sections = [];
108
109 /**
110 * Tracking all matching conditions found
111 *
112 * @var array
113 */
114 public $sectionsMatch = [];
115
116 /**
117 * If set, then syntax highlight mode is on; Call the function syntaxHighlight() to use this function
118 *
119 * @var bool
120 */
121 public $syntaxHighLight = false;
122
123 /**
124 * Syntax highlight data is accumulated in this array. Used by syntaxHighlight_print() to construct the output.
125 *
126 * @var array
127 */
128 public $highLightData = [];
129
130 /**
131 * Syntax highlight data keeping track of the curly brace level for each line
132 *
133 * @var array
134 */
135 public $highLightData_bracelevel = [];
136
137 /**
138 * DO NOT register the comments. This is default for the ordinary sitetemplate!
139 *
140 * @var bool
141 */
142 public $regComments = false;
143
144 /**
145 * DO NOT register the linenumbers. This is default for the ordinary sitetemplate!
146 *
147 * @var bool
148 */
149 public $regLinenumbers = false;
150
151 /**
152 * Error accumulation array.
153 *
154 * @var array
155 */
156 public $errors = [];
157
158 /**
159 * Used for the error messages line number reporting. Set externally.
160 *
161 * @var int
162 */
163 public $lineNumberOffset = 0;
164
165 /**
166 * Line for break point.
167 *
168 * @var int
169 */
170 public $breakPointLN = 0;
171
172 /**
173 * @var array
174 */
175 public $highLightStyles = [
176 'prespace' => ['<span class="ts-prespace">', '</span>'],
177 // Space before any content on a line
178 'objstr_postspace' => ['<span class="ts-objstr_postspace">', '</span>'],
179 // Space after the object string on a line
180 'operator_postspace' => ['<span class="ts-operator_postspace">', '</span>'],
181 // Space after the operator on a line
182 'operator' => ['<span class="ts-operator">', '</span>'],
183 // The operator char
184 'value' => ['<span class="ts-value">', '</span>'],
185 // The value of a line
186 'objstr' => ['<span class="ts-objstr">', '</span>'],
187 // The object string of a line
188 'value_copy' => ['<span class="ts-value_copy">', '</span>'],
189 // The value when the copy syntax (<) is used; that means the object reference
190 'value_unset' => ['<span class="ts-value_unset">', '</span>'],
191 // The value when an object is unset. Should not exist.
192 'ignored' => ['<span class="ts-ignored">', '</span>'],
193 // The "rest" of a line which will be ignored.
194 'default' => ['<span class="ts-default">', '</span>'],
195 // The default style if none other is applied.
196 'comment' => ['<span class="ts-comment">', '</span>'],
197 // Comment lines
198 'condition' => ['<span class="ts-condition">', '</span>'],
199 // Conditions
200 'error' => ['<span class="ts-error">', '</span>'],
201 // Error messages
202 'linenum' => ['<span class="ts-linenum">', '</span>']
203 ];
204
205 /**
206 * Additional attributes for the <span> tags for a blockmode line
207 *
208 * @var string
209 */
210 public $highLightBlockStyles = '';
211
212 /**
213 * The hex-HTML color for the blockmode
214 *
215 * @var string
216 */
217 public $highLightBlockStyles_basecolor = '#cccccc';
218
219 /**
220 * @var \TYPO3\CMS\Core\TypoScript\ExtendedTemplateService
221 */
222 public $parentObject;
223
224 /**
225 * Start parsing the input TypoScript text piece. The result is stored in $this->setup
226 *
227 * @param string $string The TypoScript text
228 * @param object|string $matchObj If is object, then this is used to match conditions found in the TypoScript code. If matchObj not specified, then no conditions will work! (Except [GLOBAL])
229 */
230 public function parse($string, $matchObj = '')
231 {
232 $this->raw = explode(LF, $string);
233 $this->rawP = 0;
234 $pre = '[GLOBAL]';
235 while ($pre) {
236 if ($this->breakPointLN && $pre === '[_BREAK]') {
237 $this->error('Breakpoint at ' . ($this->lineNumberOffset + $this->rawP - 2) . ': Line content was "' . $this->raw[$this->rawP - 2] . '"', 1);
238 break;
239 }
240 $preUppercase = strtoupper($pre);
241 if ($pre[0] === '[' &&
242 ($preUppercase === '[GLOBAL]' ||
243 $preUppercase === '[END]' ||
244 !$this->lastConditionTrue && $preUppercase === '[ELSE]')
245 ) {
246 $pre = trim($this->parseSub($this->setup));
247 $this->lastConditionTrue = 1;
248 } else {
249 // We're in a specific section. Therefore we log this section
250 $specificSection = $preUppercase !== '[ELSE]';
251 if ($specificSection) {
252 $this->sections[md5($pre)] = $pre;
253 }
254 if (is_object($matchObj) && $matchObj->match($pre) || $this->syntaxHighLight) {
255 if ($specificSection) {
256 $this->sectionsMatch[md5($pre)] = $pre;
257 }
258 $pre = trim($this->parseSub($this->setup));
259 $this->lastConditionTrue = 1;
260 } else {
261 $pre = $this->nextDivider();
262 $this->lastConditionTrue = 0;
263 }
264 }
265 }
266 if ($this->inBrace) {
267 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': The script is short of ' . $this->inBrace . ' end brace(s)', 1);
268 }
269 if ($this->multiLineEnabled) {
270 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': A multiline value section is not ended with a parenthesis!', 1);
271 }
272 $this->lineNumberOffset += count($this->raw) + 1;
273 }
274
275 /**
276 * Will search for the next condition. When found it will return the line content (the condition value) and have advanced the internal $this->rawP pointer to point to the next line after the condition.
277 *
278 * @return string The condition value
279 * @see parse()
280 */
281 public function nextDivider()
282 {
283 while (isset($this->raw[$this->rawP])) {
284 $line = trim($this->raw[$this->rawP]);
285 $this->rawP++;
286 if ($line && $line[0] === '[') {
287 return $line;
288 }
289 }
290 return '';
291 }
292
293 /**
294 * Parsing the $this->raw TypoScript lines from pointer, $this->rawP
295 *
296 * @param array $setup Reference to the setup array in which to accumulate the values.
297 * @return string|NULL Returns the string of the condition found, the exit signal or possible nothing (if it completed parsing with no interruptions)
298 */
299 public function parseSub(array &$setup)
300 {
301 while (isset($this->raw[$this->rawP])) {
302 $line = ltrim($this->raw[$this->rawP]);
303 $lineP = $this->rawP;
304 $this->rawP++;
305 if ($this->syntaxHighLight) {
306 $this->regHighLight('prespace', $lineP, strlen($line));
307 }
308 // Breakpoint?
309 // By adding 1 we get that line processed
310 if ($this->breakPointLN && $this->lineNumberOffset + $this->rawP - 1 === $this->breakPointLN + 1) {
311 return '[_BREAK]';
312 }
313 // Set comment flag?
314 if (!$this->multiLineEnabled && strpos($line, '/*') === 0) {
315 $this->commentSet = 1;
316 }
317 // If $this->multiLineEnabled we will go and get the line values here because we know, the first if() will be TRUE.
318 if (!$this->commentSet && ($line || $this->multiLineEnabled)) {
319 // If multiline is enabled. Escape by ')'
320 if ($this->multiLineEnabled) {
321 // Multiline ends...
322 if ($line[0] === ')') {
323 if ($this->syntaxHighLight) {
324 $this->regHighLight('operator', $lineP, strlen($line) - 1);
325 }
326 // Disable multiline
327 $this->multiLineEnabled = 0;
328 $theValue = implode($this->multiLineValue, LF);
329 if (strpos($this->multiLineObject, '.') !== false) {
330 // Set the value deeper.
331 $this->setVal($this->multiLineObject, $setup, [$theValue]);
332 } else {
333 // Set value regularly
334 $setup[$this->multiLineObject] = $theValue;
335 if ($this->lastComment && $this->regComments) {
336 $setup[$this->multiLineObject . '..'] .= $this->lastComment;
337 }
338 if ($this->regLinenumbers) {
339 $setup[$this->multiLineObject . '.ln..'][] = $this->lineNumberOffset + $this->rawP - 1;
340 }
341 }
342 } else {
343 if ($this->syntaxHighLight) {
344 $this->regHighLight('value', $lineP);
345 }
346 $this->multiLineValue[] = $this->raw[$this->rawP - 1];
347 }
348 } elseif ($this->inBrace === 0 && $line[0] === '[') {
349 // Beginning of condition (only on level zero compared to brace-levels
350 if ($this->syntaxHighLight) {
351 $this->regHighLight('condition', $lineP);
352 }
353 return $line;
354 } else {
355 // Return if GLOBAL condition is set - no matter what.
356 if ($line[0] === '[' && stripos($line, '[GLOBAL]') !== false) {
357 if ($this->syntaxHighLight) {
358 $this->regHighLight('condition', $lineP);
359 }
360 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': On return to [GLOBAL] scope, the script was short of ' . $this->inBrace . ' end brace(s)', 1);
361 $this->inBrace = 0;
362 return $line;
363 } elseif ($line[0] !== '}' && $line[0] !== '#' && $line[0] !== '/') {
364 // If not brace-end or comment
365 // Find object name string until we meet an operator
366 $varL = strcspn($line, TAB . ' {=<>(');
367 // check for special ":=" operator
368 if ($varL > 0 && substr($line, $varL-1, 2) === ':=') {
369 --$varL;
370 }
371 // also remove tabs after the object string name
372 $objStrName = substr($line, 0, $varL);
373 if ($this->syntaxHighLight) {
374 $this->regHighLight('objstr', $lineP, strlen(substr($line, $varL)));
375 }
376 if ($objStrName !== '') {
377 $r = [];
378 if (preg_match('/[^[:alnum:]_\\\\\\.:-]/i', $objStrName, $r)) {
379 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': Object Name String, "' . htmlspecialchars($objStrName) . '" contains invalid character "' . $r[0] . '". Must be alphanumeric or one of: "_:-\\."');
380 } else {
381 $line = ltrim(substr($line, $varL));
382 if ($this->syntaxHighLight) {
383 $this->regHighLight('objstr_postspace', $lineP, strlen($line));
384 if ($line !== '') {
385 $this->regHighLight('operator', $lineP, strlen($line) - 1);
386 $this->regHighLight('operator_postspace', $lineP, strlen(ltrim(substr($line, 1))));
387 }
388 }
389 if ($line === '') {
390 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': Object Name String, "' . htmlspecialchars($objStrName) . '" was not followed by any operator, =<>({');
391 } else {
392 // Checking for special TSparser properties (to change TS values at parsetime)
393 $match = [];
394 if ($line[0] === ':' && preg_match('/^:=\\s*([[:alpha:]]+)\\s*\\((.*)\\).*/', $line, $match)) {
395 $tsFunc = $match[1];
396 $tsFuncArg = $match[2];
397 list($currentValue) = $this->getVal($objStrName, $setup);
398 $tsFuncArg = str_replace(['\\\\', '\\n', '\\t'], ['\\', LF, TAB], $tsFuncArg);
399 $newValue = $this->executeValueModifier($tsFunc, $tsFuncArg, $currentValue);
400 if (isset($newValue)) {
401 $line = '= ' . $newValue;
402 }
403 }
404 switch ($line[0]) {
405 case '=':
406 if ($this->syntaxHighLight) {
407 $this->regHighLight('value', $lineP, strlen(ltrim(substr($line, 1))) - strlen(trim(substr($line, 1))));
408 }
409 if (strpos($objStrName, '.') !== false) {
410 $value = [];
411 $value[0] = trim(substr($line, 1));
412 $this->setVal($objStrName, $setup, $value);
413 } else {
414 $setup[$objStrName] = trim(substr($line, 1));
415 if ($this->lastComment && $this->regComments) {
416 // Setting comment..
417 $setup[$objStrName . '..'] .= $this->lastComment;
418 }
419 if ($this->regLinenumbers) {
420 $setup[$objStrName . '.ln..'][] = $this->lineNumberOffset + $this->rawP - 1;
421 }
422 }
423 break;
424 case '{':
425 $this->inBrace++;
426 if (strpos($objStrName, '.') !== false) {
427 $exitSig = $this->rollParseSub($objStrName, $setup);
428 if ($exitSig) {
429 return $exitSig;
430 }
431 } else {
432 if (!isset($setup[$objStrName . '.'])) {
433 $setup[$objStrName . '.'] = [];
434 }
435 $exitSig = $this->parseSub($setup[$objStrName . '.']);
436 if ($exitSig) {
437 return $exitSig;
438 }
439 }
440 break;
441 case '(':
442 $this->multiLineObject = $objStrName;
443 $this->multiLineEnabled = 1;
444 $this->multiLineValue = [];
445 break;
446 case '<':
447 if ($this->syntaxHighLight) {
448 $this->regHighLight('value_copy', $lineP, strlen(ltrim(substr($line, 1))) - strlen(trim(substr($line, 1))));
449 }
450 $theVal = trim(substr($line, 1));
451 if ($theVal[0] === '.') {
452 $res = $this->getVal(substr($theVal, 1), $setup);
453 } else {
454 $res = $this->getVal($theVal, $this->setup);
455 }
456 // unserialize(serialize(...)) may look stupid but is needed because of some reference issues.
457 // See forge issue #76919 and functional test hasFlakyReferences()
458 $this->setVal($objStrName, $setup, unserialize(serialize($res)), 1);
459 break;
460 case '>':
461 if ($this->syntaxHighLight) {
462 $this->regHighLight('value_unset', $lineP, strlen(ltrim(substr($line, 1))) - strlen(trim(substr($line, 1))));
463 }
464 $this->setVal($objStrName, $setup, 'UNSET');
465 break;
466 default:
467 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': Object Name String, "' . htmlspecialchars($objStrName) . '" was not followed by any operator, =<>({');
468 }
469 }
470 }
471 $this->lastComment = '';
472 }
473 } elseif ($line[0] === '}') {
474 $this->inBrace--;
475 $this->lastComment = '';
476 if ($this->syntaxHighLight) {
477 $this->regHighLight('operator', $lineP, strlen($line) - 1);
478 }
479 if ($this->inBrace < 0) {
480 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': An end brace is in excess.', 1);
481 $this->inBrace = 0;
482 } else {
483 break;
484 }
485 } else {
486 if ($this->syntaxHighLight) {
487 $this->regHighLight('comment', $lineP);
488 }
489 // Comment. The comments are concatenated in this temporary string:
490 if ($this->regComments) {
491 $this->lastComment .= rtrim($line) . LF;
492 }
493 }
494 if (strpos($line, '### ERROR') === 0) {
495 $this->error(substr($line, 11));
496 }
497 }
498 }
499 // Unset comment
500 if ($this->commentSet) {
501 if ($this->syntaxHighLight) {
502 $this->regHighLight('comment', $lineP);
503 }
504 if (strpos($line, '*/') === 0) {
505 $this->commentSet = 0;
506 }
507 }
508 }
509 return null;
510 }
511
512 /**
513 * Executes operator functions, called from TypoScript
514 * example: page.10.value := appendString(!)
515 *
516 * @param string $modifierName TypoScript function called
517 * @param string $modifierArgument Function arguments; In case of multiple arguments, the method must split on its own
518 * @param string $currentValue Current TypoScript value
519 * @return string Modification result
520 */
521 protected function executeValueModifier($modifierName, $modifierArgument = null, $currentValue = null)
522 {
523 $newValue = null;
524 switch ($modifierName) {
525 case 'prependString':
526 $newValue = $modifierArgument . $currentValue;
527 break;
528 case 'appendString':
529 $newValue = $currentValue . $modifierArgument;
530 break;
531 case 'removeString':
532 $newValue = str_replace($modifierArgument, '', $currentValue);
533 break;
534 case 'replaceString':
535 list($fromStr, $toStr) = explode('|', $modifierArgument, 2);
536 $newValue = str_replace($fromStr, $toStr, $currentValue);
537 break;
538 case 'addToList':
539 $newValue = ((string)$currentValue !== '' ? $currentValue . ',' : '') . $modifierArgument;
540 break;
541 case 'removeFromList':
542 $existingElements = GeneralUtility::trimExplode(',', $currentValue);
543 $removeElements = GeneralUtility::trimExplode(',', $modifierArgument);
544 if (!empty($removeElements)) {
545 $newValue = implode(',', array_diff($existingElements, $removeElements));
546 }
547 break;
548 case 'uniqueList':
549 $elements = GeneralUtility::trimExplode(',', $currentValue);
550 $newValue = implode(',', array_unique($elements));
551 break;
552 case 'reverseList':
553 $elements = GeneralUtility::trimExplode(',', $currentValue);
554 $newValue = implode(',', array_reverse($elements));
555 break;
556 case 'sortList':
557 $elements = GeneralUtility::trimExplode(',', $currentValue);
558 $arguments = GeneralUtility::trimExplode(',', $modifierArgument);
559 $arguments = array_map('strtolower', $arguments);
560 $sort_flags = SORT_REGULAR;
561 if (in_array('numeric', $arguments)) {
562 $sort_flags = SORT_NUMERIC;
563 // If the sorting modifier "numeric" is given, all values
564 // are checked and an exception is thrown if a non-numeric value is given
565 // otherwise there is a different behaviour between PHP7 and PHP 5.x
566 // See also the warning on http://us.php.net/manual/en/function.sort.php
567 foreach ($elements as $element) {
568 if (!is_numeric($element)) {
569 throw new \InvalidArgumentException('The list "' . $currentValue . '" should be sorted numerically but contains a non-numeric value', 1438191758);
570 }
571 }
572 }
573 sort($elements, $sort_flags);
574 if (in_array('descending', $arguments)) {
575 $elements = array_reverse($elements);
576 }
577 $newValue = implode(',', $elements);
578 break;
579 default:
580 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$modifierName])) {
581 $hookMethod = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$modifierName];
582 $params = ['currentValue' => $currentValue, 'functionArgument' => $modifierArgument];
583 $fakeThis = false;
584 $newValue = GeneralUtility::callUserFunction($hookMethod, $params, $fakeThis);
585 } else {
586 GeneralUtility::sysLog(
587 'Missing function definition for ' . $modifierName . ' on TypoScript',
588 'core',
589 GeneralUtility::SYSLOG_SEVERITY_WARNING
590 );
591 }
592 }
593 return $newValue;
594 }
595
596 /**
597 * Parsing of TypoScript keys inside a curly brace where the key is composite of at least two keys,
598 * thus having to recursively call itself to get the value
599 *
600 * @param string $string The object sub-path, eg "thisprop.another_prot
601 * @param array $setup The local setup array from the function calling this function
602 * @return string Returns the exitSignal
603 * @see parseSub()
604 */
605 public function rollParseSub($string, array &$setup)
606 {
607 if ((string)$string === '') {
608 return '';
609 }
610
611 list($key, $remainingKey) = $this->parseNextKeySegment($string);
612 $key .= '.';
613 if (!isset($setup[$key])) {
614 $setup[$key] = [];
615 }
616 $exitSig = $remainingKey === ''
617 ? $this->parseSub($setup[$key])
618 : $this->rollParseSub($remainingKey, $setup[$key]);
619 return $exitSig ?: '';
620 }
621
622 /**
623 * Get a value/property pair for an object path in TypoScript, eg. "myobject.myvalue.mysubproperty".
624 * Here: Used by the "copy" operator, <
625 *
626 * @param string $string Object path for which to get the value
627 * @param array $setup Global setup code if $string points to a global object path. But if string is prefixed with "." then its the local setup array.
628 * @return array An array with keys 0/1 being value/property respectively
629 */
630 public function getVal($string, $setup)
631 {
632 if ((string)$string === '') {
633 return [];
634 }
635
636 list($key, $remainingKey) = $this->parseNextKeySegment($string);
637 $subKey = $key . '.';
638 if ($remainingKey === '') {
639 $retArr = [];
640 if (isset($setup[$key])) {
641 $retArr[0] = $setup[$key];
642 }
643 if (isset($setup[$subKey])) {
644 $retArr[1] = $setup[$subKey];
645 }
646 return $retArr;
647 } else {
648 if ($setup[$subKey]) {
649 return $this->getVal($remainingKey, $setup[$subKey]);
650 }
651 }
652 return [];
653 }
654
655 /**
656 * Setting a value/property of an object string in the setup array.
657 *
658 * @param string $string The object sub-path, eg "thisprop.another_prot
659 * @param array $setup The local setup array from the function calling this function.
660 * @param array|string $value The value/property pair array to set. If only one of them is set, then the other is not touched (unless $wipeOut is set, which it is when copies are made which must include both value and property)
661 * @param bool $wipeOut If set, then both value and property is wiped out when a copy is made of another value.
662 */
663 public function setVal($string, array &$setup, $value, $wipeOut = false)
664 {
665 if ((string)$string === '') {
666 return;
667 }
668
669 list($key, $remainingKey) = $this->parseNextKeySegment($string);
670 $subKey = $key . '.';
671 if ($remainingKey === '') {
672 if ($value === 'UNSET') {
673 unset($setup[$key]);
674 unset($setup[$subKey]);
675 if ($this->regLinenumbers) {
676 $setup[$key . '.ln..'][] = ($this->lineNumberOffset + $this->rawP - 1) . '>';
677 }
678 } else {
679 $lnRegisDone = 0;
680 if ($wipeOut) {
681 unset($setup[$key]);
682 unset($setup[$subKey]);
683 if ($this->regLinenumbers) {
684 $setup[$key . '.ln..'][] = ($this->lineNumberOffset + $this->rawP - 1) . '<';
685 $lnRegisDone = 1;
686 }
687 }
688 if (isset($value[0])) {
689 $setup[$key] = $value[0];
690 }
691 if (isset($value[1])) {
692 $setup[$subKey] = $value[1];
693 }
694 if ($this->lastComment && $this->regComments) {
695 $setup[$key . '..'] .= $this->lastComment;
696 }
697 if ($this->regLinenumbers && !$lnRegisDone) {
698 $setup[$key . '.ln..'][] = $this->lineNumberOffset + $this->rawP - 1;
699 }
700 }
701 } else {
702 if (!isset($setup[$subKey])) {
703 $setup[$subKey] = [];
704 }
705 $this->setVal($remainingKey, $setup[$subKey], $value);
706 }
707 }
708
709 /**
710 * Determines the first key segment of a TypoScript key by searching for the first
711 * unescaped dot in the given key string.
712 *
713 * Since the escape characters are only needed to correctly determine the key
714 * segment any escape characters before the first unescaped dot are
715 * stripped from the key.
716 *
717 * @param string $key The key, possibly consisting of multiple key segments separated by unescaped dots
718 * @return array Array with key segment and remaining part of $key
719 */
720 protected function parseNextKeySegment($key)
721 {
722 // if no dot is in the key, nothing to do
723 $dotPosition = strpos($key, '.');
724 if ($dotPosition === false) {
725 return [$key, ''];
726 }
727
728 if (strpos($key, '\\') !== false) {
729 // backslashes are in the key, so we do further parsing
730
731 while ($dotPosition !== false) {
732 if ($dotPosition > 0 && $key[$dotPosition - 1] !== '\\' || $dotPosition > 1 && $key[$dotPosition - 2] === '\\') {
733 break;
734 }
735 // escaped dot found, continue
736 $dotPosition = strpos($key, '.', $dotPosition + 1);
737 }
738
739 if ($dotPosition === false) {
740 // no regular dot found
741 $keySegment = $key;
742 $remainingKey = '';
743 } else {
744 if ($dotPosition > 1 && $key[$dotPosition - 2] === '\\' && $key[$dotPosition - 1] === '\\') {
745 $keySegment = substr($key, 0, $dotPosition - 1);
746 } else {
747 $keySegment = substr($key, 0, $dotPosition);
748 }
749 $remainingKey = substr($key, $dotPosition + 1);
750 }
751
752 // fix key segment by removing escape sequences
753 $keySegment = str_replace('\\.', '.', $keySegment);
754 } else {
755 // no backslash in the key, we're fine off
756 list($keySegment, $remainingKey) = explode('.', $key, 2);
757 }
758 return [$keySegment, $remainingKey];
759 }
760
761 /**
762 * Stacks errors/messages from the TypoScript parser into an internal array, $this->error
763 * If "TT" is a global object (as it is in the frontend when backend users are logged in) the message will be registered here as well.
764 *
765 * @param string $err The error message string
766 * @param int $num The error severity (in the scale of TimeTracker::setTSlogMessage: Approx: 2=warning, 1=info, 0=nothing, 3=fatal.)
767 */
768 public function error($err, $num = 2)
769 {
770 $tt = $this->getTimeTracker();
771 if ($tt !== null) {
772 $tt->setTSlogMessage($err, $num);
773 }
774 $this->errors[] = [$err, $num, $this->rawP - 1, $this->lineNumberOffset];
775 }
776
777 /**
778 * Checks the input string (un-parsed TypoScript) for include-commands ("<INCLUDE_TYPOSCRIPT: ....")
779 * Use: \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines()
780 *
781 * @param string $string Unparsed TypoScript
782 * @param int $cycle_counter Counter for detecting endless loops
783 * @param bool $returnFiles When set an array containing the resulting typoscript and all included files will get returned
784 * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes
785 * @return string Complete TypoScript with includes added.
786 * @static
787 */
788 public static function checkIncludeLines($string, $cycle_counter = 1, $returnFiles = false, $parentFilenameOrPath = '')
789 {
790 $includedFiles = [];
791 if ($cycle_counter > 100) {
792 GeneralUtility::sysLog('It appears like TypoScript code is looping over itself. Check your templates for "&lt;INCLUDE_TYPOSCRIPT: ..." tags', 'core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
793 if ($returnFiles) {
794 return [
795 'typoscript' => '',
796 'files' => $includedFiles
797 ];
798 }
799 return '
800 ###
801 ### ERROR: Recursion!
802 ###
803 ';
804 }
805
806 // If no tags found, no need to do slower preg_split
807 if (strpos($string, '<INCLUDE_TYPOSCRIPT:') !== false) {
808 $splitRegEx = '/\r?\n\s*<INCLUDE_TYPOSCRIPT:\s*(?i)source\s*=\s*"((?i)file|dir):\s*([^"]*)"(.*)>[\ \t]*/';
809 $parts = preg_split($splitRegEx, LF . $string . LF, -1, PREG_SPLIT_DELIM_CAPTURE);
810 // First text part goes through
811 $newString = $parts[0] . LF;
812 $partCount = count($parts);
813 for ($i = 1; $i + 3 < $partCount; $i += 4) {
814 // $parts[$i] contains 'FILE' or 'DIR'
815 // $parts[$i+1] contains relative file or directory path to be included
816 // $parts[$i+2] optional properties of the INCLUDE statement
817 // $parts[$i+3] next part of the typoscript string (part in between include-tags)
818 $includeType = $parts[$i];
819 $filename = $parts[$i + 1];
820 $originalFilename = $filename;
821 $optionalProperties = $parts[$i + 2];
822 $tsContentsTillNextInclude = $parts[$i + 3];
823
824 // Check condition
825 $matches = preg_split('#(?i)condition\\s*=\\s*"((?:\\\\\\\\|\\\\"|[^\\"])*)"(\\s*|>)#', $optionalProperties, 2, PREG_SPLIT_DELIM_CAPTURE);
826 // If there was a condition
827 if (count($matches) > 1) {
828 // Unescape the condition
829 $condition = trim(stripslashes($matches[1]));
830 // If necessary put condition in square brackets
831 if ($condition[0] !== '[') {
832 $condition = '[' . $condition . ']';
833 }
834
835 /** @var AbstractConditionMatcher $conditionMatcher */
836 $conditionMatcher = null;
837 if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_FE) {
838 $conditionMatcher = GeneralUtility::makeInstance(FrontendConditionMatcher::class);
839 } else {
840 $conditionMatcher = GeneralUtility::makeInstance(BackendConditionMatcher::class);
841 }
842
843 // If it didn't match then proceed to the next include, but prepend next normal (not file) part to output string
844 if (!$conditionMatcher->match($condition)) {
845 $newString .= $tsContentsTillNextInclude . LF;
846 continue;
847 }
848 }
849
850 // Resolve a possible relative paths if a parent file is given
851 if ($parentFilenameOrPath !== '' && $filename[0] === '.') {
852 $filename = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $filename);
853 }
854
855 // There must be a line-break char after - not sure why this check is necessary, kept it for being 100% backwards compatible
856 // An empty string is also ok (means that the next line is also a valid include_typoscript tag)
857 if (!preg_match('/(^\\s*\\r?\\n|^$)/', $tsContentsTillNextInclude)) {
858 $newString .= self::typoscriptIncludeError('Invalid characters after <INCLUDE_TYPOSCRIPT: source="' . $includeType . ':' . $filename . '">-tag (rest of line must be empty).');
859 } elseif (strpos('..', $filename) !== false) {
860 $newString .= self::typoscriptIncludeError('Invalid filepath "' . $filename . '" (containing "..").');
861 } else {
862 switch (strtolower($includeType)) {
863 case 'file':
864 self::includeFile($originalFilename, $cycle_counter, $returnFiles, $newString, $includedFiles, $optionalProperties, $parentFilenameOrPath);
865 break;
866 case 'dir':
867 self::includeDirectory($originalFilename, $cycle_counter, $returnFiles, $newString, $includedFiles, $optionalProperties, $parentFilenameOrPath);
868 break;
869 default:
870 $newString .= self::typoscriptIncludeError('No valid option for INCLUDE_TYPOSCRIPT source property (valid options are FILE or DIR)');
871 }
872 }
873 // Prepend next normal (not file) part to output string
874 $newString .= $tsContentsTillNextInclude . LF;
875
876 // load default TypoScript for content rendering templates like
877 // fluid_styled_content if those have been included through f.e.
878 // <INCLUDE_TYPOSCRIPT: source="FILE:EXT:fluid_styled_content/Configuration/TypoScript/setup.txt">
879 if (strpos(strtolower($filename), 'ext:') === 0) {
880 $filePointerPathParts = explode('/', substr($filename, 4));
881
882 // remove file part, determine whether to load setup or constants
883 list($includeType, ) = explode('.', array_pop($filePointerPathParts));
884
885 if (in_array($includeType, ['setup', 'constants'])) {
886 // adapt extension key to required format (no underscores)
887 $filePointerPathParts[0] = str_replace('_', '', $filePointerPathParts[0]);
888
889 // load default TypoScript
890 $defaultTypoScriptKey = implode('/', $filePointerPathParts) . '/';
891 if (in_array($defaultTypoScriptKey, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
892 $newString .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $includeType . '.']['defaultContentRendering'];
893 }
894 }
895 }
896 }
897 // Add a line break before and after the included code in order to make sure that the parser always has a LF.
898 $string = LF . trim($newString) . LF;
899 }
900 // When all included files should get returned, simply return an compound array containing
901 // the TypoScript with all "includes" processed and the files which got included
902 if ($returnFiles) {
903 return [
904 'typoscript' => $string,
905 'files' => $includedFiles
906 ];
907 }
908 return $string;
909 }
910
911 /**
912 * Include file $filename. Contents of the file will be prepended to &$newstring, filename to &$includedFiles
913 * Further include_typoscript tags in the contents are processed recursively
914 *
915 * @param string $filename Relative path to the typoscript file to be included
916 * @param int $cycle_counter Counter for detecting endless loops
917 * @param bool $returnFiles When set, filenames of included files will be prepended to the array &$includedFiles
918 * @param string &$newString The output string to which the content of the file will be prepended (referenced
919 * @param array &$includedFiles Array to which the filenames of included files will be prepended (referenced)
920 * @param string $optionalProperties
921 * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes
922 * @static
923 */
924 public static function includeFile($filename, $cycle_counter = 1, $returnFiles = false, &$newString = '', array &$includedFiles = [], $optionalProperties = '', $parentFilenameOrPath = '')
925 {
926 // Resolve a possible relative paths if a parent file is given
927 if ($parentFilenameOrPath !== '' && $filename[0] === '.') {
928 $absfilename = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $filename);
929 } else {
930 $absfilename = $filename;
931 }
932 $absfilename = GeneralUtility::getFileAbsFileName($absfilename);
933
934 $newString .= LF . '### <INCLUDE_TYPOSCRIPT: source="FILE:' . $filename . '"' . $optionalProperties . '> BEGIN:' . LF;
935 if ((string)$filename !== '') {
936 // Must exist and must not contain '..' and must be relative
937 // Check for allowed files
938 if (!GeneralUtility::verifyFilenameAgainstDenyPattern($absfilename)) {
939 $newString .= self::typoscriptIncludeError('File "' . $filename . '" was not included since it is not allowed due to fileDenyPattern.');
940 } elseif (!@file_exists($absfilename)) {
941 $newString .= self::typoscriptIncludeError('File "' . $filename . '" was not found.');
942 } else {
943 $includedFiles[] = $absfilename;
944 // check for includes in included text
945 $included_text = self::checkIncludeLines(file_get_contents($absfilename), $cycle_counter + 1, $returnFiles, $absfilename);
946 // If the method also has to return all included files, merge currently included
947 // files with files included by recursively calling itself
948 if ($returnFiles && is_array($included_text)) {
949 $includedFiles = array_merge($includedFiles, $included_text['files']);
950 $included_text = $included_text['typoscript'];
951 }
952 $newString .= $included_text . LF;
953 }
954 }
955 $newString .= '### <INCLUDE_TYPOSCRIPT: source="FILE:' . $filename . '"' . $optionalProperties . '> END:' . LF . LF;
956 }
957
958 /**
959 * Include all files with matching Typoscript extensions in directory $dirPath. Contents of the files are
960 * prepended to &$newstring, filename to &$includedFiles.
961 * Order of the directory items to be processed: files first, then directories, both in alphabetical order.
962 * Further include_typoscript tags in the contents of the files are processed recursively.
963 *
964 * @param string $dirPath Relative path to the directory to be included
965 * @param int $cycle_counter Counter for detecting endless loops
966 * @param bool $returnFiles When set, filenames of included files will be prepended to the array &$includedFiles
967 * @param string &$newString The output string to which the content of the file will be prepended (referenced)
968 * @param array &$includedFiles Array to which the filenames of included files will be prepended (referenced)
969 * @param string $optionalProperties
970 * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes
971 * @static
972 */
973 protected static function includeDirectory($dirPath, $cycle_counter = 1, $returnFiles = false, &$newString = '', array &$includedFiles = [], $optionalProperties = '', $parentFilenameOrPath = '')
974 {
975 // Extract the value of the property extensions="..."
976 $matches = preg_split('#(?i)extensions\s*=\s*"([^"]*)"(\s*|>)#', $optionalProperties, 2, PREG_SPLIT_DELIM_CAPTURE);
977 if (count($matches) > 1) {
978 $includedFileExtensions = $matches[1];
979 } else {
980 $includedFileExtensions = '';
981 }
982
983 // Resolve a possible relative paths if a parent file is given
984 if ($parentFilenameOrPath !== '' && $dirPath[0] === '.') {
985 $resolvedDirPath = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $dirPath);
986 } else {
987 $resolvedDirPath = $dirPath;
988 }
989 $absDirPath = GeneralUtility::getFileAbsFileName($resolvedDirPath);
990 if ($absDirPath) {
991 $absDirPath = rtrim($absDirPath, '/') . '/';
992 $newString .= LF . '### <INCLUDE_TYPOSCRIPT: source="DIR:' . $dirPath . '"' . $optionalProperties . '> BEGIN:' . LF;
993 // Get alphabetically sorted file index in array
994 $fileIndex = GeneralUtility::getAllFilesAndFoldersInPath([], $absDirPath, $includedFileExtensions);
995 // Prepend file contents to $newString
996 $prefixLength = strlen(PATH_site);
997 foreach ($fileIndex as $absFileRef) {
998 $relFileRef = substr($absFileRef, $prefixLength);
999 self::includeFile($relFileRef, $cycle_counter, $returnFiles, $newString, $includedFiles, '', $absDirPath);
1000 }
1001 $newString .= '### <INCLUDE_TYPOSCRIPT: source="DIR:' . $dirPath . '"' . $optionalProperties . '> END:' . LF . LF;
1002 } else {
1003 $newString .= self::typoscriptIncludeError('The path "' . $resolvedDirPath . '" is invalid.');
1004 }
1005 }
1006
1007 /**
1008 * Process errors in INCLUDE_TYPOSCRIPT tags
1009 * Errors are logged in sysLog and printed in the concatenated Typoscript result (as can be seen in Template Analyzer)
1010 *
1011 * @param string $error Text of the error message
1012 * @return string The error message encapsulated in comments
1013 * @static
1014 */
1015 protected static function typoscriptIncludeError($error)
1016 {
1017 GeneralUtility::sysLog($error, 'core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
1018 return "\n###\n### ERROR: " . $error . "\n###\n\n";
1019 }
1020
1021 /**
1022 * Parses the string in each value of the input array for include-commands
1023 *
1024 * @param array $array Array with TypoScript in each value
1025 * @return array Same array but where the values has been parsed for include-commands
1026 */
1027 public static function checkIncludeLines_array(array $array)
1028 {
1029 foreach ($array as $k => $v) {
1030 $array[$k] = self::checkIncludeLines($array[$k]);
1031 }
1032 return $array;
1033 }
1034
1035 /**
1036 * Search for commented INCLUDE_TYPOSCRIPT statements
1037 * and save the content between the BEGIN and the END line to the specified file
1038 *
1039 * @param string $string Template content
1040 * @param int $cycle_counter Counter for detecting endless loops
1041 * @param array $extractedFileNames
1042 * @param string $parentFilenameOrPath
1043 *
1044 * @throws \RuntimeException
1045 * @throws \UnexpectedValueException
1046 * @return string Template content with uncommented include statements
1047 */
1048 public static function extractIncludes($string, $cycle_counter = 1, array $extractedFileNames = [], $parentFilenameOrPath = '')
1049 {
1050 if ($cycle_counter > 10) {
1051 GeneralUtility::sysLog('It appears like TypoScript code is looping over itself. Check your templates for "&lt;INCLUDE_TYPOSCRIPT: ..." tags', 'core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
1052 return '
1053 ###
1054 ### ERROR: Recursion!
1055 ###
1056 ';
1057 }
1058 $expectedEndTag = '';
1059 $fileContent = [];
1060 $restContent = [];
1061 $fileName = null;
1062 $inIncludePart = false;
1063 $lines = preg_split("/\r\n|\n|\r/", $string);
1064 $skipNextLineIfEmpty = false;
1065 $openingCommentedIncludeStatement = null;
1066 $optionalProperties = '';
1067 foreach ($lines as $line) {
1068 // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts
1069 // an additional empty line, remove this again
1070 if ($skipNextLineIfEmpty) {
1071 if (trim($line) === '') {
1072 continue;
1073 }
1074 $skipNextLineIfEmpty = false;
1075 }
1076
1077 // Outside commented include statements
1078 if (!$inIncludePart) {
1079 // Search for beginning commented include statements
1080 if (preg_match('/###\\s*<INCLUDE_TYPOSCRIPT:\\s*source\\s*=\\s*"\\s*((?i)file|dir)\\s*:\\s*([^"]*)"(.*)>\\s*BEGIN/i', $line, $matches)) {
1081 // Found a commented include statement
1082
1083 // Save this line in case there is no ending tag
1084 $openingCommentedIncludeStatement = trim($line);
1085 $openingCommentedIncludeStatement = preg_replace('/\\s*### Warning: .*###\\s*/', '', $openingCommentedIncludeStatement);
1086
1087 // type of match: FILE or DIR
1088 $inIncludePart = strtoupper($matches[1]);
1089 $fileName = $matches[2];
1090 $optionalProperties = $matches[3];
1091
1092 $expectedEndTag = '### <INCLUDE_TYPOSCRIPT: source="' . $inIncludePart . ':' . $fileName . '"' . $optionalProperties . '> END';
1093 // Strip all whitespace characters to make comparison safer
1094 $expectedEndTag = strtolower(preg_replace('/\s/', '', $expectedEndTag));
1095 } else {
1096 // If this is not a beginning commented include statement this line goes into the rest content
1097 $restContent[] = $line;
1098 }
1099 //if (is_array($matches)) GeneralUtility::devLog('matches', 'TypoScriptParser', 0, $matches);
1100 } else {
1101 // Inside commented include statements
1102 // Search for the matching ending commented include statement
1103 $strippedLine = preg_replace('/\s/', '', $line);
1104 if (stripos($strippedLine, $expectedEndTag) !== false) {
1105 // Found the matching ending include statement
1106 $fileContentString = implode(PHP_EOL, $fileContent);
1107
1108 // Write the content to the file
1109
1110 // Resolve a possible relative paths if a parent file is given
1111 if ($parentFilenameOrPath !== '' && $fileName[0] === '.') {
1112 $realFileName = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $fileName);
1113 } else {
1114 $realFileName = $fileName;
1115 }
1116 $realFileName = GeneralUtility::getFileAbsFileName($realFileName);
1117
1118 if ($inIncludePart === 'FILE') {
1119 // Some file checks
1120 if (!GeneralUtility::verifyFilenameAgainstDenyPattern($realFileName)) {
1121 throw new \UnexpectedValueException(sprintf('File "%s" was not included since it is not allowed due to fileDenyPattern.', $fileName), 1382651858);
1122 }
1123 if (empty($realFileName)) {
1124 throw new \UnexpectedValueException(sprintf('"%s" is not a valid file location.', $fileName), 1294586441);
1125 }
1126 if (!is_writable($realFileName)) {
1127 throw new \RuntimeException(sprintf('"%s" is not writable.', $fileName), 1294586442);
1128 }
1129 if (in_array($realFileName, $extractedFileNames)) {
1130 throw new \RuntimeException(sprintf('Recursive/multiple inclusion of file "%s"', $realFileName), 1294586443);
1131 }
1132 $extractedFileNames[] = $realFileName;
1133
1134 // Recursive call to detected nested commented include statements
1135 $fileContentString = self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName);
1136
1137 // Write the content to the file
1138 if (!GeneralUtility::writeFile($realFileName, $fileContentString)) {
1139 throw new \RuntimeException(sprintf('Could not write file "%s"', $realFileName), 1294586444);
1140 }
1141 // Insert reference to the file in the rest content
1142 $restContent[] = '<INCLUDE_TYPOSCRIPT: source="FILE:' . $fileName . '"' . $optionalProperties . '>';
1143 } else {
1144 // must be DIR
1145
1146 // Some file checks
1147 if (empty($realFileName)) {
1148 throw new \UnexpectedValueException(sprintf('"%s" is not a valid location.', $fileName), 1366493602);
1149 }
1150 if (!is_dir($realFileName)) {
1151 throw new \RuntimeException(sprintf('"%s" is not a directory.', $fileName), 1366493603);
1152 }
1153 if (in_array($realFileName, $extractedFileNames)) {
1154 throw new \RuntimeException(sprintf('Recursive/multiple inclusion of directory "%s"', $realFileName), 1366493604);
1155 }
1156 $extractedFileNames[] = $realFileName;
1157
1158 // Recursive call to detected nested commented include statements
1159 self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName);
1160
1161 // just drop content between tags since it should usually just contain individual files from that dir
1162
1163 // Insert reference to the dir in the rest content
1164 $restContent[] = '<INCLUDE_TYPOSCRIPT: source="DIR:' . $fileName . '"' . $optionalProperties . '>';
1165 }
1166
1167 // Reset variables (preparing for the next commented include statement)
1168 $fileContent = [];
1169 $fileName = null;
1170 $inIncludePart = false;
1171 $openingCommentedIncludeStatement = null;
1172 // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts
1173 // an additional empty line, remove this again
1174 $skipNextLineIfEmpty = true;
1175 } else {
1176 // If this is not an ending commented include statement this line goes into the file content
1177 $fileContent[] = $line;
1178 }
1179 }
1180 }
1181 // If we're still inside commented include statements copy the lines back to the rest content
1182 if ($inIncludePart) {
1183 $restContent[] = $openingCommentedIncludeStatement . ' ### Warning: Corresponding end line missing! ###';
1184 $restContent = array_merge($restContent, $fileContent);
1185 }
1186 $restContentString = implode(PHP_EOL, $restContent);
1187 return $restContentString;
1188 }
1189
1190 /**
1191 * Processes the string in each value of the input array with extractIncludes
1192 *
1193 * @param array $array Array with TypoScript in each value
1194 * @return array Same array but where the values has been processed with extractIncludes
1195 */
1196 public static function extractIncludes_array(array $array)
1197 {
1198 foreach ($array as $k => $v) {
1199 $array[$k] = self::extractIncludes($array[$k]);
1200 }
1201 return $array;
1202 }
1203
1204 /**********************************
1205 *
1206 * Syntax highlighting
1207 *
1208 *********************************/
1209 /**
1210 * Syntax highlight a TypoScript text
1211 * Will parse the content. Remember, the internal setup array may contain invalid parsed content since conditions are ignored!
1212 *
1213 * @param string $string The TypoScript text
1214 * @param mixed $lineNum If blank, linenumbers are NOT printed. If array then the first key is the linenumber offset to add to the internal counter.
1215 * @param bool $highlightBlockMode If set, then the highlighted output will be formatted in blocks based on the brace levels. prespace will be ignored and empty lines represented with a single no-break-space.
1216 * @return string HTML code for the syntax highlighted string
1217 */
1218 public function doSyntaxHighlight($string, $lineNum = '', $highlightBlockMode = false)
1219 {
1220 $this->syntaxHighLight = 1;
1221 $this->highLightData = [];
1222 $this->errors = [];
1223 // This is done in order to prevent empty <span>..</span> sections around CR content. Should not do anything but help lessen the amount of HTML code.
1224 $string = str_replace(CR, '', $string);
1225 $this->parse($string);
1226 return $this->syntaxHighlight_print($lineNum, $highlightBlockMode);
1227 }
1228
1229 /**
1230 * Registers a part of a TypoScript line for syntax highlighting.
1231 *
1232 * @param string $code Key from the internal array $this->highLightStyles
1233 * @param int $pointer Pointer to the line in $this->raw which this is about
1234 * @param int $strlen The number of chars LEFT on this line before the end is reached.
1235 * @access private
1236 * @see parse()
1237 */
1238 public function regHighLight($code, $pointer, $strlen = -1)
1239 {
1240 if ($strlen === -1) {
1241 $this->highLightData[$pointer] = [[$code, 0]];
1242 } else {
1243 $this->highLightData[$pointer][] = [$code, $strlen];
1244 }
1245 $this->highLightData_bracelevel[$pointer] = $this->inBrace;
1246 }
1247
1248 /**
1249 * Formatting the TypoScript code in $this->raw based on the data collected by $this->regHighLight in $this->highLightData
1250 *
1251 * @param mixed $lineNumDat If blank, linenumbers are NOT printed. If array then the first key is the linenumber offset to add to the internal counter.
1252 * @param bool $highlightBlockMode If set, then the highlighted output will be formatted in blocks based on the brace levels. prespace will be ignored and empty lines represented with a single no-break-space.
1253 * @return string HTML content
1254 * @access private
1255 * @see doSyntaxHighlight()
1256 */
1257 public function syntaxHighlight_print($lineNumDat, $highlightBlockMode)
1258 {
1259 // Registers all error messages in relation to their linenumber
1260 $errA = [];
1261 foreach ($this->errors as $err) {
1262 $errA[$err[2]][] = $err[0];
1263 }
1264 // Generates the syntax highlighted output:
1265 $lines = [];
1266 foreach ($this->raw as $rawP => $value) {
1267 $start = 0;
1268 $strlen = strlen($value);
1269 $lineC = '';
1270 if (is_array($this->highLightData[$rawP])) {
1271 foreach ($this->highLightData[$rawP] as $set) {
1272 $len = $strlen - $start - $set[1];
1273 if ($len > 0) {
1274 $part = substr($value, $start, $len);
1275 $start += $len;
1276 $st = $this->highLightStyles[isset($this->highLightStyles[$set[0]]) ? $set[0] : 'default'];
1277 if (!$highlightBlockMode || $set[0] !== 'prespace') {
1278 $lineC .= $st[0] . htmlspecialchars($part) . $st[1];
1279 }
1280 } elseif ($len < 0) {
1281 debug([$len, $value, $rawP]);
1282 }
1283 }
1284 } else {
1285 debug([$value]);
1286 }
1287 if (strlen($value) > $start) {
1288 $lineC .= $this->highLightStyles['ignored'][0] . htmlspecialchars(substr($value, $start)) . $this->highLightStyles['ignored'][1];
1289 }
1290 if ($errA[$rawP]) {
1291 $lineC .= $this->highLightStyles['error'][0] . '<strong> - ERROR:</strong> ' . htmlspecialchars(implode(';', $errA[$rawP])) . $this->highLightStyles['error'][1];
1292 }
1293 if ($highlightBlockMode && $this->highLightData_bracelevel[$rawP]) {
1294 $lineC = str_pad('', $this->highLightData_bracelevel[$rawP] * 2, ' ', STR_PAD_LEFT) . '<span style="' . $this->highLightBlockStyles . ($this->highLightBlockStyles_basecolor ? 'background-color: ' . $this->modifyHTMLColorAll($this->highLightBlockStyles_basecolor, -$this->highLightData_bracelevel[$rawP] * 16) : '') . '">' . ($lineC !== '' ? $lineC : '&nbsp;') . '</span>';
1295 }
1296 if (is_array($lineNumDat)) {
1297 $lineNum = $rawP + $lineNumDat[0];
1298 if ($this->parentObject instanceof ExtendedTemplateService) {
1299 $lineNum = $this->parentObject->ext_lnBreakPointWrap($lineNum, $lineNum);
1300 }
1301 $lineC = $this->highLightStyles['linenum'][0] . str_pad($lineNum, 4, ' ', STR_PAD_LEFT) . ':' . $this->highLightStyles['linenum'][1] . ' ' . $lineC;
1302 }
1303 $lines[] = $lineC;
1304 }
1305 return '<pre class="ts-hl">' . implode(LF, $lines) . '</pre>';
1306 }
1307
1308 /**
1309 * @return TimeTracker
1310 */
1311 protected function getTimeTracker()
1312 {
1313 return GeneralUtility::makeInstance(TimeTracker::class);
1314 }
1315
1316 /**
1317 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
1318 *
1319 * @param string $color A hexadecimal color code, #xxxxxx
1320 * @param int $R Offset value 0-255
1321 * @param int $G Offset value 0-255
1322 * @param int $B Offset value 0-255
1323 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1324 * @see modifyHTMLColorAll()
1325 */
1326 protected function modifyHTMLColor($color, $R, $G, $B)
1327 {
1328 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
1329 $nR = MathUtility::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
1330 $nG = MathUtility::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
1331 $nB = MathUtility::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
1332 return '#' . substr(('0' . dechex($nR)), -2) . substr(('0' . dechex($nG)), -2) . substr(('0' . dechex($nB)), -2);
1333 }
1334
1335 /**
1336 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
1337 *
1338 * @param string $color A hexadecimal color code, #xxxxxx
1339 * @param int $all Offset value 0-255 for all three channels.
1340 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1341 * @see modifyHTMLColor()
1342 */
1343 protected function modifyHTMLColorAll($color, $all)
1344 {
1345 return $this->modifyHTMLColor($color, $all, $all, $all);
1346 }
1347 }