dfebd16bde2ef9e07063cf50d81deb1b43038fc6
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / TypoScript / TemplateService.php
1 <?php
2 namespace TYPO3\CMS\Core\TypoScript;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19
20 /**
21 * Template object that is responsible for generating the TypoScript template based on template records.
22 *
23 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
24 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
25 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
26 */
27 class TemplateService {
28
29 // Debugging, analysis:
30 /**
31 * option to enable logging, time-tracking (FE-only)
32 * usually, this is only done when
33 * - in FE a BE_USER is logged-in
34 * - in BE when the BE_USER needs information about the template (TypoScript module)
35 * @var bool
36 */
37 protected $verbose = FALSE;
38
39 // If set, the global tt-timeobject is used to log the performance.
40 public $tt_track = 1;
41
42 // If set, the template is always rendered. Used from Admin Panel.
43 public $forceTemplateParsing = 0;
44
45 // Backend Analysis modules settings:
46 // This array is passed on to matchObj by generateConfig(). If it holds elements, they are used for matching instead. See commment at the match-class. Used for backend modules only. Never frontend!
47 public $matchAlternative = array();
48
49 // If set, the match-class matches everything! Used for backend modules only. Never frontend!
50 public $matchAll = 0;
51
52 public $backend_info = 0;
53
54 // Externally set breakpoints (used by Backend Modules)
55 public $ext_constants_BRP = 0;
56
57 public $ext_config_BRP = 0;
58
59 public $ext_regLinenumbers = FALSE;
60
61 public $ext_regComments = FALSE;
62
63 // Constants:
64 public $tempPath = 'typo3temp/';
65
66 // Set Internally:
67 // This MUST be initialized by the init() function
68 public $whereClause = '';
69
70 public $debug = 0;
71
72 // This is the only paths (relative!!) that are allowed for resources in TypoScript. Should all be appended with '/'. You can extend these by the global array TYPO3_CONF_VARS. See init() function.
73 public $allowedPaths = array();
74
75 // See init(); Set if preview of some kind is enabled.
76 public $simulationHiddenOrTime = 0;
77
78 // Set, if the TypoScript template structure is loaded and OK, see ->start()
79 public $loaded = 0;
80
81 /**
82 * @var array Contains TypoScript setup part after parsing
83 */
84 public $setup = array();
85
86 public $flatSetup = array();
87
88 // For fetching TypoScript code from template hierarchy before parsing it. Each array contains code field values from template records/files:
89 // Setup field
90 public $config = array();
91
92 // Constant field
93 public $constants = array();
94
95 /**
96 * Holds the include paths of the templates (empty if from database)
97 * @var array
98 */
99 protected $templateIncludePaths = array();
100
101 // For Template Analyser in backend
102 public $hierarchyInfo = array();
103
104 // For Template Analyser in backend (setup content only)
105 public $hierarchyInfoToRoot = array();
106
107 // Next-level flag (see runThroughTemplates())
108 public $nextLevel = 0;
109
110 // The Page UID of the root page
111 public $rootId;
112
113 // The rootline from current page to the root page
114 public $rootLine;
115
116 // Rootline all the way to the root. Set but runThroughTemplates
117 public $absoluteRootLine;
118
119 // A pointer to the last entry in the rootline where a template was found.
120 public $outermostRootlineIndexWithTemplate = 0;
121
122 // Array of arrays with title/uid of templates in hierarchy
123 public $rowSum;
124
125 // The current site title field.
126 public $sitetitle = '';
127
128 // Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
129 public $sections;
130
131 // Tracking all matching conditions found
132 public $sectionsMatch;
133
134 /**
135 * Used by Backend only (Typoscript Template Analyzer)
136 *
137 */
138 public $clearList_const = array();
139
140 /**
141 * Used by Backend only (Typoscript Template Analyzer)
142 *
143 */
144 public $clearList_setup = array();
145
146 public $parserErrors = array();
147
148 public $setup_constants = array();
149
150 // Other:
151 // Used by getFileName for caching of references to file resources
152 public $fileCache = array();
153
154 // Keys are frame names and values are type-values, which must be used to refer correctly to the content of the frames.
155 public $frames = array();
156
157 // Contains mapping of Page id numbers to MP variables.
158 public $MPmap = '';
159
160 /**
161 * Indicator that extension statics are processed.
162 *
163 * These files are considered if either a root template
164 * has been processed or the $processExtensionStatics
165 * property has been set to TRUE.
166 *
167 * @var boolean
168 */
169 protected $extensionStaticsProcessed = FALSE;
170
171 /**
172 * Trigger value, to ensure that extension statics are processed.
173 *
174 * @var boolean
175 */
176 protected $processExtensionStatics = FALSE;
177
178 /**
179 * Set to TRUE after the default TypoScript was added during parsing.
180 * This prevents double inclusion of the same TypoScript code.
181 *
182 * @see addDefaultTypoScript()
183 * @var boolean
184 */
185 protected $isDefaultTypoScriptAdded = FALSE;
186
187 /**
188 * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
189 *
190 * This prevents double processing of INCLUDES.
191 *
192 * @see processIncludes()
193 * @var boolean
194 */
195 protected $processIncludesHasBeenRun = FALSE;
196
197 /**
198 * @return bool
199 */
200 public function getProcessExtensionStatics() {
201 return $this->processExtensionStatics;
202 }
203
204 /**
205 * @param bool $processExtensionStatics
206 */
207 public function setProcessExtensionStatics($processExtensionStatics) {
208 $this->processExtensionStatics = (bool) $processExtensionStatics;
209 }
210
211 /**
212 * sets the verbose parameter
213 * @param bool $verbose
214 */
215 public function setVerbose($verbose) {
216 $this->verbose = (bool)$verbose;
217 }
218
219 /**
220 * Initialize
221 * MUST be called directly after creating a new template-object
222 *
223 * @return void
224 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initTemplate()
225 */
226 public function init() {
227 // $this->whereClause is used only to select templates from sys_template.
228 // $GLOBALS['SIM_ACCESS_TIME'] is used so that we're able to simulate a later time as a test...
229 $this->whereClause = 'AND deleted=0 ';
230 if (!$GLOBALS['TSFE']->showHiddenRecords) {
231 $this->whereClause .= 'AND hidden=0 ';
232 }
233 if ($GLOBALS['TSFE']->showHiddenRecords || $GLOBALS['SIM_ACCESS_TIME'] != $GLOBALS['ACCESS_TIME']) {
234 // Set the simulation flag, if simulation is detected!
235 $this->simulationHiddenOrTime = 1;
236 }
237 $this->whereClause .= 'AND (starttime<=' . $GLOBALS['SIM_ACCESS_TIME'] . ') AND (endtime=0 OR endtime>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
238 // Sets the paths from where TypoScript resources are allowed to be used:
239 $this->allowedPaths = array(
240 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'],
241 // fileadmin/ path
242 'uploads/',
243 'typo3temp/',
244 TYPO3_mainDir . 'ext/',
245 TYPO3_mainDir . 'sysext/',
246 TYPO3_mainDir . 'contrib/',
247 'typo3conf/ext/'
248 );
249 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths']) {
250 $pathArr = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths'], TRUE);
251 foreach ($pathArr as $p) {
252 // Once checked for path, but as this may run from typo3/mod/web/ts/ dir, that'll not work!! So the paths ar uncritically included here.
253 $this->allowedPaths[] = $p;
254 }
255 }
256 }
257
258 /**
259 * Fetches the "currentPageData" array from cache
260 *
261 * NOTE about currentPageData:
262 * It holds information about the TypoScript conditions along with the list
263 * of template uid's which is used on the page. In the getFromCache function
264 * in TSFE, currentPageData is used to evaluate if there is a template and
265 * if the matching conditions are alright. Unfortunately this does not take
266 * into account if the templates in the rowSum of currentPageData has
267 * changed composition, eg. due to hidden fields or start/end time. So if a
268 * template is hidden or times out, it'll not be discovered unless the page
269 * is regenerated - at least the this->start function must be called,
270 * because this will make a new portion of data in currentPageData string.
271 *
272 * @return array Returns the unmatched array $currentPageData if found cached in "cache_pagesection". Otherwise FALSE is returned which means that the array must be generated and stored in the cache
273 */
274 public function getCurrentPageData() {
275 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('cache_pagesection')->get((int)$GLOBALS['TSFE']->id . '_' . GeneralUtility::md5int($GLOBALS['TSFE']->MP));
276 }
277
278 /**
279 * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
280 *
281 * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
282 * @return array The input array but with a new key added, "match" which contains the items from the "all" key which when passed to tslib_matchCondition returned TRUE.
283 */
284 public function matching($cc) {
285 if (is_array($cc['all'])) {
286 /** @var $matchObj \TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher */
287 $matchObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Configuration\\TypoScript\\ConditionMatching\\ConditionMatcher');
288 $matchObj->setRootline((array) $cc['rootLine']);
289 foreach ($cc['all'] as $key => $pre) {
290 if ($matchObj->match($pre)) {
291 $sectionsMatch[$key] = $pre;
292 }
293 }
294 $cc['match'] = $sectionsMatch;
295 }
296 return $cc;
297 }
298
299 /**
300 * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
301 * The method traverses the rootline structure from out to in, fetches the hierarchy of template records and based on this either finds the cached TypoScript template structure or parses the template and caches it for next time.
302 * Sets $this->setup to the parsed TypoScript template array
303 *
304 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
305 * @return void
306 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
307 */
308 public function start($theRootLine) {
309 if (is_array($theRootLine)) {
310 $setupData = '';
311 $hash = '';
312 // Flag that indicates that the existing data in cache_pagesection
313 // could be used (this is the case if $TSFE->all is set, and the
314 // rowSum still matches). Based on this we decide if cache_pagesection
315 // needs to be updated...
316 $isCached = FALSE;
317 $this->runThroughTemplates($theRootLine);
318 if ($GLOBALS['TSFE']->all) {
319 $cc = $GLOBALS['TSFE']->all;
320 // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
321 if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
322 unset($cc);
323 } else {
324 // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
325 if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
326 $isCached = TRUE;
327 }
328 // When the data is serialized below (ROWSUM hash), it must not contain the rootline by concept. So this must be removed (and added again later)...
329 unset($cc['rootLine']);
330 }
331 }
332 // This is about getting the hash string which is used to fetch the cached TypoScript template.
333 // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
334 if (is_array($cc)) {
335 // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
336 if (!$cc['match']) {
337 // TODO: check if this can ever be the case - otherwise remove
338 $cc = $this->matching($cc);
339 ksort($cc);
340 }
341 $hash = md5(serialize($cc));
342 } else {
343 // If currentPageData was not there, we first find $rowSum (freshly generated). After that we try to see, if it is stored with a list of all conditions. If so we match the result.
344 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
345 $result = \TYPO3\CMS\Frontend\Page\PageRepository::getHash($rowSumHash);
346 if (is_array($result)) {
347 $cc = array();
348 $cc['all'] = $result;
349 $cc['rowSum'] = $this->rowSum;
350 $cc = $this->matching($cc);
351 ksort($cc);
352 $hash = md5(serialize($cc));
353 }
354 }
355 if ($hash) {
356 // Get TypoScript setup array
357 $setupData = \TYPO3\CMS\Frontend\Page\PageRepository::getHash($hash);
358 }
359 if (is_array($setupData) && !$this->forceTemplateParsing) {
360 // If TypoScript setup structure was cached we unserialize it here:
361 $this->setup = $setupData;
362 if ($this->tt_track) {
363 $GLOBALS['TT']->setTSLogMessage('Using cached TS template data');
364 }
365 } else {
366 if ($this->tt_track) {
367 $GLOBALS['TT']->setTSLogMessage('Not using any cached TS data');
368 }
369
370 // Make configuration
371 $this->generateConfig();
372 // This stores the template hash thing
373 $cc = array();
374 // All sections in the template at this point is found
375 $cc['all'] = $this->sections;
376 // The line of templates is collected
377 $cc['rowSum'] = $this->rowSum;
378 $cc = $this->matching($cc);
379 ksort($cc);
380 $hash = md5(serialize($cc));
381 // This stores the data.
382 \TYPO3\CMS\Frontend\Page\PageRepository::storeHash($hash, $this->setup, 'TS_TEMPLATE');
383 if ($this->tt_track) {
384 $GLOBALS['TT']->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
385 }
386 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
387 \TYPO3\CMS\Frontend\Page\PageRepository::storeHash($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
388 }
389 // Add rootLine
390 $cc['rootLine'] = $this->rootLine;
391 ksort($cc);
392 // Make global and save
393 $GLOBALS['TSFE']->all = $cc;
394 // Matching must be executed for every request, so this must never be part of the pagesection cache!
395 unset($cc['match']);
396 if (!$isCached && !$this->simulationHiddenOrTime && !$GLOBALS['TSFE']->no_cache) {
397 // Only save the data if we're not simulating by hidden/starttime/endtime
398 $mpvarHash = GeneralUtility::md5int($GLOBALS['TSFE']->MP);
399 /** @var $pageSectionCache \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface */
400 $pageSectionCache = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('cache_pagesection');
401 $pageSectionCache->set((int)$GLOBALS['TSFE']->id . '_' . $mpvarHash, $cc, array(
402 'pageId_' . (int)$GLOBALS['TSFE']->id,
403 'mpvarHash_' . $mpvarHash
404 ));
405 }
406 // If everything OK.
407 if ($this->rootId && $this->rootLine && $this->setup) {
408 $this->loaded = 1;
409 }
410 }
411 }
412
413 /*******************************************************************
414 *
415 * Fetching TypoScript code text for the Template Hierarchy
416 *
417 *******************************************************************/
418 /**
419 * Traverses the rootLine from the root and out. For each page it checks if there is a template record. If there is a template record, $this->processTemplate() is called.
420 * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
421 * Also creates $this->rootLine which is a root line stopping at the root template (contrary to $GLOBALS['TSFE']->rootLine which goes all the way to the root of the tree
422 *
423 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
424 * @param int $start_template_uid Set specific template record UID to select; this is only for debugging/development/analysis use in backend modules like "Web > Template". For parsing TypoScript templates in the frontend it should be 0 (zero)
425 * @return void
426 * @see start()
427 */
428 public function runThroughTemplates($theRootLine, $start_template_uid = 0) {
429 $this->constants = array();
430 $this->config = array();
431 $this->rowSum = array();
432 $this->hierarchyInfoToRoot = array();
433 $this->absoluteRootLine = $theRootLine;
434 $this->isDefaultTyposcriptAdded = FALSE;
435
436 reset($this->absoluteRootLine);
437 $c = count($this->absoluteRootLine);
438 for ($a = 0; $a < $c; $a++) {
439 // If some template loaded before has set a template-id for the next level, then load this template first!
440 if ($this->nextLevel) {
441 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'uid=' . (int)$this->nextLevel . ' ' . $this->whereClause);
442 $this->nextLevel = 0;
443 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
444 $this->versionOL($row);
445 if (is_array($row)) {
446 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
447 $this->outermostRootlineIndexWithTemplate = $a;
448 }
449 }
450 $GLOBALS['TYPO3_DB']->sql_free_result($res);
451 }
452 $addC = '';
453 // If first loop AND there is set an alternative template uid, use that
454 if ($a == $c - 1 && $start_template_uid) {
455 $addC = ' AND uid=' . (int)$start_template_uid;
456 }
457 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'pid=' . (int)$this->absoluteRootLine[$a]['uid'] . $addC . ' ' . $this->whereClause, '', 'sorting', 1);
458 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
459 $this->versionOL($row);
460 if (is_array($row)) {
461 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
462 $this->outermostRootlineIndexWithTemplate = $a;
463 }
464 }
465 $GLOBALS['TYPO3_DB']->sql_free_result($res);
466 $this->rootLine[] = $this->absoluteRootLine[$a];
467 }
468
469 // Process extension static files if not done yet, but explicitly requested
470 if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
471 $this->addExtensionStatics('sys_0', 'sys_0', 0, array());
472 }
473
474 // Add the global default TypoScript from the TYPO3_CONF_VARS
475 $this->addDefaultTypoScript();
476
477 $this->processIncludes();
478 }
479
480 /**
481 * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
482 * Builds up $this->rowSum
483 *
484 * @param array $row A full TypoScript template record (sys_template/static_template/forged "dummy" record made from static template file)
485 * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
486 * @param array $pid The PID of the input template record
487 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
488 * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
489 * @param string $includePath Specifies the path from which the template was included (used with static_includes)
490 * @return void
491 * @see runThroughTemplates()
492 */
493 public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '') {
494 // Adding basic template record information to rowSum array
495 $this->rowSum[] = array($row['uid'], $row['title'], $row['tstamp']);
496 // Processing "Clear"-flags
497 if ($row['clear']) {
498 $clConst = $row['clear'] & 1;
499 $clConf = $row['clear'] & 2;
500 if ($clConst) {
501 $this->constants = array();
502 $this->clearList_const = array();
503 }
504 if ($clConf) {
505 $this->config = array();
506 $this->hierarchyInfoToRoot = array();
507 $this->clearList_setup = array();
508 }
509 }
510 // Include static records (static_template) or files (from extensions) (#1/2)
511 // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
512 if (!$row['includeStaticAfterBasedOn']) {
513 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
514 }
515 // Include "Based On" sys_templates:
516 // 'basedOn' is a list of templates to include
517 if (trim($row['basedOn'])) {
518 // Manually you can put this value in the field and then the based_on ID will be taken from the $_GET var defined by '=....'.
519 // Example: If $row['basedOn'] is 'EXTERNAL_BASED_ON_TEMPLATE_ID=based_on_uid', then the global var, based_on_uid - given by the URL like '&based_on_uid=999' - is included instead!
520 // This feature allows us a hack to test/demonstrate various included templates on the same set of content bearing pages. Used by the "freesite" extension.
521 $basedOn_hackFeature = explode('=', $row['basedOn']);
522 if ($basedOn_hackFeature[0] == 'EXTERNAL_BASED_ON_TEMPLATE_ID' && $basedOn_hackFeature[1]) {
523 $id = (int)GeneralUtility::_GET($basedOn_hackFeature[1]);
524 // If $id is not allready included ...
525 if ($id && !GeneralUtility::inList($idList, ('sys_' . $id))) {
526 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'uid=' . $id . ' ' . $this->whereClause);
527 // there was a template, then we fetch that
528 if ($subrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
529 $this->versionOL($subrow);
530 if (is_array($subrow)) {
531 $this->processTemplate($subrow, $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
532 }
533 }
534 $GLOBALS['TYPO3_DB']->sql_free_result($res);
535 }
536 } else {
537 // Normal Operation, which is to include the "based-on" sys_templates,
538 // if they are not already included, and maintaining the sorting of the templates
539 $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn']);
540 // skip template if it's already included
541 foreach ($basedOnIds as $key => $basedOnId) {
542 if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
543 unset($basedOnIds[$key]);
544 }
545 }
546 $subTemplates = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_template', 'uid IN (' . implode(',', $basedOnIds) . ') ' . $this->whereClause, '', '', '', 'uid');
547 // Traversing list again to ensure the sorting of the templates
548 foreach ($basedOnIds as $id) {
549 if (is_array($subTemplates[$id])) {
550 $this->versionOL($subTemplates[$id]);
551 $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
552 }
553 }
554 }
555 }
556 // Include static records (static_template) or files (from extensions) (#2/2)
557 if ($row['includeStaticAfterBasedOn']) {
558 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
559 }
560 // Creating hierarchy information; Used by backend analysis tools
561 $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = array(
562 'root' => trim($row['root']),
563 'next' => $row['nextLevel'],
564 'clConst' => $clConst,
565 'clConf' => $clConf,
566 'templateID' => $templateID,
567 'templateParent' => $templateParent,
568 'title' => $row['title'],
569 'uid' => $row['uid'],
570 'pid' => $row['pid'],
571 'configLines' => substr_count($row['config'], LF) + 1
572 ));
573 // Adding the content of the fields constants (Constants) and config (Setup)
574 $this->constants[] = $row['constants'];
575 $this->config[] = $row['config'];
576 $this->templateIncludePaths[] = $includePath;
577 // For backend analysis (Template Analyser) provide the order of added constants/config template IDs
578 $this->clearList_const[] = $templateID;
579 $this->clearList_setup[] = $templateID;
580 if (trim($row['sitetitle'])) {
581 $this->sitetitle = $row['sitetitle'];
582 }
583 // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
584 if (trim($row['root'])) {
585 $this->rootId = $pid;
586 $this->rootLine = array();
587 }
588 // If a template is set to be active on the next level set this internal value to point to this UID. (See runThroughTemplates())
589 if ($row['nextLevel']) {
590 $this->nextLevel = $row['nextLevel'];
591 } else {
592 $this->nextLevel = 0;
593 }
594 }
595
596 /**
597 * This function can be used to update the data of the current rootLine
598 * e.g. when a different language is used.
599 *
600 * This function must not be used if there are different pages in the
601 * rootline as before!
602 *
603 * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
604 * @return void
605 * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
606 */
607 public function updateRootlineData($fullRootLine) {
608 if (!is_array($this->rootLine) || count($this->rootLine) === 0) {
609 return;
610 }
611
612 $fullRootLineByUid = array();
613 foreach ($fullRootLine as $rootLineData) {
614 $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
615 }
616
617 foreach ($this->rootLine as $level => $dataArray) {
618 $currentUid = $dataArray['uid'];
619
620 if (!array_key_exists($currentUid, $fullRootLineByUid)) {
621 throw new \RuntimeException(sprintf('The full rootLine does not contain data for the page with the uid %d that is contained in the template rootline.', $currentUid), 1370419654);
622 }
623
624 $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
625 }
626 }
627
628 /**
629 * Includes static template records (from static_template table, loaded through a hook) and static template files (from extensions) for the input template record row.
630 *
631 * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
632 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
633 * @param array $pid The PID of the input template record
634 * @param array $row A full TypoScript template record
635 * @return void
636 * @see processTemplate()
637 */
638 public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row) {
639 // Static Template Records (static_template): include_static is a list of static templates to include
640 // Call function for link rendering:
641 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'])) {
642 $_params = array(
643 'idList' => &$idList,
644 'templateId' => &$templateID,
645 'pid' => &$pid,
646 'row' => &$row
647 );
648 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] as $_funcRef) {
649 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
650 }
651 }
652 // If "Include before all static templates if root-flag is set" is set:
653 if ($row['static_file_mode'] == 3 && substr($templateID, 0, 4) == 'sys_' && $row['root']) {
654 $this->addExtensionStatics($idList, $templateID, $pid, $row);
655 }
656 // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
657 if (trim($row['include_static_file'])) {
658 $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], TRUE);
659 // Traversing list
660 foreach ($include_static_fileArr as $ISF_file) {
661 if (substr($ISF_file, 0, 4) == 'EXT:') {
662 list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
663 if ((string)$ISF_extKey !== '' && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
664 $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
665 $ISF_filePath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
666 if (@is_dir($ISF_filePath)) {
667 $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
668 $subrow = array(
669 'constants' => @file_exists(($ISF_filePath . 'constants.txt')) ? GeneralUtility::getUrl($ISF_filePath . 'constants.txt') : '',
670 'config' => @file_exists(($ISF_filePath . 'setup.txt')) ? GeneralUtility::getUrl($ISF_filePath . 'setup.txt') : '',
671 'include_static' => @file_exists(($ISF_filePath . 'include_static.txt')) ? implode(',', array_unique(GeneralUtility::intExplode(',', GeneralUtility::getUrl($ISF_filePath . 'include_static.txt')))) : '',
672 'include_static_file' => @file_exists(($ISF_filePath . 'include_static_file.txt')) ? implode(',', array_unique(explode(',', GeneralUtility::getUrl($ISF_filePath . 'include_static_file.txt')))) : '',
673 'title' => $ISF_file,
674 'uid' => $mExtKey
675 );
676 $subrow = $this->prependStaticExtra($subrow);
677 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
678 }
679 }
680 }
681 }
682 }
683 // If "Default (include before if root flag is set)" is set OR
684 // "Always include before this template record" AND root-flag are set
685 if ($row['static_file_mode'] == 1 || $row['static_file_mode'] == 0 && substr($templateID, 0, 4) == 'sys_' && $row['root']) {
686 $this->addExtensionStatics($idList, $templateID, $pid, $row);
687 }
688 // Include Static Template Records after all other TypoScript has been included.
689 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'])) {
690 $_params = array(
691 'idList' => &$idList,
692 'templateId' => &$templateID,
693 'pid' => &$pid,
694 'row' => &$row
695 );
696 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] as $_funcRef) {
697 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
698 }
699 }
700 }
701
702 /**
703 * Adds the default TypoScript files for extensions if any.
704 *
705 * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
706 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
707 * @param array $pid The PID of the input template record
708 * @param array $row A full TypoScript template record
709 * @return void
710 * @access private
711 * @see includeStaticTypoScriptSources()
712 */
713 public function addExtensionStatics($idList, $templateID, $pid, $row) {
714 $this->extensionStaticsProcessed = TRUE;
715
716 // @TODO: Change to use new API
717 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extKey => $files) {
718 if ((is_array($files) || $files instanceof \ArrayAccess) && ($files['ext_typoscript_constants.txt'] || $files['ext_typoscript_setup.txt'])) {
719 $mExtKey = str_replace('_', '', $extKey);
720 $subrow = array(
721 'constants' => $files['ext_typoscript_constants.txt'] ? GeneralUtility::getUrl($files['ext_typoscript_constants.txt']) : '',
722 'config' => $files['ext_typoscript_setup.txt'] ? GeneralUtility::getUrl($files['ext_typoscript_setup.txt']) : '',
723 'title' => $extKey,
724 'uid' => $mExtKey
725 );
726 $subrow = $this->prependStaticExtra($subrow);
727 $extPath = ExtensionManagementUtility::extPath($extKey);
728 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $extPath);
729 }
730 }
731 }
732
733 /**
734 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
735 * For DB records the "uid" value is the integer of the "static_template" record.
736 * For files the "uid" value is the extension key but with any underscores removed. Possibly with a path if its a static file selected in the template record
737 *
738 * @param array $subrow Static template record/file
739 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
740 * @access private
741 * @see addExtensionStatics(), includeStaticTypoScriptSources()
742 */
743 public function prependStaticExtra($subrow) {
744 // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
745 $identifier = $subrow['uid'];
746 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier];
747 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier];
748 // if this is a template of type "default content rendering", also see if other extensions have added their TypoScript that should be included after the content definitions
749 if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], TRUE)) {
750 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
751 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
752 }
753 return $subrow;
754 }
755
756 /**
757 * Creating versioning overlay of a sys_template record.
758 * This will use either frontend or backend overlay functionality depending on environment.
759 *
760 * @param array $row Row to overlay (passed by reference)
761 * @return void
762 */
763 public function versionOL(&$row) {
764 // Distinguish frontend and backend call:
765 // To do the fronted call a full frontend is required, just checking for
766 // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
767 // eId scripts that run in frontend scope, but do not have a full blown frontend.
768 if (is_object($GLOBALS['TSFE']) === TRUE && property_exists($GLOBALS['TSFE'], 'sys_page') === TRUE && method_exists($GLOBALS['TSFE']->sys_page, 'versionOL') === TRUE) {
769 // Frontend
770 $GLOBALS['TSFE']->sys_page->versionOL('sys_template', $row);
771 } else {
772 // Backend
773 \TYPO3\CMS\Backend\Utility\BackendUtility::workspaceOL('sys_template', $row);
774 }
775 }
776
777 /*******************************************************************
778 *
779 * Parsing TypoScript code text from Template Records into PHP array
780 *
781 *******************************************************************/
782 /**
783 * Generates the configuration array by replacing constants and parsing the whole thing.
784 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
785 *
786 * @return void
787 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
788 */
789 public function generateConfig() {
790 // Add default TS for all code types
791 $this->addDefaultTypoScript();
792
793 // Parse the TypoScript code text for include-instructions!
794 $this->processIncludes();
795 // These vars are also set lateron...
796 $this->setup['sitetitle'] = $this->sitetitle;
797 // ****************************
798 // Parse TypoScript Constants
799 // ****************************
800 // Initialize parser and match-condition classes:
801 /** @var $constants \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
802 $constants = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
803 $constants->breakPointLN = (int)$this->ext_constants_BRP;
804 $constants->setup = $this->mergeConstantsFromPageTSconfig(array());
805 /** @var $matchObj \TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher */
806 $matchObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Configuration\\TypoScript\\ConditionMatching\\ConditionMatcher');
807 $matchObj->setSimulateMatchConditions($this->matchAlternative);
808 $matchObj->setSimulateMatchResult((bool) $this->matchAll);
809 // Traverse constants text fields and parse them
810 foreach ($this->constants as $str) {
811 $constants->parse($str, $matchObj);
812 }
813 // Read out parse errors if any
814 $this->parserErrors['constants'] = $constants->errors;
815 // Then flatten the structure from a multi-dim array to a single dim array with all constants listed as key/value pairs (ready for substitution)
816 $this->flatSetup = array();
817 $this->flattenSetup($constants->setup, '', '');
818 // ***********************************************
819 // Parse TypoScript Setup (here called "config")
820 // ***********************************************
821 // Initialize parser and match-condition classes:
822 /** @var $config \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
823 $config = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
824 $config->breakPointLN = (int)$this->ext_config_BRP;
825 $config->regLinenumbers = $this->ext_regLinenumbers;
826 $config->regComments = $this->ext_regComments;
827 $config->setup = $this->setup;
828 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
829 $config->sections = $constants->sections;
830 $config->sectionsMatch = $constants->sectionsMatch;
831 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
832 $all = '';
833 foreach ($this->config as $str) {
834 $all .= '
835 [GLOBAL]
836 ' . $str;
837 }
838 // Substitute constants in the Setup code:
839 if ($this->tt_track) {
840 $GLOBALS['TT']->push('Substitute Constants (' . count($this->flatSetup) . ')');
841 }
842 $all = $this->substituteConstants($all);
843 if ($this->tt_track) {
844 $GLOBALS['TT']->pull();
845 }
846
847 // Searching for possible unsubstituted constants left (only for information)
848 if ($this->verbose) {
849 if (strstr($all, '{$')) {
850 $theConstList = array();
851 $findConst = explode('{$', $all);
852 array_shift($findConst);
853 foreach ($findConst as $constVal) {
854 $constLen = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(strcspn($constVal, '}'), 0, 50);
855 $theConstList[] = '{$' . substr($constVal, 0, ($constLen + 1));
856 }
857 if ($this->tt_track) {
858 $GLOBALS['TT']->setTSlogMessage(implode(', ', $theConstList) . ': Constants may remain un-substituted!!', 2);
859 }
860 }
861
862 }
863
864 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
865 if ($this->tt_track) {
866 $GLOBALS['TT']->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
867 }
868 // Finally parse the Setup field TypoScript code (where constants are now substituted)
869 $config->parse($all, $matchObj);
870 // Read out parse errors if any
871 $this->parserErrors['config'] = $config->errors;
872 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
873 $this->setup = $config->setup;
874 if ($this->backend_info) {
875 // Used for backend purposes only
876 $this->setup_constants = $constants->setup;
877 }
878 // ****************************************************************
879 // Final processing of the $this->setup TypoScript Template array
880 // Basically: This is unsetting/setting of certain reserved keys.
881 // ****************************************************************
882 // These vars are allready set after 'processTemplate', but because $config->setup overrides them (in the line above!), we set them again. They are not changed compared to the value they had in the top of the page!
883 unset($this->setup['sitetitle']);
884 unset($this->setup['sitetitle.']);
885 $this->setup['sitetitle'] = $this->sitetitle;
886 // Unsetting some vars...
887 unset($this->setup['types.']);
888 unset($this->setup['types']);
889 if (is_array($this->setup)) {
890 foreach ($this->setup as $key => $value) {
891 if ($value == 'PAGE') {
892 // Set the typeNum of the current page object:
893 if (isset($this->setup[$key . '.']['typeNum'])) {
894 $typeNum = $this->setup[$key . '.']['typeNum'];
895 $this->setup['types.'][$typeNum] = $key;
896 } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
897 $this->setup['types.'][0] = $key;
898 }
899 }
900 }
901 }
902 unset($this->setup['temp.']);
903 unset($constants);
904 // Storing the conditions found/matched information:
905 $this->sections = $config->sections;
906 $this->sectionsMatch = $config->sectionsMatch;
907 }
908
909 /**
910 * Searching TypoScript code text (for constants and config (Setup))
911 * for include instructions and does the inclusion of external TypoScript files
912 * if needed.
913 *
914 * @return void
915 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
916 */
917 public function processIncludes() {
918 if ($this->processIncludesHasBeenRun) {
919 return;
920 }
921
922 $paths = $this->templateIncludePaths;
923 $files = array();
924 foreach ($this->constants as &$value) {
925 $includeData = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
926 $files = array_merge($files, $includeData['files']);
927 $value = $includeData['typoscript'];
928 }
929 unset($value);
930 $paths = $this->templateIncludePaths;
931 foreach ($this->config as &$value) {
932 $includeData = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
933 $files = array_merge($files, $includeData['files']);
934 $value = $includeData['typoscript'];
935 }
936 unset($value);
937
938 if (!empty($files)) {
939 $files = array_unique($files);
940 foreach ($files as $file) {
941 $this->rowSum[] = array($file, filemtime($file));
942 }
943 }
944
945 $this->processIncludesHasBeenRun = TRUE;
946 }
947
948 /**
949 * Loads Page TSconfig until the outermost template record and parses the configuration - if TSFE.constants object path is found it is merged with the default data in here!
950 *
951 * @param array $constArray Constants array, default input.
952 * @return array Constants array, modified
953 * @todo Apply caching to the parsed Page TSconfig. This is done in the other similar functions for both frontend and backend. However, since this functions works for BOTH frontend and backend we will have to either write our own local caching function or (more likely) detect if we are in FE or BE and use caching functions accordingly. Not having caching affects mostly the backend modules inside the "Template" module since the overhead in the frontend is only seen when TypoScript templates are parsed anyways (after which point they are cached anyways...)
954 */
955 public function mergeConstantsFromPageTSconfig($constArray) {
956 $TSdataArray = array();
957 // Setting default configuration:
958 $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
959 for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
960 $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
961 }
962 // Parsing the user TS (or getting from cache)
963 $TSdataArray = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
964 $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
965 /** @var $parseObj \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
966 $parseObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
967 $parseObj->parse($userTS);
968 if (is_array($parseObj->setup['TSFE.']['constants.'])) {
969 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
970 }
971 return $constArray;
972 }
973
974 /**
975 * This flattens a hierarchical TypoScript array to $this->flatSetup
976 *
977 * @param array $setupArray TypoScript array
978 * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
979 * @return void
980 * @see generateConfig()
981 */
982 public function flattenSetup($setupArray, $prefix) {
983 if (is_array($setupArray)) {
984 foreach ($setupArray as $key => $val) {
985 if ($prefix || substr($key, 0, 16) != 'TSConstantEditor') {
986 // We don't want 'TSConstantEditor' in the flattend setup on the first level (190201)
987 if (is_array($val)) {
988 $this->flattenSetup($val, $prefix . $key);
989 } else {
990 $this->flatSetup[$prefix . $key] = $val;
991 }
992 }
993 }
994 }
995 }
996
997 /**
998 * Substitutes the constants from $this->flatSetup in the text string $all
999 *
1000 * @param string $all TypoScript code text string
1001 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1002 * @see generateConfig(), flattenSetup()
1003 */
1004 public function substituteConstants($all) {
1005 if ($this->tt_track) {
1006 $GLOBALS['TT']->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1007 }
1008 $noChange = FALSE;
1009 // Recursive substitution of constants (up to 10 nested levels)
1010 for ($i = 0; $i < 10 && !$noChange; $i++) {
1011 $old_all = $all;
1012 $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', array($this, 'substituteConstantsCallBack'), $all);
1013 if ($old_all == $all) {
1014 $noChange = TRUE;
1015 }
1016 }
1017 return $all;
1018 }
1019
1020 /**
1021 * Call back method for preg_replace_callback in substituteConstants
1022 *
1023 * @param array $matches Regular expression matches
1024 * @return string Replacement
1025 * @see substituteConstants()
1026 */
1027 public function substituteConstantsCallBack($matches) {
1028 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1029 return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1030 }
1031
1032 /*******************************************************************
1033 *
1034 * Various API functions, used from elsewhere in the frontend classes
1035 *
1036 *******************************************************************/
1037 /**
1038 * Implementation of the "optionSplit" feature in TypoScript (used eg. for MENU objects)
1039 * What it does is to split the incoming TypoScript array so that the values are exploded by certain strings ("||" and "|*|") and each part distributed into individual TypoScript arrays with a similar structure, but individualized values.
1040 * The concept is known as "optionSplit" and is rather advanced to handle but quite powerful, in particular for creating menus in TYPO3.
1041 *
1042 * @param array $conf A TypoScript array
1043 * @param int $splitCount The number of items for which to generated individual TypoScript arrays
1044 * @return array The individualized TypoScript array.
1045 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::IMGTEXT(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::procesItemStates()
1046 */
1047 public function splitConfArray($conf, $splitCount) {
1048 // Initialize variables:
1049 $splitCount = (int)$splitCount;
1050 $conf2 = array();
1051 if ($splitCount && is_array($conf)) {
1052 // Initialize output to carry at least the keys:
1053 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1054 $conf2[$aKey] = array();
1055 }
1056 // Recursive processing of array keys:
1057 foreach ($conf as $cKey => $val) {
1058 if (is_array($val)) {
1059 $tempConf = $this->splitConfArray($val, $splitCount);
1060 foreach ($tempConf as $aKey => $val) {
1061 $conf2[$aKey][$cKey] = $val;
1062 }
1063 } else {
1064 // Splitting of all values on this level of the TypoScript object tree:
1065 if (!strstr($val, '|*|') && !strstr($val, '||')) {
1066 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1067 $conf2[$aKey][$cKey] = $val;
1068 }
1069 } else {
1070 $main = explode('|*|', $val);
1071 $mainCount = count($main);
1072 $lastC = 0;
1073 $middleC = 0;
1074 $firstC = 0;
1075 if ($main[0]) {
1076 $first = explode('||', $main[0]);
1077 $firstC = count($first);
1078 }
1079 if ($main[1]) {
1080 $middle = explode('||', $main[1]);
1081 $middleC = count($middle);
1082 }
1083 if ($main[2]) {
1084 $last = explode('||', $main[2]);
1085 $lastC = count($last);
1086 $value = $last[0];
1087 }
1088 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1089 if ($firstC && isset($first[$aKey])) {
1090 $value = $first[$aKey];
1091 } elseif ($middleC) {
1092 $value = $middle[($aKey - $firstC) % $middleC];
1093 }
1094 if ($lastC && $lastC >= $splitCount - $aKey) {
1095 $value = $last[$lastC - ($splitCount - $aKey)];
1096 }
1097 $conf2[$aKey][$cKey] = trim($value);
1098 }
1099 }
1100 }
1101 }
1102 }
1103 return $conf2;
1104 }
1105
1106 /**
1107 * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
1108 *
1109 * @param string $fileFromSetup TypoScript "resource" data type value.
1110 * @return string Resulting filename, is either a full absolute URL or a relative path
1111 */
1112 public function getFileName($fileFromSetup) {
1113 $file = trim($fileFromSetup);
1114 if (!$file) {
1115 return;
1116 } elseif (strpos($file, '../') !== FALSE) {
1117 if ($this->tt_track) {
1118 $GLOBALS['TT']->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
1119 }
1120 return;
1121 }
1122 // Cache
1123 $hash = md5($file);
1124 if (isset($this->fileCache[$hash])) {
1125 return $this->fileCache[$hash];
1126 }
1127
1128 // if this is an URL, it can be returned directly
1129 $urlScheme = parse_url($file, PHP_URL_SCHEME);
1130 if ($urlScheme === 'https' || $urlScheme === 'http') {
1131 return $file;
1132 }
1133
1134 // this call also resolves EXT:myext/ files
1135 $file = GeneralUtility::getFileAbsFileName($file);
1136 if (!$file) {
1137 if ($this->tt_track) {
1138 $GLOBALS['TT']->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
1139 }
1140 return;
1141 }
1142
1143 $file = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($file);
1144
1145 // Check if the found file is in the allowed paths
1146 foreach ($this->allowedPaths as $val) {
1147 if (GeneralUtility::isFirstPartOfStr($file, $val)) {
1148 $this->fileCache[$hash] = $file;
1149 return $file;
1150 }
1151 }
1152
1153 if ($this->tt_track) {
1154 $GLOBALS['TT']->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1155 }
1156 }
1157
1158 /**
1159 * Compiles the content for the page <title> tag.
1160 *
1161 * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1162 * @param bool $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1163 * @param bool $showTitleFirst If set, then "sitetitle" and $title is swapped
1164 * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1165 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::tempPageCacheContent(), TSpagegen::renderContentWithHeader()
1166 */
1167 public function printTitle($pageTitle, $noTitle = FALSE, $showTitleFirst = FALSE) {
1168 $siteTitle = trim($this->setup['sitetitle']);
1169 $pageTitle = $noTitle ? '' : $pageTitle;
1170 $pageTitleSeparator = '';
1171 if ($showTitleFirst) {
1172 $temp = $siteTitle;
1173 $siteTitle = $pageTitle;
1174 $pageTitle = $temp;
1175 }
1176 if ($pageTitle != '' && $siteTitle != '') {
1177 $pageTitleSeparator = ': ';
1178 if (isset($this->setup['config.']['pageTitleSeparator']) && $this->setup['config.']['pageTitleSeparator']) {
1179 $pageTitleSeparator = $this->setup['config.']['pageTitleSeparator'];
1180
1181 if (is_object($GLOBALS['TSFE']->cObj) && isset($this->setup['config.']['pageTitleSeparator.']) && is_array($this->setup['config.']['pageTitleSeparator.'])) {
1182 $pageTitleSeparator = $GLOBALS['TSFE']->cObj->stdWrap($pageTitleSeparator, $this->setup['config.']['pageTitleSeparator.']);
1183 } else {
1184 $pageTitleSeparator .= ' ';
1185 }
1186 }
1187 }
1188 return $siteTitle . $pageTitleSeparator . $pageTitle;
1189 }
1190
1191 /**
1192 * Reads the fileContent of $fileName and returns it.
1193 * Similar to GeneralUtility::getUrl() but with an additional check if the path is allowed
1194 *
1195 * @param string $fileName Absolute filepath to record
1196 * @return NULL|string The content returned
1197 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::fileResource(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::MULTIMEDIA(), GeneralUtility::getUrl()
1198 */
1199 public function fileContent($fileName) {
1200 $fileName = $this->getFileName($fileName);
1201 if ($fileName) {
1202 return GeneralUtility::getUrl($fileName);
1203 }
1204 return NULL;
1205 }
1206
1207 /**
1208 * Ordinary "wrapping" function. Used in the AbstractMenuContentObject class and extension classes instead of the similar function in ContentObjectRenderer
1209 *
1210 * @param string $content The content to wrap
1211 * @param string $wrap The wrap value, eg. "<strong> | </strong>
1212 * @return string Wrapped input string
1213 * @deprecated since TYPO3 CMS 6.3, remove later - use \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::wrap() instead
1214 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject, \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::wrap()
1215 */
1216 public function wrap($content, $wrap) {
1217 GeneralUtility::logDeprecatedFunction();
1218 if ($wrap) {
1219 $wrapArr = explode('|', $wrap);
1220 return trim($wrapArr[0]) . $content . trim($wrapArr[1]);
1221 } else {
1222 return $content;
1223 }
1224 }
1225
1226 /**
1227 * Removes the "?" of input string IF the "?" is the last character.
1228 *
1229 * @param string $url Input string
1230 * @return string Output string, free of "?" in the end, if any such character.
1231 * @see linkData(), \TYPO3\CMS\Frontend\Page\FramesetRenderer::frameParams()
1232 */
1233 public function removeQueryString($url) {
1234 if (substr($url, -1) == '?') {
1235 return substr($url, 0, -1);
1236 } else {
1237 return $url;
1238 }
1239 }
1240
1241 /**
1242 * Takes a TypoScript array as input and returns an array which contains all integer properties found which had a value (not only properties). The output array will be sorted numerically.
1243 * Call it like \TYPO3\CMS\Core\TypoScript\TemplateService::sortedKeyList()
1244 *
1245 * @param array $setupArr TypoScript array with numerical array in
1246 * @param bool $acceptOnlyProperties If set, then a value is not required - the properties alone will be enough.
1247 * @return array An array with all integer properties listed in numeric order.
1248 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::cObjGet(), \TYPO3\CMS\Frontend\Imaging\GifBuilder, \TYPO3\CMS\Frontend\ContentObject\Menu\ImageMenuContentObject::makeImageMap()
1249 */
1250 static public function sortedKeyList($setupArr, $acceptOnlyProperties = FALSE) {
1251 $keyArr = array();
1252 $setupArrKeys = array_keys($setupArr);
1253 foreach ($setupArrKeys as $key) {
1254 if ($acceptOnlyProperties || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($key)) {
1255 $keyArr[] = (int)$key;
1256 }
1257 }
1258 $keyArr = array_unique($keyArr);
1259 sort($keyArr);
1260 return $keyArr;
1261 }
1262
1263 /**
1264 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1265 *
1266 * @param string $list A list of UIDs for which the rootline-level should get returned
1267 * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1268 */
1269 public function getRootlineLevel($list) {
1270 $idx = 0;
1271 foreach ($this->rootLine as $page) {
1272 if (GeneralUtility::inList($list, $page['uid'])) {
1273 return $idx;
1274 }
1275 $idx++;
1276 }
1277 return FALSE;
1278 }
1279
1280 /*******************************************************************
1281 *
1282 * Functions for creating links
1283 *
1284 *******************************************************************/
1285 /**
1286 * The mother of all functions creating links/URLs etc in a TypoScript environment.
1287 * See the references below.
1288 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1289 * It is important to pass all links created through this function since this is the guarantee that globally configured settings for link creating are observed and that your applications will conform to the various/many configuration options in TypoScript Templates regarding this.
1290 *
1291 * @param array $page The page record of the page to which we are creating a link. Needed due to fields like uid, alias, target, no_cache, title and sectionIndex_uid.
1292 * @param string $oTarget Default target string to use IF not $page['target'] is set.
1293 * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1294 * @param string $script Alternative script name if you don't want to use $GLOBALS['TSFE']->config['mainScript'] (normally set to "index.php")
1295 * @param array $overrideArray Array with overriding values for the $page array.
1296 * @param string $addParams Additional URL parameters to set in the URL. Syntax is "&foo=bar&foo2=bar2" etc. Also used internally to add parameters if needed.
1297 * @param string $typeOverride If you set this value to something else than a blank string, then the typeNumber used in the link will be forced to this value. Normally the typeNum is based on the target set OR on $GLOBALS['TSFE']->config['config']['forceTypeValue'] if found.
1298 * @param string $targetDomain The target Doamin, if any was detected in typolink
1299 * @return array Contains keys like "totalURL", "url", "sectionIndex", "linkVars", "no_cache", "type", "target" of which "totalURL" is normally the value you would use while the other keys contains various parts that was used to construct "totalURL
1300 * @see \TYPO3\CMS\Frontend\Page\FramesetRenderer::frameParams(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::SEARCHRESULT(), TSpagegen::pagegenInit(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
1301 */
1302 public function linkData($page, $oTarget, $no_cache, $script, $overrideArray = NULL, $addParams = '', $typeOverride = '', $targetDomain = '') {
1303 $LD = array();
1304 // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1305 if (is_array($overrideArray)) {
1306 foreach ($overrideArray as $theKey => $theNewVal) {
1307 $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1308 $page[$theKey] = $theNewVal;
1309 }
1310 }
1311 // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1312 if (!strstr($addParams, '&MP=')) {
1313 // Looking for hardcoded defaults:
1314 if (trim($GLOBALS['TSFE']->MP_defaults[$page['uid']])) {
1315 $addParams .= '&MP=' . rawurlencode(trim($GLOBALS['TSFE']->MP_defaults[$page['uid']]));
1316 } elseif ($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']) {
1317 // Else look in automatically created map:
1318 $m = $this->getFromMPmap($page['uid']);
1319 if ($m) {
1320 $addParams .= '&MP=' . rawurlencode($m);
1321 }
1322 }
1323 }
1324 // Setting ID/alias:
1325 if (!$script) {
1326 $script = $GLOBALS['TSFE']->config['mainScript'];
1327 }
1328 if ($page['alias']) {
1329 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1330 } else {
1331 $LD['url'] = $script . '?id=' . $page['uid'];
1332 }
1333 // Setting target
1334 $LD['target'] = trim($page['target']) ?: $oTarget;
1335 // typeNum
1336 $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1337 if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$GLOBALS['TSFE']->config['config']['forceTypeValue']) {
1338 $typeOverride = (int)$GLOBALS['TSFE']->config['config']['forceTypeValue'];
1339 }
1340 if ((string)$typeOverride !== '') {
1341 $typeNum = $typeOverride;
1342 }
1343 // Override...
1344 if ($typeNum) {
1345 $LD['type'] = '&type=' . (int)$typeNum;
1346 } else {
1347 $LD['type'] = '';
1348 }
1349 // Preserving the type number.
1350 $LD['orig_type'] = $LD['type'];
1351 // noCache
1352 $LD['no_cache'] = trim($page['no_cache']) || $no_cache ? '&no_cache=1' : '';
1353 // linkVars
1354 if ($GLOBALS['TSFE']->config['config']['uniqueLinkVars']) {
1355 if ($addParams) {
1356 $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($GLOBALS['TSFE']->linkVars . $addParams), '', FALSE, TRUE);
1357 } else {
1358 $LD['linkVars'] = $GLOBALS['TSFE']->linkVars;
1359 }
1360 } else {
1361 $LD['linkVars'] = $GLOBALS['TSFE']->linkVars . $addParams;
1362 }
1363 // Add absRefPrefix if exists.
1364 $LD['url'] = $GLOBALS['TSFE']->absRefPrefix . $LD['url'];
1365 // If the special key 'sectionIndex_uid' (added 'manually' in tslib/menu.php to the page-record) is set, then the link jumps directly to a section on the page.
1366 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1367 // Compile the normal total url
1368 $LD['totalURL'] = $this->removeQueryString(($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $GLOBALS['TSFE']->getMethodUrlIdToken)) . $LD['sectionIndex'];
1369 // Call post processing function for link rendering:
1370 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'])) {
1371 $_params = array(
1372 'LD' => &$LD,
1373 'args' => array('page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain),
1374 'typeNum' => $typeNum
1375 );
1376 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] as $_funcRef) {
1377 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1378 }
1379 }
1380 // Return the LD-array
1381 return $LD;
1382 }
1383
1384 /**
1385 * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1386 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1387 *
1388 * @param int $pageId Page id to return MPvar value for.
1389 * @return string
1390 * @see initMPmap_create()
1391 * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1392 */
1393 public function getFromMPmap($pageId = 0) {
1394 // Create map if not found already:
1395 if (!is_array($this->MPmap)) {
1396 $this->MPmap = array();
1397 $rootPoints = GeneralUtility::trimExplode(',', strtolower($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']), TRUE);
1398 // Traverse rootpoints:
1399 foreach ($rootPoints as $p) {
1400 if ($p == 'root') {
1401 $p = $this->rootLine[0]['uid'];
1402 $initMParray = array();
1403 if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1404 $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1405 }
1406 }
1407 $this->initMPmap_create($p, $initMParray);
1408 }
1409 }
1410 // Finding MP var for Page ID:
1411 if ($pageId) {
1412 if (is_array($this->MPmap[$pageId]) && count($this->MPmap[$pageId])) {
1413 return implode(',', $this->MPmap[$pageId]);
1414 }
1415 }
1416 }
1417
1418 /**
1419 * Creating MPmap for a certain ID root point.
1420 *
1421 * @param int $id Root id from which to start map creation.
1422 * @param array $MP_array MP_array passed from root page.
1423 * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1424 * @return void
1425 * @see getFromMPvar()
1426 */
1427 public function initMPmap_create($id, $MP_array = array(), $level = 0) {
1428 $id = (int)$id;
1429 if ($id <= 0) {
1430 return;
1431 }
1432 // First level, check id
1433 if (!$level) {
1434 // Find mount point if any:
1435 $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($id);
1436 // Overlay mode:
1437 if (is_array($mount_info) && $mount_info['overlay']) {
1438 $MP_array[] = $mount_info['MPvar'];
1439 $id = $mount_info['mount_pid'];
1440 }
1441 // Set mapping information for this level:
1442 $this->MPmap[$id] = $MP_array;
1443 // Normal mode:
1444 if (is_array($mount_info) && !$mount_info['overlay']) {
1445 $MP_array[] = $mount_info['MPvar'];
1446 $id = $mount_info['mount_pid'];
1447 }
1448 }
1449 if ($id && $level < 20) {
1450 $nextLevelAcc = array();
1451 // Select and traverse current level pages:
1452 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol', 'pages', 'pid=' . (int)$id . ' AND deleted=0 AND doktype<>' . \TYPO3\CMS\Frontend\Page\PageRepository::DOKTYPE_RECYCLER . ' AND doktype<>' . \TYPO3\CMS\Frontend\Page\PageRepository::DOKTYPE_BE_USER_SECTION);
1453 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1454 // Find mount point if any:
1455 $next_id = $row['uid'];
1456 $next_MP_array = $MP_array;
1457 $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($next_id, $row);
1458 // Overlay mode:
1459 if (is_array($mount_info) && $mount_info['overlay']) {
1460 $next_MP_array[] = $mount_info['MPvar'];
1461 $next_id = $mount_info['mount_pid'];
1462 }
1463 if (!isset($this->MPmap[$next_id])) {
1464 // Set mapping information for this level:
1465 $this->MPmap[$next_id] = $next_MP_array;
1466 // Normal mode:
1467 if (is_array($mount_info) && !$mount_info['overlay']) {
1468 $next_MP_array[] = $mount_info['MPvar'];
1469 $next_id = $mount_info['mount_pid'];
1470 }
1471 // Register recursive call
1472 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1473 $nextLevelAcc[] = array($next_id, $next_MP_array);
1474 }
1475 }
1476 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1477 // Call recursively, if any:
1478 foreach ($nextLevelAcc as $pSet) {
1479 $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1480 }
1481 }
1482 }
1483
1484 /**
1485 * Adds the TypoScript from the global array.
1486 * The class property isDefaultTypoScriptAdded ensures
1487 * that the adding only happens once.
1488 *
1489 * @return void
1490 * @see isDefaultTypoScriptAdded
1491 */
1492 protected function addDefaultTypoScript() {
1493 // Add default TS for all code types, if not done already
1494 if (!$this->isDefaultTypoScriptAdded) {
1495 // adding default setup and constants
1496 // defaultTypoScript_setup is *very* unlikely to be empty
1497 // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1498 array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1499 array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1500 array_unshift($this->templateIncludePaths, '');
1501 // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1502 $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo)-1]['templateID'];
1503 $defaultTemplateInfo = array(
1504 'root' => '',
1505 'next' => '',
1506 'clConst' => '',
1507 'clConf' => '',
1508 'templateID' => '_defaultTypoScript_',
1509 'templateParent' => $rootTemplateId,
1510 'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1511 'uid' => '_defaultTypoScript_',
1512 'pid' => '',
1513 'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1514 );
1515 // push info to information arrays used in BE by TemplateTools (Analyzer)
1516 array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1517 array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1518 array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1519 $this->isDefaultTypoScriptAdded = TRUE;
1520 }
1521 }
1522
1523 }