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