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