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