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