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