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