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