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