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