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