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