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