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