bug #6601: fixed mount point issues with the local page tree cache
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_page.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2008 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 * 109: class t3lib_pageSelect
42 * 134: function init($show_hidden)
43 *
44 * SECTION: Selecting page records
45 * 184: function getPage($uid, $disableGroupAccessCheck=FALSE)
46 * 200: function getPage_noCheck($uid)
47 * 216: function getFirstWebPage($uid)
48 * 234: function getPageIdFromAlias($alias)
49 * 250: function getPageOverlay($pageInput,$lUid=-1)
50 * 314: function getRecordOverlay($table,$row,$sys_language_content,$OLmode='')
51 *
52 * SECTION: Page related: Menu, Domain record, Root line
53 * 413: function getMenu($uid,$fields='*',$sortField='sorting',$addWhere='',$checkShortcuts=1)
54 * 471: function getDomainStartPage($domain, $path='',$request_uri='')
55 * 519: function getRootLine($uid, $MP='', $ignoreMPerrors=FALSE)
56 * 640: function getPathFromRootline($rl,$len=20)
57 * 661: function getExtURL($pagerow,$disable=0)
58 * 685: function getMountPointInfo($pageId, $pageRec=FALSE, $prevMountPids=array(), $firstPageUid=0)
59 *
60 * SECTION: Selecting records in general
61 * 762: function checkRecord($table,$uid,$checkPage=0)
62 * 797: function getRawRecord($table,$uid,$fields='*',$noWSOL=FALSE)
63 * 823: function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='')
64 *
65 * SECTION: Caching and standard clauses
66 * 875: function getHash($hash,$expTime=0)
67 * 898: function storeHash($hash,$data,$ident)
68 * 916: function deleteClause($table)
69 * 936: function enableFields($table,$show_hidden=-1,$ignore_array=array(),$noVersionPreview=FALSE)
70 * 1008: function getMultipleGroupsWhereClause($field, $table)
71 *
72 * SECTION: Versioning Preview
73 * 1055: function fixVersioningPid($table,&$rr)
74 * 1096: function versionOL($table,&$row)
75 * 1151: function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields='*')
76 *
77 * TOTAL FUNCTIONS: 24
78 * (This index is automatically created/updated by the extension "extdeveval")
79 *
80 */
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99 /**
100 * Page functions, a lot of sql/pages-related functions
101 * Mainly used in the frontend but also in some cases in the backend.
102 * It's important to set the right $where_hid_del in the object so that the functions operate properly
103 *
104 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
105 * @package TYPO3
106 * @subpackage t3lib
107 * @see tslib_fe::fetch_the_id()
108 */
109 class t3lib_pageSelect {
110 var $urltypes = Array('','http://','ftp://','mailto:','https://');
111 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
112 var $where_groupAccess = ''; // Clause for fe_group access
113 var $sys_language_uid = 0;
114
115 // Versioning preview related:
116 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!!!
117 var $versioningWorkspaceId = 0; // Workspace ID for preview
118 var $workspaceCache = array();
119
120
121 // Internal, dynamic:
122 var $error_getRootLine = ''; // Error string set by getRootLine()
123 var $error_getRootLine_failPid = 0; // Error uid set by getRootLine()
124
125 // Internal caching
126 protected $cache_getRootLine = array();
127 protected $cache_getPage = array();
128 protected $cache_getMountPointInfo = array();
129
130 /**
131 * init() MUST be run directly after creating a new template-object
132 * This sets the internal variable $this->where_hid_del to the correct where clause for page records taking deleted/hidden/starttime/endtime/t3ver_state into account
133 *
134 * @param boolean If $show_hidden is true, the hidden-field is ignored!! Normally this should be false. Is used for previewing.
135 * @return void
136 * @see tslib_fe::fetch_the_id(), tx_tstemplateanalyzer::initialize_editor()
137 */
138 function init($show_hidden) {
139 $this->where_groupAccess = '';
140 $this->where_hid_del = ' AND pages.deleted=0 ';
141 if (!$show_hidden) {
142 $this->where_hid_del.= 'AND pages.hidden=0 ';
143 }
144 $this->where_hid_del.= 'AND (pages.starttime<='.$GLOBALS['SIM_ACCESS_TIME'].') AND (pages.endtime=0 OR pages.endtime>'.$GLOBALS['SIM_ACCESS_TIME'].') ';
145
146 // Filter out new/deleted place-holder pages in case we are NOT in a versioning preview (that means we are online!)
147 if (!$this->versioningPreview) {
148 $this->where_hid_del.= ' AND NOT(pages.t3ver_state>0)';
149 } else {
150 // For version previewing, make sure that enable-fields are not de-selecting hidden pages - we need versionOL() to unset them only if the overlay record instructs us to.
151 $this->versioningPreview_where_hid_del = $this->where_hid_del; // Copy where_hid_del to other variable (used in relation to versionOL())
152 $this->where_hid_del = ' AND pages.deleted=0 '; // Clear where_hid_del
153 }
154 }
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172 /*******************************************
173 *
174 * Selecting page records
175 *
176 ******************************************/
177
178 /**
179 * Returns the $row for the page with uid = $uid (observing ->where_hid_del)
180 * Any pages_language_overlay will be applied before the result is returned.
181 * If no page is found an empty array is returned.
182 *
183 * @param integer The page id to look up.
184 * @param boolean If set, the check for group access is disabled. VERY rarely used
185 * @return array The page row with overlayed localized fields. Empty it no page.
186 * @see getPage_noCheck()
187 */
188 function getPage($uid, $disableGroupAccessCheck=FALSE) {
189 $accessCheck = $disableGroupAccessCheck ? '' : $this->where_groupAccess;
190 $cacheKey = md5($accessCheck . '-' . $this->where_hid_del . '-' . $this->sys_language_uid);
191
192 if (is_array($this->cache_getPage[$uid][$cacheKey])) {
193 return $this->cache_getPage[$uid][$cacheKey];
194 }
195 $result = array();
196 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($uid).$this->where_hid_del.$accessCheck);
197 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
198 $GLOBALS['TYPO3_DB']->sql_free_result($res);
199 if ($row) {
200 $this->versionOL('pages',$row);
201 if (is_array($row)) {
202 $result = $this->getPageOverlay($row);
203 }
204 }
205 $this->cache_getPage[$uid][$cacheKey] = $result;
206 return $result;
207 }
208
209 /**
210 * Return the $row for the page with uid = $uid WITHOUT checking for ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
211 *
212 * @param integer The page id to look up
213 * @return array The page row with overlayed localized fields. Empty it no page.
214 * @see getPage()
215 */
216 function getPage_noCheck($uid) {
217 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($uid).$this->deleteClause('pages'));
218 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
219 $GLOBALS['TYPO3_DB']->sql_free_result($res);
220 if ($row) {
221 $this->versionOL('pages',$row);
222 if (is_array($row)) {
223 return $this->getPageOverlay($row);
224 }
225 }
226 return Array();
227 }
228
229 /**
230 * Returns the $row of the first web-page in the tree (for the default menu...)
231 *
232 * @param integer The page id for which to fetch first subpages (PID)
233 * @return mixed If found: The page record (with overlayed localized fields, if any). If NOT found: blank value (not array!)
234 * @see tslib_fe::fetch_the_id()
235 */
236 function getFirstWebPage($uid) {
237 $output = '';
238 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'pid='.intval($uid).$this->where_hid_del.$this->where_groupAccess, '', 'sorting', '1');
239 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
240 $GLOBALS['TYPO3_DB']->sql_free_result($res);
241 if ($row) {
242 $this->versionOL('pages',$row);
243 if (is_array($row)) {
244 $output = $this->getPageOverlay($row);
245 }
246 }
247 return $output;
248 }
249
250 /**
251 * Returns a pagerow for the page with alias $alias
252 *
253 * @param string The alias to look up the page uid for.
254 * @return integer Returns page uid (integer) if found, otherwise 0 (zero)
255 * @see tslib_fe::checkAndSetAlias(), tslib_cObj::typoLink()
256 */
257 function getPageIdFromAlias($alias) {
258 $alias = strtolower($alias);
259 $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" because of versioning (means that aliases sent MUST be online!)
260 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
261 $GLOBALS['TYPO3_DB']->sql_free_result($res);
262 if ($row) {
263 return $row['uid'];
264 }
265 return 0;
266 }
267
268 /**
269 * Returns the relevant page overlay record fields
270 *
271 * @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.
272 * @param integer Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
273 * @return array Page row which is overlayed with language_overlay record (or the overlay record alone)
274 */
275 function getPageOverlay($pageInput,$lUid=-1) {
276
277 // Initialize:
278 if ($lUid<0) $lUid = $this->sys_language_uid;
279 $row = NULL;
280
281 // If language UID is different from zero, do overlay:
282 if ($lUid) {
283 $fieldArr = explode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['pageOverlayFields']);
284 if (is_array($pageInput)) {
285 $page_id = $pageInput['uid']; // Was the whole record
286 $fieldArr = array_intersect($fieldArr,array_keys($pageInput)); // Make sure that only fields which exist in the incoming record are overlaid!
287 } else {
288 $page_id = $pageInput; // Was the id
289 }
290
291 if (count($fieldArr)) {
292 /*
293 NOTE to enabledFields('pages_language_overlay'):
294 Currently the showHiddenRecords of TSFE set will allow pages_language_overlay records to be selected as they are child-records of a page.
295 However you may argue that the showHiddenField flag should determine this. But that's not how it's done right now.
296 */
297
298 // Selecting overlay record:
299 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
300 implode(',',$fieldArr),
301 'pages_language_overlay',
302 'pid='.intval($page_id).'
303 AND sys_language_uid='.intval($lUid).
304 $this->enableFields('pages_language_overlay'),
305 '',
306 '',
307 '1'
308 );
309 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
310 $GLOBALS['TYPO3_DB']->sql_free_result($res);
311 $this->versionOL('pages_language_overlay',$row);
312
313 if (is_array($row)) {
314 $row['_PAGES_OVERLAY'] = TRUE;
315
316 // Unset vital fields that are NOT allowed to be overlaid:
317 unset($row['uid']);
318 unset($row['pid']);
319 }
320 }
321 }
322
323 // Create output:
324 if (is_array($pageInput)) {
325 return is_array($row) ? array_merge($pageInput,$row) : $pageInput; // If the input was an array, simply overlay the newfound array and return...
326 } else {
327 return is_array($row) ? $row : array(); // always an array in return
328 }
329 }
330
331 /**
332 * Creates language-overlay for records in general (where translation is found in records from the same table)
333 *
334 * @param string Table name
335 * @param array Record to overlay. Must containt uid, pid and $table]['ctrl']['languageField']
336 * @param integer Pointer to the sys_language uid for content on the site.
337 * @param string Overlay mode. If "hideNonTranslated" then records without translation will not be returned un-translated but unset (and return value is false)
338 * @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.
339 */
340 function getRecordOverlay($table,$row,$sys_language_content,$OLmode='') {
341 global $TCA;
342
343 if ($row['uid']>0 && $row['pid']>0) {
344 if ($TCA[$table] && $TCA[$table]['ctrl']['languageField'] && $TCA[$table]['ctrl']['transOrigPointerField']) {
345 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....)
346
347 // Will try to overlay a record only if the sys_language_content value is larger than zero.
348 if ($sys_language_content>0) {
349
350 // Must be default language or [All], otherwise no overlaying:
351 if ($row[$TCA[$table]['ctrl']['languageField']]<=0) {
352
353 // Select overlay record:
354 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
355 '*',
356 $table,
357 'pid='.intval($row['pid']).
358 ' AND '.$TCA[$table]['ctrl']['languageField'].'='.intval($sys_language_content).
359 ' AND '.$TCA[$table]['ctrl']['transOrigPointerField'].'='.intval($row['uid']).
360 $this->enableFields($table),
361 '',
362 '',
363 '1'
364 );
365 $olrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
366 $GLOBALS['TYPO3_DB']->sql_free_result($res);
367 $this->versionOL($table,$olrow);
368
369 // Merge record content by traversing all fields:
370 if (is_array($olrow)) {
371 foreach($row as $fN => $fV) {
372 if ($fN!='uid' && $fN!='pid' && isset($olrow[$fN])) {
373
374 if ($GLOBALS['TSFE']->TCAcachedExtras[$table]['l10n_mode'][$fN]!='exclude'
375 && ($GLOBALS['TSFE']->TCAcachedExtras[$table]['l10n_mode'][$fN]!='mergeIfNotBlank' || strcmp(trim($olrow[$fN]),''))) {
376 $row[$fN] = $olrow[$fN];
377 }
378 } elseif ($fN=='uid') {
379 $row['_LOCALIZED_UID'] = $olrow['uid'];
380 }
381 }
382 } 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.
383 unset($row);
384 }
385
386 // 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.
387 } elseif ($sys_language_content!=$row[$TCA[$table]['ctrl']['languageField']]) {
388 unset($row);
389 }
390 } else {
391 // When default language is displayed, we never want to return a record carrying another language!:
392 if ($row[$TCA[$table]['ctrl']['languageField']]>0) {
393 unset($row);
394 }
395 }
396 }
397 }
398 }
399
400 return $row;
401 }
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420 /*******************************************
421 *
422 * Page related: Menu, Domain record, Root line
423 *
424 ******************************************/
425
426 /**
427 * Returns an array with pagerows for subpages with pid=$uid (which is pid here!). This is used for menus.
428 * If there are mount points in overlay mode the _MP_PARAM field is set to the corret MPvar.
429 * If the $uid being input does in itself require MPvars to define a correct rootline these must be handled externally to this function.
430 *
431 * @param integer The page id for which to fetch subpages (PID)
432 * @param string List of fields to select. Default is "*" = all
433 * @param string The field to sort by. Default is "sorting"
434 * @param string Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
435 * @param boolean check if shortcuts exist, checks by default
436 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlayed localized fields, if any)
437 * @see tslib_fe::getPageShortcut(), tslib_menu::makeMenu(), tx_wizardcrpages_webfunc_2, tx_wizardsortpages_webfunc_2
438 */
439 function getMenu($uid,$fields='*',$sortField='sorting',$addWhere='',$checkShortcuts=1) {
440
441 $output = Array();
442 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'pages', 'pid='.intval($uid).$this->where_hid_del.$this->where_groupAccess.' '.$addWhere, '', $sortField);
443 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
444 $this->versionOL('pages',$row,TRUE);
445 if (is_array($row)) {
446 // Keep mount point:
447 $origUid = $row['uid'];
448 $mount_info = $this->getMountPointInfo($origUid, $row); // $row MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
449 if (is_array($mount_info) && $mount_info['overlay']) { // There is a valid mount point.
450 $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!
451 if (count($mp_row)) {
452 $row = $mp_row;
453 $row['_MP_PARAM'] = $mount_info['MPvar'];
454 } 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!
455 }
456
457 // if shortcut, look up if the target exists and is currently visible
458 if ($row['doktype'] == 4 && ($row['shortcut'] || $row['shortcut_mode']) && $checkShortcuts) {
459 if ($row['shortcut_mode'] == 0) {
460 $searchField = 'uid';
461 $searchUid = intval($row['shortcut']);
462 } else { // check subpages - first subpage or random subpage
463 $searchField = 'pid';
464 // If a shortcut mode is set and no valid page is given to select subpags from use the actual page.
465 $searchUid = intval($row['shortcut'])?intval($row['shortcut']):$row['uid'];
466 }
467 $res2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', $searchField.'='.$searchUid.$this->where_hid_del.$this->where_groupAccess.' '.$addWhere, '', $sortField);
468 if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res2)) {
469 unset($row);
470 }
471 $GLOBALS['TYPO3_DB']->sql_free_result($res2);
472 } elseif ($row['doktype'] == 4 && $checkShortcuts) {
473 // Neither shortcut target nor mode is set. Remove the page from the menu.
474 unset($row);
475 }
476
477 // Add to output array after overlaying language:
478 if (is_array($row)) {
479 $output[$origUid] = $this->getPageOverlay($row);
480 }
481 }
482 }
483 $GLOBALS['TYPO3_DB']->sql_free_result($res);
484 return $output;
485 }
486
487 /**
488 * Will find the page carrying the domain record matching the input domain.
489 * Might exit after sending a redirect-header IF a found domain record instructs to do so.
490 *
491 * @param string Domain name to search for. Eg. "www.typo3.com". Typical the HTTP_HOST value.
492 * @param string Path for the current script in domain. Eg. "/somedir/subdir". Typ. supplied by t3lib_div::getIndpEnv('SCRIPT_NAME')
493 * @param string Request URI: Used to get parameters from if they should be appended. Typ. supplied by t3lib_div::getIndpEnv('REQUEST_URI')
494 * @return mixed If found, returns integer with page UID where found. Otherwise blank. Might exit if location-header is sent, see description.
495 * @see tslib_fe::findDomainRecord()
496 */
497 function getDomainStartPage($domain, $path='',$request_uri='') {
498 $domain = explode(':',$domain);
499 $domain = strtolower(ereg_replace('\.$','',$domain[0]));
500 // Removing extra trailing slashes
501 $path = trim(ereg_replace('\/[^\/]*$','',$path));
502 // Appending to domain string
503 $domain.= $path;
504 $domain = ereg_replace('\/*$','',$domain);
505
506 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
507 'pages.uid,sys_domain.redirectTo,sys_domain.prepend_params',
508 'pages,sys_domain',
509 'pages.uid=sys_domain.pid
510 AND sys_domain.hidden=0
511 AND (sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain').' OR sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain.'/', 'sys_domain').') '.
512 $this->where_hid_del.$this->where_groupAccess,
513 '',
514 '',
515 1
516 );
517 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
518 $GLOBALS['TYPO3_DB']->sql_free_result($res);
519 if ($row) {
520 if ($row['redirectTo']) {
521 $rURL = $row['redirectTo'];
522 if ($row['prepend_params']) {
523 $rURL = ereg_replace('\/$','',$rURL);
524 $prependStr = ereg_replace('^\/','',substr($request_uri,strlen($path)));
525 $rURL.= '/'.$prependStr;
526 }
527 Header('HTTP/1.1 301 Moved Permanently');
528 Header('Location: '.t3lib_div::locationHeaderUrl($rURL));
529 exit;
530 } else {
531 return $row['uid'];
532 }
533 }
534 }
535
536 /**
537 * Returns array with fields of the pages from here ($uid) and back to the root
538 * NOTICE: This function only takes deleted pages into account! So hidden, starttime and endtime restricted pages are included no matter what.
539 * Further: If any "recycler" page is found (doktype=255) then it will also block for the rootline)
540 * 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']
541 *
542 * @param integer The page uid for which to seek back to the page tree root.
543 * @param string Commalist of MountPoint parameters, eg. "1-2,3-4" etc. Normally this value comes from the GET var, MP
544 * @param boolean If set, some errors related to Mount Points in root line are ignored.
545 * @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.
546 * @see tslib_fe::getPageAndRootline()
547 */
548 function getRootLine($uid, $MP='', $ignoreMPerrors=FALSE) {
549 if (is_array($this->cache_getRootLine[$uid][$MP][$ignoreMPerrors?1:0])) {
550 return $this->cache_getRootLine[$uid][$MP][$ignoreMPerrors?1:0];
551 }
552
553 // Initialize:
554 $selFields = t3lib_div::uniqueList('pid,uid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_swapmode,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']);
555 $this->error_getRootLine = '';
556 $this->error_getRootLine_failPid = 0;
557
558 // Splitting the $MP parameters if present
559 $MPA = array();
560 if ($MP) {
561 $MPA = explode(',',$MP);
562 reset($MPA);
563 while(list($MPAk) = each($MPA)) {
564 $MPA[$MPAk] = explode('-', $MPA[$MPAk]);
565 }
566 }
567
568 $loopCheck = 0;
569 $theRowArray = Array();
570 $uid = intval($uid);
571
572 while ($uid!=0 && $loopCheck<20) { // Max 20 levels in the page tree.
573 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($selFields, 'pages', 'uid='.intval($uid).' AND pages.deleted=0 AND pages.doktype!=255');
574 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
575 $GLOBALS['TYPO3_DB']->sql_free_result($res);
576 if ($row) {
577 $this->versionOL('pages',$row, FALSE, TRUE);
578 $this->fixVersioningPid('pages',$row);
579
580 if (is_array($row)) {
581 // 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:
582 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] && $row['doktype']==7 && !$ignoreMPerrors) {
583 $mount_info = $this->getMountPointInfo($row['uid'], $row);
584 if ($loopCheck>0 || $mount_info['overlay']) {
585 $this->error_getRootLine = 'Illegal Mount Point found in rootline';
586 return array();
587 }
588 }
589
590 $uid = $row['pid']; // Next uid
591
592 if (count($MPA) && $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
593 $curMP = end($MPA);
594 if (!strcmp($row['uid'],$curMP[0])) {
595
596 array_pop($MPA);
597 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($selFields, 'pages', 'uid='.intval($curMP[1]).' AND pages.deleted=0 AND pages.doktype!=255');
598 $mp_row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
599 $GLOBALS['TYPO3_DB']->sql_free_result($res);
600
601 $this->versionOL('pages',$mp_row, FALSE, TRUE);
602 $this->fixVersioningPid('pages',$mp_row);
603
604 if (is_array($mp_row)) {
605 $mount_info = $this->getMountPointInfo($mp_row['uid'], $mp_row);
606 if (is_array($mount_info) && $mount_info['mount_pid']==$curMP[0]) {
607 $uid = $mp_row['pid']; // Setting next uid
608
609 if ($mount_info['overlay']) { // Symlink style: Keep mount point (current row).
610 $row['_MOUNT_OL'] = TRUE; // Set overlay mode:
611 $row['_MOUNT_PAGE'] = array(
612 'uid' => $mp_row['uid'],
613 'pid' => $mp_row['pid'],
614 'title' => $mp_row['title'],
615 );
616 } else { // Normal operation: Insert the mount page row in rootline instead mount point.
617 if ($loopCheck>0) {
618 $row = $mp_row;
619 } else {
620 $this->error_getRootLine = 'Current Page Id is a mounted page of the overlay type and cannot be accessed directly!';
621 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!)
622 }
623 }
624
625 $row['_MOUNTED_FROM'] = $curMP[0];
626 $row['_MP_PARAM'] = $mount_info['MPvar'];
627 } else {
628 $this->error_getRootLine = 'MP var was corrupted';
629 return array(); // The MP variables did NOT connect proper mount points:
630 }
631 } else {
632 $this->error_getRootLine = 'No moint point record found according to PID in MP var';
633 return array(); // The second PID in MP var was NOT a valid page.
634 }
635 }
636 }
637 }
638 // Add row to rootline with language overlaid:
639 $theRowArray[] = $this->getPageOverlay($row);
640 } else {
641 $this->error_getRootLine = 'Broken rootline';
642 $this->error_getRootLine_failPid = $uid;
643 return array(); // broken rootline.
644 }
645
646 $loopCheck++;
647 }
648
649 // If the MPA array is NOT empty, we have to return an error; All MP elements were not resolved!
650 if (count($MPA)) {
651 $this->error_getRootLine = 'MP value remain!';
652 return array();
653 }
654
655 // Create output array (with reversed order of numeric keys):
656 $output = Array();
657 $c = count($theRowArray);
658 foreach($theRowArray as $key => $val) {
659 $c--;
660 $output[$c] = $val;
661 }
662
663 // Note: rootline errors are not cached
664 $this->cache_getRootLine[$uid][$MP][$ignoreMPerrors?1:0] = $output;
665 return $output;
666 }
667
668 /**
669 * Creates a "path" string for the input root line array titles.
670 * Used for writing statistics.
671 *
672 * @param array A rootline array!
673 * @param integer The max length of each title from the rootline.
674 * @return string The path in the form "/page title/This is another pageti.../Another page"
675 * @see tslib_fe::getConfigArray()
676 */
677 function getPathFromRootline($rl,$len=20) {
678 if (is_array($rl)) {
679 $c=count($rl);
680 $path = '';
681 for ($a=0;$a<$c;$a++) {
682 if ($rl[$a]['uid']) {
683 $path.='/'.t3lib_div::fixed_lgd_cs(strip_tags($rl[$a]['title']),$len);
684 }
685 }
686 return $path;
687 }
688 }
689
690 /**
691 * Returns the URL type for the input page row IF the doktype is 3 and not disabled.
692 *
693 * @param array The page row to return URL type for
694 * @param boolean A flag to simply disable any output from here.
695 * @return string The URL type from $this->urltypes array. False if not found or disabled.
696 * @see tslib_fe::setExternalJumpUrl()
697 */
698 function getExtURL($pagerow,$disable=0) {
699 if ($pagerow['doktype']==3 && !$disable) {
700 $redirectTo = $this->urltypes[$pagerow['urltype']].$pagerow['url'];
701
702 // If relative path, prefix Site URL:
703 $uI = parse_url($redirectTo);
704 if (!$uI['scheme'] && substr($redirectTo,0,1)!='/') { // relative path assumed now...
705 $redirectTo = t3lib_div::getIndpEnv('TYPO3_SITE_URL').$redirectTo;
706 }
707 return $redirectTo;
708 }
709 }
710
711 /**
712 * Returns MountPoint id for page
713 * 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.
714 *
715 * @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...)
716 * @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
717 * @param array Array accumulating formerly tested page ids for mount points. Used for recursivity brake.
718 * @param integer The first page id.
719 * @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.
720 * @see tslib_menu
721 */
722 function getMountPointInfo($pageId, $pageRec=FALSE, $prevMountPids=array(), $firstPageUid=0) {
723 $result = FALSE;
724
725 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
726
727 if (isset($this->cache_getMountPointInfo[$pageId])) {
728 return $this->cache_getMountPointInfo[$pageId];
729 }
730
731 // Get pageRec if not supplied:
732 if (!is_array($pageRec)) {
733 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol,t3ver_state', 'pages', 'uid='.intval($pageId).' AND pages.deleted=0 AND pages.doktype!=255');
734 $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
735 $GLOBALS['TYPO3_DB']->sql_free_result($res);
736 $this->versionOL('pages',$pageRec); // Only look for version overlay if page record is not supplied; This assumes that the input record is overlaid with preview version, if any!
737 }
738
739 // Set first Page uid:
740 if (!$firstPageUid) {
741 $firstPageUid = $pageRec['uid'];
742 }
743
744 // Look for mount pid value plus other required circumstances:
745 $mount_pid = intval($pageRec['mount_pid']);
746 if (is_array($pageRec) && $pageRec['doktype']==7 && $mount_pid>0 && !in_array($mount_pid, $prevMountPids)) {
747
748 // Get the mount point record (to verify its general existence):
749 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol,t3ver_state', 'pages', 'uid='.$mount_pid.' AND pages.deleted=0 AND pages.doktype!=255');
750 $mountRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
751 $GLOBALS['TYPO3_DB']->sql_free_result($res);
752 $this->versionOL('pages',$mountRec);
753
754 if (is_array($mountRec)) {
755 // Look for recursive mount point:
756 $prevMountPids[] = $mount_pid;
757 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
758
759 // Return mount point information:
760 $result = $recursiveMountPid ?
761 $recursiveMountPid :
762 array(
763 'mount_pid' => $mount_pid,
764 'overlay' => $pageRec['mount_pid_ol'],
765 'MPvar' => $mount_pid.'-'.$firstPageUid,
766 'mount_point_rec' => $pageRec,
767 'mount_pid_rec' => $mountRec,
768 );
769 } else {
770 $result = -1; // Means, there SHOULD have been a mount point, but there was none!
771 }
772 }
773 }
774
775 $this->cache_getMountPointInfo[$pageId] = $result;
776 return $result;
777 }
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795 /*********************************
796 *
797 * Selecting records in general
798 *
799 **********************************/
800
801 /**
802 * Checks if a record exists and is accessible.
803 * The row is returned if everything's OK.
804 *
805 * @param string The table name to search
806 * @param integer The uid to look up in $table
807 * @param boolean If checkPage is set, it's also required that the page on which the record resides is accessible
808 * @return mixed Returns array (the record) if OK, otherwise blank/0 (zero)
809 */
810 function checkRecord($table,$uid,$checkPage=0) {
811 global $TCA;
812 $uid = intval($uid);
813 if (is_array($TCA[$table])) {
814 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($uid).$this->enableFields($table));
815 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
816 $GLOBALS['TYPO3_DB']->sql_free_result($res);
817 if ($row) {
818 $this->versionOL($table,$row);
819 if (is_array($row)) {
820 if ($checkPage) {
821 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid='.intval($row['pid']).$this->enableFields('pages'));
822 $numRows = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
823 $GLOBALS['TYPO3_DB']->sql_free_result($res);
824 if ($numRows>0) {
825 return $row;
826 } else {
827 return 0;
828 }
829 } else {
830 return $row;
831 }
832 }
833 }
834 }
835 }
836
837 /**
838 * Returns record no matter what - except if record is deleted
839 *
840 * @param string The table name to search
841 * @param integer The uid to look up in $table
842 * @param string The fields to select, default is "*"
843 * @param boolean If set, no version overlay is applied
844 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
845 * @see getPage_noCheck()
846 */
847 function getRawRecord($table,$uid,$fields='*',$noWSOL=FALSE) {
848 global $TCA;
849 $uid = intval($uid);
850 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()...
851 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid='.intval($uid).$this->deleteClause($table));
852 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
853 $GLOBALS['TYPO3_DB']->sql_free_result($res);
854 if ($row) {
855 if (!$noWSOL) {
856 $this->versionOL($table,$row);
857 }
858 if (is_array($row)) {
859 return $row;
860 }
861 }
862 }
863 }
864
865 /**
866 * Selects records based on matching a field (ei. other than UID) with a value
867 *
868 * @param string The table name to search, eg. "pages" or "tt_content"
869 * @param string The fieldname to match, eg. "uid" or "alias"
870 * @param string The value that fieldname must match, eg. "123" or "frontpage"
871 * @param string Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
872 * @param string Optional GROUP BY field(s), if none, supply blank string.
873 * @param string Optional ORDER BY field(s), if none, supply blank string.
874 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
875 * @return mixed Returns array (the record) if found, otherwise nothing (void)
876 */
877 function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='') {
878 global $TCA;
879 if (is_array($TCA[$theTable])) {
880 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
881 '*',
882 $theTable,
883 $theField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable).
884 $this->deleteClause($theTable).' '.
885 $whereClause, // whereClauseMightContainGroupOrderBy
886 $groupBy,
887 $orderBy,
888 $limit
889 );
890 $rows = array();
891 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
892 #$this->versionOL($theTable,$row); // not used since records here are fetched based on other fields than uid!
893 if (is_array($row)) $rows[] = $row;
894 }
895 $GLOBALS['TYPO3_DB']->sql_free_result($res);
896 if (count($rows)) {
897 return $rows;
898 }
899 }
900 }
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915 /*********************************
916 *
917 * Caching and standard clauses
918 *
919 **********************************/
920
921 /**
922 * Returns string value stored for the hash string in the table "cache_hash"
923 * Can be used to retrieved a cached value
924 * Can be used from your frontend plugins if you like. It is also used to store the parsed TypoScript template structures. You can call it directly like t3lib_pageSelect::getHash()
925 *
926 * @param string The hash-string which was used to store the data value
927 * @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.
928 * @return string The "content" field of the "cache_hash" table row.
929 * @see tslib_TStemplate::start(), storeHash()
930 */
931 function getHash($hash,$expTime=0) {
932 // if expTime is not set, the hash will never expire
933 $expTime = intval($expTime);
934 if ($expTime) {
935 $whereAdd = ' AND tstamp > '.(time()-$expTime);
936 }
937 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('content', 'cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash').$whereAdd);
938 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
939 $GLOBALS['TYPO3_DB']->sql_free_result($res);
940 if ($row) {
941 return $row['content'];
942 }
943 }
944
945 /**
946 * Stores a string value in the cache_hash table identified by $hash.
947 * Can be used from your frontend plugins if you like. You can call it directly like t3lib_pageSelect::storeHash()
948 *
949 * @param string 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
950 * @param string The data string. If you want to store an array, then just serialize it first.
951 * @param string $ident is just a textual identification in order to inform about the content! May be 20 characters long.
952 * @return void
953 * @see tslib_TStemplate::start(), getHash()
954 */
955 function storeHash($hash,$data,$ident) {
956 $insertFields = array(
957 'hash' => $hash,
958 'content' => $data,
959 'ident' => $ident,
960 'tstamp' => time()
961 );
962 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash'));
963 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_hash', $insertFields);
964 }
965
966 /**
967 * Returns the "AND NOT deleted" clause for the tablename given IF $TCA configuration points to such a field.
968 *
969 * @param string Tablename
970 * @return string
971 * @see enableFields()
972 */
973 function deleteClause($table) {
974 global $TCA;
975 if (!strcmp($table,'pages')) { // Hardcode for pages because TCA might not be loaded yet (early frontend initialization)
976 return ' AND pages.deleted=0';
977 } else {
978 return $TCA[$table]['ctrl']['delete'] ? ' AND '.$table.'.'.$TCA[$table]['ctrl']['delete'].'=0' : '';
979 }
980 }
981
982 /**
983 * 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.
984 * Is using the $TCA arrays "ctrl" part where the key "enablefields" determines for each table which of these features applies to that table.
985 *
986 * @param string Table name found in the $TCA array
987 * @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.
988 * @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.
989 * @param boolean If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
990 * @return string The clause starting like " AND ...=... AND ...=..."
991 * @see tslib_cObj::enableFields(), deleteClause()
992 */
993 function enableFields($table,$show_hidden=-1,$ignore_array=array(),$noVersionPreview=FALSE) {
994 global $TYPO3_CONF_VARS;
995
996 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
997 $show_hidden = $table=='pages' ? $GLOBALS['TSFE']->showHiddenPage : $GLOBALS['TSFE']->showHiddenRecords;
998 }
999 if ($show_hidden==-1) $show_hidden=0; // If show_hidden was not changed during the previous evaluation, do it here.
1000
1001 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
1002 $query='';
1003 if (is_array($ctrl)) {
1004
1005 // Delete field check:
1006 if ($ctrl['delete']) {
1007 $query.=' AND '.$table.'.'.$ctrl['delete'].'=0';
1008 }
1009
1010 // Filter out new place-holder records in case we are NOT in a versioning preview (that means we are online!)
1011 if ($ctrl['versioningWS'] && !$this->versioningPreview) {
1012 $query.=' AND '.$table.'.t3ver_state<=0'; // Shadow state for new items MUST be ignored!
1013 }
1014
1015 // Enable fields:
1016 if (is_array($ctrl['enablecolumns'])) {
1017 if (!$this->versioningPreview || !$ctrl['versioningWS'] || $noVersionPreview) { // In case of versioning-preview, enableFields are ignored (checked in versionOL())
1018 if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
1019 $field = $table.'.'.$ctrl['enablecolumns']['disabled'];
1020 $query.=' AND '.$field.'=0';
1021 }
1022 if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
1023 $field = $table.'.'.$ctrl['enablecolumns']['starttime'];
1024 $query.=' AND ('.$field.'<='.$GLOBALS['SIM_ACCESS_TIME'].')';
1025 }
1026 if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
1027 $field = $table.'.'.$ctrl['enablecolumns']['endtime'];
1028 $query.=' AND ('.$field.'=0 OR '.$field.'>'.$GLOBALS['SIM_ACCESS_TIME'].')';
1029 }
1030 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1031 $field = $table.'.'.$ctrl['enablecolumns']['fe_group'];
1032 $query.= $this->getMultipleGroupsWhereClause($field, $table);
1033 }
1034
1035 // Call hook functions for additional enableColumns
1036 // It is used by the extension ingmar_accessctrl which enables assigning more than one usergroup to content and page records
1037 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'])) {
1038 $_params = array(
1039 'table' => $table,
1040 'show_hidden' => $show_hidden,
1041 'ignore_array' => $ignore_array,
1042 'ctrl' => $ctrl
1043 );
1044 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] as $_funcRef) {
1045 $query .= t3lib_div::callUserFunction($_funcRef,$_params,$this);
1046 }
1047 }
1048 }
1049 }
1050 } else {
1051 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.');
1052 }
1053
1054 return $query;
1055 }
1056
1057 /**
1058 * Creating where-clause for checking group access to elements in enableFields function
1059 *
1060 * @param string Field with group list
1061 * @param string Table name
1062 * @return string AND sql-clause
1063 * @see enableFields()
1064 */
1065 function getMultipleGroupsWhereClause($field, $table) {
1066 $memberGroups = t3lib_div::intExplode(',',$GLOBALS['TSFE']->gr_list);
1067 $orChecks=array();
1068 $orChecks[]=$field.'=\'\''; // If the field is empty, then OK
1069 $orChecks[]=$field.' IS NULL'; // If the field is NULL, then OK
1070 $orChecks[]=$field.'=\'0\''; // If the field contsains zero, then OK
1071
1072 foreach($memberGroups as $value) {
1073 $orChecks[] = $GLOBALS['TYPO3_DB']->listQuery($field, $value, $table);
1074 }
1075
1076 return ' AND ('.implode(' OR ',$orChecks).')';
1077 }
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093 /*********************************
1094 *
1095 * Versioning Preview
1096 *
1097 **********************************/
1098
1099 /**
1100 * Finding online PID for offline version record
1101 * ONLY active when backend user is previewing records. MUST NEVER affect a site served which is not previewed by backend users!!!
1102 * Will look if the "pid" value of the input record is -1 (it is an offline version) and if the table supports versioning; if so, it will translate the -1 PID into the PID of the original record
1103 * Used whenever you are tracking something back, like making the root line.
1104 * Principle; Record offline! => Find online?
1105 *
1106 * @param string Table name
1107 * @param array Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid" and "t3ver_wsid" is nice and will save you a DB query.
1108 * @return void (Passed by ref).
1109 * @see t3lib_BEfunc::fixVersioningPid(), versionOL(), getRootLine()
1110 */
1111 function fixVersioningPid($table,&$rr) {
1112 global $TCA;
1113
1114 if ($this->versioningPreview && is_array($rr) && $rr['pid']==-1 && ($table=='pages' || $TCA[$table]['ctrl']['versioningWS'])) { // Have to hardcode it for "pages" table since TCA is not loaded at this moment!
1115
1116 // Check values for t3ver_oid and t3ver_wsid:
1117 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) { // If "t3ver_oid" is already a field, just set this:
1118 $oid = $rr['t3ver_oid'];
1119 $wsid = $rr['t3ver_wsid'];
1120 } else { // Otherwise we have to expect "uid" to be in the record and look up based on this:
1121 $newPidRec = $this->getRawRecord($table,$rr['uid'],'t3ver_oid,t3ver_wsid',TRUE);
1122 if (is_array($newPidRec)) {
1123 $oid = $newPidRec['t3ver_oid'];
1124 $wsid = $newPidRec['t3ver_wsid'];
1125 }
1126 }
1127
1128 // If workspace ids matches and ID of current online version is found, look up the PID value of that:
1129 if ($oid && (($this->versioningWorkspaceId == 0 && $this->checkWorkspaceAccess($wsid)) || !strcmp((int)$wsid,$this->versioningWorkspaceId))) {
1130 $oidRec = $this->getRawRecord($table,$oid,'pid',TRUE);
1131
1132 if (is_array($oidRec)) {
1133 # SWAP uid as well? Well no, because when fixing a versioning PID happens it is assumed that this is a "branch" type page and therefore the uid should be kept (like in versionOL()). However if the page is NOT a branch version it should not happen - but then again, direct access to that uid should not happen!
1134 $rr['_ORIG_pid'] = $rr['pid'];
1135 $rr['pid'] = $oidRec['pid'];
1136 }
1137 }
1138 }
1139
1140 // changing PID in case of moving pointer:
1141 if ($movePlhRec = $this->getMovePlaceholder($table,$rr['uid'],'pid')) {
1142 $rr['pid'] = $movePlhRec['pid'];
1143 }
1144 }
1145
1146 /**
1147 * Versioning Preview Overlay
1148 * ONLY active when backend user is previewing records. MUST NEVER affect a site served which is not previewed by backend users!!!
1149 * Generally ALWAYS used when records are selected based on uid or pid. If records are selected on other fields than uid or pid (eg. "email = ....") then usage might produce undesired results and that should be evaluated on individual basis.
1150 * Principle; Record online! => Find offline?
1151 *
1152 * @param string Table name
1153 * @param array Record array passed by reference. As minimum, the "uid", "pid" and "t3ver_state" fields must exist! The record MAY be set to FALSE in which case the calling function should act as if the record is forbidden to access!
1154 * @param boolean If set, the $row is cleared in case it is a move-pointer. This is only for preview of moved records (to remove the record from the original location so it appears only in the new location)
1155 * @param boolean Unless this option is TRUE, the $row is unset if enablefields for BOTH the version AND the online record deselects it. This is because when versionOL() is called it is assumed that the online record is already selected with no regards to it's enablefields. However, after looking for a new version the online record enablefields must ALSO be evaluated of course. This is done all by this function!
1156 * @return void (Passed by ref).
1157 * @see fixVersioningPid(), t3lib_BEfunc::workspaceOL()
1158 */
1159 function versionOL($table,&$row,$unsetMovePointers=FALSE,$bypassEnableFieldsCheck=FALSE) {
1160 global $TCA;
1161
1162 if ($this->versioningPreview && is_array($row)) {
1163 $movePldSwap = $this->movePlhOL($table,$row); // will overlay any movePlhOL found with the real record, which in turn will be overlaid with its workspace version if any.
1164 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], implode(',',array_keys($row)), $bypassEnableFieldsCheck)) { // implode(',',array_keys($row)) = Using fields from original record to make sure no additional fields are selected. This is best for eg. getPageOverlay()
1165 if (is_array($wsAlt)) {
1166 // Always fix PID (like in fixVersioningPid() above). [This is usually not the important factor for versioning OL]
1167 $wsAlt['_ORIG_pid'] = $wsAlt['pid']; // Keep the old (-1) - indicates it was a version...
1168 $wsAlt['pid'] = $row['pid']; // Set in the online versions PID.
1169
1170 // "element" and "page" type versions:
1171 // For versions of single elements or page+content, preserve online UID and PID (this will produce true "overlay" of element _content_, not any references)
1172 // For page+content the "_ORIG_uid" should actually be used as PID for selection of tables with "versioning_followPages" enabled.
1173 if ($table!=='pages' || $wsAlt['t3ver_swapmode']<=0) {
1174 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1175 $wsAlt['uid'] = $row['uid'];
1176
1177 // Translate page alias as well so links are pointing to the _online_ page:
1178 if ($table==='pages') {
1179 $wsAlt['alias'] = $row['alias'];
1180 }
1181 } else {
1182 // "branch" versions:
1183 // Keeping overlay uid and pid so references are changed. This is only for page-versions with BRANCH below!
1184 $wsAlt['_ONLINE_uid'] = $row['uid']; // The UID of the versionized record is kept and the uid of the online version is stored
1185 }
1186
1187 // Changing input record to the workspace version alternative:
1188 $row = $wsAlt;
1189
1190 // Check if it is deleted/new
1191 if ((int)$row['t3ver_state']===1 || (int)$row['t3ver_state']===2) {
1192 $row = FALSE; // Unset record if it turned out to be deleted in workspace
1193 }
1194
1195 // Check if move-pointer in workspace (unless if a move-placeholder is the reason why it appears!):
1196 // You have to specifically set $unsetMovePointers in order to clear these because it is normally a display issue if it should be shown or not.
1197 if ((int)$row['t3ver_state']===4 && !$movePldSwap && $unsetMovePointers) {
1198 $row = FALSE; // Unset record if it turned out to be deleted in workspace
1199 }
1200 } else {
1201 // No version found, then check if t3ver_state =1 (online version is dummy-representation)
1202 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if enablefields for BOTH the version AND the online record deselects it. See note for $bypassEnableFieldsCheck
1203 if ($wsAlt<=-1 || (int)$row['t3ver_state']>0) {
1204 $row = FALSE; // Unset record if it turned out to be "hidden"
1205 }
1206 }
1207 }
1208 }
1209 }
1210
1211 /**
1212 * Checks if record is a move-placeholder (t3ver_state==3) and if so it will set $row to be the pointed-to live record (and return TRUE)
1213 * Used from versionOL
1214 *
1215 * @param string Table name
1216 * @param array Row (passed by reference) - only online records...
1217 * @return boolean True if overlay is made.
1218 * @see t3lib_BEfunc::movePlhOl()
1219 */
1220 function movePlhOL($table,&$row) {
1221 global $TCA;
1222
1223 if (($table=='pages' || (int)$TCA[$table]['ctrl']['versioningWS']>=2) && (int)$row['t3ver_state']===3) { // Only for WS ver 2... (moving)
1224
1225 // If t3ver_move_id is not found, then find it... (but we like best if it is here...)
1226 if (!isset($row['t3ver_move_id'])) {
1227 $moveIDRec = $this->getRawRecord($table,$row['uid'],'t3ver_move_id',TRUE);
1228 $moveID = $moveIDRec['t3ver_move_id'];
1229 } else {
1230 $moveID = $row['t3ver_move_id'];
1231 }
1232
1233 // Find pointed-to record.
1234 if ($moveID) {
1235 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',',array_keys($row)), $table, 'uid='.intval($moveID).$this->enableFields($table));
1236 $origRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1237 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1238 if ($origRow) {
1239 $row = $origRow;
1240 return TRUE;
1241 }
1242 }
1243 }
1244 return FALSE;
1245 }
1246
1247 /**
1248 * Returns move placeholder of online (live) version
1249 *
1250 * @param string Table name
1251 * @param integer Record UID of online version
1252 * @param string Field list, default is *
1253 * @return array If found, the record, otherwise nothing.
1254 * @see t3lib_BEfunc::getMovePlaceholder()
1255 */
1256 function getMovePlaceholder($table,$uid,$fields='*') {
1257 global $TCA;
1258
1259 if ($this->versioningPreview) {
1260 $workspace = (int)$this->versioningWorkspaceId;
1261 if (($table=='pages' || (int)$TCA[$table]['ctrl']['versioningWS']>=2) && $workspace!==0) {
1262
1263 // Select workspace version of record:
1264 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1265 $fields,
1266 $table,
1267 'pid!=-1 AND
1268 t3ver_state=3 AND
1269 t3ver_move_id='.intval($uid).' AND
1270 t3ver_wsid='.intval($workspace).
1271 $this->deleteClause($table)
1272 );
1273
1274 if (is_array($rows[0])) {
1275 return $rows[0];
1276 }
1277 }
1278 }
1279 return FALSE;
1280 }
1281
1282 /**
1283 * Select the version of a record for a workspace
1284 *
1285 * @param integer Workspace ID
1286 * @param string Table name to select from
1287 * @param integer Record uid for which to find workspace version.
1288 * @param string Field list to select
1289 * @param boolean If true, enablefields are not checked for.
1290 * @return mixed If found, return record, otherwise other value: Returns 1 if version was sought for but not found, returns -1/-2 if record (offline/online) existed but had enableFields that would disable it. Returns FALSE if not in workspace or no versioning for record. Notice, that the enablefields of the online record is also tested.
1291 * @see t3lib_befunc::getWorkspaceVersionOfRecord()
1292 */
1293 function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields='*',$bypassEnableFieldsCheck=FALSE) {
1294 global $TCA;
1295
1296 if ($workspace!==0 && ($table=='pages' || $TCA[$table]['ctrl']['versioningWS'])) { // Have to hardcode it for "pages" table since TCA is not loaded at this moment!
1297
1298 // Setting up enableFields for version record:
1299 if ($table=='pages') {
1300 $enFields = $this->versioningPreview_where_hid_del;
1301 } else {
1302 $enFields = $this->enableFields($table,-1,array(),TRUE);
1303 }
1304
1305 // Select workspace version of record, only testing for deleted.
1306 list($newrow) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1307 $fields,
1308 $table,
1309 'pid=-1 AND
1310 t3ver_oid='.intval($uid).' AND
1311 t3ver_wsid='.intval($workspace).
1312 $this->deleteClause($table)
1313 );
1314
1315 // If version found, check if it could have been selected with enableFields on as well:
1316 if (is_array($newrow)) {
1317 if ($bypassEnableFieldsCheck || $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1318 'uid',
1319 $table,
1320 'pid=-1 AND
1321 t3ver_oid='.intval($uid).' AND
1322 t3ver_wsid='.intval($workspace).
1323 $enFields
1324 )) {
1325 return $newrow; // Return offline version, tested for its enableFields.
1326 } else {
1327 return -1; // Return -1 because offline version was de-selected due to its enableFields.
1328 }
1329 } else {
1330 // OK, so no workspace version was found. Then check if online version can be selected with full enable fields and if so, return 1:
1331 if ($bypassEnableFieldsCheck || $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1332 'uid',
1333 $table,
1334 'uid='.intval($uid).$enFields
1335 )) {
1336 return 1; // Means search was done, but no version found.
1337 } else {
1338 return -2; // Return -2 because the online record was de-selected due to its enableFields.
1339 }
1340 }
1341 }
1342
1343 return FALSE; // No look up in database because versioning not enabled / or workspace not offline
1344 }
1345
1346 /**
1347 * Checks if user has access to workspace.
1348 *
1349 * @param int $wsid Workspace ID
1350 * @return boolean <code>true</code> if has access
1351 */
1352 function checkWorkspaceAccess($wsid) {
1353 if (!$GLOBALS['BE_USER']) {
1354 return false;
1355 }
1356 if (isset($this->workspaceCache[$wsid])) {
1357 $ws = $this->workspaceCache[$wsid];
1358 }
1359 else {
1360 if ($wsid > 0) {
1361 $ws = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_workspace', 'uid='.intval($wsid).' AND deleted=0'); // No $TCA yet!
1362 if (count($ws)) {
1363 $ws = $ws[0];
1364 }
1365 else {
1366 return false;
1367 }
1368 }
1369 else {
1370 $ws = $wsid;
1371 }
1372 $ws = $GLOBALS['BE_USER']->checkWorkspace($ws);
1373 $this->workspaceCache[$wsid] = $ws;
1374 }
1375 return ($ws['_ACCESS'] != '');
1376 }
1377 }
1378
1379
1380
1381 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_page.php']) {
1382 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_page.php']);
1383 }
1384 ?>