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