(minor) Fixed bug #6138: Prevent recursive inclusion of external TypoScript files...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tsparser.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains the TypoScript parser class
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 80: class t3lib_TSparser
41 * 133: function parse($string,$matchObj='')
42 * 169: function nextDivider()
43 * 185: function parseSub(&$setup)
44 * 389: function rollParseSub($string,&$setup)
45 * 413: function getVal($string,$setup)
46 * 439: function setVal($string,&$setup,$value,$wipeOut=0)
47 * 485: function error($err,$num=2)
48 * 497: function checkIncludeLines($string)
49 * 541: function checkIncludeLines_array($array)
50 *
51 * SECTION: Syntax highlighting
52 * 584: function doSyntaxHighlight($string,$lineNum='',$highlightBlockMode=0)
53 * 605: function regHighLight($code,$pointer,$strlen=-1)
54 * 623: function syntaxHighlight_print($lineNumDat,$highlightBlockMode)
55 *
56 * TOTAL FUNCTIONS: 12
57 * (This index is automatically created/updated by the extension "extdeveval")
58 *
59 */
60
61
62
63
64
65
66
67
68
69
70
71
72 /**
73 * The TypoScript parser
74 *
75 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
76 * @package TYPO3
77 * @subpackage t3lib
78 * @see t3lib_tstemplate, t3lib_matchcondition, t3lib_BEfunc::getPagesTSconfig(), t3lib_userAuthGroup::fetchGroupData(), t3lib_TStemplate::generateConfig()
79 */
80 class t3lib_TSparser {
81 var $strict = 1; // If set, then key names cannot contain characters other than [:alnum:]_\.-
82
83 // Internal
84 var $setup = Array(); // TypoScript hierarchy being build during parsing.
85 var $raw; // raw data, the input string exploded by chr(10)
86 var $rawP; // pointer to entry in raw data array
87 var $lastComment=''; // Holding the value of the last comment
88 var $commentSet=0; // Internally set, used as internal flag to create a multi-line comment (one of those like /*... */)
89 var $multiLineEnabled=0; // Internally set, when multiline value is accumulated
90 var $multiLineObject=''; // Internally set, when multiline value is accumulated
91 var $multiLineValue=array(); // Internally set, when multiline value is accumulated
92 var $inBrace = 0; // Internally set, when in brace. Counter.
93 var $lastConditionTrue = 1; // 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.
94 var $sections=array(); // Tracking all conditions found
95 var $sectionsMatch=array(); // Tracking all matching conditions found
96 var $syntaxHighLight = 0; // If set, then syntax highlight mode is on; Call the function syntaxHighlight() to use this function
97 var $highLightData=array(); // Syntax highlight data is accumulated in this array. Used by syntaxHighlight_print() to construct the output.
98 var $highLightData_bracelevel = array(); // Syntax highlight data keeping track of the curly brace level for each line
99 var $includedFiles = array(); // Keeps track of the TypoScript files that were included by e.g. <INCLUDE_TYPOSCRIPT: source="FILE:include.ts">
100
101 // Debugging, analysis:
102 var $regComments = 0; // DO NOT register the comments. This is default for the ordinary sitetemplate!
103 var $regLinenumbers = 0; // DO NOT register the linenumbers. This is default for the ordinary sitetemplate!
104 var $errors=array(); // Error accumulation array.
105 var $lineNumberOffset=0; // Used for the error messages line number reporting. Set externally.
106 var $breakPointLN=0; // Line for break point.
107 var $highLightStyles=array(
108 'prespace' => array('<span class="ts-prespace">','</span>'), // Space before any content on a line
109 'objstr_postspace' => array('<span class="ts-objstr_postspace">','</span>'), // Space after the object string on a line
110 'operator_postspace' => array('<span class="ts-operator_postspace">','</span>'), // Space after the operator on a line
111 'operator' => array('<span class="ts-operator">','</span>'), // The operator char
112 'value' => array('<span class="ts-value">','</span>'), // The value of a line
113 'objstr' => array('<span class="ts-objstr">','</span>'), // The object string of a line
114 'value_copy' => array('<span class="ts-value_copy">','</span>'), // The value when the copy syntax (<) is used; that means the object reference
115 'value_unset' => array('<span class="ts-value_unset">','</span>'), // The value when an object is unset. Should not exist.
116 'ignored' => array('<span class="ts-ignored">','</span>'), // The "rest" of a line which will be ignored.
117 'default' => array('<span class="ts-default">','</span>'), // The default style if none other is applied.
118 'comment' => array('<span class="ts-comment">','</span>'), // Comment lines
119 'condition' => array('<span class="ts-condition">','</span>'), // Conditions
120 'error' => array('<span class="ts-error">','</span>'), // Error messages
121 'linenum' => array('<span class="ts-linenum">','</span>'), // Line numbers
122 );
123 var $highLightBlockStyles = ''; // Additional attributes for the <span> tags for a blockmode line
124 var $highLightBlockStyles_basecolor = '#cccccc'; // The hex-HTML color for the blockmode
125
126
127 /**
128 * Start parsing the input TypoScript text piece. The result is stored in $this->setup
129 *
130 * @param string The TypoScript text
131 * @param object If is object (instance of t3lib_matchcondition), then this is used to match conditions found in the TypoScript code. If matchObj not specified, then no conditions will work! (Except [GLOBAL])
132 * @return void
133 */
134 function parse($string,$matchObj='') {
135 $this->raw = explode(chr(10),$string);
136 $this->rawP = 0;
137 $pre = '[GLOBAL]';
138 while($pre) {
139 if ($this->breakPointLN && $pre=='[_BREAK]') {
140 $this->error('Breakpoint at '.($this->lineNumberOffset+$this->rawP-2).': Line content was "'.$this->raw[$this->rawP-2].'"',1);
141 break;
142 }
143
144 if (strtoupper($pre)=='[GLOBAL]' || strtoupper($pre)=='[END]' || (!$this->lastConditionTrue && strtoupper($pre)=='[ELSE]')) {
145 $pre = trim($this->parseSub($this->setup));
146 $this->lastConditionTrue=1;
147 } else {
148 if (strtoupper($pre)!='[ELSE]') {$this->sections[md5($pre)]=$pre;} // we're in a specific section. Therefore we log this section
149 if ((is_object($matchObj) && $matchObj->match($pre)) || $this->syntaxHighLight) {
150 if (strtoupper($pre)!='[ELSE]') {$this->sectionsMatch[md5($pre)]=$pre;}
151 $pre = trim($this->parseSub($this->setup));
152 $this->lastConditionTrue=1;
153 } else {
154 $pre = trim($this->nextDivider());
155 $this->lastConditionTrue=0;
156 }
157 }
158 }
159 if ($this->inBrace) {$this->error('Line '.($this->lineNumberOffset+$this->rawP-1).': The script is short of '.$this->inBrace.' end brace(s)',1); }
160 if ($this->multiLineEnabled) {$this->error('Line '.($this->lineNumberOffset+$this->rawP-1).': A multiline value section is not ended with a parenthesis!',1); }
161 $this->lineNumberOffset+=count($this->raw)+1;
162 }
163
164 /**
165 * 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.
166 *
167 * @return string The condition value
168 * @see parse()
169 */
170 function nextDivider() {
171 while (isset($this->raw[$this->rawP])) {
172 $line = ltrim($this->raw[$this->rawP]);
173 $this->rawP++;
174 if ($line && substr($line,0,1)=='[') {
175 return $line;
176 }
177 }
178 }
179
180 /**
181 * Parsing the $this->raw TypoScript lines from pointer, $this->rawP
182 *
183 * @param array Reference to the setup array in which to accumulate the values.
184 * @return string Returns the string of the condition found, the exit signal or possible nothing (if it completed parsing with no interruptions)
185 */
186 function parseSub(&$setup) {
187 global $TYPO3_CONF_VARS;
188
189 while (isset($this->raw[$this->rawP])) {
190 $line = ltrim($this->raw[$this->rawP]);
191 $lineP = $this->rawP;
192 $this->rawP++;
193 if ($this->syntaxHighLight) $this->regHighLight("prespace",$lineP,strlen($line));
194
195 // Breakpoint?
196 if ($this->breakPointLN && ($this->lineNumberOffset+$this->rawP-1)==($this->breakPointLN+1)) { // by adding 1 we get that line processed
197 return '[_BREAK]';
198 }
199
200 // Set comment flag?
201 if (!$this->multiLineEnabled && substr($line,0,2)=='/*') {
202 $this->commentSet=1;
203 }
204
205 if (!$this->commentSet && ($line || $this->multiLineEnabled)) { // If $this->multiLineEnabled we will go and get the line values here because we know, the first if() will be true.
206 if ($this->multiLineEnabled) { // If multiline is enabled. Escape by ')'
207 if (substr($line,0,1)==')') { // Multiline ends...
208 if ($this->syntaxHighLight) $this->regHighLight("operator",$lineP,strlen($line)-1);
209 $this->multiLineEnabled=0; // Disable multiline
210 $theValue = implode($this->multiLineValue,chr(10));
211 if (strstr($this->multiLineObject,'.')) {
212 $this->setVal($this->multiLineObject,$setup,array($theValue)); // Set the value deeper.
213 } else {
214 $setup[$this->multiLineObject] = $theValue; // Set value regularly
215 if ($this->lastComment && $this->regComments) {
216 $setup[$this->multiLineObject.'..'].=$this->lastComment;
217 }
218 if ($this->regLinenumbers) {
219 $setup[$this->multiLineObject.'.ln..'][]=($this->lineNumberOffset+$this->rawP-1);
220 }
221 }
222 } else {
223 if ($this->syntaxHighLight) $this->regHighLight("value",$lineP);
224 $this->multiLineValue[]=$this->raw[($this->rawP-1)];
225 }
226 } elseif ($this->inBrace==0 && substr($line,0,1)=='[') { // Beginning of condition (only on level zero compared to brace-levels
227 if ($this->syntaxHighLight) $this->regHighLight("condition",$lineP);
228 return $line;
229 } else {
230 if (substr($line,0,1)=='[' && strtoupper(trim($line))=='[GLOBAL]') { // Return if GLOBAL condition is set - no matter what.
231 if ($this->syntaxHighLight) $this->regHighLight("condition",$lineP);
232 $this->error('Line '.($this->lineNumberOffset+$this->rawP-1).': On return to [GLOBAL] scope, the script was short of '.$this->inBrace.' end brace(s)',1);
233 $this->inBrace=0;
234 return $line;
235 } elseif (strcspn($line,'}#/')!=0) { // If not brace-end or comment
236 $varL = strcspn($line,' {=<>:('); // Find object name string until we meet an operator
237 $objStrName=trim(substr($line,0,$varL));
238 if ($this->syntaxHighLight) $this->regHighLight("objstr",$lineP,strlen(substr($line,$varL)));
239 if (strlen($objStrName)) {
240 $r = array();
241 if ($this->strict && preg_match('/[^[:alnum:]_\.-]/i',$objStrName,$r)) {
242 $this->error('Line '.($this->lineNumberOffset+$this->rawP-1).': Object Name String, "'.htmlspecialchars($objStrName).'" contains invalid character "'.$r[0].'". Must be alphanumeric or one of: "_-."');
243 } else {
244 $line = ltrim(substr($line,$varL));
245 if ($this->syntaxHighLight) {
246 $this->regHighLight("objstr_postspace", $lineP, strlen($line));
247 if (strlen($line)>0) {
248 $this->regHighLight("operator", $lineP, strlen($line)-1);
249 $this->regHighLight("operator_postspace", $lineP, strlen(ltrim(substr($line,1))));
250 }
251 }
252
253 // Checking for special TSparser properties (to change TS values at parsetime)
254 $match = array();
255 if (preg_match('/^:=([^\(]+)\((.+)\).*/', $line, $match)) {
256 $tsFunc = trim($match[1]);
257 $tsFuncArg = $match[2];
258 list ($currentValue) = $this->getVal($objStrName,$setup);
259
260 switch ($tsFunc) {
261 case 'prependString':
262 $newValue = $tsFuncArg . $currentValue;
263 break;
264 case 'appendString':
265 $newValue = $currentValue . $tsFuncArg;
266 break;
267 case 'removeString':
268 $newValue = str_replace($tsFuncArg, '', $currentValue);
269 break;
270 case 'replaceString':
271 list($fromStr,$toStr) = explode('|', $tsFuncArg, 2);
272 $newValue = str_replace($fromStr, $toStr, $currentValue);
273 break;
274 case 'addToList':
275 $newValue = (strcmp('',$currentValue) ? $currentValue.',' : '') . trim($tsFuncArg);
276 break;
277 case 'removeFromList':
278 $existingElements = t3lib_div::trimExplode(',',$currentValue);
279 $removeElements = t3lib_div::trimExplode(',',$tsFuncArg);
280 if (count($removeElements)) {
281 $newValue = implode(',', array_diff($existingElements, $removeElements));
282 }
283 break;
284 default:
285 if (isset($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$tsFunc])) {
286 $hookMethod = $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$tsFunc];
287 $params = array('currentValue'=>$currentValue, 'functionArgument'=>$tsFuncArg);
288 $fakeThis = FALSE;
289 $newValue = t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
290 } else {
291 t3lib_div::sysLog('Missing function definition for '.$tsFunc.' on TypoScript line '.$lineP,'Core',2);
292 }
293 }
294
295 if (isset($newValue)) {
296 $line = '= '.$newValue;
297 }
298 }
299
300 switch(substr($line,0,1)) {
301 case '=':
302 if ($this->syntaxHighLight) $this->regHighLight('value', $lineP, strlen(ltrim(substr($line,1)))-strlen(trim(substr($line,1))));
303
304 if (strstr($objStrName,'.')) {
305 $value = Array();
306 $value[0] = trim(substr($line,1));
307 $this->setVal($objStrName,$setup,$value);
308 } else {
309 $setup[$objStrName] = trim(substr($line,1));
310 if ($this->lastComment && $this->regComments) { // Setting comment..
311 $setup[$objStrName.'..'].=$this->lastComment;
312 }
313 if ($this->regLinenumbers) {
314 $setup[$objStrName.'.ln..'][]=($this->lineNumberOffset+$this->rawP-1);
315 }
316 }
317 break;
318 case '{':
319 $this->inBrace++;
320 if (strstr($objStrName,'.')) {
321 $exitSig=$this->rollParseSub($objStrName,$setup);
322 if ($exitSig) return $exitSig;
323 } else {
324 if (!isset($setup[$objStrName.'.'])) {$setup[$objStrName.'.'] = Array();}
325 $exitSig=$this->parseSub($setup[$objStrName.'.']);
326 if ($exitSig) return $exitSig;
327 }
328 break;
329 case '(':
330 $this->multiLineObject = $objStrName;
331 $this->multiLineEnabled=1;
332 $this->multiLineValue=array();
333 break;
334 case '<':
335 if ($this->syntaxHighLight) $this->regHighLight("value_copy", $lineP, strlen(ltrim(substr($line,1)))-strlen(trim(substr($line,1))));
336 $theVal = trim(substr($line,1));
337 if (substr($theVal,0,1)=='.') {
338 $res = $this->getVal(substr($theVal,1),$setup);
339 } else {
340 $res = $this->getVal($theVal,$this->setup);
341 }
342 $this->setVal($objStrName,$setup,unserialize(serialize($res)),1); // 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.
343 break;
344 case '>':
345 if ($this->syntaxHighLight) $this->regHighLight("value_unset", $lineP, strlen(ltrim(substr($line,1)))-strlen(trim(substr($line,1))));
346 $this->setVal($objStrName,$setup,'UNSET');
347 break;
348 default:
349 $this->error('Line '.($this->lineNumberOffset+$this->rawP-1).': Object Name String, "'.htmlspecialchars($objStrName).'" was not preceeded by any operator, =<>({');
350 break;
351 }
352 }
353 $this->lastComment='';
354 }
355 } elseif (substr($line,0,1)=='}') {
356 $this->inBrace--;
357 $this->lastComment='';
358 if ($this->syntaxHighLight) $this->regHighLight("operator", $lineP, strlen($line)-1);
359 if ($this->inBrace<0) {
360 $this->error('Line '.($this->lineNumberOffset+$this->rawP-1).': An end brace is in excess.',1);
361 $this->inBrace=0;
362 } else {
363 break;
364 }
365 } else {
366 if ($this->syntaxHighLight) $this->regHighLight("comment", $lineP);
367
368 // Comment. The comments are concatenated in this temporary string:
369 if ($this->regComments) $this->lastComment.= trim($line).chr(10);
370 }
371 }
372 }
373
374 // Unset comment
375 if ($this->commentSet) {
376 if ($this->syntaxHighLight) $this->regHighLight("comment", $lineP);
377 if (substr($line,0,2)=='*/') $this->commentSet=0;
378 }
379 }
380 }
381
382 /**
383 * 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
384 *
385 * @param string The object sub-path, eg "thisprop.another_prot"
386 * @param array The local setup array from the function calling this function
387 * @return string Returns the exitSignal
388 * @see parseSub()
389 */
390 function rollParseSub($string,&$setup) {
391 if ((string)$string!='') {
392 $keyLen = strcspn($string,'.');
393 if ($keyLen==strlen($string)) {
394 $key = $string.'.';
395 if (!isset($setup[$key])){$setup[$key]=Array();}
396 $exitSig=$this->parseSub($setup[$key]);
397 if ($exitSig) return $exitSig;
398 } else {
399 $key = substr($string,0,$keyLen).'.';
400 if (!isset($setup[$key])){$setup[$key]=Array();}
401 $exitSig=$this->rollParseSub(substr($string,$keyLen+1),$setup[$key]);
402 if ($exitSig) return $exitSig;
403 }
404 }
405 }
406
407 /**
408 * Get a value/property pair for an object path in TypoScript, eg. "myobject.myvalue.mysubproperty". Here: Used by the "copy" operator, <
409 *
410 * @param string Object path for which to get the value
411 * @param array Global setup code if $string points to a global object path. But if string is prefixed with "." then its the local setup array.
412 * @return array An array with keys 0/1 being value/property respectively
413 */
414 function getVal($string,$setup) {
415 if ((string)$string!='') {
416 $keyLen = strcspn($string,'.');
417 if ($keyLen==strlen($string)) {
418 $retArr=array(); // Added 6/6/03. Shouldn't hurt
419 if (isset($setup[$string])) {$retArr[0]=$setup[$string]; }
420 if (isset($setup[$string.'.'])) {$retArr[1]=$setup[$string.'.']; }
421 return $retArr;
422 } else {
423 $key = substr($string,0,$keyLen).'.';
424 if ($setup[$key]) {
425 return $this->getVal(substr($string,$keyLen+1),$setup[$key]);
426 }
427 }
428 }
429 }
430
431 /**
432 * Setting a value/property of an object string in the setup array.
433 *
434 * @param string The object sub-path, eg "thisprop.another_prot"
435 * @param array The local setup array from the function calling this function.
436 * @param array 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)
437 * @param boolean If set, then both value and property is wiped out when a copy is made of another value.
438 * @return void
439 */
440 function setVal($string,&$setup,$value,$wipeOut=0) {
441 if ((string)$string!='') {
442 $keyLen = strcspn($string,'.');
443 if ($keyLen==strlen($string)) {
444 if ($value=='UNSET') {
445 unset($setup[$string]);
446 unset($setup[$string.'.']);
447 if ($this->regLinenumbers) {
448 $setup[$string.'.ln..'][]=($this->lineNumberOffset+$this->rawP-1).'>';
449 }
450 } else {
451 $lnRegisDone=0;
452 if ($wipeOut && $this->strict) {
453 if ((isset($setup[$string]) && !isset($value[0])) || (isset($setup[$string.'.']) && !isset($value[1]))) {$this->error('Line '.($this->lineNumberOffset+$this->rawP-1).': Object copied in this line "'.trim($this->raw[($this->rawP-1)]).'" would leave either the value or properties untouched in TypoScript Version 1. Please check that this is not a problem for you.',1);}
454 unset($setup[$string]);
455 unset($setup[$string.'.']);
456 if ($this->regLinenumbers) {
457 $setup[$string.'.ln..'][]=($this->lineNumberOffset+$this->rawP-1).'<';
458 $lnRegisDone=1;
459 }
460 }
461 if (isset($value[0])) {$setup[$string] = $value[0];}
462 if (isset($value[1])) {$setup[$string.'.'] = $value[1];}
463 if ($this->lastComment && $this->regComments) {
464 $setup[$string.'..'].=$this->lastComment;
465 }
466 if ($this->regLinenumbers && !$lnRegisDone) {
467 $setup[$string.'.ln..'][]=($this->lineNumberOffset+$this->rawP-1);
468 }
469 }
470 } else {
471 $key = substr($string,0,$keyLen).'.';
472 if (!isset($setup[$key])){$setup[$key]=Array();}
473 $this->setVal(substr($string,$keyLen+1),$setup[$key],$value);
474 }
475 }
476 }
477
478 /**
479 * Stacks errors/messages from the TypoScript parser into an internal array, $this->error
480 * 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.
481 *
482 * @param string The error message string
483 * @param integer The error severity (in the scale of $GLOBALS['TT']->setTSlogMessage: Approx: 2=warning, 1=info, 0=nothing, 3=fatal.)
484 * @return void
485 */
486 function error($err,$num=2) {
487 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage($err,$num);
488 $this->errors[]=array($err,$num,$this->rawP-1,$this->lineNumberOffset);
489 }
490
491 /**
492 * Checks the input string (un-parsed TypoScript) for include-commands ("<INCLUDE_TYPOSCRIPT: ....")
493 * Use: t3lib_TSparser::checkIncludeLines()
494 *
495 * @param string Unparsed TypoScript
496 * @return string Complete TypoScript with includes added.
497 */
498 function checkIncludeLines($string) {
499 $splitStr='<INCLUDE_TYPOSCRIPT:';
500 if (strstr($string,$splitStr)) {
501 $newString='';
502 $allParts = explode($splitStr,chr(10).$string.chr(10)); // adds line break char before/after
503 reset($allParts);
504 while(list($c,$v)=each($allParts)) {
505 if (!$c) { // first goes through
506 $newString.=$v;
507 } elseif (preg_match('/\r?\n\s*$/',$allParts[$c-1])) { // There must be a line-break char before.
508 $subparts=explode('>',$v,2);
509 if (preg_match('/^\s*\r?\n/',$subparts[1])) { // There must be a line-break char after
510 // SO, the include was positively recognized:
511 $newString.='### '.$splitStr.$subparts[0].'> BEGIN:'.chr(10);
512 $params = t3lib_div::get_tag_attributes($subparts[0]);
513 if ($params['source']) {
514 $sourceParts = explode(':',$params['source'],2);
515 switch(strtolower(trim($sourceParts[0]))) {
516 case 'file':
517 $filename = t3lib_div::getFileAbsFileName(trim($sourceParts[1]));
518 if (!isset($this->includedFiles[$filename])) {
519 if (strcmp($filename,'')) { // Must exist and must not contain '..' and must be relative
520 if (@is_file($filename) && filesize($filename)<100000) { // Max. 100 KB include files!
521 $this->includedFiles[$filename] = 1;
522 // check for includes in included text
523 $included_text = t3lib_TSparser::checkIncludeLines(t3lib_div::getUrl($filename));
524 $newString.= $included_text.chr(10);
525 }
526 }
527 } else {
528 t3lib_div::sysLog('It appears like TypoScript code is looping over itself. Check your templates for "'.htmlspecialchars('<INCLUDE_TYPOSCRIPT:'.$subparts[0].'>').'"','Core',2);
529 }
530 break;
531 }
532 }
533 $newString.='### '.$splitStr.$subparts[0].'> END:'.chr(10);
534 $newString.=$subparts[1];
535 } else $newString.=$splitStr.$v;
536 } else $newString.=$splitStr.$v;
537 }
538 $string=substr($newString,1,-1); // not the first/last linebreak char.
539 }
540 return $string;
541 }
542
543 /**
544 * Parses the string in each value of the input array for include-commands
545 *
546 * @param array Array with TypoScript in each value
547 * @return array Same array but where the values has been parsed for include-commands
548 */
549 function checkIncludeLines_array($array) {
550 reset($array);
551 while(list($k)=each($array)) {
552 $array[$k]=t3lib_TSparser::checkIncludeLines($array[$k]);
553 }
554 return $array;
555 }
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577 /**********************************
578 *
579 * Syntax highlighting
580 *
581 *********************************/
582
583 /**
584 * Syntax highlight a TypoScript text
585 * Will parse the content. Remember, the internal setup array may contain invalid parsed content since conditions are ignored!
586 *
587 * @param string The TypoScript text
588 * @param mixed If blank, linenumbers are NOT printed. If array then the first key is the linenumber offset to add to the internal counter.
589 * @param boolean 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.
590 * @return string HTML code for the syntax highlighted string
591 */
592 function doSyntaxHighlight($string,$lineNum='',$highlightBlockMode=0) {
593 $this->syntaxHighLight=1;
594 $this->highLightData=array();
595 $this->error=array();
596 $string = str_replace(chr(13),'',$string); // This is done in order to prevent empty <span>..</span> sections around chr(13) content. Should not do anything but help lessen the amount of HTML code.
597
598 $this->parse($string);
599
600 return $this->syntaxHighlight_print($lineNum,$highlightBlockMode);
601 }
602
603 /**
604 * Registers a part of a TypoScript line for syntax highlighting.
605 *
606 * @param string Key from the internal array $this->highLightStyles
607 * @param integer Pointer to the line in $this->raw which this is about
608 * @param integer The number of chars LEFT on this line before the end is reached.
609 * @return void
610 * @access private
611 * @see parse()
612 */
613 function regHighLight($code,$pointer,$strlen=-1) {
614 if ($strlen==-1) {
615 $this->highLightData[$pointer] = array(array($code,0));
616 } else {
617 $this->highLightData[$pointer][] = array($code,$strlen);
618 }
619 $this->highLightData_bracelevel[$pointer] = $this->inBrace;
620 }
621
622 /**
623 * Formatting the TypoScript code in $this->raw based on the data collected by $this->regHighLight in $this->highLightData
624 *
625 * @param mixed If blank, linenumbers are NOT printed. If array then the first key is the linenumber offset to add to the internal counter.
626 * @param boolean 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.
627 * @return string HTML content
628 * @access private
629 * @see doSyntaxHighlight()
630 */
631 function syntaxHighlight_print($lineNumDat,$highlightBlockMode) {
632 // Registers all error messages in relation to their linenumber
633 $errA=array();
634 foreach($this->errors as $err) {
635 $errA[$err[2]][]=$err[0];
636 }
637 // Generates the syntax highlighted output:
638 $lines=array();
639 foreach($this->raw as $rawP => $value) {
640 $start=0;
641 $strlen=strlen($value);
642 $lineC='';
643
644 if (is_array($this->highLightData[$rawP])) {
645 foreach($this->highLightData[$rawP] as $set) {
646 $len = $strlen-$start-$set[1];
647 if ($len > 0) {
648 $part = substr($value,$start,$len);
649 $start+=$len;
650 $st = $this->highLightStyles[(isset($this->highLightStyles[$set[0]])?$set[0]:'default')];
651 if (!$highlightBlockMode || $set[0]!='prespace') $lineC.=$st[0].htmlspecialchars($part).$st[1];
652 }elseif ($len < 0) debug(array($len,$value,$rawP));
653 }
654 } else debug(array($value));
655
656 if (strlen(substr($value,$start))) $lineC.=$this->highLightStyles['ignored'][0].htmlspecialchars(substr($value,$start)).$this->highLightStyles['ignored'][1];
657
658 if ($errA[$rawP]) {
659 $lineC.=$this->highLightStyles['error'][0].'<strong> - ERROR:</strong> '.htmlspecialchars(implode(';',$errA[$rawP])).$this->highLightStyles['error'][1];
660 }
661
662 if ($highlightBlockMode && $this->highLightData_bracelevel[$rawP]) {
663 $lineC = str_pad('',$this->highLightData_bracelevel[$rawP]*2,' ',STR_PAD_LEFT).'<span style="'.$this->highLightBlockStyles.($this->highLightBlockStyles_basecolor?'background-color: '.t3lib_div::modifyHTMLColorAll($this->highLightBlockStyles_basecolor,-$this->highLightData_bracelevel[$rawP]*16):'').'">'.(strcmp($lineC,'')?$lineC:'&nbsp;').'</span>';
664 }
665
666 if (is_array($lineNumDat)) {
667 $lineNum = $rawP+$lineNumDat[0];
668 $lineC = $this->highLightStyles['linenum'][0].str_pad($lineNum,4,' ',STR_PAD_LEFT).':'.$this->highLightStyles['linenum'][1].' '.$lineC;
669 }
670
671
672 $lines[] = $lineC;
673 }
674
675 return '<pre class="ts-hl">'.implode(chr(10),$lines).'</pre>';
676 }
677 }
678
679
680 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tsparser.php']) {
681 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tsparser.php']);
682 }
683 ?>