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