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