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