[FEATURE] Add support for native date/time fields
[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 // Traversing list
592 foreach ($include_static_fileArr as $ISF_file) {
593 if (substr($ISF_file, 0, 4) == 'EXT:') {
594 list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
595 if (strcmp($ISF_extKey, '') && t3lib_extMgm::isLoaded($ISF_extKey) && strcmp($ISF_localPath, '')) {
596 $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
597 $ISF_filePath = t3lib_extMgm::extPath($ISF_extKey) . $ISF_localPath;
598 if (@is_dir($ISF_filePath)) {
599 $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
600 $subrow = array(
601 'constants' => @is_file($ISF_filePath . 'constants.txt') ? t3lib_div::getUrl($ISF_filePath . 'constants.txt') : '',
602 'config' => @is_file($ISF_filePath . 'setup.txt') ? t3lib_div::getUrl($ISF_filePath . 'setup.txt') : '',
603 'include_static' => @is_file($ISF_filePath . 'include_static.txt') ? implode(',', array_unique(t3lib_div::intExplode(',', t3lib_div::getUrl($ISF_filePath . 'include_static.txt')))) : '',
604 'include_static_file' => @is_file($ISF_filePath . 'include_static_file.txt') ? implode(',', array_unique(explode(',', t3lib_div::getUrl($ISF_filePath . 'include_static_file.txt')))) : '',
605 'title' => $ISF_file,
606 'uid' => $mExtKey
607 );
608 $subrow = $this->prependStaticExtra($subrow);
609
610 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID);
611 }
612 }
613 }
614 }
615 }
616
617 // If "Default (include before if root flag is set)" is set OR
618 // "Always include before this template record" AND root-flag are set
619 if ($row['static_file_mode'] == 1 || ($row['static_file_mode'] == 0 && substr($templateID, 0, 4) == 'sys_' && $row['root'])) {
620 $this->addExtensionStatics($idList, $templateID, $pid, $row);
621 }
622
623 // Include Static Template Records after all other TypoScript has been included.
624 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'])) {
625 $_params = array(
626 'idList' => &$idList,
627 'templateId' => &$templateID,
628 'pid' => &$pid,
629 'row' => &$row
630 );
631 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] as $_funcRef) {
632 t3lib_div::callUserFunction($_funcRef, $_params, $this);
633 }
634 }
635 }
636
637 /**
638 * Adds the default TypoScript files for extensions if any.
639 *
640 * @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.
641 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123"
642 * @param array $pid The PID of the input template record
643 * @param array $row A full TypoScript template record
644 * @return void
645 * @access private
646 * @see includeStaticTypoScriptSources()
647 */
648 function addExtensionStatics($idList, $templateID, $pid, $row) {
649
650 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extKey => $files) {
651 if (is_array($files) && ($files['ext_typoscript_constants.txt'] || $files['ext_typoscript_setup.txt'])) {
652 $mExtKey = str_replace('_', '', $extKey);
653 $subrow = array(
654 'constants' => $files['ext_typoscript_constants.txt'] ? t3lib_div::getUrl($files['ext_typoscript_constants.txt']) : '',
655 'config' => $files['ext_typoscript_setup.txt'] ? t3lib_div::getUrl($files['ext_typoscript_setup.txt']) : '',
656 'title' => $extKey,
657 'uid' => $mExtKey
658 );
659 $subrow = $this->prependStaticExtra($subrow);
660 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID);
661 }
662 }
663 }
664
665 /**
666 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
667 * For records the "uid" value is the integer of the "static_template" record
668 * 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
669 *
670 * @param array $subrow Static template record/file
671 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
672 * @access private
673 * @see addExtensionStatics(), includeStaticTypoScriptSources()
674 */
675 function prependStaticExtra($subrow) {
676 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$subrow['uid']];
677 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$subrow['uid']];
678 return $subrow;
679 }
680
681 /**
682 * Creating versioning overlay of a sys_template record.
683 * This will use either frontend or backend overlay functionality depending on environment.
684 *
685 * @param array $row Row to overlay (passed by reference)
686 * @return void
687 */
688 function versionOL(&$row) {
689 // Distinguish frontend and backend call:
690 // To do the fronted call a full frontend is required, just checking for
691 // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
692 // eId scripts that run in frontend scope, but do not have a full blown frontend.
693 if (
694 is_object($GLOBALS['TSFE']) === TRUE
695 && property_exists($GLOBALS['TSFE'], 'sys_page') === TRUE
696 && method_exists($GLOBALS['TSFE']->sys_page, 'versionOL') === TRUE
697 ) {
698 // Frontend
699 $GLOBALS['TSFE']->sys_page->versionOL('sys_template', $row);
700 } else {
701 // Backend
702 t3lib_BEfunc::workspaceOL('sys_template', $row);
703 }
704 }
705
706 /*******************************************************************
707 *
708 * Parsing TypoScript code text from Template Records into PHP array
709 *
710 *******************************************************************/
711
712 /**
713 * Generates the configuration array by replacing constants and parsing the whole thing.
714 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
715 *
716 * @return void
717 * @see t3lib_TSparser, start()
718 */
719 function generateConfig() {
720 // Add default TS for all three code types:
721 array_unshift($this->constants, '' . $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']); // Adding default TS/constants
722 array_unshift($this->config, '' . $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']); // Adding default TS/setup
723
724 // Parse the TypoScript code text for include-instructions!
725 $this->processIncludes();
726
727 // These vars are also set lateron...
728 $this->setup['sitetitle'] = $this->sitetitle;
729
730 // ****************************
731 // Parse TypoScript Constants
732 // ****************************
733
734 // Initialize parser and match-condition classes:
735 /** @var $constants t3lib_TSparser */
736 $constants = t3lib_div::makeInstance('t3lib_TSparser');
737 $constants->breakPointLN = intval($this->ext_constants_BRP);
738 $constants->setup = $this->const;
739 $constants->setup = $this->mergeConstantsFromPageTSconfig($constants->setup);
740
741 /** @var $matchObj t3lib_matchCondition_frontend */
742 $matchObj = t3lib_div::makeInstance('t3lib_matchCondition_frontend');
743 $matchObj->setSimulateMatchConditions($this->matchAlternative);
744 $matchObj->setSimulateMatchResult((bool) $this->matchAll);
745
746 // Traverse constants text fields and parse them
747 foreach ($this->constants as $str) {
748 $constants->parse($str, $matchObj);
749 }
750
751 // Read out parse errors if any
752 $this->parserErrors['constants'] = $constants->errors;
753
754 // 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)
755 $this->flatSetup = array();
756 $this->flattenSetup($constants->setup, '', '');
757
758 // ***********************************************
759 // Parse TypoScript Setup (here called "config")
760 // ***********************************************
761 // Initialize parser and match-condition classes:
762 /** @var $config t3lib_TSparser */
763 $config = t3lib_div::makeInstance('t3lib_TSparser');
764 $config->breakPointLN = intval($this->ext_config_BRP);
765 $config->regLinenumbers = $this->ext_regLinenumbers;
766 $config->regComments = $this->ext_regComments;
767 $config->setup = $this->setup;
768
769 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
770 $config->sections = $constants->sections;
771 $config->sectionsMatch = $constants->sectionsMatch;
772
773 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
774 $all = '';
775 foreach ($this->config as $str) {
776 $all .= "\n[GLOBAL]\n" . $str;
777 }
778
779 // Substitute constants in the Setup code:
780 if ($this->tt_track) {
781 $GLOBALS['TT']->push('Substitute Constants (' . count($this->flatSetup) . ')');
782 }
783 $all = $this->substituteConstants($all);
784 if ($this->tt_track) {
785 $GLOBALS['TT']->pull();
786 }
787
788 // Searching for possible unsubstituted constants left (only for information)
789 if (strstr($all, '{$')) {
790 $theConstList = array();
791 $findConst = explode('{$', $all);
792 array_shift($findConst);
793 foreach ($findConst as $constVal) {
794 $constLen = t3lib_utility_Math::forceIntegerInRange(strcspn($constVal, '}'), 0, 50);
795 $theConstList[] = '{$' . substr($constVal, 0, $constLen + 1);
796 }
797 if ($this->tt_track) {
798 $GLOBALS['TT']->setTSlogMessage(implode(', ', $theConstList) . ': Constants may remain un-substituted!!', 2);
799 }
800 }
801
802 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
803 if ($this->tt_track) {
804 $GLOBALS['TT']->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
805 }
806
807 // Finally parse the Setup field TypoScript code (where constants are now substituted)
808 $config->parse($all, $matchObj);
809
810 // Read out parse errors if any
811 $this->parserErrors['config'] = $config->errors;
812
813 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
814 $this->setup = $config->setup;
815 if ($this->backend_info) {
816 // Used for backend purposes only
817 $this->setup_constants = $constants->setup;
818 }
819
820 // ****************************************************************
821 // Final processing of the $this->setup TypoScript Template array
822 // Basically: This is unsetting/setting of certain reserved keys.
823 // ****************************************************************
824
825 // 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!
826 unset($this->setup['sitetitle']);
827 unset($this->setup['sitetitle.']);
828 $this->setup['sitetitle'] = $this->sitetitle;
829
830 // Unsetting some vars...
831 unset($this->setup['types.']);
832 unset($this->setup['types']);
833 if (is_array($this->setup)) {
834 foreach ($this->setup as $key => $value) {
835 if ($value == 'PAGE') {
836 // Set the typeNum of the current page object:
837 if (isset($this->setup[$key . '.']['typeNum'])) {
838 $typeNum = $this->setup[$key . '.']['typeNum'];
839 $this->setup['types.'][$typeNum] = $key;
840 // If there is no type 0 yet and typeNum was not set, we use the current object as the default
841 } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
842 $this->setup['types.'][0] = $key;
843 }
844 }
845 }
846 }
847 unset($this->setup['styles.']);
848 unset($this->setup['temp.']);
849 unset($constants);
850
851 // Storing the conditions found/matched information:
852 $this->sections = $config->sections;
853 $this->sectionsMatch = $config->sectionsMatch;
854 }
855
856 /**
857 * Searching TypoScript code text (for constants and config (Setup))
858 * for include instructions and does the inclusion of external TypoScript files
859 * if needed.
860 *
861 * @return void
862 * @see t3lib_TSparser, generateConfig()
863 */
864 public function processIncludes() {
865 $files = array();
866 foreach ($this->constants as &$value) {
867 $includeData = t3lib_TSparser::checkIncludeLines($value, 1, TRUE);
868 $files = array_merge($files, $includeData['files']);
869 $value = $includeData['typoscript'];
870 }
871 unset($value);
872
873 foreach ($this->config as &$value) {
874 $includeData = t3lib_TSparser::checkIncludeLines($value, 1, TRUE);
875 $files = array_merge($files, $includeData['files']);
876 $value = $includeData['typoscript'];
877 }
878 unset($value);
879
880 if (count($files)) {
881 $files = array_unique($files);
882 foreach ($files as $file) {
883 $this->rowSum[] = array($file, filemtime($file));
884 }
885 }
886 }
887
888 /**
889 * 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!
890 *
891 * @param array $constArray Constants array, default input.
892 * @return array Constants array, modified
893 * @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...)
894 */
895 function mergeConstantsFromPageTSconfig($constArray) {
896 $TSdataArray = array();
897 // Setting default configuration:
898 $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
899
900 for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
901 $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
902 }
903 // Parsing the user TS (or getting from cache)
904 $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
905 $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
906
907 /** @var $parseObj t3lib_TSparser */
908 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
909 $parseObj->parse($userTS);
910
911 if (is_array($parseObj->setup['TSFE.']['constants.'])) {
912 $constArray = t3lib_div::array_merge_recursive_overrule($constArray, $parseObj->setup['TSFE.']['constants.']);
913 }
914 return $constArray;
915 }
916
917 /**
918 * This flattens a hierarchical TypoScript array to $this->flatSetup
919 *
920 * @param array $setupArray TypoScript array
921 * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
922 * @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.
923 * @return void
924 * @see generateConfig()
925 */
926 function flattenSetup($setupArray, $prefix, $resourceFlag) {
927 if (is_array($setupArray)) {
928 foreach ($setupArray as $key => $val) {
929 if ($prefix || substr($key, 0, 16) != 'TSConstantEditor') { // We don't want 'TSConstantEditor' in the flattend setup on the first level (190201)
930 if (is_array($val)) {
931 $this->flattenSetup($val, $prefix . $key, ($key == 'file.'));
932 } elseif ($resourceFlag) {
933 $this->flatSetup[$prefix . $key] = $this->getFileName($val);
934 } else {
935 $this->flatSetup[$prefix . $key] = $val;
936 }
937 }
938 }
939 }
940 }
941
942 /**
943 * Substitutes the constants from $this->flatSetup in the text string $all
944 *
945 * @param string $all TypoScript code text string
946 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
947 * @see generateConfig(), flattenSetup()
948 */
949 function substituteConstants($all) {
950 if ($this->tt_track) {
951 $GLOBALS['TT']->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
952 }
953
954 $noChange = FALSE;
955 // Recursive substitution of constants (up to 10 nested levels)
956 for ($i = 0; $i < 10 && !$noChange; $i++) {
957 $old_all = $all;
958 $all = preg_replace_callback('/\{\$(.[^}]*)\}/', array($this, 'substituteConstantsCallBack'), $all);
959 if ($old_all == $all) {
960 $noChange = TRUE;
961 }
962 }
963
964 return $all;
965 }
966
967 /**
968 * Call back method for preg_replace_callback in substituteConstants
969 *
970 * @param array $matches Regular expression matches
971 * @return string Replacement
972 * @see substituteConstants()
973 */
974 function substituteConstantsCallBack($matches) {
975 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
976 return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
977 }
978
979 /*******************************************************************
980 *
981 * Various API functions, used from elsewhere in the frontend classes
982 *
983 *******************************************************************/
984
985 /**
986 * Implementation of the "optionSplit" feature in TypoScript (used eg. for MENU objects)
987 * 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.
988 * The concept is known as "optionSplit" and is rather advanced to handle but quite powerful, in particular for creating menus in TYPO3.
989 *
990 * @param array $conf A TypoScript array
991 * @param integer $splitCount The number of items for which to generated individual TypoScript arrays
992 * @return array The individualized TypoScript array.
993 * @see tslib_cObj::IMGTEXT(), tslib_menu::procesItemStates()
994 */
995 function splitConfArray($conf, $splitCount) {
996
997 // Initialize variables:
998 $splitCount = intval($splitCount);
999 $conf2 = array();
1000
1001 if ($splitCount && is_array($conf)) {
1002
1003 // Initialize output to carry at least the keys:
1004 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1005 $conf2[$aKey] = array();
1006 }
1007
1008 // Recursive processing of array keys:
1009 foreach ($conf as $cKey => $val) {
1010 if (is_array($val)) {
1011 $tempConf = $this->splitConfArray($val, $splitCount);
1012 foreach ($tempConf as $aKey => $val) {
1013 $conf2[$aKey][$cKey] = $val;
1014 }
1015 } else {
1016 // Splitting of all values on this level of the TypoScript object tree:
1017 if (!strstr($val, '|*|') && !strstr($val, '||')) {
1018 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1019 $conf2[$aKey][$cKey] = $val;
1020 }
1021 } else {
1022 $main = explode('|*|', $val);
1023 $mainCount = count($main);
1024
1025 $lastC = 0;
1026 $middleC = 0;
1027 $firstC = 0;
1028
1029 if ($main[0]) {
1030 $first = explode('||', $main[0]);
1031 $firstC = count($first);
1032 }
1033 if ($main[1]) {
1034 $middle = explode('||', $main[1]);
1035 $middleC = count($middle);
1036 }
1037 if ($main[2]) {
1038 $last = explode('||', $main[2]);
1039 $lastC = count($last);
1040 $value = $last[0];
1041 }
1042
1043 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1044 if ($firstC && isset($first[$aKey])) {
1045 $value = $first[$aKey];
1046 } elseif ($middleC) {
1047 $value = $middle[($aKey - $firstC) % $middleC];
1048 }
1049 if ($lastC && $lastC >= ($splitCount - $aKey)) {
1050 $value = $last[$lastC - ($splitCount - $aKey)];
1051 }
1052 $conf2[$aKey][$cKey] = trim($value);
1053 }
1054 }
1055 }
1056 }
1057 }
1058 return $conf2;
1059 }
1060
1061 /**
1062 * Returns the reference to a 'resource' in TypoScript.
1063 * This could be from the filesystem if '/' is found in the value $fileFromSetup, else from the resource-list
1064 *
1065 * @param string $fileFromSetup TypoScript "resource" data type value.
1066 * @return string Resulting filename, if any.
1067 */
1068 function getFileName($fileFromSetup) {
1069 $file = trim($fileFromSetup);
1070 if (!$file) {
1071 return;
1072 } elseif (strstr($file, '../')) {
1073 if ($this->tt_track) {
1074 $GLOBALS['TT']->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
1075 }
1076 return;
1077 }
1078 // Cache
1079 $hash = md5($file);
1080 if (isset($this->fileCache[$hash])) {
1081 return $this->fileCache[$hash];
1082 }
1083
1084 if (!strcmp(substr($file, 0, 4), 'EXT:')) {
1085 $newFile = '';
1086 list($extKey, $script) = explode('/', substr($file, 4), 2);
1087 if ($extKey && t3lib_extMgm::isLoaded($extKey)) {
1088 $extPath = t3lib_extMgm::extPath($extKey);
1089 $newFile = substr($extPath, strlen(PATH_site)) . $script;
1090 }
1091 if (!@is_file(PATH_site . $newFile)) {
1092 if ($this->tt_track) {
1093 $GLOBALS['TT']->setTSlogMessage('Extension media file "' . $newFile . '" was not found!', 3);
1094 }
1095 return;
1096 } else {
1097 $file = $newFile;
1098 }
1099 }
1100
1101 if (parse_url($file) !== FALSE) {
1102 return $file;
1103 }
1104
1105 // Find
1106 if (strpos($file, '/') !== FALSE) {
1107 // If the file is in the media/ folder but it doesn't exist,
1108 // it is assumed that it's in the tslib folder
1109 if (t3lib_div::isFirstPartOfStr($file, 'media/') && !is_file($this->getFileName_backPath . $file)) {
1110 $file = t3lib_extMgm::siteRelPath('cms') . 'tslib/' . $file;
1111 }
1112 if (is_file($this->getFileName_backPath . $file)) {
1113 $outFile = $file;
1114 $fileInfo = t3lib_div::split_fileref($outFile);
1115 $OK = 0;
1116 foreach ($this->allowedPaths as $val) {
1117 if (substr($fileInfo['path'], 0, strlen($val)) == $val) {
1118 $OK = 1;
1119 break;
1120 }
1121 }
1122 if ($OK) {
1123 $this->fileCache[$hash] = $outFile;
1124 return $outFile;
1125 } elseif ($this->tt_track) {
1126 $GLOBALS['TT']->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1127 }
1128 } elseif ($this->tt_track) {
1129 $GLOBALS['TT']->setTSlogMessage('"' . $this->getFileName_backPath . $file . '" is not a file (non-uploads/.. resource, did not exist).', 3);
1130 }
1131 }
1132 }
1133
1134 /**
1135 * Compiles the content for the page <title> tag.
1136 *
1137 * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1138 * @param boolean $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1139 * @param boolean $showTitleFirst If set, then "sitetitle" and $title is swapped
1140 * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1141 * @see tslib_fe::tempPageCacheContent(), TSpagegen::renderContentWithHeader()
1142 */
1143 function printTitle($pageTitle, $noTitle = FALSE, $showTitleFirst = FALSE) {
1144 $siteTitle = trim($this->setup['sitetitle']) ? $this->setup['sitetitle'] : '';
1145 $pageTitle = $noTitle ? '' : $pageTitle;
1146 $pageTitleSeparator = '';
1147
1148 if ($showTitleFirst) {
1149 $temp = $siteTitle;
1150 $siteTitle = $pageTitle;
1151 $pageTitle = $temp;
1152 }
1153
1154 if ($pageTitle != '' && $siteTitle != '') {
1155 $pageTitleSeparator = ': ';
1156 if (isset($this->setup['config.']['pageTitleSeparator']) && $this->setup['config.']['pageTitleSeparator']) {
1157 $pageTitleSeparator = $this->setup['config.']['pageTitleSeparator'] . ' ';
1158 }
1159 }
1160
1161 return $siteTitle . $pageTitleSeparator . $pageTitle;
1162 }
1163
1164 /**
1165 * Reads the fileContent of $fName and returns it.
1166 * Similar to t3lib_div::getUrl()
1167 *
1168 * @param string $fName Absolute filepath to record
1169 * @return string The content returned
1170 * @see tslib_cObj::fileResource(), tslib_cObj::MULTIMEDIA(), t3lib_div::getUrl()
1171 */
1172 function fileContent($fName) {
1173 $incFile = $this->getFileName($fName);
1174 if ($incFile) {
1175 return @file_get_contents($incFile);
1176 }
1177 }
1178
1179 /**
1180 * Ordinary "wrapping" function. Used in the tslib_menu class and extension classes instead of the similar function in tslib_cObj
1181 *
1182 * @param string $content The content to wrap
1183 * @param string $wrap The wrap value, eg. "<strong> | </strong>"
1184 * @return string Wrapped input string
1185 * @see tslib_menu, tslib_cObj::wrap()
1186 */
1187 function wrap($content, $wrap) {
1188 if ($wrap) {
1189 $wrapArr = explode('|', $wrap);
1190 return trim($wrapArr[0]) . $content . trim($wrapArr[1]);
1191 } else {
1192 return $content;
1193 }
1194 }
1195
1196 /**
1197 * Removes the "?" of input string IF the "?" is the last character.
1198 *
1199 * @param string $url Input string
1200 * @return string Output string, free of "?" in the end, if any such character.
1201 * @see linkData(), tslib_frameset::frameParams()
1202 */
1203 function removeQueryString($url) {
1204 if (substr($url, -1) == '?') {
1205 return substr($url, 0, -1);
1206 } else {
1207 return $url;
1208 }
1209 }
1210
1211 /**
1212 * 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.
1213 * Call it like t3lib_TStemplate::sortedKeyList()
1214 *
1215 * @param array $setupArr TypoScript array with numerical array in
1216 * @param boolean $acceptOnlyProperties If set, then a value is not required - the properties alone will be enough.
1217 * @return array An array with all integer properties listed in numeric order.
1218 * @see tslib_cObj::cObjGet(), tslib_gifBuilder, tslib_imgmenu::makeImageMap()
1219 */
1220 public static function sortedKeyList($setupArr, $acceptOnlyProperties = FALSE) {
1221 $keyArr = array();
1222 $setupArrKeys = array_keys($setupArr);
1223 foreach ($setupArrKeys as $key) {
1224 if ($acceptOnlyProperties || t3lib_utility_Math::canBeInterpretedAsInteger($key)) {
1225 $keyArr[] = intval($key);
1226 }
1227 }
1228 $keyArr = array_unique($keyArr);
1229 sort($keyArr);
1230 return $keyArr;
1231 }
1232
1233
1234 /**
1235 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1236 *
1237 * @param string $list A list of UIDs for which the rootline-level should get returned
1238 * @return integer The level in the rootline. If more than one page was given the lowest level will get returned.
1239 */
1240 function getRootlineLevel($list) {
1241 $idx = 0;
1242 foreach ($this->rootLine as $page) {
1243 if (t3lib_div::inList($list, $page['uid'])) {
1244 return $idx;
1245 }
1246 $idx++;
1247 }
1248 return FALSE;
1249 }
1250
1251 /*******************************************************************
1252 *
1253 * Functions for creating links
1254 *
1255 *******************************************************************/
1256
1257 /**
1258 * The mother of all functions creating links/URLs etc in a TypoScript environment.
1259 * See the references below.
1260 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1261 * 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.
1262 *
1263 * @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.
1264 * @param string $oTarget Default target string to use IF not $page['target'] is set.
1265 * @param boolean $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1266 * @param string $script Alternative script name if you don't want to use $GLOBALS['TSFE']->config['mainScript'] (normally set to "index.php")
1267 * @param array $overrideArray Array with overriding values for the $page array.
1268 * @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.
1269 * @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.
1270 * @param string $targetDomain The target Doamin, if any was detected in typolink
1271 * @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"
1272 * @see tslib_frameset::frameParams(), tslib_cObj::typoLink(), tslib_cObj::SEARCHRESULT(), TSpagegen::pagegenInit(), tslib_menu::link()
1273 */
1274 function linkData($page, $oTarget, $no_cache, $script, $overrideArray = NULL, $addParams = '', $typeOverride = '', $targetDomain = '') {
1275
1276 $LD = array();
1277
1278 // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1279 if (is_array($overrideArray)) {
1280 foreach ($overrideArray as $theKey => $theNewVal) {
1281 $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1282 $page[$theKey] = $theNewVal;
1283 }
1284 }
1285
1286 // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1287 if (!strstr($addParams, '&MP=')) {
1288 // Looking for hardcoded defaults:
1289 if (trim($GLOBALS['TSFE']->MP_defaults[$page['uid']])) {
1290 $addParams .= '&MP=' . rawurlencode(trim($GLOBALS['TSFE']->MP_defaults[$page['uid']]));
1291 } elseif ($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']) { // Else look in automatically created map:
1292 $m = $this->getFromMPmap($page['uid']);
1293 if ($m) {
1294 $addParams .= '&MP=' . rawurlencode($m);
1295 }
1296 }
1297 }
1298
1299 // Setting ID/alias:
1300 if (!$script) {
1301 $script = $GLOBALS['TSFE']->config['mainScript'];
1302 }
1303 if ($page['alias']) {
1304 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1305 } else {
1306 $LD['url'] = $script . '?id=' . $page['uid'];
1307 }
1308 // Setting target
1309 $LD['target'] = trim($page['target']) ? trim($page['target']) : $oTarget;
1310
1311 // typeNum
1312 $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1313 if (!t3lib_utility_Math::canBeInterpretedAsInteger($typeOverride) && intval($GLOBALS['TSFE']->config['config']['forceTypeValue'])) {
1314 $typeOverride = intval($GLOBALS['TSFE']->config['config']['forceTypeValue']);
1315 }
1316 if (strcmp($typeOverride, '')) {
1317 $typeNum = $typeOverride;
1318 } // Override...
1319 if ($typeNum) {
1320 $LD['type'] = '&type=' . intval($typeNum);
1321 } else {
1322 $LD['type'] = '';
1323 }
1324 // Preserving the type number.
1325 $LD['orig_type'] = $LD['type'];
1326
1327 // noCache
1328 $LD['no_cache'] = (trim($page['no_cache']) || $no_cache) ? '&no_cache=1' : '';
1329
1330 // linkVars
1331 if ($GLOBALS['TSFE']->config['config']['uniqueLinkVars']) {
1332 if ($addParams) {
1333 $LD['linkVars'] = t3lib_div::implodeArrayForUrl('', t3lib_div::explodeUrl2Array($GLOBALS['TSFE']->linkVars . $addParams), '', FALSE, TRUE);
1334 } else {
1335 $LD['linkVars'] = $GLOBALS['TSFE']->linkVars;
1336 }
1337 } else {
1338 $LD['linkVars'] = $GLOBALS['TSFE']->linkVars . $addParams;
1339 }
1340
1341 // Add absRefPrefix if exists.
1342 $LD['url'] = $GLOBALS['TSFE']->absRefPrefix . $LD['url'];
1343
1344 // 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.
1345 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1346
1347 // Compile the normal total url
1348 $LD['totalURL'] = $this->removeQueryString($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $GLOBALS['TSFE']->getMethodUrlIdToken) . $LD['sectionIndex'];
1349
1350 // Call post processing function for link rendering:
1351 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'])) {
1352 $_params = array(
1353 'LD' => &$LD,
1354 'args' => array('page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain),
1355 'typeNum' => $typeNum
1356 );
1357 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] as $_funcRef) {
1358 t3lib_div::callUserFunction($_funcRef, $_params, $this);
1359 }
1360 }
1361
1362 // Return the LD-array
1363 return $LD;
1364 }
1365
1366 /**
1367 * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1368 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1369 *
1370 * @param integer $pageId Page id to return MPvar value for.
1371 * @return string
1372 * @see initMPmap_create()
1373 * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1374 */
1375 function getFromMPmap($pageId = 0) {
1376
1377 // Create map if not found already:
1378 if (!is_array($this->MPmap)) {
1379 $this->MPmap = array();
1380
1381 $rootPoints = t3lib_div::trimExplode(',', strtolower($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']), 1);
1382 // Traverse rootpoints:
1383 foreach ($rootPoints as $p) {
1384 if ($p == 'root') {
1385 $p = $this->rootLine[0]['uid'];
1386 $initMParray = array();
1387 if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1388 $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1389 }
1390 }
1391 $this->initMPmap_create($p, $initMParray);
1392 }
1393 }
1394
1395 // Finding MP var for Page ID:
1396 if ($pageId) {
1397 if (is_array($this->MPmap[$pageId]) && count($this->MPmap[$pageId])) {
1398 return implode(',', $this->MPmap[$pageId]);
1399 }
1400 }
1401 }
1402
1403 /**
1404 * Creating MPmap for a certain ID root point.
1405 *
1406 * @param integer $id Root id from which to start map creation.
1407 * @param array $MP_array MP_array passed from root page.
1408 * @param integer $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1409 * @return void
1410 * @see getFromMPvar()
1411 */
1412 function initMPmap_create($id, $MP_array = array(), $level = 0) {
1413
1414 $id = intval($id);
1415 if ($id <= 0) {
1416 return;
1417 }
1418
1419 // First level, check id
1420 if (!$level) {
1421
1422 // Find mount point if any:
1423 $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($id);
1424
1425 // Overlay mode:
1426 if (is_array($mount_info) && $mount_info['overlay']) {
1427 $MP_array[] = $mount_info['MPvar'];
1428 $id = $mount_info['mount_pid'];
1429 }
1430
1431 // Set mapping information for this level:
1432 $this->MPmap[$id] = $MP_array;
1433
1434 // Normal mode:
1435 if (is_array($mount_info) && !$mount_info['overlay']) {
1436 $MP_array[] = $mount_info['MPvar'];
1437 $id = $mount_info['mount_pid'];
1438 }
1439 }
1440
1441 if ($id && $level < 20) {
1442
1443 $nextLevelAcc = array();
1444
1445 // Select and traverse current level pages:
1446 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1447 'uid,pid,doktype,mount_pid,mount_pid_ol',
1448 'pages',
1449 'pid=' . intval($id) . ' AND deleted=0 AND doktype<>' . t3lib_pageSelect::DOKTYPE_RECYCLER .
1450 ' AND doktype<>' . t3lib_pageSelect::DOKTYPE_BE_USER_SECTION
1451 );
1452 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1453
1454 // Find mount point if any:
1455 $next_id = $row['uid'];
1456 $next_MP_array = $MP_array;
1457 $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($next_id, $row);
1458
1459 // Overlay mode:
1460 if (is_array($mount_info) && $mount_info['overlay']) {
1461 $next_MP_array[] = $mount_info['MPvar'];
1462 $next_id = $mount_info['mount_pid'];
1463 }
1464
1465 if (!isset($this->MPmap[$next_id])) {
1466
1467 // Set mapping information for this level:
1468 $this->MPmap[$next_id] = $next_MP_array;
1469
1470 // Normal mode:
1471 if (is_array($mount_info) && !$mount_info['overlay']) {
1472 $next_MP_array[] = $mount_info['MPvar'];
1473 $next_id = $mount_info['mount_pid'];
1474 }
1475
1476 // Register recursive call
1477 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1478 $nextLevelAcc[] = array($next_id, $next_MP_array);
1479 }
1480 }
1481 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1482
1483 // Call recursively, if any:
1484 foreach ($nextLevelAcc as $pSet) {
1485 $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1486 }
1487 }
1488 }
1489 }
1490 ?>