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