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