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