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