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