| Total Complexity | 219 |
| Total Lines | 1272 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like TypoScriptParser often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use TypoScriptParser, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 36 | class TypoScriptParser |
||
| 37 | { |
||
| 38 | /** |
||
| 39 | * TypoScript hierarchy being build during parsing. |
||
| 40 | * |
||
| 41 | * @var array |
||
| 42 | */ |
||
| 43 | public $setup = []; |
||
| 44 | |||
| 45 | /** |
||
| 46 | * Raw data, the input string exploded by LF |
||
| 47 | * |
||
| 48 | * @var string[] |
||
| 49 | */ |
||
| 50 | protected $raw; |
||
| 51 | |||
| 52 | /** |
||
| 53 | * Pointer to entry in raw data array |
||
| 54 | * |
||
| 55 | * @var int |
||
| 56 | */ |
||
| 57 | protected $rawP; |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Holding the value of the last comment |
||
| 61 | * |
||
| 62 | * @var string |
||
| 63 | */ |
||
| 64 | protected $lastComment = ''; |
||
| 65 | |||
| 66 | /** |
||
| 67 | * Internally set, used as internal flag to create a multi-line comment (one of those like /* ... * / |
||
| 68 | * |
||
| 69 | * @var bool |
||
| 70 | */ |
||
| 71 | protected $commentSet = false; |
||
| 72 | |||
| 73 | /** |
||
| 74 | * Internally set, when multiline value is accumulated |
||
| 75 | * |
||
| 76 | * @var bool |
||
| 77 | */ |
||
| 78 | protected $multiLineEnabled = false; |
||
| 79 | |||
| 80 | /** |
||
| 81 | * Internally set, when multiline value is accumulated |
||
| 82 | * |
||
| 83 | * @var string |
||
| 84 | */ |
||
| 85 | protected $multiLineObject = ''; |
||
| 86 | |||
| 87 | /** |
||
| 88 | * Internally set, when multiline value is accumulated |
||
| 89 | * |
||
| 90 | * @var array |
||
| 91 | */ |
||
| 92 | protected $multiLineValue = []; |
||
| 93 | |||
| 94 | /** |
||
| 95 | * Internally set, when in brace. Counter. |
||
| 96 | * |
||
| 97 | * @var int |
||
| 98 | */ |
||
| 99 | protected $inBrace = 0; |
||
| 100 | |||
| 101 | /** |
||
| 102 | * For each condition this flag is set, if the condition is TRUE, |
||
| 103 | * else it's cleared. Then it's used by the [ELSE] condition to determine if the next part should be parsed. |
||
| 104 | * |
||
| 105 | * @var bool |
||
| 106 | */ |
||
| 107 | protected $lastConditionTrue = true; |
||
| 108 | |||
| 109 | /** |
||
| 110 | * Tracking all conditions found |
||
| 111 | * |
||
| 112 | * @var array |
||
| 113 | */ |
||
| 114 | public $sections = []; |
||
| 115 | |||
| 116 | /** |
||
| 117 | * Tracking all matching conditions found |
||
| 118 | * |
||
| 119 | * @var array |
||
| 120 | */ |
||
| 121 | public $sectionsMatch = []; |
||
| 122 | |||
| 123 | /** |
||
| 124 | * DO NOT register the comments. This is default for the ordinary sitetemplate! |
||
| 125 | * |
||
| 126 | * @var bool |
||
| 127 | */ |
||
| 128 | public $regComments = false; |
||
| 129 | |||
| 130 | /** |
||
| 131 | * DO NOT register the linenumbers. This is default for the ordinary sitetemplate! |
||
| 132 | * |
||
| 133 | * @var bool |
||
| 134 | */ |
||
| 135 | public $regLinenumbers = false; |
||
| 136 | |||
| 137 | /** |
||
| 138 | * Error accumulation array. |
||
| 139 | * |
||
| 140 | * @var array |
||
| 141 | */ |
||
| 142 | public $errors = []; |
||
| 143 | |||
| 144 | /** |
||
| 145 | * Used for the error messages line number reporting. Set externally. |
||
| 146 | * |
||
| 147 | * @var int |
||
| 148 | */ |
||
| 149 | public $lineNumberOffset = 0; |
||
| 150 | |||
| 151 | /** |
||
| 152 | * @deprecated Unused since v11, will be removed in v12 |
||
| 153 | */ |
||
| 154 | public $breakPointLN = 0; |
||
| 155 | |||
| 156 | /** |
||
| 157 | * @deprecated Unused since v11, will be removed in v12 |
||
| 158 | */ |
||
| 159 | public $parentObject; |
||
| 160 | |||
| 161 | /** |
||
| 162 | * Start parsing the input TypoScript text piece. The result is stored in $this->setup |
||
| 163 | * |
||
| 164 | * @param string $string The TypoScript text |
||
| 165 | * @param object|string $matchObj If is object, then this is used to match conditions found in the TypoScript code. If matchObj not specified, then no conditions will work! (Except [GLOBAL]) |
||
| 166 | */ |
||
| 167 | public function parse($string, $matchObj = '') |
||
| 168 | { |
||
| 169 | $this->raw = explode(LF, $string); |
||
| 170 | $this->rawP = 0; |
||
| 171 | $pre = '[GLOBAL]'; |
||
| 172 | while ($pre) { |
||
| 173 | if ($pre === '[]') { |
||
| 174 | $this->error('Empty condition is always false, this does not make sense. At line ' . ($this->lineNumberOffset + $this->rawP - 1), LogLevel::WARNING); |
||
| 175 | break; |
||
| 176 | } |
||
| 177 | $preUppercase = strtoupper($pre); |
||
| 178 | if ($pre[0] === '[' && |
||
| 179 | ($preUppercase === '[GLOBAL]' || |
||
| 180 | $preUppercase === '[END]' || |
||
| 181 | !$this->lastConditionTrue && $preUppercase === '[ELSE]') |
||
| 182 | ) { |
||
| 183 | $pre = trim($this->parseSub($this->setup)); |
||
| 184 | $this->lastConditionTrue = true; |
||
| 185 | } else { |
||
| 186 | // We're in a specific section. Therefore we log this section |
||
| 187 | $specificSection = $preUppercase !== '[ELSE]'; |
||
| 188 | if ($specificSection) { |
||
| 189 | $this->sections[md5($pre)] = $pre; |
||
| 190 | } |
||
| 191 | if (is_object($matchObj) && $matchObj->match($pre)) { |
||
| 192 | if ($specificSection) { |
||
| 193 | $this->sectionsMatch[md5($pre)] = $pre; |
||
| 194 | } |
||
| 195 | $pre = trim($this->parseSub($this->setup)); |
||
| 196 | $this->lastConditionTrue = true; |
||
| 197 | } else { |
||
| 198 | $pre = $this->nextDivider(); |
||
| 199 | $this->lastConditionTrue = false; |
||
| 200 | } |
||
| 201 | } |
||
| 202 | } |
||
| 203 | if ($this->inBrace) { |
||
| 204 | $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': The script is short of ' . $this->inBrace . ' end brace(s)', LogLevel::INFO); |
||
| 205 | } |
||
| 206 | if ($this->multiLineEnabled) { |
||
| 207 | $this->error('Line ' . ($this->lineNumberOffset + $this->rawP - 1) . ': A multiline value section is not ended with a parenthesis!', LogLevel::INFO); |
||
| 208 | } |
||
| 209 | $this->lineNumberOffset += count($this->raw) + 1; |
||
| 210 | } |
||
| 211 | |||
| 212 | /** |
||
| 213 | * 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. |
||
| 214 | * |
||
| 215 | * @return string The condition value |
||
| 216 | * @see parse() |
||
| 217 | */ |
||
| 218 | protected function nextDivider() |
||
| 219 | { |
||
| 220 | while (isset($this->raw[$this->rawP])) { |
||
| 221 | $line = trim($this->raw[$this->rawP]); |
||
| 222 | $this->rawP++; |
||
| 223 | if ($line && $line[0] === '[') { |
||
| 224 | return $line; |
||
| 225 | } |
||
| 226 | } |
||
| 227 | return ''; |
||
| 228 | } |
||
| 229 | |||
| 230 | /** |
||
| 231 | * Parsing the $this->raw TypoScript lines from pointer, $this->rawP |
||
| 232 | * |
||
| 233 | * @param array $setup Reference to the setup array in which to accumulate the values. |
||
| 234 | * @return string Returns the string of the condition found, the exit signal or possible nothing (if it completed parsing with no interruptions) |
||
| 235 | */ |
||
| 236 | protected function parseSub(array &$setup) |
||
| 413 | } |
||
| 414 | |||
| 415 | /** |
||
| 416 | * Executes operator functions, called from TypoScript |
||
| 417 | * example: page.10.value := appendString(!) |
||
| 418 | * |
||
| 419 | * @param string $modifierName TypoScript function called |
||
| 420 | * @param string $modifierArgument Function arguments; In case of multiple arguments, the method must split on its own |
||
| 421 | * @param string $currentValue Current TypoScript value |
||
| 422 | * @return string|null Modified result or null for no modification |
||
| 423 | */ |
||
| 424 | protected function executeValueModifier($modifierName, $modifierArgument = null, $currentValue = null) |
||
| 425 | { |
||
| 426 | $modifierArgumentAsString = (string)$modifierArgument; |
||
| 427 | $currentValueAsString = (string)$currentValue; |
||
| 428 | $newValue = null; |
||
| 429 | switch ($modifierName) { |
||
| 430 | case 'prependString': |
||
| 431 | $newValue = $modifierArgumentAsString . $currentValueAsString; |
||
| 432 | break; |
||
| 433 | case 'appendString': |
||
| 434 | $newValue = $currentValueAsString . $modifierArgumentAsString; |
||
| 435 | break; |
||
| 436 | case 'removeString': |
||
| 437 | $newValue = str_replace($modifierArgumentAsString, '', $currentValueAsString); |
||
| 438 | break; |
||
| 439 | case 'replaceString': |
||
| 440 | $modifierArgumentArray = explode('|', $modifierArgumentAsString, 2); |
||
| 441 | $fromStr = $modifierArgumentArray[0] ?? ''; |
||
| 442 | $toStr = $modifierArgumentArray[1] ?? ''; |
||
| 443 | $newValue = str_replace($fromStr, $toStr, $currentValueAsString); |
||
| 444 | break; |
||
| 445 | case 'addToList': |
||
| 446 | $newValue = ($currentValueAsString !== '' ? $currentValueAsString . ',' : '') . $modifierArgumentAsString; |
||
| 447 | break; |
||
| 448 | case 'removeFromList': |
||
| 449 | $existingElements = GeneralUtility::trimExplode(',', $currentValueAsString); |
||
| 450 | $removeElements = GeneralUtility::trimExplode(',', $modifierArgumentAsString); |
||
| 451 | if (!empty($removeElements)) { |
||
| 452 | $newValue = implode(',', array_diff($existingElements, $removeElements)); |
||
| 453 | } |
||
| 454 | break; |
||
| 455 | case 'uniqueList': |
||
| 456 | $elements = GeneralUtility::trimExplode(',', $currentValueAsString); |
||
| 457 | $newValue = implode(',', array_unique($elements)); |
||
| 458 | break; |
||
| 459 | case 'reverseList': |
||
| 460 | $elements = GeneralUtility::trimExplode(',', $currentValueAsString); |
||
| 461 | $newValue = implode(',', array_reverse($elements)); |
||
| 462 | break; |
||
| 463 | case 'sortList': |
||
| 464 | $elements = GeneralUtility::trimExplode(',', $currentValueAsString); |
||
| 465 | $arguments = GeneralUtility::trimExplode(',', $modifierArgumentAsString); |
||
| 466 | $arguments = array_map('strtolower', $arguments); |
||
| 467 | $sort_flags = SORT_REGULAR; |
||
| 468 | if (in_array('numeric', $arguments)) { |
||
| 469 | $sort_flags = SORT_NUMERIC; |
||
| 470 | // If the sorting modifier "numeric" is given, all values |
||
| 471 | // are checked and an exception is thrown if a non-numeric value is given |
||
| 472 | // otherwise there is a different behaviour between PHP7 and PHP 5.x |
||
| 473 | // See also the warning on http://us.php.net/manual/en/function.sort.php |
||
| 474 | foreach ($elements as $element) { |
||
| 475 | if (!is_numeric($element)) { |
||
| 476 | throw new \InvalidArgumentException('The list "' . $currentValueAsString . '" should be sorted numerically but contains a non-numeric value', 1438191758); |
||
| 477 | } |
||
| 478 | } |
||
| 479 | } |
||
| 480 | sort($elements, $sort_flags); |
||
| 481 | if (in_array('descending', $arguments)) { |
||
| 482 | $elements = array_reverse($elements); |
||
| 483 | } |
||
| 484 | $newValue = implode(',', $elements); |
||
| 485 | break; |
||
| 486 | case 'getEnv': |
||
| 487 | $environmentValue = getenv(trim($modifierArgumentAsString)); |
||
| 488 | if ($environmentValue !== false) { |
||
| 489 | $newValue = $environmentValue; |
||
| 490 | } |
||
| 491 | break; |
||
| 492 | default: |
||
| 493 | if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$modifierName])) { |
||
| 494 | $hookMethod = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsparser.php']['preParseFunc'][$modifierName]; |
||
| 495 | $params = ['currentValue' => $currentValue, 'functionArgument' => $modifierArgument]; |
||
| 496 | $fakeThis = null; |
||
| 497 | $newValue = GeneralUtility::callUserFunction($hookMethod, $params, $fakeThis); |
||
| 498 | } else { |
||
| 499 | self::getLogger()->warning('Missing function definition for {modifier_name} on TypoScript', [ |
||
| 500 | 'modifier_name' => $modifierName, |
||
| 501 | ]); |
||
| 502 | } |
||
| 503 | } |
||
| 504 | return $newValue; |
||
| 505 | } |
||
| 506 | |||
| 507 | /** |
||
| 508 | * Parsing of TypoScript keys inside a curly brace where the key is composite of at least two keys, |
||
| 509 | * thus having to recursively call itself to get the value |
||
| 510 | * |
||
| 511 | * @param string $string The object sub-path, eg "thisprop.another_prot |
||
| 512 | * @param array $setup The local setup array from the function calling this function |
||
| 513 | * @return string Returns the exitSignal |
||
| 514 | * @see parseSub() |
||
| 515 | */ |
||
| 516 | protected function rollParseSub($string, array &$setup) |
||
| 517 | { |
||
| 518 | if ((string)$string === '') { |
||
| 519 | return ''; |
||
| 520 | } |
||
| 521 | |||
| 522 | [$key, $remainingKey] = $this->parseNextKeySegment($string); |
||
| 523 | $key .= '.'; |
||
| 524 | if (!isset($setup[$key])) { |
||
| 525 | $setup[$key] = []; |
||
| 526 | } |
||
| 527 | $exitSig = $remainingKey === '' |
||
| 528 | ? $this->parseSub($setup[$key]) |
||
| 529 | : $this->rollParseSub($remainingKey, $setup[$key]); |
||
| 530 | return $exitSig ?: ''; |
||
| 531 | } |
||
| 532 | |||
| 533 | /** |
||
| 534 | * Get a value/property pair for an object path in TypoScript, eg. "myobject.myvalue.mysubproperty". |
||
| 535 | * Here: Used by the "copy" operator, < |
||
| 536 | * |
||
| 537 | * @param string $string Object path for which to get the value |
||
| 538 | * @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. |
||
| 539 | * @return array An array with keys 0/1 being value/property respectively |
||
| 540 | */ |
||
| 541 | public function getVal($string, $setup): array |
||
| 542 | { |
||
| 543 | $retArr = [ |
||
| 544 | 0 => '', |
||
| 545 | 1 => [], |
||
| 546 | ]; |
||
| 547 | if ((string)$string === '') { |
||
| 548 | return $retArr; |
||
| 549 | } |
||
| 550 | |||
| 551 | [$key, $remainingKey] = $this->parseNextKeySegment($string); |
||
| 552 | $subKey = $key . '.'; |
||
| 553 | if ($remainingKey === '') { |
||
| 554 | $retArr[0] = $setup[$key] ?? $retArr[0]; |
||
| 555 | $retArr[1] = $setup[$subKey] ?? $retArr[1]; |
||
| 556 | return $retArr; |
||
| 557 | } |
||
| 558 | if (isset($setup[$subKey])) { |
||
| 559 | return $this->getVal($remainingKey, $setup[$subKey]); |
||
| 560 | } |
||
| 561 | |||
| 562 | return $retArr; |
||
| 563 | } |
||
| 564 | |||
| 565 | /** |
||
| 566 | * Setting a value/property of an object string in the setup array. |
||
| 567 | * |
||
| 568 | * @param string $string The object sub-path, eg "thisprop.another_prot |
||
| 569 | * @param array $setup The local setup array from the function calling this function. |
||
| 570 | * @param array|string $value The value/property pair array to set. If only one of them is set, then the other is not touched (unless $wipeOut is set, which it is when copies are made which must include both value and property) |
||
| 571 | * @param bool $wipeOut If set, then both value and property is wiped out when a copy is made of another value. |
||
| 572 | */ |
||
| 573 | protected function setVal($string, array &$setup, $value, $wipeOut = false) |
||
| 574 | { |
||
| 575 | if ((string)$string === '') { |
||
| 576 | return; |
||
| 577 | } |
||
| 578 | |||
| 579 | [$key, $remainingKey] = $this->parseNextKeySegment($string); |
||
| 580 | $subKey = $key . '.'; |
||
| 581 | if ($remainingKey === '') { |
||
| 582 | if ($value === 'UNSET') { |
||
| 583 | unset($setup[$key]); |
||
| 584 | unset($setup[$subKey]); |
||
| 585 | if ($this->regLinenumbers) { |
||
| 586 | $setup[$key . '.ln..'][] = ($this->lineNumberOffset + $this->rawP - 1) . '>'; |
||
| 587 | } |
||
| 588 | } else { |
||
| 589 | $lnRegisDone = 0; |
||
| 590 | if ($wipeOut) { |
||
| 591 | unset($setup[$key]); |
||
| 592 | unset($setup[$subKey]); |
||
| 593 | if ($this->regLinenumbers) { |
||
| 594 | $setup[$key . '.ln..'][] = ($this->lineNumberOffset + $this->rawP - 1) . '<'; |
||
| 595 | $lnRegisDone = 1; |
||
| 596 | } |
||
| 597 | } |
||
| 598 | if (isset($value[0])) { |
||
| 599 | $setup[$key] = $value[0]; |
||
| 600 | } |
||
| 601 | if (isset($value[1])) { |
||
| 602 | $setup[$subKey] = $value[1]; |
||
| 603 | } |
||
| 604 | if ($this->lastComment && $this->regComments) { |
||
| 605 | $setup[$key . '..'] = $setup[$key . '..'] ?? '' . $this->lastComment; |
||
| 606 | } |
||
| 607 | if ($this->regLinenumbers && !$lnRegisDone) { |
||
| 608 | $setup[$key . '.ln..'][] = $this->lineNumberOffset + $this->rawP - 1; |
||
| 609 | } |
||
| 610 | } |
||
| 611 | } else { |
||
| 612 | if (!isset($setup[$subKey])) { |
||
| 613 | $setup[$subKey] = []; |
||
| 614 | } |
||
| 615 | $this->setVal($remainingKey, $setup[$subKey], $value); |
||
| 616 | } |
||
| 617 | } |
||
| 618 | |||
| 619 | /** |
||
| 620 | * Determines the first key segment of a TypoScript key by searching for the first |
||
| 621 | * unescaped dot in the given key string. |
||
| 622 | * |
||
| 623 | * Since the escape characters are only needed to correctly determine the key |
||
| 624 | * segment any escape characters before the first unescaped dot are |
||
| 625 | * stripped from the key. |
||
| 626 | * |
||
| 627 | * @param string $key The key, possibly consisting of multiple key segments separated by unescaped dots |
||
| 628 | * @return array Array with key segment and remaining part of $key |
||
| 629 | */ |
||
| 630 | protected function parseNextKeySegment($key) |
||
| 631 | { |
||
| 632 | // if no dot is in the key, nothing to do |
||
| 633 | $dotPosition = strpos($key, '.'); |
||
| 634 | if ($dotPosition === false) { |
||
| 635 | return [$key, '']; |
||
| 636 | } |
||
| 637 | |||
| 638 | if (str_contains($key, '\\')) { |
||
| 639 | // backslashes are in the key, so we do further parsing |
||
| 640 | |||
| 641 | while ($dotPosition !== false) { |
||
| 642 | if ($dotPosition > 0 && $key[$dotPosition - 1] !== '\\' || $dotPosition > 1 && $key[$dotPosition - 2] === '\\') { |
||
|
|
|||
| 643 | break; |
||
| 644 | } |
||
| 645 | // escaped dot found, continue |
||
| 646 | $dotPosition = strpos($key, '.', $dotPosition + 1); |
||
| 647 | } |
||
| 648 | |||
| 649 | if ($dotPosition === false) { |
||
| 650 | // no regular dot found |
||
| 651 | $keySegment = $key; |
||
| 652 | $remainingKey = ''; |
||
| 653 | } else { |
||
| 654 | if ($dotPosition > 1 && $key[$dotPosition - 2] === '\\' && $key[$dotPosition - 1] === '\\') { |
||
| 655 | $keySegment = substr($key, 0, $dotPosition - 1); |
||
| 656 | } else { |
||
| 657 | $keySegment = substr($key, 0, $dotPosition); |
||
| 658 | } |
||
| 659 | $remainingKey = substr($key, $dotPosition + 1); |
||
| 660 | } |
||
| 661 | |||
| 662 | // fix key segment by removing escape sequences |
||
| 663 | $keySegment = str_replace('\\.', '.', $keySegment); |
||
| 664 | } else { |
||
| 665 | // no backslash in the key, we're fine off |
||
| 666 | [$keySegment, $remainingKey] = explode('.', $key, 2); |
||
| 667 | } |
||
| 668 | return [$keySegment, $remainingKey]; |
||
| 669 | } |
||
| 670 | |||
| 671 | /** |
||
| 672 | * Stacks errors/messages from the TypoScript parser into an internal array, $this->error |
||
| 673 | * 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. |
||
| 674 | * |
||
| 675 | * @param string $message The error message string |
||
| 676 | * @param int|string $logLevel The error severity (in the scale of TimeTracker::setTSlogMessage: Approx: 2=warning, 1=info, 0=nothing, 3=fatal.) |
||
| 677 | */ |
||
| 678 | protected function error($message, $logLevel = LogLevel::WARNING) |
||
| 682 | } |
||
| 683 | |||
| 684 | /** |
||
| 685 | * Checks the input string (un-parsed TypoScript) for include-commands ("<INCLUDE_TYPOSCRIPT: ....") |
||
| 686 | * Use: \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines() |
||
| 687 | * |
||
| 688 | * @param string $string Unparsed TypoScript |
||
| 689 | * @param int $cycle_counter Counter for detecting endless loops |
||
| 690 | * @param bool $returnFiles When set an array containing the resulting typoscript and all included files will get returned |
||
| 691 | * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes |
||
| 692 | * @return string|array Complete TypoScript with includes added. |
||
| 693 | * @static |
||
| 694 | */ |
||
| 695 | public static function checkIncludeLines($string, $cycle_counter = 1, $returnFiles = false, $parentFilenameOrPath = '') |
||
| 696 | { |
||
| 697 | $includedFiles = []; |
||
| 698 | if ($cycle_counter > 100) { |
||
| 699 | self::getLogger()->warning('It appears like TypoScript code is looping over itself. Check your templates for "<INCLUDE_TYPOSCRIPT: ..." tags'); |
||
| 700 | if ($returnFiles) { |
||
| 701 | return [ |
||
| 702 | 'typoscript' => '', |
||
| 703 | 'files' => $includedFiles, |
||
| 704 | ]; |
||
| 705 | } |
||
| 706 | return ' |
||
| 707 | ### |
||
| 708 | ### ERROR: Recursion! |
||
| 709 | ### |
||
| 710 | '; |
||
| 711 | } |
||
| 712 | |||
| 713 | // Return early if $string is invalid |
||
| 714 | if (!is_string($string) || empty($string)) { |
||
| 715 | return !$returnFiles |
||
| 716 | ? '' |
||
| 717 | : [ |
||
| 718 | 'typoscript' => '', |
||
| 719 | 'files' => $includedFiles, |
||
| 720 | ] |
||
| 721 | ; |
||
| 722 | } |
||
| 723 | |||
| 724 | $string = StringUtility::removeByteOrderMark($string); |
||
| 725 | |||
| 726 | // Checking for @import syntax imported files |
||
| 727 | $string = self::addImportsFromExternalFiles($string, $cycle_counter, $returnFiles, $includedFiles, $parentFilenameOrPath); |
||
| 728 | |||
| 729 | // If no tags found, no need to do slower preg_split |
||
| 730 | if (str_contains($string, '<INCLUDE_TYPOSCRIPT:')) { |
||
| 731 | $splitRegEx = '/\r?\n\s*<INCLUDE_TYPOSCRIPT:\s*(?i)source\s*=\s*"((?i)file|dir):\s*([^"]*)"(.*)>[\ \t]*/'; |
||
| 732 | $parts = preg_split($splitRegEx, LF . $string . LF, -1, PREG_SPLIT_DELIM_CAPTURE); |
||
| 733 | $parts = is_array($parts) ? $parts : []; |
||
| 734 | |||
| 735 | // First text part goes through |
||
| 736 | $newString = ($parts[0] ?? '') . LF; |
||
| 737 | $partCount = count($parts); |
||
| 738 | for ($i = 1; $i + 3 < $partCount; $i += 4) { |
||
| 739 | // $parts[$i] contains 'FILE' or 'DIR' |
||
| 740 | // $parts[$i+1] contains relative file or directory path to be included |
||
| 741 | // $parts[$i+2] optional properties of the INCLUDE statement |
||
| 742 | // $parts[$i+3] next part of the typoscript string (part in between include-tags) |
||
| 743 | $includeType = $parts[$i]; |
||
| 744 | $filename = $parts[$i + 1]; |
||
| 745 | $originalFilename = $filename; |
||
| 746 | $optionalProperties = $parts[$i + 2]; |
||
| 747 | $tsContentsTillNextInclude = $parts[$i + 3]; |
||
| 748 | |||
| 749 | // Check condition |
||
| 750 | $matches = preg_split('#(?i)condition\\s*=\\s*"((?:\\\\\\\\|\\\\"|[^\\"])*)"(\\s*|>)#', $optionalProperties, 2, PREG_SPLIT_DELIM_CAPTURE); |
||
| 751 | $matches = is_array($matches) ? $matches : []; |
||
| 752 | |||
| 753 | // If there was a condition |
||
| 754 | if (count($matches) > 1) { |
||
| 755 | // Unescape the condition |
||
| 756 | $condition = trim(stripslashes($matches[1])); |
||
| 757 | // If necessary put condition in square brackets |
||
| 758 | if ($condition[0] !== '[') { |
||
| 759 | $condition = '[' . $condition . ']'; |
||
| 760 | } |
||
| 761 | |||
| 762 | /** @var AbstractConditionMatcher $conditionMatcher */ |
||
| 763 | $conditionMatcher = null; |
||
| 764 | if (($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface |
||
| 765 | && ApplicationType::fromRequest($GLOBALS['TYPO3_REQUEST'])->isFrontend() |
||
| 766 | ) { |
||
| 767 | $conditionMatcher = GeneralUtility::makeInstance(FrontendConditionMatcher::class); |
||
| 768 | } else { |
||
| 769 | $conditionMatcher = GeneralUtility::makeInstance(BackendConditionMatcher::class); |
||
| 770 | } |
||
| 771 | |||
| 772 | // If it didn't match then proceed to the next include, but prepend next normal (not file) part to output string |
||
| 773 | if (!$conditionMatcher->match($condition)) { |
||
| 774 | $newString .= $tsContentsTillNextInclude . LF; |
||
| 775 | continue; |
||
| 776 | } |
||
| 777 | } |
||
| 778 | |||
| 779 | // Resolve a possible relative paths if a parent file is given |
||
| 780 | if ($parentFilenameOrPath !== '' && $filename[0] === '.') { |
||
| 781 | $filename = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $filename); |
||
| 782 | } |
||
| 783 | |||
| 784 | // There must be a line-break char after - not sure why this check is necessary, kept it for being 100% backwards compatible |
||
| 785 | // An empty string is also ok (means that the next line is also a valid include_typoscript tag) |
||
| 786 | if (!preg_match('/(^\\s*\\r?\\n|^$)/', $tsContentsTillNextInclude)) { |
||
| 787 | $newString .= self::typoscriptIncludeError('Invalid characters after <INCLUDE_TYPOSCRIPT: source="' . $includeType . ':' . $filename . '">-tag (rest of line must be empty).'); |
||
| 788 | } elseif (str_contains('..', $filename)) { |
||
| 789 | $newString .= self::typoscriptIncludeError('Invalid filepath "' . $filename . '" (containing "..").'); |
||
| 790 | } else { |
||
| 791 | switch (strtolower($includeType)) { |
||
| 792 | case 'file': |
||
| 793 | self::includeFile($originalFilename, $cycle_counter, $returnFiles, $newString, $includedFiles, $optionalProperties, $parentFilenameOrPath); |
||
| 794 | break; |
||
| 795 | case 'dir': |
||
| 796 | self::includeDirectory($originalFilename, $cycle_counter, $returnFiles, $newString, $includedFiles, $optionalProperties, $parentFilenameOrPath); |
||
| 797 | break; |
||
| 798 | default: |
||
| 799 | $newString .= self::typoscriptIncludeError('No valid option for INCLUDE_TYPOSCRIPT source property (valid options are FILE or DIR)'); |
||
| 800 | } |
||
| 801 | } |
||
| 802 | // Prepend next normal (not file) part to output string |
||
| 803 | $newString .= $tsContentsTillNextInclude . LF; |
||
| 804 | |||
| 805 | // load default TypoScript for content rendering templates like |
||
| 806 | // fluid_styled_content if those have been included through f.e. |
||
| 807 | // <INCLUDE_TYPOSCRIPT: source="FILE:EXT:fluid_styled_content/Configuration/TypoScript/setup.typoscript"> |
||
| 808 | if (strpos(strtolower($filename), 'ext:') === 0) { |
||
| 809 | $filePointerPathParts = explode('/', substr($filename, 4)); |
||
| 810 | |||
| 811 | // remove file part, determine whether to load setup or constants |
||
| 812 | [$includeType, ] = explode('.', (string)array_pop($filePointerPathParts)); |
||
| 813 | |||
| 814 | if (in_array($includeType, ['setup', 'constants'])) { |
||
| 815 | // adapt extension key to required format (no underscores) |
||
| 816 | $filePointerPathParts[0] = str_replace('_', '', $filePointerPathParts[0]); |
||
| 817 | |||
| 818 | // load default TypoScript |
||
| 819 | $defaultTypoScriptKey = implode('/', $filePointerPathParts) . '/'; |
||
| 820 | if (in_array($defaultTypoScriptKey, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) { |
||
| 821 | $newString .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $includeType . '.']['defaultContentRendering'] ?? ''; |
||
| 822 | } |
||
| 823 | } |
||
| 824 | } |
||
| 825 | } |
||
| 826 | // Add a line break before and after the included code in order to make sure that the parser always has a LF. |
||
| 827 | $string = LF . trim($newString) . LF; |
||
| 828 | } |
||
| 829 | // When all included files should get returned, simply return a compound array containing |
||
| 830 | // the TypoScript with all "includes" processed and the files which got included |
||
| 831 | if ($returnFiles) { |
||
| 832 | return [ |
||
| 833 | 'typoscript' => $string, |
||
| 834 | 'files' => $includedFiles, |
||
| 835 | ]; |
||
| 836 | } |
||
| 837 | return $string; |
||
| 838 | } |
||
| 839 | |||
| 840 | /** |
||
| 841 | * Splits the unparsed TypoScript content into import statements |
||
| 842 | * |
||
| 843 | * @param string $typoScript unparsed TypoScript |
||
| 844 | * @param int $cycleCounter counter to stop recursion |
||
| 845 | * @param bool $returnFiles whether to populate the included Files or not |
||
| 846 | * @param array $includedFiles - by reference - if any included files are added, they are added here |
||
| 847 | * @param string $parentFilenameOrPath the current imported file to resolve relative paths - handled by reference |
||
| 848 | * @return string the unparsed TypoScript with included external files |
||
| 849 | */ |
||
| 850 | protected static function addImportsFromExternalFiles($typoScript, $cycleCounter, $returnFiles, &$includedFiles, &$parentFilenameOrPath) |
||
| 851 | { |
||
| 852 | // Check for new syntax "@import 'EXT:bennilove/Configuration/TypoScript/*'" |
||
| 853 | if (is_string($typoScript) && (str_contains($typoScript, '@import \'') || str_contains($typoScript, '@import "'))) { |
||
| 854 | $splitRegEx = '/\r?\n\s*@import\s[\'"]([^\'"]*)[\'"][\ \t]?/'; |
||
| 855 | $parts = preg_split($splitRegEx, LF . $typoScript . LF, -1, PREG_SPLIT_DELIM_CAPTURE); |
||
| 856 | $parts = is_array($parts) ? $parts : []; |
||
| 857 | // First text part goes through |
||
| 858 | $newString = $parts[0] . LF; |
||
| 859 | $partCount = count($parts); |
||
| 860 | for ($i = 1; $i + 2 <= $partCount; $i += 2) { |
||
| 861 | $filename = $parts[$i]; |
||
| 862 | $tsContentsTillNextInclude = $parts[$i + 1]; |
||
| 863 | // Resolve a possible relative paths if a parent file is given |
||
| 864 | if ($parentFilenameOrPath !== '' && $filename[0] === '.') { |
||
| 865 | $filename = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $filename); |
||
| 866 | } |
||
| 867 | $newString .= self::importExternalTypoScriptFile($filename, $cycleCounter, $returnFiles, $includedFiles); |
||
| 868 | // Prepend next normal (not file) part to output string |
||
| 869 | $newString .= $tsContentsTillNextInclude; |
||
| 870 | } |
||
| 871 | // Add a line break before and after the included code in order to make sure that the parser always has a LF. |
||
| 872 | $typoScript = LF . trim($newString) . LF; |
||
| 873 | } |
||
| 874 | return $typoScript; |
||
| 875 | } |
||
| 876 | |||
| 877 | /** |
||
| 878 | * Include file $filename. Contents of the file will be returned, filename is added to &$includedFiles. |
||
| 879 | * Further include/import statements in the contents are processed recursively. |
||
| 880 | * |
||
| 881 | * @param string $filename Full absolute path+filename to the typoscript file to be included |
||
| 882 | * @param int $cycleCounter Counter for detecting endless loops |
||
| 883 | * @param bool $returnFiles When set, filenames of included files will be prepended to the array $includedFiles |
||
| 884 | * @param array $includedFiles Array to which the filenames of included files will be prepended (referenced) |
||
| 885 | * @return string the unparsed TypoScript content from external files |
||
| 886 | */ |
||
| 887 | protected static function importExternalTypoScriptFile($filename, $cycleCounter, $returnFiles, array &$includedFiles) |
||
| 888 | { |
||
| 889 | if (str_contains('..', $filename)) { |
||
| 890 | return self::typoscriptIncludeError('Invalid filepath "' . $filename . '" (containing "..").'); |
||
| 891 | } |
||
| 892 | |||
| 893 | $content = ''; |
||
| 894 | $absoluteFileName = GeneralUtility::getFileAbsFileName($filename); |
||
| 895 | if ((string)$absoluteFileName === '') { |
||
| 896 | return self::typoscriptIncludeError('Illegal filepath "' . $filename . '".'); |
||
| 897 | } |
||
| 898 | |||
| 899 | $finder = new Finder(); |
||
| 900 | $finder |
||
| 901 | // no recursive mode on purpose |
||
| 902 | ->depth(0) |
||
| 903 | // no directories should be fetched |
||
| 904 | ->files() |
||
| 905 | ->sortByName(); |
||
| 906 | |||
| 907 | // Search all files in the folder |
||
| 908 | if (is_dir($absoluteFileName)) { |
||
| 909 | $finder |
||
| 910 | ->in($absoluteFileName) |
||
| 911 | ->name('*.typoscript'); |
||
| 912 | // Used for the TypoScript comments |
||
| 913 | $readableFilePrefix = $filename; |
||
| 914 | } else { |
||
| 915 | try { |
||
| 916 | // Apparently this is not a folder, so the restriction |
||
| 917 | // is the folder so we restrict into this folder |
||
| 918 | $finder->in(PathUtility::dirname($absoluteFileName)); |
||
| 919 | if (!is_file($absoluteFileName) |
||
| 920 | && !str_contains(PathUtility::basename($absoluteFileName), '*') |
||
| 921 | && substr(PathUtility::basename($absoluteFileName), -11) !== '.typoscript') { |
||
| 922 | $absoluteFileName .= '*.typoscript'; |
||
| 923 | } |
||
| 924 | $finder->name(PathUtility::basename($absoluteFileName)); |
||
| 925 | $readableFilePrefix = PathUtility::dirname($filename); |
||
| 926 | } catch (\InvalidArgumentException $e) { |
||
| 927 | return self::typoscriptIncludeError($e->getMessage()); |
||
| 928 | } |
||
| 929 | } |
||
| 930 | |||
| 931 | foreach ($finder as $fileObject) { |
||
| 932 | // Clean filename output for comments |
||
| 933 | $readableFileName = rtrim($readableFilePrefix, '/') . '/' . $fileObject->getFilename(); |
||
| 934 | $content .= LF . '### @import \'' . $readableFileName . '\' begin ###' . LF; |
||
| 935 | // Check for allowed files |
||
| 936 | if (!GeneralUtility::makeInstance(FileNameValidator::class)->isValid($fileObject->getFilename())) { |
||
| 937 | $content .= self::typoscriptIncludeError('File "' . $readableFileName . '" was not included since it is not allowed due to fileDenyPattern.'); |
||
| 938 | } else { |
||
| 939 | $includedFiles[] = $fileObject->getPathname(); |
||
| 940 | // check for includes in included text |
||
| 941 | $included_text = self::checkIncludeLines($fileObject->getContents(), $cycleCounter++, $returnFiles, $absoluteFileName); |
||
| 942 | // If the method also has to return all included files, merge currently included |
||
| 943 | // files with files included by recursively calling itself |
||
| 944 | if ($returnFiles && is_array($included_text)) { |
||
| 945 | $includedFiles = array_merge($includedFiles, $included_text['files']); |
||
| 946 | $included_text = $included_text['typoscript']; |
||
| 947 | } |
||
| 948 | $content .= $included_text . LF; |
||
| 949 | } |
||
| 950 | $content .= '### @import \'' . $readableFileName . '\' end ###' . LF . LF; |
||
| 951 | |||
| 952 | // load default TypoScript for content rendering templates like |
||
| 953 | // fluid_styled_content if those have been included through e.g. |
||
| 954 | // @import "fluid_styled_content/Configuration/TypoScript/setup.typoscript" |
||
| 955 | if (PathUtility::isExtensionPath(strtoupper($filename))) { |
||
| 956 | $filePointerPathParts = explode('/', substr($filename, 4)); |
||
| 957 | // remove file part, determine whether to load setup or constants |
||
| 958 | [$includeType] = explode('.', (string)array_pop($filePointerPathParts)); |
||
| 959 | |||
| 960 | if (in_array($includeType, ['setup', 'constants'], true)) { |
||
| 961 | // adapt extension key to required format (no underscores) |
||
| 962 | $filePointerPathParts[0] = str_replace('_', '', $filePointerPathParts[0]); |
||
| 963 | |||
| 964 | // load default TypoScript |
||
| 965 | $defaultTypoScriptKey = implode('/', $filePointerPathParts) . '/'; |
||
| 966 | if (in_array($defaultTypoScriptKey, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) { |
||
| 967 | $content .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $includeType . '.']['defaultContentRendering'] ?? ''; |
||
| 968 | } |
||
| 969 | } |
||
| 970 | } |
||
| 971 | } |
||
| 972 | |||
| 973 | if (empty($content)) { |
||
| 974 | return self::typoscriptIncludeError('No file or folder found for importing TypoScript on "' . $filename . '".'); |
||
| 975 | } |
||
| 976 | return $content; |
||
| 977 | } |
||
| 978 | |||
| 979 | /** |
||
| 980 | * Include file $filename. Contents of the file will be prepended to &$newstring, filename to &$includedFiles |
||
| 981 | * Further include_typoscript tags in the contents are processed recursively |
||
| 982 | * |
||
| 983 | * @param string $filename Relative path to the typoscript file to be included |
||
| 984 | * @param int $cycle_counter Counter for detecting endless loops |
||
| 985 | * @param bool $returnFiles When set, filenames of included files will be prepended to the array $includedFiles |
||
| 986 | * @param string $newString The output string to which the content of the file will be prepended (referenced |
||
| 987 | * @param array $includedFiles Array to which the filenames of included files will be prepended (referenced) |
||
| 988 | * @param string $optionalProperties |
||
| 989 | * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes |
||
| 990 | * @static |
||
| 991 | * @internal |
||
| 992 | */ |
||
| 993 | public static function includeFile($filename, $cycle_counter = 1, $returnFiles = false, &$newString = '', array &$includedFiles = [], $optionalProperties = '', $parentFilenameOrPath = '') |
||
| 994 | { |
||
| 995 | // Resolve a possible relative paths if a parent file is given |
||
| 996 | if ($parentFilenameOrPath !== '' && $filename[0] === '.') { |
||
| 997 | $absfilename = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $filename); |
||
| 998 | } else { |
||
| 999 | $absfilename = $filename; |
||
| 1000 | } |
||
| 1001 | $absfilename = GeneralUtility::getFileAbsFileName($absfilename); |
||
| 1002 | |||
| 1003 | $newString .= LF . '### <INCLUDE_TYPOSCRIPT: source="FILE:' . $filename . '"' . $optionalProperties . '> BEGIN:' . LF; |
||
| 1004 | if ((string)$filename !== '') { |
||
| 1005 | // Must exist and must not contain '..' and must be relative |
||
| 1006 | // Check for allowed files |
||
| 1007 | if (!GeneralUtility::makeInstance(FileNameValidator::class)->isValid($absfilename)) { |
||
| 1008 | $newString .= self::typoscriptIncludeError('File "' . $filename . '" was not included since it is not allowed due to fileDenyPattern.'); |
||
| 1009 | } else { |
||
| 1010 | $fileExists = false; |
||
| 1011 | if (@file_exists($absfilename)) { |
||
| 1012 | $fileExists = true; |
||
| 1013 | } |
||
| 1014 | |||
| 1015 | if ($fileExists) { |
||
| 1016 | $includedFiles[] = $absfilename; |
||
| 1017 | // check for includes in included text |
||
| 1018 | $included_text = self::checkIncludeLines((string)file_get_contents($absfilename), $cycle_counter + 1, $returnFiles, $absfilename); |
||
| 1019 | // If the method also has to return all included files, merge currently included |
||
| 1020 | // files with files included by recursively calling itself |
||
| 1021 | if ($returnFiles && is_array($included_text)) { |
||
| 1022 | $includedFiles = array_merge($includedFiles, $included_text['files']); |
||
| 1023 | $included_text = $included_text['typoscript']; |
||
| 1024 | } |
||
| 1025 | $newString .= $included_text . LF; |
||
| 1026 | } else { |
||
| 1027 | $newString .= self::typoscriptIncludeError('File "' . $filename . '" was not found.'); |
||
| 1028 | } |
||
| 1029 | } |
||
| 1030 | } |
||
| 1031 | $newString .= '### <INCLUDE_TYPOSCRIPT: source="FILE:' . $filename . '"' . $optionalProperties . '> END:' . LF . LF; |
||
| 1032 | } |
||
| 1033 | |||
| 1034 | /** |
||
| 1035 | * Include all files with matching Typoscript extensions in directory $dirPath. Contents of the files are |
||
| 1036 | * prepended to &$newstring, filename to &$includedFiles. |
||
| 1037 | * Order of the directory items to be processed: files first, then directories, both in alphabetical order. |
||
| 1038 | * Further include_typoscript tags in the contents of the files are processed recursively. |
||
| 1039 | * |
||
| 1040 | * @param string $dirPath Relative path to the directory to be included |
||
| 1041 | * @param int $cycle_counter Counter for detecting endless loops |
||
| 1042 | * @param bool $returnFiles When set, filenames of included files will be prepended to the array $includedFiles |
||
| 1043 | * @param string $newString The output string to which the content of the file will be prepended (referenced) |
||
| 1044 | * @param array $includedFiles Array to which the filenames of included files will be prepended (referenced) |
||
| 1045 | * @param string $optionalProperties |
||
| 1046 | * @param string $parentFilenameOrPath The parent file (with absolute path) or path for relative includes |
||
| 1047 | * @static |
||
| 1048 | */ |
||
| 1049 | protected static function includeDirectory($dirPath, $cycle_counter = 1, $returnFiles = false, &$newString = '', array &$includedFiles = [], $optionalProperties = '', $parentFilenameOrPath = '') |
||
| 1050 | { |
||
| 1051 | // Extract the value of the property extensions="..." |
||
| 1052 | $matches = preg_split('#(?i)extensions\s*=\s*"([^"]*)"(\s*|>)#', $optionalProperties, 2, PREG_SPLIT_DELIM_CAPTURE); |
||
| 1053 | $matches = is_array($matches) ? $matches : []; |
||
| 1054 | if (count($matches) > 1) { |
||
| 1055 | $includedFileExtensions = $matches[1]; |
||
| 1056 | } else { |
||
| 1057 | $includedFileExtensions = ''; |
||
| 1058 | } |
||
| 1059 | |||
| 1060 | // Resolve a possible relative paths if a parent file is given |
||
| 1061 | if ($parentFilenameOrPath !== '' && $dirPath[0] === '.') { |
||
| 1062 | $resolvedDirPath = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $dirPath); |
||
| 1063 | } else { |
||
| 1064 | $resolvedDirPath = $dirPath; |
||
| 1065 | } |
||
| 1066 | $absDirPath = GeneralUtility::getFileAbsFileName($resolvedDirPath); |
||
| 1067 | if ($absDirPath) { |
||
| 1068 | $absDirPath = rtrim($absDirPath, '/') . '/'; |
||
| 1069 | $newString .= LF . '### <INCLUDE_TYPOSCRIPT: source="DIR:' . $dirPath . '"' . $optionalProperties . '> BEGIN:' . LF; |
||
| 1070 | // Get alphabetically sorted file index in array |
||
| 1071 | $fileIndex = GeneralUtility::getAllFilesAndFoldersInPath([], $absDirPath, $includedFileExtensions); |
||
| 1072 | // Prepend file contents to $newString |
||
| 1073 | foreach ($fileIndex as $absFileRef) { |
||
| 1074 | self::includeFile($absFileRef, $cycle_counter, $returnFiles, $newString, $includedFiles); |
||
| 1075 | } |
||
| 1076 | $newString .= '### <INCLUDE_TYPOSCRIPT: source="DIR:' . $dirPath . '"' . $optionalProperties . '> END:' . LF . LF; |
||
| 1077 | } else { |
||
| 1078 | $newString .= self::typoscriptIncludeError('The path "' . $resolvedDirPath . '" is invalid.'); |
||
| 1079 | } |
||
| 1080 | } |
||
| 1081 | |||
| 1082 | /** |
||
| 1083 | * Process errors in INCLUDE_TYPOSCRIPT tags |
||
| 1084 | * Errors are logged and printed in the concatenated TypoScript result (as can be seen in Template Analyzer) |
||
| 1085 | * |
||
| 1086 | * @param string $error Text of the error message |
||
| 1087 | * @return string The error message encapsulated in comments |
||
| 1088 | * @static |
||
| 1089 | */ |
||
| 1090 | protected static function typoscriptIncludeError($error) |
||
| 1094 | } |
||
| 1095 | |||
| 1096 | /** |
||
| 1097 | * Parses the string in each value of the input array for include-commands |
||
| 1098 | * |
||
| 1099 | * @param array $array Array with TypoScript in each value |
||
| 1100 | * @return array Same array but where the values has been parsed for include-commands |
||
| 1101 | */ |
||
| 1102 | public static function checkIncludeLines_array(array $array) |
||
| 1103 | { |
||
| 1104 | foreach ($array as $k => $v) { |
||
| 1105 | $array[$k] = self::checkIncludeLines($array[$k]); |
||
| 1106 | } |
||
| 1107 | return $array; |
||
| 1108 | } |
||
| 1109 | |||
| 1110 | /** |
||
| 1111 | * Search for commented INCLUDE_TYPOSCRIPT statements |
||
| 1112 | * and save the content between the BEGIN and the END line to the specified file |
||
| 1113 | * |
||
| 1114 | * @param string $string Template content |
||
| 1115 | * @param int $cycle_counter Counter for detecting endless loops |
||
| 1116 | * @param array $extractedFileNames |
||
| 1117 | * @param string $parentFilenameOrPath |
||
| 1118 | * |
||
| 1119 | * @throws \RuntimeException |
||
| 1120 | * @throws \UnexpectedValueException |
||
| 1121 | * @return string Template content with uncommented include statements |
||
| 1122 | * @internal |
||
| 1123 | */ |
||
| 1124 | public static function extractIncludes($string, $cycle_counter = 1, array $extractedFileNames = [], $parentFilenameOrPath = '') |
||
| 1125 | { |
||
| 1126 | if ($cycle_counter > 10) { |
||
| 1127 | self::getLogger()->warning('It appears like TypoScript code is looping over itself. Check your templates for "<INCLUDE_TYPOSCRIPT: ..." tags'); |
||
| 1128 | return ' |
||
| 1129 | ### |
||
| 1130 | ### ERROR: Recursion! |
||
| 1131 | ### |
||
| 1132 | '; |
||
| 1133 | } |
||
| 1134 | $expectedEndTag = ''; |
||
| 1135 | $fileContent = []; |
||
| 1136 | $restContent = []; |
||
| 1137 | $fileName = null; |
||
| 1138 | $inIncludePart = false; |
||
| 1139 | $lines = preg_split("/\r\n|\n|\r/", $string); |
||
| 1140 | $skipNextLineIfEmpty = false; |
||
| 1141 | $openingCommentedIncludeStatement = null; |
||
| 1142 | $optionalProperties = ''; |
||
| 1143 | foreach ($lines as $line) { |
||
| 1144 | // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts |
||
| 1145 | // an additional empty line, remove this again |
||
| 1146 | if ($skipNextLineIfEmpty) { |
||
| 1147 | if (trim($line) === '') { |
||
| 1148 | continue; |
||
| 1149 | } |
||
| 1150 | $skipNextLineIfEmpty = false; |
||
| 1151 | } |
||
| 1152 | |||
| 1153 | // Outside commented include statements |
||
| 1154 | if (!$inIncludePart) { |
||
| 1155 | // Search for beginning commented include statements |
||
| 1156 | if (preg_match('/###\\s*<INCLUDE_TYPOSCRIPT:\\s*source\\s*=\\s*"\\s*((?i)file|dir)\\s*:\\s*([^"]*)"(.*)>\\s*BEGIN/i', $line, $matches)) { |
||
| 1157 | // Found a commented include statement |
||
| 1158 | |||
| 1159 | // Save this line in case there is no ending tag |
||
| 1160 | $openingCommentedIncludeStatement = trim($line); |
||
| 1161 | $openingCommentedIncludeStatement = preg_replace('/\\s*### Warning: .*###\\s*/', '', $openingCommentedIncludeStatement); |
||
| 1162 | |||
| 1163 | // type of match: FILE or DIR |
||
| 1164 | $inIncludePart = strtoupper($matches[1]); |
||
| 1165 | $fileName = $matches[2]; |
||
| 1166 | $optionalProperties = $matches[3]; |
||
| 1167 | |||
| 1168 | $expectedEndTag = '### <INCLUDE_TYPOSCRIPT: source="' . $inIncludePart . ':' . $fileName . '"' . $optionalProperties . '> END'; |
||
| 1169 | // Strip all whitespace characters to make comparison safer |
||
| 1170 | $expectedEndTag = strtolower(preg_replace('/\s/', '', $expectedEndTag) ?? ''); |
||
| 1171 | } else { |
||
| 1172 | // If this is not a beginning commented include statement this line goes into the rest content |
||
| 1173 | $restContent[] = $line; |
||
| 1174 | } |
||
| 1175 | } else { |
||
| 1176 | // Inside commented include statements |
||
| 1177 | // Search for the matching ending commented include statement |
||
| 1178 | $strippedLine = preg_replace('/\s/', '', $line); |
||
| 1179 | if (stripos($strippedLine, $expectedEndTag) !== false) { |
||
| 1180 | // Found the matching ending include statement |
||
| 1181 | $fileContentString = implode(PHP_EOL, $fileContent); |
||
| 1182 | |||
| 1183 | // Write the content to the file |
||
| 1184 | |||
| 1185 | // Resolve a possible relative paths if a parent file is given |
||
| 1186 | if ($parentFilenameOrPath !== '' && $fileName[0] === '.') { |
||
| 1187 | $realFileName = PathUtility::getAbsolutePathOfRelativeReferencedFileOrPath($parentFilenameOrPath, $fileName); |
||
| 1188 | } else { |
||
| 1189 | $realFileName = $fileName; |
||
| 1190 | } |
||
| 1191 | $realFileName = GeneralUtility::getFileAbsFileName($realFileName); |
||
| 1192 | |||
| 1193 | if ($inIncludePart === 'FILE') { |
||
| 1194 | // Some file checks |
||
| 1195 | if (!GeneralUtility::makeInstance(FileNameValidator::class)->isValid($realFileName)) { |
||
| 1196 | throw new \UnexpectedValueException(sprintf('File "%s" was not included since it is not allowed due to fileDenyPattern.', $fileName), 1382651858); |
||
| 1197 | } |
||
| 1198 | if (empty($realFileName)) { |
||
| 1199 | throw new \UnexpectedValueException(sprintf('"%s" is not a valid file location.', $fileName), 1294586441); |
||
| 1200 | } |
||
| 1201 | if (!is_writable($realFileName)) { |
||
| 1202 | throw new \RuntimeException(sprintf('"%s" is not writable.', $fileName), 1294586442); |
||
| 1203 | } |
||
| 1204 | if (in_array($realFileName, $extractedFileNames)) { |
||
| 1205 | throw new \RuntimeException(sprintf('Recursive/multiple inclusion of file "%s"', $realFileName), 1294586443); |
||
| 1206 | } |
||
| 1207 | $extractedFileNames[] = $realFileName; |
||
| 1208 | |||
| 1209 | // Recursive call to detected nested commented include statements |
||
| 1210 | $fileContentString = self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName); |
||
| 1211 | |||
| 1212 | // Write the content to the file |
||
| 1213 | if (!GeneralUtility::writeFile($realFileName, $fileContentString)) { |
||
| 1214 | throw new \RuntimeException(sprintf('Could not write file "%s"', $realFileName), 1294586444); |
||
| 1215 | } |
||
| 1216 | // Insert reference to the file in the rest content |
||
| 1217 | $restContent[] = '<INCLUDE_TYPOSCRIPT: source="FILE:' . $fileName . '"' . $optionalProperties . '>'; |
||
| 1218 | } else { |
||
| 1219 | // must be DIR |
||
| 1220 | |||
| 1221 | // Some file checks |
||
| 1222 | if (empty($realFileName)) { |
||
| 1223 | throw new \UnexpectedValueException(sprintf('"%s" is not a valid location.', $fileName), 1366493602); |
||
| 1224 | } |
||
| 1225 | if (!is_dir($realFileName)) { |
||
| 1226 | throw new \RuntimeException(sprintf('"%s" is not a directory.', $fileName), 1366493603); |
||
| 1227 | } |
||
| 1228 | if (in_array($realFileName, $extractedFileNames)) { |
||
| 1229 | throw new \RuntimeException(sprintf('Recursive/multiple inclusion of directory "%s"', $realFileName), 1366493604); |
||
| 1230 | } |
||
| 1231 | $extractedFileNames[] = $realFileName; |
||
| 1232 | |||
| 1233 | // Recursive call to detected nested commented include statements |
||
| 1234 | self::extractIncludes($fileContentString, $cycle_counter + 1, $extractedFileNames, $realFileName); |
||
| 1235 | |||
| 1236 | // just drop content between tags since it should usually just contain individual files from that dir |
||
| 1237 | |||
| 1238 | // Insert reference to the dir in the rest content |
||
| 1239 | $restContent[] = '<INCLUDE_TYPOSCRIPT: source="DIR:' . $fileName . '"' . $optionalProperties . '>'; |
||
| 1240 | } |
||
| 1241 | |||
| 1242 | // Reset variables (preparing for the next commented include statement) |
||
| 1243 | $fileContent = []; |
||
| 1244 | $fileName = null; |
||
| 1245 | $inIncludePart = false; |
||
| 1246 | $openingCommentedIncludeStatement = null; |
||
| 1247 | // \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines inserts |
||
| 1248 | // an additional empty line, remove this again |
||
| 1249 | $skipNextLineIfEmpty = true; |
||
| 1250 | } else { |
||
| 1251 | // If this is not an ending commented include statement this line goes into the file content |
||
| 1252 | $fileContent[] = $line; |
||
| 1253 | } |
||
| 1254 | } |
||
| 1255 | } |
||
| 1256 | // If we're still inside commented include statements copy the lines back to the rest content |
||
| 1257 | if ($inIncludePart) { |
||
| 1258 | $restContent[] = $openingCommentedIncludeStatement . ' ### Warning: Corresponding end line missing! ###'; |
||
| 1259 | $restContent = array_merge($restContent, $fileContent); |
||
| 1260 | } |
||
| 1261 | $restContentString = implode(PHP_EOL, $restContent); |
||
| 1262 | return $restContentString; |
||
| 1263 | } |
||
| 1264 | |||
| 1265 | /** |
||
| 1266 | * Processes the string in each value of the input array with extractIncludes |
||
| 1267 | * |
||
| 1268 | * @param array $array Array with TypoScript in each value |
||
| 1269 | * @return array Same array but where the values has been processed with extractIncludes |
||
| 1270 | */ |
||
| 1271 | public static function extractIncludes_array(array $array) |
||
| 1272 | { |
||
| 1273 | foreach ($array as $k => $v) { |
||
| 1274 | $array[$k] = self::extractIncludes($array[$k]); |
||
| 1275 | } |
||
| 1276 | return $array; |
||
| 1277 | } |
||
| 1278 | |||
| 1279 | /** |
||
| 1280 | * @param string $string |
||
| 1281 | * @return string |
||
| 1282 | * @deprecated since v11, will be removed in v12. |
||
| 1283 | */ |
||
| 1284 | public function doSyntaxHighlight($string) |
||
| 1285 | { |
||
| 1286 | return $string; |
||
| 1287 | } |
||
| 1288 | |||
| 1289 | /** |
||
| 1290 | * @return TimeTracker |
||
| 1291 | */ |
||
| 1292 | protected function getTimeTracker() |
||
| 1293 | { |
||
| 1294 | return GeneralUtility::makeInstance(TimeTracker::class); |
||
| 1295 | } |
||
| 1296 | |||
| 1297 | /** |
||
| 1298 | * Get a logger instance |
||
| 1299 | * |
||
| 1300 | * This class uses logging mostly in static functions, hence we need a static getter for the logger. |
||
| 1301 | * Injection of a logger instance via GeneralUtility::makeInstance is not possible. |
||
| 1302 | * |
||
| 1303 | * @return LoggerInterface |
||
| 1304 | */ |
||
| 1305 | protected static function getLogger() |
||
| 1308 | } |
||
| 1309 | } |
||
| 1310 |