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