[TASK] Streamline return tags in phpdocs
[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 } else {
484 if (preg_match('|^\s*/[^/]|', $line)) {
485 $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': Single slash headed one-line comments are deprecated.', 2);
486 }
487 if ($this->syntaxHighLight) {
488 $this->regHighLight('comment', $lineP);
489 }
490 // Comment. The comments are concatenated in this temporary string:
491 if ($this->regComments) {
492 $this->lastComment .= rtrim($line) . LF;
493 }
494 }
495 if (strpos($line, '### ERROR') === 0) {
496 $this->error(substr($line, 11));
497 }
498 }
499 }
500 // Unset comment
501 if ($this->commentSet) {
502 if ($this->syntaxHighLight) {
503 $this->regHighLight('comment', $lineP);
504 }
505 if (strpos($line, '*/') === 0) {
506 $this->commentSet = 0;
507 }
508 }
509 }
510 return null;
511 }
512
513 /**
514 * Executes operator functions, called from TypoScript
515 * example: page.10.value := appendString(!)
516 *
517 * @param string $modifierName TypoScript function called
518 * @param string $modifierArgument Function arguments; In case of multiple arguments, the method must split on its own
519 * @param string $currentValue Current TypoScript value
520 * @return string Modification result
521 */
522 protected function executeValueModifier($modifierName, $modifierArgument = null, $currentValue = null)
523 {
524 $newValue = null;
525 switch ($modifierName) {
526 case 'prependString':
527 $newValue = $modifierArgument . $currentValue;
528 break;
529 case 'appendString':
530 $newValue = $currentValue . $modifierArgument;
531 break;
532 case 'removeString':
533 $newValue = str_replace($modifierArgument, '', $currentValue);
534 break;
535 case 'replaceString':
536 list($fromStr, $toStr) = explode('|', $modifierArgument, 2);
537 $newValue = str_replace($fromStr, $toStr, $currentValue);
538 break;
539 case 'addToList':
540 $newValue = ((string)$currentValue !== '' ? $currentValue . ',' : '') . $modifierArgument;
541 break;
542 case 'removeFromList':
543 $existingElements = GeneralUtility::trimExplode(',', $currentValue);
544 $removeElements = GeneralUtility::trimExplode(',', $modifierArgument);
545 if (!empty($removeElements)) {
546 $newValue = implode(',', array_diff($existingElements, $removeElements));
547 }
548 break;
549 case 'uniqueList':
550 $elements = GeneralUtility::trimExplode(',', $currentValue);
551 $newValue = implode(',', array_unique($elements));
552 break;
553 case 'reverseList':
554 $elements = GeneralUtility::trimExplode(',', $currentValue);
555 $newValue = implode(',', array_reverse($elements));
556 break;
557 case 'sortList':
558 $elements = GeneralUtility::trimExplode(',', $currentValue);
559 $arguments = GeneralUtility::trimExplode(',', $modifierArgument);
560 $arguments = array_map('strtolower', $arguments);
561 $sort_flags = SORT_REGULAR;
562 if (in_array('numeric', $arguments)) {
563 $sort_flags = SORT_NUMERIC;
564 // If the sorting modifier "numeric" is given, all values
565 // are checked and an exception is thrown if a non-numeric value is given
566 // otherwise there is a different behaviour between PHP7 and PHP 5.x
567 // See also the warning on http://us.php.net/manual/en/function.sort.php
568 foreach ($elements as $element) {
569 if (!is_numeric($element)) {
570 throw new \InvalidArgumentException('The list "' . $currentValue . '" should be sorted numerically but contains a non-numeric value', 1438191758);
571 }
572 }
573 }
574 sort($elements, $sort_flags);
575 if (in_array('descending', $arguments)) {
576 $elements = array_reverse($elements);
577 }
578 $newValue = implode(',', $elements);
579 break;
580 default:
581 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$modifierName])) {
582 $hookMethod = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$modifierName];
583 $params = ['currentValue' => $currentValue, 'functionArgument' => $modifierArgument];
584 $fakeThis = false;
585 $newValue = GeneralUtility::callUserFunction($hookMethod, $params, $fakeThis);
586 } else {
587 GeneralUtility::sysLog(
588 'Missing function definition for ' . $modifierName . ' on TypoScript',
589 'core',
590 GeneralUtility::SYSLOG_SEVERITY_WARNING
591 );
592 }
593 }
594 return $newValue;
595 }
596
597 /**
598 * Parsing of TypoScript keys inside a curly brace where the key is composite of at least two keys,
599 * thus having to recursively call itself to get the value
600 *
601 * @param string $string The object sub-path, eg "thisprop.another_prot
602 * @param array $setup The local setup array from the function calling this function
603 * @return string Returns the exitSignal
604 * @see parseSub()
605 */
606 public function rollParseSub($string, array &$setup)
607 {
608 if ((string)$string === '') {
609 return '';
610 }
611
612 list($key, $remainingKey) = $this->parseNextKeySegment($string);
613 $key .= '.';
614 if (!isset($setup[$key])) {
615 $setup[$key] = [];
616 }
617 $exitSig = $remainingKey === ''
618 ? $this->parseSub($setup[$key])
619 : $this->rollParseSub($remainingKey, $setup[$key]);
620 return $exitSig ?: '';
621 }
622
623 /**
624 * Get a value/property pair for an object path in TypoScript, eg. "myobject.myvalue.mysubproperty".
625 * Here: Used by the "copy" operator, <
626 *
627 * @param string $string Object path for which to get the value
628 * @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.
629 * @return array An array with keys 0/1 being value/property respectively
630 */
631 public function getVal($string, $setup)
632 {
633 if ((string)$string === '') {
634 return [];
635 }
636
637 list($key, $remainingKey) = $this->parseNextKeySegment($string);
638 $subKey = $key . '.';
639 if ($remainingKey === '') {
640 $retArr = [];
641 if (isset($setup[$key])) {
642 $retArr[0] = $setup[$key];
643 }
644 if (isset($setup[$subKey])) {
645 $retArr[1] = $setup[$subKey];
646 }
647 return $retArr;
648 } else {
649 if ($setup[$subKey]) {
650 return $this->getVal($remainingKey, $setup[$subKey]);
651 }
652 }
653 return [];
654 }
655
656 /**
657 * Setting a value/property of an object string in the setup array.
658 *
659 * @param string $string The object sub-path, eg "thisprop.another_prot
660 * @param array $setup The local setup array from the function calling this function.
661 * @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)
662 * @param bool $wipeOut If set, then both value and property is wiped out when a copy is made of another value.
663 */
664 public function setVal($string, array &$setup, $value, $wipeOut = false)
665 {
666 if ((string)$string === '') {
667 return;
668 }
669
670 list($key, $remainingKey) = $this->parseNextKeySegment($string);
671 $subKey = $key . '.';
672 if ($remainingKey === '') {
673 if ($value === 'UNSET') {
674 unset($setup[$key]);
675 unset($setup[$subKey]);
676 if ($this->regLinenumbers) {
677 $setup[$key . '.ln..'][] = ($this->lineNumberOffset + $this->rawP - 1) . '>';
678 }
679 } else {
680 $lnRegisDone = 0;
681 if ($wipeOut) {
682 unset($setup[$key]);
683 unset($setup[$subKey]);
684 if ($this->regLinenumbers) {
685 $setup[$key . '.ln..'][] = ($this->lineNumberOffset + $this->rawP - 1) . '<';
686 $lnRegisDone = 1;
687 }
688 }
689 if (isset($value[0])) {
690 $setup[$key] = $value[0];
691 }
692 if (isset($value[1])) {
693 $setup[$subKey] = $value[1];
694 }
695 if ($this->lastComment && $this->regComments) {
696 $setup[$key . '..'] .= $this->lastComment;
697 }
698 if ($this->regLinenumbers && !$lnRegisDone) {
699 $setup[$key . '.ln..'][] = $this->lineNumberOffset + $this->rawP - 1;
700 }
701 }
702 } else {
703 if (!isset($setup[$subKey])) {
704 $setup[$subKey] = [];
705 }
706 $this->setVal($remainingKey, $setup[$subKey], $value);
707 }
708 }
709
710 /**
711 * Determines the first key segment of a TypoScript key by searching for the first
712 * unescaped dot in the given key string.
713 *
714 * Since the escape characters are only needed to correctly determine the key
715 * segment any escape characters before the first unescaped dot are
716 * stripped from the key.
717 *
718 * @param string $key The key, possibly consisting of multiple key segments separated by unescaped dots
719 * @return array Array with key segment and remaining part of $key
720 */
721 protected function parseNextKeySegment($key)
722 {
723 // if no dot is in the key, nothing to do
724 $dotPosition = strpos($key, '.');
725 if ($dotPosition === false) {
726 return [$key, ''];
727 }
728
729 if (strpos($key, '\\') !== false) {
730 // backslashes are in the key, so we do further parsing
731
732 while ($dotPosition !== false) {
733 if ($dotPosition > 0 && $key[$dotPosition - 1] !== '\\' || $dotPosition > 1 && $key[$dotPosition - 2] === '\\') {
734 break;
735 }
736 // escaped dot found, continue
737 $dotPosition = strpos($key, '.', $dotPosition + 1);
738 }
739
740 if ($dotPosition === false) {
741 // no regular dot found
742 $keySegment = $key;
743 $remainingKey = '';
744 } else {
745 if ($dotPosition > 1 && $key[$dotPosition - 2] === '\\' && $key[$dotPosition - 1] === '\\') {
746 $keySegment = substr($key, 0, $dotPosition - 1);
747 } else {
748 $keySegment = substr($key, 0, $dotPosition);
749 }
750 $remainingKey = substr($key, $dotPosition + 1);
751 }
752
753 // fix key segment by removing escape sequences
754 $keySegment = str_replace('\\.', '.', $keySegment);
755 } else {
756 // no backslash in the key, we're fine off
757 list($keySegment, $remainingKey) = explode('.', $key, 2);
758 }
759 return [$keySegment, $remainingKey];
760 }
761
762 /**
763 * Stacks errors/messages from the TypoScript parser into an internal array, $this->error
764 * 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.
765 *
766 * @param string $err The error message string
767 * @param int $num The error severity (in the scale of TimeTracker::setTSlogMessage: Approx: 2=warning, 1=info, 0=nothing, 3=fatal.)
768 */
769 public function error($err, $num = 2)
770 {
771 $tt = $this->getTimeTracker();
772 if ($tt !== null) {
773 $tt->setTSlogMessage($err, $num);
774 }
775 $this->errors[] = [$err, $num, $this->rawP - 1, $this->lineNumberOffset];
776 }
777
778 /**
779 * Checks the input string (un-parsed TypoScript) for include-commands ("<INCLUDE_TYPOSCRIPT: ....")
780 * Use: \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines()
781 *
782 * @param string $string Unparsed TypoScript
783 * @param int $cycle_counter Counter for detecting endless loops
784 * @param bool $returnFiles When set an array containing the resulting typoscript and all included files will get returned
785 * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes
786 * @return string Complete TypoScript with includes added.
787 * @static
788 */
789 public static function checkIncludeLines($string, $cycle_counter = 1, $returnFiles = false, $parentFilenameOrPath = '')
790 {
791 $includedFiles = [];
792 if ($cycle_counter > 100) {
793 GeneralUtility::sysLog('It appears like TypoScript code is looping over itself. Check your templates for "&lt;INCLUDE_TYPOSCRIPT: ..." tags', 'core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
794 if ($returnFiles) {
795 return [
796 'typoscript' => '',
797 'files' => $includedFiles
798 ];
799 }
800 return '
801 ###
802 ### ERROR: Recursion!
803 ###
804 ';
805 }
806
807 // If no tags found, no need to do slower preg_split
808 if (strpos($string, '<INCLUDE_TYPOSCRIPT:') !== false) {
809 $splitRegEx = '/\r?\n\s*<INCLUDE_TYPOSCRIPT:\s*(?i)source\s*=\s*"((?i)file|dir):\s*([^"]*)"(.*)>[\ \t]*/';
810 $parts = preg_split($splitRegEx, LF . $string . LF, -1, PREG_SPLIT_DELIM_CAPTURE);
811 // First text part goes through
812 $newString = $parts[0] . LF;
813 $partCount = count($parts);
814 for ($i = 1; $i + 3 < $partCount; $i += 4) {
815 // $parts[$i] contains 'FILE' or 'DIR'
816 // $parts[$i+1] contains relative file or directory path to be included
817 // $parts[$i+2] optional properties of the INCLUDE statement
818 // $parts[$i+3] next part of the typoscript string (part in between include-tags)
819 $includeType = $parts[$i];
820 $filename = $parts[$i + 1];
821 $originalFilename = $filename;
822 $optionalProperties = $parts[$i + 2];
823 $tsContentsTillNextInclude = $parts[$i + 3];
824
825 // Check condition
826 $matches = preg_split('#(?i)condition\\s*=\\s*"((?:\\\\\\\\|\\\\"|[^\\"])*)"(\\s*|>)#', $optionalProperties, 2, PREG_SPLIT_DELIM_CAPTURE);
827 // If there was a condition
828 if (count($matches) > 1) {
829 // Unescape the condition
830 $condition = trim(stripslashes($matches[1]));
831 // If necessary put condition in square brackets
832 if ($condition[0] !== '[') {
833 $condition = '[' . $condition . ']';
834 }
835 /** @var ConditionMatcher $conditionMatcher */
836 $conditionMatcher = GeneralUtility::makeInstance(ConditionMatcher::class);
837 // If it didn't match then proceed to the next include, but prepend next normal (not file) part to output string
838 if (!$conditionMatcher->match($condition)) {
839 $newString .= $tsContentsTillNextInclude . LF;
840 continue;
841 }
842 }
843
844 // Resolve a possible relative paths if a parent file is given
845 if ($parentFilenameOrPath !== '' && $filename[0] === '.') {
846 $filename = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $filename);
847 }
848
849 // There must be a line-break char after - not sure why this check is necessary, kept it for being 100% backwards compatible
850 // An empty string is also ok (means that the next line is also a valid include_typoscript tag)
851 if (!preg_match('/(^\\s*\\r?\\n|^$)/', $tsContentsTillNextInclude)) {
852 $newString .= self::typoscriptIncludeError('Invalid characters after <INCLUDE_TYPOSCRIPT: source="' . $includeType . ':' . $filename . '">-tag (rest of line must be empty).');
853 } elseif (strpos('..', $filename) !== false) {
854 $newString .= self::typoscriptIncludeError('Invalid filepath "' . $filename . '" (containing "..").');
855 } else {
856 switch (strtolower($includeType)) {
857 case 'file':
858 self::includeFile($originalFilename, $cycle_counter, $returnFiles, $newString, $includedFiles, $optionalProperties, $parentFilenameOrPath);
859 break;
860 case 'dir':
861 self::includeDirectory($originalFilename, $cycle_counter, $returnFiles, $newString, $includedFiles, $optionalProperties, $parentFilenameOrPath);
862 break;
863 default:
864 $newString .= self::typoscriptIncludeError('No valid option for INCLUDE_TYPOSCRIPT source property (valid options are FILE or DIR)');
865 }
866 }
867 // Prepend next normal (not file) part to output string
868 $newString .= $tsContentsTillNextInclude . LF;
869
870 // load default TypoScript for content rendering templates like
871 // css_styled_content if those have been included through f.e.
872 // <INCLUDE_TYPOSCRIPT: source="FILE:EXT:css_styled_content/static/setup.txt">
873 if (strpos(strtolower($filename), 'ext:') === 0) {
874 $filePointerPathParts = explode('/', substr($filename, 4));
875
876 // remove file part, determine whether to load setup or constants
877 list($includeType, ) = explode('.', array_pop($filePointerPathParts));
878
879 if (in_array($includeType, ['setup', 'constants'])) {
880 // adapt extension key to required format (no underscores)
881 $filePointerPathParts[0] = str_replace('_', '', $filePointerPathParts[0]);
882
883 // load default TypoScript
884 $defaultTypoScriptKey = implode('/', $filePointerPathParts) . '/';
885 if (in_array($defaultTypoScriptKey, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
886 $newString .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $includeType . '.']['defaultContentRendering'];
887 }
888 }
889 }
890 }
891 // Add a line break before and after the included code in order to make sure that the parser always has a LF.
892 $string = LF . trim($newString) . LF;
893 }
894 // When all included files should get returned, simply return an compound array containing
895 // the TypoScript with all "includes" processed and the files which got included
896 if ($returnFiles) {
897 return [
898 'typoscript' => $string,
899 'files' => $includedFiles
900 ];
901 }
902 return $string;
903 }
904
905 /**
906 * Include file $filename. Contents of the file will be prepended to &$newstring, filename to &$includedFiles
907 * Further include_typoscript tags in the contents are processed recursively
908 *
909 * @param string $filename Relative path to the typoscript file to be included
910 * @param int $cycle_counter Counter for detecting endless loops
911 * @param bool $returnFiles When set, filenames of included files will be prepended to the array &$includedFiles
912 * @param string &$newString The output string to which the content of the file will be prepended (referenced
913 * @param array &$includedFiles Array to which the filenames of included files will be prepended (referenced)
914 * @param string $optionalProperties
915 * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes
916 * @static
917 */
918 public static function includeFile($filename, $cycle_counter = 1, $returnFiles = false, &$newString = '', array &$includedFiles = [], $optionalProperties = '', $parentFilenameOrPath = '')
919 {
920 // Resolve a possible relative paths if a parent file is given
921 if ($parentFilenameOrPath !== '' && $filename[0] === '.') {
922 $absfilename = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $filename);
923 } else {
924 $absfilename = $filename;
925 }
926 $absfilename = GeneralUtility::getFileAbsFileName($absfilename);
927
928 $newString .= LF . '### <INCLUDE_TYPOSCRIPT: source="FILE:' . $filename . '"' . $optionalProperties . '> BEGIN:' . LF;
929 if ((string)$filename !== '') {
930 // Must exist and must not contain '..' and must be relative
931 // Check for allowed files
932 if (!GeneralUtility::verifyFilenameAgainstDenyPattern($absfilename)) {
933 $newString .= self::typoscriptIncludeError('File "' . $filename . '" was not included since it is not allowed due to fileDenyPattern.');
934 } elseif (!@file_exists($absfilename)) {
935 $newString .= self::typoscriptIncludeError('File "' . $filename . '" was not found.');
936 } else {
937 $includedFiles[] = $absfilename;
938 // check for includes in included text
939 $included_text = self::checkIncludeLines(file_get_contents($absfilename), $cycle_counter + 1, $returnFiles, $absfilename);
940 // If the method also has to return all included files, merge currently included
941 // files with files included by recursively calling itself
942 if ($returnFiles && is_array($included_text)) {
943 $includedFiles = array_merge($includedFiles, $included_text['files']);
944 $included_text = $included_text['typoscript'];
945 }
946 $newString .= $included_text . LF;
947 }
948 }
949 $newString .= '### <INCLUDE_TYPOSCRIPT: source="FILE:' . $filename . '"' . $optionalProperties . '> END:' . LF . LF;
950 }
951
952 /**
953 * Include all files with matching Typoscript extensions in directory $dirPath. Contents of the files are
954 * prepended to &$newstring, filename to &$includedFiles.
955 * Order of the directory items to be processed: files first, then directories, both in alphabetical order.
956 * Further include_typoscript tags in the contents of the files are processed recursively.
957 *
958 * @param string $dirPath Relative path to the directory to be included
959 * @param int $cycle_counter Counter for detecting endless loops
960 * @param bool $returnFiles When set, filenames of included files will be prepended to the array &$includedFiles
961 * @param string &$newString The output string to which the content of the file will be prepended (referenced)
962 * @param array &$includedFiles Array to which the filenames of included files will be prepended (referenced)
963 * @param string $optionalProperties
964 * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes
965 * @static
966 */
967 protected static function includeDirectory($dirPath, $cycle_counter = 1, $returnFiles = false, &$newString = '', array &$includedFiles = [], $optionalProperties = '', $parentFilenameOrPath = '')
968 {
969 // Extract the value of the property extensions="..."
970 $matches = preg_split('#(?i)extensions\s*=\s*"([^"]*)"(\s*|>)#', $optionalProperties, 2, PREG_SPLIT_DELIM_CAPTURE);
971 if (count($matches) > 1) {
972 $includedFileExtensions = $matches[1];
973 } else {
974 $includedFileExtensions = '';
975 }
976
977 // Resolve a possible relative paths if a parent file is given
978 if ($parentFilenameOrPath !== '' && $dirPath[0] === '.') {
979 $resolvedDirPath = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $dirPath);
980 } else {
981 $resolvedDirPath = $dirPath;
982 }
983 $absDirPath = GeneralUtility::getFileAbsFileName($resolvedDirPath);
984 if ($absDirPath) {
985 $absDirPath = rtrim($absDirPath, '/') . '/';
986 $newString .= LF . '### <INCLUDE_TYPOSCRIPT: source="DIR:' . $dirPath . '"' . $optionalProperties . '> BEGIN:' . LF;
987 // Get alphabetically sorted file index in array
988 $fileIndex = GeneralUtility::getAllFilesAndFoldersInPath([], $absDirPath, $includedFileExtensions);
989 // Prepend file contents to $newString
990 $prefixLength = strlen(PATH_site);
991 foreach ($fileIndex as $absFileRef) {
992 $relFileRef = substr($absFileRef, $prefixLength);
993 self::includeFile($relFileRef, $cycle_counter, $returnFiles, $newString, $includedFiles, '', $absDirPath);
994 }
995 $newString .= '### <INCLUDE_TYPOSCRIPT: source="DIR:' . $dirPath . '"' . $optionalProperties . '> END:' . LF . LF;
996 } else {
997 $newString .= self::typoscriptIncludeError('The path "' . $resolvedDirPath . '" is invalid.');
998 }
999 }
1000
1001 /**
1002 * Process errors in INCLUDE_TYPOSCRIPT tags
1003 * Errors are logged in sysLog and printed in the concatenated Typoscript result (as can be seen in Template Analyzer)
1004 *
1005 * @param string $error Text of the error message
1006 * @return string The error message encapsulated in comments
1007 * @static
1008 */
1009 protected static function typoscriptIncludeError($error)
1010 {
1011 GeneralUtility::sysLog($error, 'core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
1012 return "\n###\n### ERROR: " . $error . "\n###\n\n";
1013 }
1014
1015 /**
1016 * Parses the string in each value of the input array for include-commands
1017 *
1018 * @param array $array Array with TypoScript in each value
1019 * @return array Same array but where the values has been parsed for include-commands
1020 */
1021 public static function checkIncludeLines_array(array $array)
1022 {
1023 foreach ($array as $k => $v) {
1024 $array[$k] = self::checkIncludeLines($array[$k]);
1025 }
1026 return $array;
1027 }
1028
1029 /**
1030 * Search for commented INCLUDE_TYPOSCRIPT statements
1031 * and save the content between the BEGIN and the END line to the specified file
1032 *
1033 * @param string $string Template content
1034 * @param int $cycle_counter Counter for detecting endless loops
1035 * @param array $extractedFileNames
1036 * @param string $parentFilenameOrPath
1037 *
1038 * @throws \RuntimeException
1039 * @throws \UnexpectedValueException
1040 * @return string Template content with uncommented include statements
1041 */
1042 public static function extractIncludes($string, $cycle_counter = 1, array $extractedFileNames = [], $parentFilenameOrPath = '')
1043 {
1044 if ($cycle_counter > 10) {
1045 GeneralUtility::sysLog('It appears like TypoScript code is looping over itself. Check your templates for "&lt;INCLUDE_TYPOSCRIPT: ..." tags', 'core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
1046 return '
1047 ###
1048 ### ERROR: Recursion!
1049 ###
1050 ';
1051 }
1052 $expectedEndTag = '';
1053 $fileContent = [];
1054 $restContent = [];
1055 $fileName = null;
1056 $inIncludePart = false;
1057 $lines = preg_split("/\r\n|\n|\r/", $string);
1058 $skipNextLineIfEmpty = false;
1059 $openingCommentedIncludeStatement = null;
1060 $optionalProperties = '';
1061 foreach ($lines as $line) {
1062 // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts
1063 // an additional empty line, remove this again
1064 if ($skipNextLineIfEmpty) {
1065 if (trim($line) === '') {
1066 continue;
1067 }
1068 $skipNextLineIfEmpty = false;
1069 }
1070
1071 // Outside commented include statements
1072 if (!$inIncludePart) {
1073 // Search for beginning commented include statements
1074 if (preg_match('/###\\s*<INCLUDE_TYPOSCRIPT:\\s*source\\s*=\\s*"\\s*((?i)file|dir)\\s*:\\s*([^"]*)"(.*)>\\s*BEGIN/i', $line, $matches)) {
1075 // Found a commented include statement
1076
1077 // Save this line in case there is no ending tag
1078 $openingCommentedIncludeStatement = trim($line);
1079 $openingCommentedIncludeStatement = preg_replace('/\\s*### Warning: .*###\\s*/', '', $openingCommentedIncludeStatement);
1080
1081 // type of match: FILE or DIR
1082 $inIncludePart = strtoupper($matches[1]);
1083 $fileName = $matches[2];
1084 $optionalProperties = $matches[3];
1085
1086 $expectedEndTag = '### <INCLUDE_TYPOSCRIPT: source="' . $inIncludePart . ':' . $fileName . '"' . $optionalProperties . '> END';
1087 // Strip all whitespace characters to make comparison safer
1088 $expectedEndTag = strtolower(preg_replace('/\s/', '', $expectedEndTag));
1089 } else {
1090 // If this is not a beginning commented include statement this line goes into the rest content
1091 $restContent[] = $line;
1092 }
1093 //if (is_array($matches)) GeneralUtility::devLog('matches', 'TypoScriptParser', 0, $matches);
1094 } else {
1095 // Inside commented include statements
1096 // Search for the matching ending commented include statement
1097 $strippedLine = preg_replace('/\s/', '', $line);
1098 if (stripos($strippedLine, $expectedEndTag) !== false) {
1099 // Found the matching ending include statement
1100 $fileContentString = implode(PHP_EOL, $fileContent);
1101
1102 // Write the content to the file
1103
1104 // Resolve a possible relative paths if a parent file is given
1105 if ($parentFilenameOrPath !== '' && $fileName[0] === '.') {
1106 $realFileName = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $fileName);
1107 } else {
1108 $realFileName = $fileName;
1109 }
1110 $realFileName = GeneralUtility::getFileAbsFileName($realFileName);
1111
1112 if ($inIncludePart === 'FILE') {
1113 // Some file checks
1114 if (!GeneralUtility::verifyFilenameAgainstDenyPattern($realFileName)) {
1115 throw new \UnexpectedValueException(sprintf('File "%s" was not included since it is not allowed due to fileDenyPattern.', $fileName), 1382651858);
1116 }
1117 if (empty($realFileName)) {
1118 throw new \UnexpectedValueException(sprintf('"%s" is not a valid file location.', $fileName), 1294586441);
1119 }
1120 if (!is_writable($realFileName)) {
1121 throw new \RuntimeException(sprintf('"%s" is not writable.', $fileName), 1294586442);
1122 }
1123 if (in_array($realFileName, $extractedFileNames)) {
1124 throw new \RuntimeException(sprintf('Recursive/multiple inclusion of file "%s"', $realFileName), 1294586443);
1125 }
1126 $extractedFileNames[] = $realFileName;
1127
1128 // Recursive call to detected nested commented include statements
1129 $fileContentString = self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName);
1130
1131 // Write the content to the file
1132 if (!GeneralUtility::writeFile($realFileName, $fileContentString)) {
1133 throw new \RuntimeException(sprintf('Could not write file "%s"', $realFileName), 1294586444);
1134 }
1135 // Insert reference to the file in the rest content
1136 $restContent[] = '<INCLUDE_TYPOSCRIPT: source="FILE:' . $fileName . '"' . $optionalProperties . '>';
1137 } else {
1138 // must be DIR
1139
1140 // Some file checks
1141 if (empty($realFileName)) {
1142 throw new \UnexpectedValueException(sprintf('"%s" is not a valid location.', $fileName), 1366493602);
1143 }
1144 if (!is_dir($realFileName)) {
1145 throw new \RuntimeException(sprintf('"%s" is not a directory.', $fileName), 1366493603);
1146 }
1147 if (in_array($realFileName, $extractedFileNames)) {
1148 throw new \RuntimeException(sprintf('Recursive/multiple inclusion of directory "%s"', $realFileName), 1366493604);
1149 }
1150 $extractedFileNames[] = $realFileName;
1151
1152 // Recursive call to detected nested commented include statements
1153 self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName);
1154
1155 // just drop content between tags since it should usually just contain individual files from that dir
1156
1157 // Insert reference to the dir in the rest content
1158 $restContent[] = '<INCLUDE_TYPOSCRIPT: source="DIR:' . $fileName . '"' . $optionalProperties . '>';
1159 }
1160
1161 // Reset variables (preparing for the next commented include statement)
1162 $fileContent = [];
1163 $fileName = null;
1164 $inIncludePart = false;
1165 $openingCommentedIncludeStatement = null;
1166 // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts
1167 // an additional empty line, remove this again
1168 $skipNextLineIfEmpty = true;
1169 } else {
1170 // If this is not an ending commented include statement this line goes into the file content
1171 $fileContent[] = $line;
1172 }
1173 }
1174 }
1175 // If we're still inside commented include statements copy the lines back to the rest content
1176 if ($inIncludePart) {
1177 $restContent[] = $openingCommentedIncludeStatement . ' ### Warning: Corresponding end line missing! ###';
1178 $restContent = array_merge($restContent, $fileContent);
1179 }
1180 $restContentString = implode(PHP_EOL, $restContent);
1181 return $restContentString;
1182 }
1183
1184 /**
1185 * Processes the string in each value of the input array with extractIncludes
1186 *
1187 * @param array $array Array with TypoScript in each value
1188 * @return array Same array but where the values has been processed with extractIncludes
1189 */
1190 public static function extractIncludes_array(array $array)
1191 {
1192 foreach ($array as $k => $v) {
1193 $array[$k] = self::extractIncludes($array[$k]);
1194 }
1195 return $array;
1196 }
1197
1198 /**********************************
1199 *
1200 * Syntax highlighting
1201 *
1202 *********************************/
1203 /**
1204 * Syntax highlight a TypoScript text
1205 * Will parse the content. Remember, the internal setup array may contain invalid parsed content since conditions are ignored!
1206 *
1207 * @param string $string The TypoScript text
1208 * @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.
1209 * @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.
1210 * @return string HTML code for the syntax highlighted string
1211 */
1212 public function doSyntaxHighlight($string, $lineNum = '', $highlightBlockMode = false)
1213 {
1214 $this->syntaxHighLight = 1;
1215 $this->highLightData = [];
1216 $this->errors = [];
1217 // 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.
1218 $string = str_replace(CR, '', $string);
1219 $this->parse($string);
1220 return $this->syntaxHighlight_print($lineNum, $highlightBlockMode);
1221 }
1222
1223 /**
1224 * Registers a part of a TypoScript line for syntax highlighting.
1225 *
1226 * @param string $code Key from the internal array $this->highLightStyles
1227 * @param int $pointer Pointer to the line in $this->raw which this is about
1228 * @param int $strlen The number of chars LEFT on this line before the end is reached.
1229 * @access private
1230 * @see parse()
1231 */
1232 public function regHighLight($code, $pointer, $strlen = -1)
1233 {
1234 if ($strlen === -1) {
1235 $this->highLightData[$pointer] = [[$code, 0]];
1236 } else {
1237 $this->highLightData[$pointer][] = [$code, $strlen];
1238 }
1239 $this->highLightData_bracelevel[$pointer] = $this->inBrace;
1240 }
1241
1242 /**
1243 * Formatting the TypoScript code in $this->raw based on the data collected by $this->regHighLight in $this->highLightData
1244 *
1245 * @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.
1246 * @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.
1247 * @return string HTML content
1248 * @access private
1249 * @see doSyntaxHighlight()
1250 */
1251 public function syntaxHighlight_print($lineNumDat, $highlightBlockMode)
1252 {
1253 // Registers all error messages in relation to their linenumber
1254 $errA = [];
1255 foreach ($this->errors as $err) {
1256 $errA[$err[2]][] = $err[0];
1257 }
1258 // Generates the syntax highlighted output:
1259 $lines = [];
1260 foreach ($this->raw as $rawP => $value) {
1261 $start = 0;
1262 $strlen = strlen($value);
1263 $lineC = '';
1264 if (is_array($this->highLightData[$rawP])) {
1265 foreach ($this->highLightData[$rawP] as $set) {
1266 $len = $strlen - $start - $set[1];
1267 if ($len > 0) {
1268 $part = substr($value, $start, $len);
1269 $start += $len;
1270 $st = $this->highLightStyles[isset($this->highLightStyles[$set[0]]) ? $set[0] : 'default'];
1271 if (!$highlightBlockMode || $set[0] !== 'prespace') {
1272 $lineC .= $st[0] . htmlspecialchars($part) . $st[1];
1273 }
1274 } elseif ($len < 0) {
1275 debug([$len, $value, $rawP]);
1276 }
1277 }
1278 } else {
1279 debug([$value]);
1280 }
1281 if (strlen($value) > $start) {
1282 $lineC .= $this->highLightStyles['ignored'][0] . htmlspecialchars(substr($value, $start)) . $this->highLightStyles['ignored'][1];
1283 }
1284 if ($errA[$rawP]) {
1285 $lineC .= $this->highLightStyles['error'][0] . '<strong> - ERROR:</strong> ' . htmlspecialchars(implode(';', $errA[$rawP])) . $this->highLightStyles['error'][1];
1286 }
1287 if ($highlightBlockMode && $this->highLightData_bracelevel[$rawP]) {
1288 $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>';
1289 }
1290 if (is_array($lineNumDat)) {
1291 $lineNum = $rawP + $lineNumDat[0];
1292 if ($this->parentObject instanceof ExtendedTemplateService) {
1293 $lineNum = $this->parentObject->ext_lnBreakPointWrap($lineNum, $lineNum);
1294 }
1295 $lineC = $this->highLightStyles['linenum'][0] . str_pad($lineNum, 4, ' ', STR_PAD_LEFT) . ':' . $this->highLightStyles['linenum'][1] . ' ' . $lineC;
1296 }
1297 $lines[] = $lineC;
1298 }
1299 return '<pre class="ts-hl">' . implode(LF, $lines) . '</pre>';
1300 }
1301
1302 /**
1303 * @return TimeTracker
1304 */
1305 protected function getTimeTracker()
1306 {
1307 return GeneralUtility::makeInstance(TimeTracker::class);
1308 }
1309
1310 /**
1311 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
1312 *
1313 * @param string $color A hexadecimal color code, #xxxxxx
1314 * @param int $R Offset value 0-255
1315 * @param int $G Offset value 0-255
1316 * @param int $B Offset value 0-255
1317 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1318 * @see modifyHTMLColorAll()
1319 */
1320 protected function modifyHTMLColor($color, $R, $G, $B)
1321 {
1322 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
1323 $nR = MathUtility::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
1324 $nG = MathUtility::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
1325 $nB = MathUtility::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
1326 return '#' . substr(('0' . dechex($nR)), -2) . substr(('0' . dechex($nG)), -2) . substr(('0' . dechex($nB)), -2);
1327 }
1328
1329 /**
1330 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
1331 *
1332 * @param string $color A hexadecimal color code, #xxxxxx
1333 * @param int $all Offset value 0-255 for all three channels.
1334 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1335 * @see modifyHTMLColor()
1336 */
1337 protected function modifyHTMLColorAll($color, $all)
1338 {
1339 return $this->modifyHTMLColor($color, $all, $all, $all);
1340 }
1341 }