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