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