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