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