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