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