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