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