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