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