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