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