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