28e07913c1f790b7ac60539cd83320bac4d4464d
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_page.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2004 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains a class with "Page functions" mainly for the frontend
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 2/2003 by Kasper Skaarhoj
32 * XHTML-trans compliant
33 *
34 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
35 */
36 /**
37 * [CLASS/FUNCTION INDEX of SCRIPT]
38 *
39 *
40 *
41 * 107: class t3lib_pageSelect
42 * 132: function init($show_hidden)
43 *
44 * SECTION: Selecting page records
45 * 171: function getPage($uid)
46 * 187: function getPage_noCheck($uid)
47 * 203: function getFirstWebPage($uid)
48 * 221: function getPageIdFromAlias($alias)
49 * 237: function getPageOverlay($pageInput,$lUid=-1)
50 * 300: function getRecordOverlay($table,$row,$sys_language_content,$OLmode='')
51 *
52 * SECTION: Page related: Menu, Domain record, Root line
53 * 396: function getMenu($uid,$fields='*',$sortField='sorting',$addWhere='')
54 * 431: function getDomainStartPage($domain, $path='',$request_uri='')
55 * 479: function getRootLine($uid, $MP='', $ignoreMPerrors=FALSE)
56 * 597: function getPathFromRootline($rl,$len=20)
57 * 618: function getExtURL($pagerow,$disable=0)
58 * 642: function getMountPointInfo($pageId, $pageRec=FALSE, $prevMountPids=array(), $firstPageUid=0)
59 *
60 * SECTION: Selecting records in general
61 * 719: function checkRecord($table,$uid,$checkPage=0)
62 * 750: function getRawRecord($table,$uid,$fields='*')
63 * 774: function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='')
64 *
65 * SECTION: Caching and standard clauses
66 * 826: function getHash($hash,$expTime=0)
67 * 849: function storeHash($hash,$data,$ident)
68 * 867: function deleteClause($table)
69 * 886: function enableFields($table,$show_hidden=-1,$ignore_array=array())
70 *
71 * SECTION: Versioning Preview
72 * 954: function fixVersioningPid($table,&$rr)
73 * 986: function versionOL($table,&$row)
74 *
75 * TOTAL FUNCTIONS: 22
76 * (This index is automatically created/updated by the extension "extdeveval")
77 *
78 */
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97 /**
98 * Page functions, a lot of sql/pages-related functions
99 * Mainly used in the frontend but also in some cases in the backend.
100 * It's important to set the right $where_hid_del in the object so that the functions operate properly
101 *
102 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
103 * @package TYPO3
104 * @subpackage t3lib
105 * @see tslib_fe::fetch_the_id()
106 */
107 class t3lib_pageSelect {
108 var $urltypes = Array('','http://','ftp://','mailto:');
109 var $where_hid_del = ' AND pages.deleted=0'; // This is not the final clauses. There will normally be conditions for the hidden,starttime and endtime fields as well. You MUST initialize the object by the init() function
110 var $sys_language_uid = 0;
111
112 // Versioning preview related:
113 var $versioningPreview = FALSE; // If true, preview of other record versions is allowed. THIS MUST ONLY BE SET IF the page is not cached and truely previewed by a backend user!!!
114 var $versionPreviewMap = array(
115 # EXAMPLE: 'tt_content:421' => 427
116 );
117
118
119 // Internal, dynamic:
120 var $error_getRootLine = ''; // Error string set by getRootLine()
121 var $error_getRootLine_failPid = 0; // Error uid set by getRootLine()
122
123
124 /**
125 * init() MUST be run directly after creating a new template-object
126 * This sets the internal variable $this->where_hid_del to the correct where clause for page records taking deleted/hidden/starttime/endtime into account
127 *
128 * @param boolean If $show_hidden is true, the hidden-field is ignored!! Normally this should be false. Is used for previewing.
129 * @return void
130 * @see tslib_fe::fetch_the_id(), tx_tstemplateanalyzer::initialize_editor()
131 */
132 function init($show_hidden) {
133 $this->where_hid_del = ' AND pages.deleted=0 ';
134 if (!$show_hidden) {
135 $this->where_hid_del.= 'AND pages.hidden=0 ';
136 }
137 $this->where_hid_del.= 'AND (pages.starttime<='.$GLOBALS['SIM_EXEC_TIME'].') AND (pages.endtime=0 OR pages.endtime>'.$GLOBALS['SIM_EXEC_TIME'].') ';
138 }
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156 /*******************************************
157 *
158 * Selecting page records
159 *
160 ******************************************/
161
162 /**
163 * Returns the $row for the page with uid = $uid (observing ->where_hid_del)
164 * Any pages_language_overlay will be applied before the result is returned.
165 * If no page is found an empty array is returned.
166 *
167 * @param integer The page id to look up.
168 * @return array The page row with overlayed localized fields. Empty it no page.
169 * @see getPage_noCheck()
170 */
171 function getPage($uid) {
172 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($uid).$this->where_hid_del);
173 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
174 #?? $this->versionOL('pages',$row);
175 return $this->getPageOverlay($row);
176 }
177 return Array();
178 }
179
180 /**
181 * Return the $row for the page with uid = $uid WITHOUT checking for ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
182 *
183 * @param integer The page id to look up
184 * @return array The page row with overlayed localized fields. Empty it no page.
185 * @see getPage()
186 */
187 function getPage_noCheck($uid) {
188 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($uid).$this->deleteClause('pages'));
189 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
190 #?? $this->versionOL('pages',$row);
191 return $this->getPageOverlay($row);
192 }
193 return Array();
194 }
195
196 /**
197 * Returns the $row of the first web-page in the tree (for the default menu...)
198 *
199 * @param integer The page id for which to fetch first subpages (PID)
200 * @return mixed If found: The page record (with overlayed localized fields, if any). If NOT found: blank value (not array!)
201 * @see tslib_fe::fetch_the_id()
202 */
203 function getFirstWebPage($uid) {
204 $output = '';
205 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'pid='.intval($uid).$this->where_hid_del, '', 'sorting', '1');
206 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
207 #?? $this->versionOL('pages',$row);
208 $output = $this->getPageOverlay($row);
209 }
210 $GLOBALS['TYPO3_DB']->sql_free_result($res);
211 return $output;
212 }
213
214 /**
215 * Returns a pagerow for the page with alias $alias
216 *
217 * @param string The alias to look up the page uid for.
218 * @return integer Returns page uid (integer) if found, otherwise 0 (zero)
219 * @see tslib_fe::checkAndSetAlias(), tslib_cObj::typoLink()
220 */
221 function getPageIdFromAlias($alias) {
222 $alias = strtolower($alias);
223 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'alias='.$GLOBALS['TYPO3_DB']->fullQuoteStr($alias, 'pages').' AND pid>=0 AND pages.deleted=0'); // "AND pid>=0" is because of versioning...
224 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
225 return $row['uid'];
226 }
227 return 0;
228 }
229
230 /**
231 * Returns the relevant page overlay record fields
232 *
233 * @param mixed If $pageInput is an integer, it's the pid of the pageOverlay record and thus the page overlay record is returned. If $pageInput is an array, it's a page-record and based on this page record the language record is found and OVERLAYED before the page record is returned.
234 * @param integer Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
235 * @return array Page row which is overlayed with language_overlay record (or the overlay record alone)
236 */
237 function getPageOverlay($pageInput,$lUid=-1) {
238
239 // Initialize:
240 if ($lUid<0) $lUid = $this->sys_language_uid;
241 unset($row);
242
243 // If language UID is different from zero, do overlay:
244 if ($lUid) {
245 $fieldArr = explode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['pageOverlayFields']);
246 if (is_array($pageInput)) {
247 $page_id = $pageInput['uid']; // Was the whole record
248 $fieldArr = array_intersect($fieldArr,array_keys($pageInput)); // Make sure that only fields which exist in the incoming record are overlaid!
249 } else {
250 $page_id = $pageInput; // Was the id
251 }
252
253 if (count($fieldArr)) {
254 /*
255 NOTE to enabledFields('pages_language_overlay'):
256 Currently the showHiddenRecords of TSFE set will allow pages_language_overlay records to be selected as they are child-records of a page.
257 However you may argue that the showHiddenField flag should determine this. But that's not how it's done right now.
258 */
259
260 // Selecting overlay record:
261 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
262 implode(',',$fieldArr),
263 'pages_language_overlay',
264 'pid='.intval($page_id).'
265 AND sys_language_uid='.intval($lUid).
266 $this->enableFields('pages_language_overlay'),
267 '',
268 '',
269 '1'
270 );
271 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
272 if (is_array($row)) {
273 $row['_PAGES_OVERLAY'] = TRUE;
274 $this->versionOL('pages_language_overlay',$row);
275
276 // Unset vital fields that are NOT allowed to be overlaid:
277 unset($row['uid']);
278 unset($row['pid']);
279 }
280 }
281 }
282
283 // Create output:
284 if (is_array($pageInput)) {
285 return is_array($row) ? array_merge($pageInput,$row) : $pageInput; // If the input was an array, simply overlay the newfound array and return...
286 } else {
287 return is_array($row) ? $row : array(); // always an array in return
288 }
289 }
290
291 /**
292 * Creates language-overlay for records in general (where translation is found in records from the same table)
293 *
294 * @param string Table name
295 * @param array Record to overlay. Must containt uid, pid and $table]['ctrl']['languageField']
296 * @param integer Pointer to the sys_language uid for content on the site.
297 * @param string Overlay mode. If "hideNonTranslated" then records without translation will not be returned un-translated but unset (and return value is false)
298 * @return mixed Returns the input record, possibly overlaid with a translation. But if $OLmode is "hideNonTranslated" then it will return false if no translation is found.
299 */
300 function getRecordOverlay($table,$row,$sys_language_content,$OLmode='') {
301 global $TCA;
302
303 if ($row['uid']>0 && $row['pid']>0) {
304 if ($TCA[$table] && $TCA[$table]['ctrl']['languageField'] && $TCA[$table]['ctrl']['transOrigPointerField']) {
305 if (!$TCA[$table]['ctrl']['transOrigPointerTable']) { // Will not be able to work with other tables (Just didn't implement it yet; Requires a scan over all tables [ctrl] part for first FIND the table that carries localization information for this table (which could even be more than a single table) and then use that. Could be implemented, but obviously takes a little more....)
306
307 // Will try to overlay a record only if the sys_language_content value is larger that zero.
308 if ($sys_language_content>0) {
309
310 // Must be default language or [All], otherwise no overlaying:
311 if ($row[$TCA[$table]['ctrl']['languageField']]<=0) {
312
313 // Select overlay record:
314 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
315 '*',
316 $table,
317 'pid='.intval($row['pid']).
318 ' AND '.$TCA[$table]['ctrl']['languageField'].'='.intval($sys_language_content).
319 ' AND '.$TCA[$table]['ctrl']['transOrigPointerField'].'='.intval($row['uid']).
320 $this->enableFields($table),
321 '',
322 '',
323 '1'
324 );
325 $olrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
326 $this->versionOL($table,$olrow);
327 #debug($row);
328 #debug($olrow);
329 // Merge record content by traversing all fields:
330 if (is_array($olrow)) {
331 foreach($row as $fN => $fV) {
332 if ($fN!='uid' && $fN!='pid' && isset($olrow[$fN])) {
333
334 if ($GLOBALS['TSFE']->TCAcachedExtras[$table]['l10n_mode'][$fN]!='exclude'
335 && ($GLOBALS['TSFE']->TCAcachedExtras[$table]['l10n_mode'][$fN]!='mergeIfNotBlank' || strcmp(trim($olrow[$fN]),''))) {
336 $row[$fN] = $olrow[$fN];
337 }
338 }
339 }
340 } elseif ($OLmode==='hideNonTranslated' && $row[$TCA[$table]['ctrl']['languageField']]==0) { // Unset, if non-translated records should be hidden. ONLY done if the source record really is default language and not [All] in which case it is allowed.
341 unset($row);
342 }
343
344 // Otherwise, check if sys_language_content is different from the value of the record - that means a japanese site might try to display french content.
345 } elseif ($sys_language_content!=$row[$TCA[$table]['ctrl']['languageField']]) {
346 unset($row);
347 }
348 } else {
349 // When default language is displayed, we never want to return a record carrying another language!:
350 if ($row[$TCA[$table]['ctrl']['languageField']]>0) {
351 unset($row);
352 }
353 }
354 }
355 }
356 }
357
358 return $row;
359 }
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378 /*******************************************
379 *
380 * Page related: Menu, Domain record, Root line
381 *
382 ******************************************/
383
384 /**
385 * Returns an array with pagerows for subpages with pid=$uid (which is pid here!). This is used for menus.
386 * If there are mount points in overlay mode the _MP_PARAM field is set to the corret MPvar.
387 * If the $uid being input does in itself require MPvars to define a correct rootline these must be handled externally to this function.
388 *
389 * @param integer The page id for which to fetch subpages (PID)
390 * @param string List of fields to select. Default is "*" = all
391 * @param string The field to sort by. Default is "sorting"
392 * @param string Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
393 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlayed localized fields, if any)
394 * @see tslib_fe::getPageShortcut(), tslib_menu::makeMenu(), tx_wizardcrpages_webfunc_2, tx_wizardsortpages_webfunc_2
395 */
396 function getMenu($uid,$fields='*',$sortField='sorting',$addWhere='') {
397 $output = Array();
398 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'pages', 'pid='.intval($uid).$this->where_hid_del.' '.$addWhere, '', $sortField);
399 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
400 #?? $this->versionOL('pages',$row);
401
402 // Keep mount point:
403 $origUid = $row['uid'];
404 $mount_info = $this->getMountPointInfo($origUid, $row); // $row MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
405 if (is_array($mount_info) && $mount_info['overlay']) { // There is a valid mount point.
406 $mp_row = $this->getPage($mount_info['mount_pid']); // Using "getPage" is OK since we need the check for enableFields AND for type 2 of mount pids we DO require a doktype < 200!
407 if (count($mp_row)) {
408 $row = $mp_row;
409 $row['_MP_PARAM'] = $mount_info['MPvar'];
410 } else unset($row); // If the mount point could not be fetched with respect to enableFields, unset the row so it does not become a part of the menu!
411 }
412
413 // Add to output array after overlaying language:
414 if (is_array($row)) {
415 $output[$origUid] = $this->getPageOverlay($row);
416 }
417 }
418 return $output;
419 }
420
421 /**
422 * Will find the page carrying the domain record matching the input domain.
423 * Might exit after sending a redirect-header IF a found domain record instructs to do so.
424 *
425 * @param string Domain name to search for. Eg. "www.typo3.com". Typical the HTTP_HOST value.
426 * @param string Path for the current script in domain. Eg. "/somedir/subdir". Typ. supplied by t3lib_div::getIndpEnv('SCRIPT_NAME')
427 * @param string Request URI: Used to get parameters from if they should be appended. Typ. supplied by t3lib_div::getIndpEnv('REQUEST_URI')
428 * @return mixed If found, returns integer with page UID where found. Otherwise blank. Might exit if location-header is sent, see description.
429 * @see tslib_fe::findDomainRecord()
430 */
431 function getDomainStartPage($domain, $path='',$request_uri='') {
432 $domain = explode(':',$domain);
433 $domain = strtolower(ereg_replace('\.$','',$domain[0]));
434 // Removing extra trailing slashes
435 $path = trim(ereg_replace('\/[^\/]*$','',$path));
436 // Appending to domain string
437 $domain.= $path;
438 $domain = ereg_replace('\/*$','',$domain);
439
440 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
441 'pages.uid,sys_domain.redirectTo,sys_domain.prepend_params',
442 'pages,sys_domain',
443 'pages.uid=sys_domain.pid
444 AND sys_domain.hidden=0
445 AND (sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain').' OR sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain.'/', 'sys_domain').') '.
446 $this->where_hid_del,
447 '',
448 '',
449 1
450 );
451 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
452 if ($row['redirectTo']) {
453 $rURL = $row['redirectTo'];
454 if ($row['prepend_params']) {
455 $rURL = ereg_replace('\/$','',$rURL);
456 $prependStr = ereg_replace('^\/','',substr($request_uri,strlen($path)));
457 $rURL.='/'.$prependStr;
458 }
459 Header('Location: '.t3lib_div::locationHeaderUrl($rURL));
460 exit;
461 } else {
462 return $row['uid'];
463 }
464 }
465 }
466
467 /**
468 * Returns array with fields of the pages from here ($uid) and back to the root
469 * NOTICE: This function only takes deleted pages into account! So hidden, starttime and endtime restricted pages are included no matter what.
470 * Further: If any "recycler" page is found (doktype=255) then it will also block for the rootline)
471 * If you want more fields in the rootline records than default such can be added by listing them in $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']
472 *
473 * @param integer The page uid for which to seek back to the page tree root.
474 * @param string Commalist of MountPoint parameters, eg. "1-2,3-4" etc. Normally this value comes from the GET var, MP
475 * @param boolean If set, some errors related to Mount Points in root line are ignored.
476 * @return array Array with page records from the root line as values. The array is ordered with the outer records first and root record in the bottom. The keys are numeric but in reverse order. So if you traverse/sort the array by the numeric keys order you will get the order from root and out. If an error is found (like eternal looping or invalid mountpoint) it will return an empty array.
477 * @see tslib_fe::getPageAndRootline()
478 */
479 function getRootLine($uid, $MP='', $ignoreMPerrors=FALSE) {
480
481 // Initialize:
482 $selFields = t3lib_div::uniqueList('pid,uid,t3ver_oid,title,alias,nav_title,media,layout,hidden,starttime,endtime,fe_group,extendToSubpages,doktype,TSconfig,storage_pid,is_siteroot,mount_pid,mount_pid_ol,'.$GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']);
483 $this->error_getRootLine = '';
484 $this->error_getRootLine_failPid = 0;
485
486 // Splitting the $MP parameters if present
487 $MPA = array();
488 if ($MP) {
489 $MPA = explode(',',$MP);
490 reset($MPA);
491 while(list($MPAk) = each($MPA)) {
492 $MPA[$MPAk] = explode('-', $MPA[$MPAk]);
493 }
494 }
495
496 $loopCheck = 0;
497 $theRowArray = Array();
498 $uid = intval($uid);
499
500 while ($uid!=0 && $loopCheck<20) { // Max 20 levels in the page tree.
501 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($selFields, 'pages', 'uid='.intval($uid).' AND pages.deleted=0 AND pages.doktype!=255');
502 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
503 $this->fixVersioningPid('pages',$row);
504 #?? $this->versionOL('pages',$row);
505
506 // Mount Point page types are allowed ONLY a) if they are the outermost record in rootline and b) if the overlay flag is not set:
507 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] && $row['doktype']==7 && !$ignoreMPerrors) {
508 $mount_info = $this->getMountPointInfo($row['uid'], $row);
509 if ($loopCheck>0 || $mount_info['overlay']) {
510 $this->error_getRootLine = 'Illegal Mount Point found in rootline';
511 return array();
512 }
513 }
514
515 $uid = $row['pid']; // Next uid
516
517 if (count($MPA) && $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
518 $curMP = end($MPA);
519 if (!strcmp($row['uid'],$curMP[0])) {
520
521 array_pop($MPA);
522 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($selFields, 'pages', 'uid='.intval($curMP[1]).' AND pages.deleted=0 AND pages.doktype!=255');
523 $mp_row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
524
525 if (is_array($mp_row)) {
526 $this->fixVersioningPid('pages',$mp_row);
527 #?? $this->versionOL('pages',$mp_row);
528 $mount_info = $this->getMountPointInfo($mp_row['uid'], $mp_row);
529 if (is_array($mount_info) && $mount_info['mount_pid']==$curMP[0]) {
530 $uid = $mp_row['pid']; // Setting next uid
531
532 if ($mount_info['overlay']) { // Symlink style: Keep mount point (current row).
533 $row['_MOUNT_OL'] = TRUE; // Set overlay mode:
534 $row['_MOUNT_PAGE'] = array(
535 'uid' => $mp_row['uid'],
536 'pid' => $mp_row['pid'],
537 'title' => $mp_row['title'],
538 );
539 } else { // Normal operation: Insert the mount page row in rootline instead mount point.
540 if ($loopCheck>0) {
541 $row = $mp_row;
542 } else {
543 $this->error_getRootLine = 'Current Page Id is a mounted page of the overlay type and cannot be accessed directly!';
544 return array(); // Matching the page id (first run, $loopCheck = 0) with the MPvar is ONLY allowed if the mount point is the "overlay" type (otherwise it could be forged!)
545 }
546 }
547
548 $row['_MOUNTED_FROM'] = $curMP[0];
549 $row['_MP_PARAM'] = $mount_info['MPvar'];
550 } else {
551 $this->error_getRootLine = 'MP var was corrupted';
552 return array(); // The MP variables did NOT connect proper mount points:
553 }
554 } else {
555 $this->error_getRootLine = 'No moint point record found according to PID in MP var';
556 return array(); // The second PID in MP var was NOT a valid page.
557 }
558 }
559 }
560 // Add row to rootline with language overlaid:
561 $theRowArray[] = $this->getPageOverlay($row);
562 } else {
563 $this->error_getRootLine = 'Broken rootline';
564 $this->error_getRootLine_failPid = $uid;
565 return array(); // broken rootline.
566 }
567
568 $loopCheck++;
569 }
570
571 // If the MPA array is NOT empty, we have to return an error; All MP elements were not resolved!
572 if (count($MPA)) {
573 $this->error_getRootLine = 'MP value remain!';
574 return array();
575 }
576
577 // Create output array (with reversed order of numeric keys):
578 $output = Array();
579 $c = count($theRowArray);
580 foreach($theRowArray as $key => $val) {
581 $c--;
582 $output[$c] = $val;
583 }
584
585 return $output;
586 }
587
588 /**
589 * Creates a "path" string for the input root line array titles.
590 * Used for writing statistics.
591 *
592 * @param array A rootline array!
593 * @param integer The max length of each title from the rootline.
594 * @return string The path in the form "/page title/This is another pageti.../Another page"
595 * @see tslib_fe::getConfigArray()
596 */
597 function getPathFromRootline($rl,$len=20) {
598 if (is_array($rl)) {
599 $c=count($rl);
600 $path = '';
601 for ($a=0;$a<$c;$a++) {
602 if ($rl[$a]['uid']) {
603 $path.='/'.t3lib_div::fixed_lgd_cs(strip_tags($rl[$a]['title']),$len);
604 }
605 }
606 return $path;
607 }
608 }
609
610 /**
611 * Returns the URL type for the input page row IF the doktype is 3 and not disabled.
612 *
613 * @param array The page row to return URL type for
614 * @param boolean A flag to simply disable any output from here.
615 * @return string The URL type from $this->urltypes array. False if not found or disabled.
616 * @see tslib_fe::checkJumpUrl()
617 */
618 function getExtURL($pagerow,$disable=0) {
619 if ($pagerow['doktype']==3 && !$disable) {
620 $redirectTo = $this->urltypes[$pagerow['urltype']].$pagerow['url'];
621
622 // If relative path, prefix Site URL:
623 $uI = parse_url($redirectTo);
624 if (!$uI['scheme'] && substr($redirectTo,0,1)!='/') { // relative path assumed now...
625 $redirectTo = t3lib_div::getIndpEnv('TYPO3_SITE_URL').$redirectTo;
626 }
627 return $redirectTo;
628 }
629 }
630
631 /**
632 * Returns MountPoint id for page
633 * Does a recursive search if the mounted page should be a mount page itself. It has a run-away break so it can't go into infinite loops.
634 *
635 * @param integer Page id for which to look for a mount pid. Will be returned only if mount pages are enabled, the correct doktype (7) is set for page and there IS a mount_pid (which has a valid record that is not deleted...)
636 * @param array Optional page record for the page id. If not supplied it will be looked up by the system. Must contain at least uid,pid,doktype,mount_pid,mount_pid_ol
637 * @param array Array accumulating formerly tested page ids for mount points. Used for recursivity brake.
638 * @param integer The first page id.
639 * @return mixed Returns FALSE if no mount point was found, "-1" if there should have been one, but no connection to it, otherwise an array with information about mount pid and modes.
640 * @see tslib_menu
641 */
642 function getMountPointInfo($pageId, $pageRec=FALSE, $prevMountPids=array(), $firstPageUid=0) {
643 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
644
645 // Get pageRec if not supplied:
646 if (!is_array($pageRec)) {
647 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol', 'pages', 'uid='.intval($pageId).' AND pages.deleted=0 AND pages.doktype!=255');
648 $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
649 #?? $this->versionOL('pages',$pageRec);
650 }
651
652 // Set first Page uid:
653 if (!$firstPageUid) $firstPageUid = $pageRec['uid'];
654
655 // Look for mount pid value plus other required circumstances:
656 $mount_pid = intval($pageRec['mount_pid']);
657 if (is_array($pageRec) && $pageRec['doktype']==7 && $mount_pid>0 && !in_array($mount_pid, $prevMountPids)) {
658
659 // Get the mount point record (to verify its general existence):
660 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol', 'pages', 'uid='.$mount_pid.' AND pages.deleted=0 AND pages.doktype!=255');
661 $mount_rec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
662 if (is_array($mount_rec)) {
663 #?? $this->versionOL('pages',$mount_rec);
664
665 // Look for recursive mount point:
666 $prevMountPids[] = $mount_pid;
667 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mount_rec, $prevMountPids, $firstPageUid);
668
669 // Return mount point information:
670 return $recursiveMountPid ?
671 $recursiveMountPid :
672 array(
673 'mount_pid' => $mount_pid,
674 'overlay' => $pageRec['mount_pid_ol'],
675 'MPvar' => $mount_pid.'-'.$firstPageUid,
676 'mount_point_rec' => $pageRec,
677 'mount_pid_rec' => $mount_rec,
678 );
679 } else {
680 return -1; // Means, there SHOULD have been a mount point, but there was none!
681 }
682 }
683 }
684
685 return FALSE;
686 }
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704 /*********************************
705 *
706 * Selecting records in general
707 *
708 **********************************/
709
710 /**
711 * Checks if a record exists and is accessible.
712 * The row is returned if everything's OK.
713 *
714 * @param string The table name to search
715 * @param integer The uid to look up in $table
716 * @param boolean If checkPage is set, it's also required that the page on which the record resides is accessible
717 * @return mixed Returns array (the record) if OK, otherwise blank/0 (zero)
718 */
719 function checkRecord($table,$uid,$checkPage=0) {
720 global $TCA;
721 $uid=intval($uid);
722 if (is_array($TCA[$table])) {
723 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($uid).$this->enableFields($table));
724 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
725 #?? $this->versionOL($table,$row);
726 $GLOBALS['TYPO3_DB']->sql_free_result($res);
727 if ($checkPage) {
728 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid='.intval($row['pid']).$this->enableFields('pages'));
729 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
730 return $row;
731 } else {
732 return 0;
733 }
734 } else {
735 return $row;
736 }
737 }
738 }
739 }
740
741 /**
742 * Returns record no matter what - except if record is deleted
743 *
744 * @param string The table name to search
745 * @param integer The uid to look up in $table
746 * @param string The fields to select, default is "*"
747 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
748 * @see getPage_noCheck()
749 */
750 function getRawRecord($table,$uid,$fields='*') {
751 global $TCA;
752 $uid = intval($uid);
753 if (is_array($TCA[$table]) || $table=='pages') { // Excluding pages here so we can ask the function BEFORE TCA gets initialized. Support for this is followed up in deleteClause()...
754 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid='.intval($uid).$this->deleteClause($table));
755 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
756 #?? $this->versionOL($table,$row);
757 return $row;
758 }
759 }
760 }
761
762 /**
763 * Selects records based on matching a field (ei. other than UID) with a value
764 *
765 * @param string The table name to search, eg. "pages" or "tt_content"
766 * @param string The fieldname to match, eg. "uid" or "alias"
767 * @param string The value that fieldname must match, eg. "123" or "frontpage"
768 * @param string Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
769 * @param string Optional GROUP BY field(s), if none, supply blank string.
770 * @param string Optional ORDER BY field(s), if none, supply blank string.
771 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
772 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
773 */
774 function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='') {
775 global $TCA;
776 if (is_array($TCA[$theTable])) {
777 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
778 '*',
779 $theTable,
780 $theField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable).
781 $this->deleteClause($theTable).' '.
782 $whereClause, // whereClauseMightContainGroupOrderBy
783 $groupBy,
784 $orderBy,
785 $limit
786 );
787 $rows = array();
788 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
789 #?? $this->versionOL($theTable,$row);
790 $rows[] = $row;
791 }
792 $GLOBALS['TYPO3_DB']->sql_free_result($res);
793 if (count($rows)) return $rows;
794 }
795 }
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810 /*********************************
811 *
812 * Caching and standard clauses
813 *
814 **********************************/
815
816 /**
817 * Returns string value stored for the hash string in the table "cache_hash"
818 * Can be used to retrieved a cached value
819 * Can be used from your frontend plugins if you like. Is also used to store the parsed TypoScript template structures. You can call it directly like t3lib_pageSelect::getHash()
820 *
821 * @param string The hash-string which was used to store the data value
822 * @param integer Allowed expiretime in seconds. Basically a record is selected only if it is not older than this value in seconds. If expTime is not set, the hashed value will never expire.
823 * @return string The "content" field of the "cache_hash" table row.
824 * @see tslib_TStemplate::start(), storeHash()
825 */
826 function getHash($hash,$expTime=0) {
827 //
828 $expTime = intval($expTime);
829 if ($expTime) {
830 $whereAdd = ' AND tstamp > '.(time()-$expTime);
831 }
832 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('content', 'cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash').$whereAdd);
833 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
834 $GLOBALS['TYPO3_DB']->sql_free_result($res);
835 return $row['content'];
836 }
837 }
838
839 /**
840 * Stores a string value in the cache_hash table identified by $hash.
841 * Can be used from your frontend plugins if you like. You can call it directly like t3lib_pageSelect::storeHash()
842 *
843 * @param string 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
844 * @param string The data string. If you want to store an array, then just serialize it first.
845 * @param string $ident is just a textual identification in order to inform about the content! May be 20 characters long.
846 * @return void
847 * @see tslib_TStemplate::start(), getHash()
848 */
849 function storeHash($hash,$data,$ident) {
850 $insertFields = array(
851 'hash' => $hash,
852 'content' => $data,
853 'ident' => $ident,
854 'tstamp' => time()
855 );
856 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash'));
857 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_hash', $insertFields);
858 }
859
860 /**
861 * Returns the "AND NOT deleted" clause for the tablename given IF $TCA configuration points to such a field.
862 *
863 * @param string Tablename
864 * @return string
865 * @see enableFields()
866 */
867 function deleteClause($table) {
868 global $TCA;
869 if (!strcmp($table,'pages')) { // Hardcode for pages...:
870 return ' AND deleted=0';
871 } else {
872 return $TCA[$table]['ctrl']['delete'] ? ' AND '.$TCA[$table]['ctrl']['delete'].'=0' : '';
873 }
874 }
875
876 /**
877 * Returns a part of a WHERE clause which will filter out records with start/end times or hidden/fe_groups fields set to values that should de-select them according to the current time, preview settings or user login. Definitely a frontend function.
878 * Is using the $TCA arrays "ctrl" part where the key "enablefields" determines for each table which of these features applies to that table.
879 *
880 * @param string Table name found in the $TCA array
881 * @param integer If $show_hidden is set (0/1), any hidden-fields in records are ignored. NOTICE: If you call this function, consider what to do with the show_hidden parameter. Maybe it should be set? See tslib_cObj->enableFields where it's implemented correctly.
882 * @param array Array you can pass where keys can be "disabled", "starttime", "endtime", "fe_group" (keys from "enablefields" in TCA) and if set they will make sure that part of the clause is not added. Thus disables the specific part of the clause. For previewing etc.
883 * @return string The clause starting like " AND ...=... AND ...=..."
884 * @see tslib_cObj::enableFields(), deleteClause()
885 */
886 function enableFields($table,$show_hidden=-1,$ignore_array=array()) {
887 if ($show_hidden==-1 && is_object($GLOBALS['TSFE'])) { // If show_hidden was not set from outside and if TSFE is an object, set it based on showHiddenPage and showHiddenRecords from TSFE
888 $show_hidden = $table=='pages' ? $GLOBALS['TSFE']->showHiddenPage : $GLOBALS['TSFE']->showHiddenRecords;
889 }
890 if ($show_hidden==-1) $show_hidden=0; // If show_hidden was not changed during the previous evaluation, do it here.
891
892 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
893 $query='';
894 if (is_array($ctrl)) {
895 if ($ctrl['delete']) {
896 $query.=' AND '.$table.'.'.$ctrl['delete'].'=0';
897 }
898 if (is_array($ctrl['enablecolumns'])) {
899 if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
900 $field = $table.'.'.$ctrl['enablecolumns']['disabled'];
901 $query.=' AND '.$field.'=0';
902 }
903 if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
904 $field = $table.'.'.$ctrl['enablecolumns']['starttime'];
905 $query.=' AND ('.$field.'<='.$GLOBALS['SIM_EXEC_TIME'].')';
906 }
907 if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
908 $field = $table.'.'.$ctrl['enablecolumns']['endtime'];
909 $query.=' AND ('.$field.'=0 OR '.$field.'>'.$GLOBALS['SIM_EXEC_TIME'].')';
910 }
911 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
912 $field = $table.'.'.$ctrl['enablecolumns']['fe_group'];
913 $gr_list = $GLOBALS['TSFE']->gr_list;
914 if (!strcmp($gr_list,'')) $gr_list=0;
915 $query.=' AND '.$field.' IN ('.$gr_list.')';
916 }
917 }
918 } else {
919 die ('NO entry in the $TCA-array for the table "'.$table.'". This means that the function enableFields() is called with an invalid table name as argument.');
920 }
921
922 return $query;
923 }
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939 /*********************************
940 *
941 * Versioning Preview
942 *
943 **********************************/
944
945 /**
946 * Find page-tree PID for versionized record
947 * Will look if the "pid" value of the input record is -1 and if the table supports versioning - if so, it will translate the -1 PID into the PID of the original record
948 *
949 * @param string Table name
950 * @param array Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid" is nice and will save you a DB query.
951 * @return void (Passed by ref).
952 * @see t3lib_BEfunc::fixVersioningPid()
953 */
954 function fixVersioningPid($table,&$rr) {
955 global $TCA;
956 # SWAP uid as well???
957 if ($this->versioningPreview && $rr['pid']==-1 && ($table=='pages' || $TCA[$table]['ctrl']['versioning'])) { // Have to hardcode it for "pages" table since TCA is not loaded at this moment!
958 if ($rr['t3ver_oid']>0) { // If "t3ver_oid" is already a field, just set this:
959 $oid = $rr['t3ver_oid'];
960 } else { // Otherwise we have to expect "uid" to be in the record and look up based on this:
961 $newPidRec = $this->getRawRecord($table,$rr['uid'],'t3ver_oid');
962 if (is_array($newPidRec)) {
963 $oid = $newPidRec['t3ver_oid'];
964 }
965 }
966
967 // If ID of current online version is found, look up the PID value of that:
968 if ($oid) {
969 $oidRec = $this->getRawRecord($table,$oid,'pid');
970 if (is_array($oidRec)) {
971 $rr['_ORIG_pid'] = $rr['pid'];
972 $rr['pid'] = $oidRec['pid'];
973 }
974 }
975 }
976 }
977
978 /**
979 * Versioning Preview Overlay
980 * ONLY active when backend user is previewing records. MUST NEVER affect a site served which is not previewed by backend users!!!
981 *
982 * @param string Table name
983 * @param array Record array passed by reference. As minimum, the "uid" field must exist!
984 * @return void (Passed by ref).
985 */
986 function versionOL($table,&$row) {
987 global $TCA;
988
989 if ($this->versioningPreview && $TCA[$table]['ctrl']['versioning']) {
990 #debug($row,$table);
991 #debug($this->versionPreviewMap);
992 if (is_array($row) && isset($this->versionPreviewMap[$table.':'.$row['uid']])) {
993
994 // ID to look for:
995 $lookFor = $this->versionPreviewMap[$table.':'.$row['uid']];
996
997 // Select the alternative version:
998 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($lookFor).$this->deleteClause($table));
999 if ($altrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1000 if ($altrow['pid']==-1 && $altrow['t3ver_oid']==$row['uid']) {
1001 unset($altrow['pid']); // Unsetting PID since this is basically the same as what fixVersioningPid would do to the record...
1002 unset($altrow['uid']); // Unsetting UID because the overlaid record should KEEP its own UID.
1003 # unset(...); // more fields being unset???
1004 $row = t3lib_div::array_merge_recursive_overrule($row,$altrow,TRUE);
1005 #debug($row,'Found:');
1006 }
1007 }
1008 }
1009 }
1010 }
1011 }
1012
1013
1014
1015 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_page.php']) {
1016 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_page.php']);
1017 }
1018 ?>