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