2 namespace TYPO3\CMS\Frontend\Page
;
5 * This file is part of the TYPO3 CMS project.
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.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use TYPO3\CMS\Core\Cache\CacheManager
;
18 use TYPO3\CMS\Core\
Resource\FileRepository
;
19 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility
;
20 use TYPO3\CMS\Core\Utility\GeneralUtility
;
21 use TYPO3\CMS\Core\Utility\HttpUtility
;
22 use TYPO3\CMS\Core\Utility\RootlineUtility
;
23 use TYPO3\CMS\Core\Versioning\VersionState
;
26 * Page functions, a lot of sql/pages-related functions
28 * Mainly used in the frontend but also in some cases in the backend. It's
29 * important to set the right $where_hid_del in the object so that the
30 * functions operate properly
31 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
33 class PageRepository
{
38 public $urltypes = array('', 'http://', 'ftp://', 'mailto:', 'https://');
41 * This is not the final clauses. There will normally be conditions for the
42 * hidden, starttime and endtime fields as well. You MUST initialize the object
43 * by the init() function
47 public $where_hid_del = ' AND pages.deleted=0';
50 * Clause for fe_group access
54 public $where_groupAccess = '';
59 public $sys_language_uid = 0;
62 * If TRUE, versioning preview of other record versions is allowed. THIS MUST
63 * ONLY BE SET IF the page is not cached and truely previewed by a backend
68 public $versioningPreview = FALSE;
73 public $versioningPreview_where_hid_del = '';
76 * Workspace ID for preview
80 public $versioningWorkspaceId = 0;
85 public $workspaceCache = array();
88 * Error string set by getRootLine()
92 public $error_getRootLine = '';
95 * Error uid set by getRootLine()
99 public $error_getRootLine_failPid = 0;
104 protected $cache_getRootLine = array();
109 protected $cache_getPage = array();
114 protected $cache_getPage_noCheck = array();
119 protected $cache_getPageIdFromAlias = array();
124 protected $cache_getMountPointInfo = array();
129 protected $tableNamesAllowedOnRootLevel = array(
135 * Computed properties that are added to database rows.
139 protected $computedPropertyNames = array(
145 '_PAGES_OVERLAY_UID',
146 '_PAGES_OVERLAY_LANGUAGE',
150 * Named constants for "magic numbers" of the field doktype
152 const DOKTYPE_DEFAULT
= 1;
153 const DOKTYPE_LINK
= 3;
154 const DOKTYPE_SHORTCUT
= 4;
155 const DOKTYPE_BE_USER_SECTION
= 6;
156 const DOKTYPE_MOUNTPOINT
= 7;
157 const DOKTYPE_SPACER
= 199;
158 const DOKTYPE_SYSFOLDER
= 254;
159 const DOKTYPE_RECYCLER
= 255;
162 * Named constants for "magic numbers" of the field shortcut_mode
164 const SHORTCUT_MODE_NONE
= 0;
165 const SHORTCUT_MODE_FIRST_SUBPAGE
= 1;
166 const SHORTCUT_MODE_RANDOM_SUBPAGE
= 2;
167 const SHORTCUT_MODE_PARENT_PAGE
= 3;
170 * init() MUST be run directly after creating a new template-object
171 * This sets the internal variable $this->where_hid_del to the correct where
172 * clause for page records taking deleted/hidden/starttime/endtime/t3ver_state
175 * @param bool $show_hidden If $show_hidden is TRUE, the hidden-field is ignored!! Normally this should be FALSE. Is used for previewing.
177 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id(), \TYPO3\CMS\Tstemplate\Controller\TemplateAnalyzerModuleFunctionController::initialize_editor()
179 public function init($show_hidden) {
180 $this->where_groupAccess
= '';
182 if ($this->versioningPreview
) {
183 // For version previewing, make sure that enable-fields are not
184 // de-selecting hidden pages - we need versionOL() to unset them only
185 // if the overlay record instructs us to.
186 // Clear where_hid_del and restrict to live and current workspaces
187 $this->where_hid_del
= ' AND pages.deleted=0 AND (pages.t3ver_wsid=0 OR pages.t3ver_wsid=' . (int)$this->versioningWorkspaceId
. ')';
189 // add starttime / endtime, and check for hidden/deleted
190 // Filter out new/deleted place-holder pages in case we are NOT in a
191 // versioning preview (that means we are online!)
192 $this->where_hid_del
= $this->enableFields('pages', $show_hidden, array('fe_group' => TRUE), TRUE);
194 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][PageRepository
::class]['init'])) {
195 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][PageRepository
::class]['init'] as $classRef) {
196 $hookObject = GeneralUtility
::makeInstance($classRef);
197 if (!$hookObject instanceof PageRepositoryInitHookInterface
) {
198 throw new \
UnexpectedValueException($hookObject . ' must implement interface TYPO3\\CMS\\Frontend\\Page\\PageRepositoryInitHookInterface', 1379579812);
200 $hookObject->init_postProcess($this);
205 /**************************
207 * Selecting page records
209 **************************/
212 * Returns the $row for the page with uid = $uid (observing ->where_hid_del)
213 * Any pages_language_overlay will be applied before the result is returned.
214 * If no page is found an empty array is returned.
216 * @param int $uid The page id to look up.
217 * @param bool $disableGroupAccessCheck If set, the check for group access is disabled. VERY rarely used
218 * @throws \UnexpectedValueException
219 * @return array The page row with overlayed localized fields. Empty it no page.
220 * @see getPage_noCheck()
222 public function getPage($uid, $disableGroupAccessCheck = FALSE) {
223 // Hook to manipulate the page uid for special overlay handling
224 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'])) {
225 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'] as $classRef) {
226 $hookObject = GeneralUtility
::getUserObj($classRef);
227 if (!$hookObject instanceof PageRepositoryGetPageHookInterface
) {
228 throw new \
UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetPageHookInterface
::class, 1251476766);
230 $hookObject->getPage_preProcess($uid, $disableGroupAccessCheck, $this);
233 $accessCheck = $disableGroupAccessCheck ?
'' : $this->where_groupAccess
;
234 $cacheKey = md5($accessCheck . '-' . $this->where_hid_del
. '-' . $this->sys_language_uid
);
235 if (is_array($this->cache_getPage
[$uid][$cacheKey])) {
236 return $this->cache_getPage
[$uid][$cacheKey];
238 $workspaceVersion = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId
, 'pages', $uid);
239 $db = $this->getDatabaseConnection();
240 if (is_array($workspaceVersion)) {
241 $workspaceVersionAccess = $db->exec_SELECTgetSingleRow(
244 'uid=' . intval($workspaceVersion['uid']) . $this->where_hid_del
. $accessCheck
246 if (is_array($workspaceVersionAccess)) {
251 $row = $db->exec_SELECTgetSingleRow('*', 'pages', 'uid=' . (int)$uid . $this->where_hid_del
. $accessCheck);
253 $this->versionOL('pages', $row);
254 if (is_array($row)) {
255 $result = $this->getPageOverlay($row);
258 $this->cache_getPage
[$uid][$cacheKey] = $result;
263 * Return the $row for the page with uid = $uid WITHOUT checking for
264 * ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
266 * @param int $uid The page id to look up
267 * @return array The page row with overlayed localized fields. Empty array if no page.
270 public function getPage_noCheck($uid) {
271 if ($this->cache_getPage_noCheck
[$uid]) {
272 return $this->cache_getPage_noCheck
[$uid];
274 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'pages', 'uid=' . (int)$uid . $this->deleteClause('pages'));
275 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
276 $this->getDatabaseConnection()->sql_free_result($res);
279 $this->versionOL('pages', $row);
280 if (is_array($row)) {
281 $result = $this->getPageOverlay($row);
284 $this->cache_getPage_noCheck
[$uid] = $result;
289 * Returns the $row of the first web-page in the tree (for the default menu...)
291 * @param int $uid The page id for which to fetch first subpages (PID)
292 * @return mixed If found: The page record (with overlayed localized fields, if any). If NOT found: blank value (not array!)
293 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
295 public function getFirstWebPage($uid) {
297 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'pages', 'pid=' . (int)$uid . $this->where_hid_del
. $this->where_groupAccess
, '', 'sorting', '1');
298 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
299 $this->getDatabaseConnection()->sql_free_result($res);
301 $this->versionOL('pages', $row);
302 if (is_array($row)) {
303 $output = $this->getPageOverlay($row);
310 * Returns a pagerow for the page with alias $alias
312 * @param string $alias The alias to look up the page uid for.
313 * @return int Returns page uid (int) if found, otherwise 0 (zero)
314 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::checkAndSetAlias(), ContentObjectRenderer::typoLink()
316 public function getPageIdFromAlias($alias) {
317 $alias = strtolower($alias);
318 if ($this->cache_getPageIdFromAlias
[$alias]) {
319 return $this->cache_getPageIdFromAlias
[$alias];
321 $db = $this->getDatabaseConnection();
322 $row = $db->exec_SELECTgetSingleRow('uid', 'pages', 'alias=' . $db->fullQuoteStr($alias, 'pages') . ' AND pid>=0 AND pages.deleted=0');
323 // "AND pid>=0" because of versioning (means that aliases sent MUST be online!)
325 $this->cache_getPageIdFromAlias
[$alias] = $row['uid'];
328 $this->cache_getPageIdFromAlias
[$alias] = 0;
333 * Returns the relevant page overlay record fields
335 * @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.
336 * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
337 * @throws \UnexpectedValueException
338 * @return array Page row which is overlayed with language_overlay record (or the overlay record alone)
340 public function getPageOverlay($pageInput, $lUid = -1) {
341 $rows = $this->getPagesOverlay(array($pageInput), $lUid);
342 // Always an array in return
343 return isset($rows[0]) ?
$rows[0] : array();
347 * Returns the relevant page overlay record fields
349 * @param array $pagesInput Array of integers or array of arrays. If each value is an integer, it's the pids of the pageOverlay records and thus the page overlay records are returned. If each value is an array, it's page-records and based on this page records the language records are found and OVERLAYED before the page records are returned.
350 * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
351 * @throws \UnexpectedValueException
352 * @return array Page rows which are overlayed with language_overlay record.
353 * If the input was an array of integers, missing records are not
354 * included. If the input were page rows, untranslated pages
357 public function getPagesOverlay(array $pagesInput, $lUid = -1) {
358 if (empty($pagesInput)) {
363 $lUid = $this->sys_language_uid
;
366 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'])) {
367 foreach ($pagesInput as $origPage) {
368 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'] as $classRef) {
369 $hookObject = GeneralUtility
::getUserObj($classRef);
370 if (!$hookObject instanceof PageRepositoryGetPageOverlayHookInterface
) {
371 throw new \
UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetPageOverlayHookInterface
::class, 1269878881);
373 $hookObject->getPageOverlay_preProcess($origPage, $lUid, $this);
377 // If language UID is different from zero, do overlay:
379 $fieldArr = GeneralUtility
::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['pageOverlayFields'], TRUE);
382 $origPage = reset($pagesInput);
383 if (is_array($origPage)) {
384 // Make sure that only fields which exist in the first incoming record are overlaid!
385 $fieldArr = array_intersect($fieldArr, array_keys($origPage));
387 foreach ($pagesInput as $origPage) {
388 if (is_array($origPage)) {
389 // Was the whole record
390 $page_ids[] = $origPage['uid'];
393 $page_ids[] = $origPage;
396 if (!empty($fieldArr)) {
397 if (!in_array('pid', $fieldArr, TRUE)) {
400 // NOTE to enabledFields('pages_language_overlay'):
401 // Currently the showHiddenRecords of TSFE set will allow
402 // pages_language_overlay records to be selected as they are
403 // child-records of a page.
404 // However you may argue that the showHiddenField flag should
405 // determine this. But that's not how it's done right now.
406 // Selecting overlay record:
407 $db = $this->getDatabaseConnection();
408 $res = $db->exec_SELECTquery(
409 implode(',', $fieldArr),
410 'pages_language_overlay',
411 'pid IN(' . implode(',', $db->cleanIntArray($page_ids)) . ')'
412 . ' AND sys_language_uid=' . (int)$lUid . $this->enableFields('pages_language_overlay')
415 while ($row = $db->sql_fetch_assoc($res)) {
416 $this->versionOL('pages_language_overlay', $row);
417 if (is_array($row)) {
418 $row['_PAGES_OVERLAY'] = TRUE;
419 $row['_PAGES_OVERLAY_UID'] = $row['uid'];
420 $row['_PAGES_OVERLAY_LANGUAGE'] = $lUid;
421 $origUid = $row['pid'];
422 // Unset vital fields that are NOT allowed to be overlaid:
425 $overlays[$origUid] = $row;
428 $db->sql_free_result($res);
432 $pagesOutput = array();
433 foreach ($pagesInput as $key => $origPage) {
434 if (is_array($origPage)) {
435 $pagesOutput[$key] = $origPage;
436 if (isset($overlays[$origPage['uid']])) {
437 // Overwrite the original field with the overlay
438 foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
439 if ($fieldName !== 'uid' && $fieldName !== 'pid') {
440 if ($this->shouldFieldBeOverlaid('pages_language_overlay', $fieldName, $fieldValue)) {
441 $pagesOutput[$key][$fieldName] = $fieldValue;
447 if (isset($overlays[$origPage])) {
448 $pagesOutput[$key] = $overlays[$origPage];
456 * Creates language-overlay for records in general (where translation is found
457 * in records from the same table)
459 * @param string $table Table name
460 * @param array $row Record to overlay. Must containt uid, pid and $table]['ctrl']['languageField']
461 * @param int $sys_language_content Pointer to the sys_language uid for content on the site.
462 * @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned un-translated but unset (and return value is FALSE)
463 * @throws \UnexpectedValueException
464 * @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.
466 public function getRecordOverlay($table, $row, $sys_language_content, $OLmode = '') {
467 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'])) {
468 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] as $classRef) {
469 $hookObject = GeneralUtility
::getUserObj($classRef);
470 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface
) {
471 throw new \
UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetRecordOverlayHookInterface
::class, 1269881658);
473 $hookObject->getRecordOverlay_preProcess($table, $row, $sys_language_content, $OLmode, $this);
476 if ($row['uid'] > 0 && ($row['pid'] > 0 ||
in_array($table, $this->tableNamesAllowedOnRootLevel
, TRUE))) {
477 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
478 if (!$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
479 // Will not be able to work with other tables (Just didn't implement it yet;
480 // Requires a scan over all tables [ctrl] part for first FIND the table that
481 // carries localization information for this table (which could even be more
482 // than a single table) and then use that. Could be implemented, but obviously
483 // takes a little more....) Will try to overlay a record only if the
484 // sys_language_content value is larger than zero.
485 if ($sys_language_content > 0) {
486 // Must be default language or [All], otherwise no overlaying:
487 if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] <= 0) {
488 // Select overlay record:
489 $res = $this->getDatabaseConnection()->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');
490 $olrow = $this->getDatabaseConnection()->sql_fetch_assoc($res);
491 $this->getDatabaseConnection()->sql_free_result($res);
492 $this->versionOL($table, $olrow);
493 // Merge record content by traversing all fields:
494 if (is_array($olrow)) {
495 if (isset($olrow['_ORIG_uid'])) {
496 $row['_ORIG_uid'] = $olrow['_ORIG_uid'];
498 if (isset($olrow['_ORIG_pid'])) {
499 $row['_ORIG_pid'] = $olrow['_ORIG_pid'];
501 foreach ($row as $fN => $fV) {
502 if ($fN !== 'uid' && $fN !== 'pid' && isset($olrow[$fN])) {
503 if ($this->shouldFieldBeOverlaid($table, $fN, $olrow[$fN])) {
504 $row[$fN] = $olrow[$fN];
506 } elseif ($fN === 'uid') {
507 $row['_LOCALIZED_UID'] = $olrow['uid'];
510 } elseif ($OLmode === 'hideNonTranslated' && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
511 // Unset, if non-translated records should be hidden. ONLY done if the source
512 // record really is default language and not [All] in which case it is allowed.
515 } elseif ($sys_language_content != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
519 // When default language is displayed, we never want to return a record carrying
521 if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
528 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'])) {
529 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] as $classRef) {
530 $hookObject = GeneralUtility
::getUserObj($classRef);
531 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface
) {
532 throw new \
UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetRecordOverlayHookInterface
::class, 1269881659);
534 $hookObject->getRecordOverlay_postProcess($table, $row, $sys_language_content, $OLmode, $this);
540 /************************************************
542 * Page related: Menu, Domain record, Root line
544 ************************************************/
547 * Returns an array with page rows for subpages of a certain page ID. This is used for menus in the frontend.
548 * If there are mount points in overlay mode the _MP_PARAM field is set to the corret MPvar.
550 * If the $pageId being input does in itself require MPvars to define a correct
551 * rootline these must be handled externally to this function.
553 * @param int|int[] $pageId The page id (or array of page ids) for which to fetch subpages (PID)
554 * @param string $fields List of fields to select. Default is "*" = all
555 * @param string $sortField The field to sort by. Default is "sorting
556 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
557 * @param bool $checkShortcuts Check if shortcuts exist, checks by default
558 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlayed localized fields, if any)
559 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageShortcut(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
560 * @see \TYPO3\CMS\WizardCrpages\Controller\CreatePagesWizardModuleFunctionController, \TYPO3\CMS\WizardSortpages\View\SortPagesWizardModuleFunction
562 public function getMenu($pageId, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = TRUE) {
563 return $this->getSubpagesForPages((array)$pageId, $fields, $sortField, $additionalWhereClause, $checkShortcuts);
567 * Returns an array with page-rows for pages with uid in $pageIds.
569 * This is used for menus. If there are mount points in overlay mode
570 * the _MP_PARAM field is set to the correct MPvar.
572 * @param int[] $pageIds Array of page ids to fetch
573 * @param string $fields List of fields to select. Default is "*" = all
574 * @param string $sortField The field to sort by. Default is "sorting"
575 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
576 * @param bool $checkShortcuts Check if shortcuts exist, checks by default
577 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlayed localized fields, if any)
579 public function getMenuForPages(array $pageIds, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = TRUE) {
580 return $this->getSubpagesForPages($pageIds, $fields, $sortField, $additionalWhereClause, $checkShortcuts, FALSE);
584 * Internal method used by getMenu() and getMenuForPages()
585 * Returns an array with page rows for subpages with pid is in $pageIds or uid is in $pageIds, depending on $parentPages
586 * This is used for menus. If there are mount points in overlay mode
587 * the _MP_PARAM field is set to the corret MPvar.
589 * If the $pageIds being input does in itself require MPvars to define a correct
590 * rootline these must be handled externally to this function.
592 * @param int[] $pageIds The page id (or array of page ids) for which to fetch subpages (PID)
593 * @param string $fields List of fields to select. Default is "*" = all
594 * @param string $sortField The field to sort by. Default is "sorting
595 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
596 * @param bool $checkShortcuts Check if shortcuts exist, checks by default
597 * @param bool $parentPages Whether the uid list is meant as list of parent pages or the page itself TRUE means id list is checked agains pid field
598 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlayed localized fields, if any)
599 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageShortcut(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
600 * @see \TYPO3\CMS\WizardCrpages\Controller\CreatePagesWizardModuleFunctionController, \TYPO3\CMS\WizardSortpages\View\SortPagesWizardModuleFunction
602 protected function getSubpagesForPages(array $pageIds, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = TRUE, $parentPages = TRUE) {
604 $relationField = $parentPages ?
'pid' : 'uid';
605 $db = $this->getDatabaseConnection();
607 $whereStatement = $relationField . ' IN ('
608 . implode(',', $db->cleanIntArray($pageIds)) . ')'
609 . $this->where_hid_del
610 . $this->where_groupAccess
612 . $additionalWhereClause;
614 // Check the user group access for draft pages in preview
615 if ($this->versioningWorkspaceId
!= 0) {
616 $databaseResource = $db->exec_SELECTquery(
619 $relationField . ' IN (' . implode(',', $db->cleanIntArray($pageIds)) . ')'
620 . $this->where_hid_del
. ' ' . $additionalWhereClause,
625 $draftUserGroupAccessWhereStatement = $this->getDraftUserGroupAccessWhereStatement(
628 $additionalWhereClause
631 if ($draftUserGroupAccessWhereStatement !== FALSE) {
632 $whereStatement = $draftUserGroupAccessWhereStatement;
636 $databaseResource = $db->exec_SELECTquery(
644 while (($page = $db->sql_fetch_assoc($databaseResource))) {
645 $originalUid = $page['uid'];
647 // Versioning Preview Overlay
648 $this->versionOL('pages', $page, TRUE);
650 // Add a mount point parameter if needed
651 $page = $this->addMountPointParameterToPage((array)$page);
653 // If shortcut, look up if the target exists and is currently visible
654 if ($checkShortcuts) {
655 $page = $this->checkValidShortcutOfPage((array)$page, $additionalWhereClause);
658 // If the page still is there, we add it to the output
660 $pages[$originalUid] = $page;
664 $db->sql_free_result($databaseResource);
666 // Finally load language overlays
667 return $this->getPagesOverlay($pages);
671 * Prevent pages being shown in menu's for preview which contain usergroup access rights in a draft workspace
673 * Returns an adapted "WHERE" statement if pages are in draft
675 * @param bool|\mysqli_result|object $databaseResource MySQLi result object / DBAL object
676 * @param string $sortField The field to sort by
677 * @param string $addWhere Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
678 * @return bool|string FALSE if no records are available in draft, a WHERE statement with the uid's if available
680 protected function getDraftUserGroupAccessWhereStatement($databaseResource, $sortField, $addWhere) {
681 $draftUserGroupAccessWhereStatement = FALSE;
684 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($databaseResource)) {
685 $workspaceRow = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId
, 'pages', $row['uid']);
687 $realUid = is_array($workspaceRow) ?
$workspaceRow['uid'] : $row['uid'];
689 $result = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
692 'uid=' . intval($realUid)
693 . $this->where_hid_del
694 . $this->where_groupAccess
700 if (is_array($result)) {
701 $recordArray[] = $row['uid'];
705 if (!empty($recordArray)) {
706 $draftUserGroupAccessWhereStatement = 'uid IN (' . implode(',', $recordArray) . ')';
709 return $draftUserGroupAccessWhereStatement;
713 * Add the mount point parameter to the page if needed
715 * @param array $page The page to check
718 protected function addMountPointParameterToPage(array $page) {
723 // $page MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
724 $mountPointInfo = $this->getMountPointInfo($page['uid'], $page);
726 // There is a valid mount point.
727 if (is_array($mountPointInfo) && $mountPointInfo['overlay']) {
729 // Using "getPage" is OK since we need the check for enableFields AND for type 2
730 // of mount pids we DO require a doktype < 200!
731 $mountPointPage = $this->getPage($mountPointInfo['mount_pid']);
733 if (!empty($mountPointPage)) {
734 $page = $mountPointPage;
735 $page['_MP_PARAM'] = $mountPointInfo['MPvar'];
744 * If shortcut, look up if the target exists and is currently visible
746 * @param array $page The page to check
747 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
750 protected function checkValidShortcutOfPage(array $page, $additionalWhereClause) {
755 $dokType = (int)$page['doktype'];
756 $shortcutMode = (int)$page['shortcut_mode'];
758 if ($dokType === self
::DOKTYPE_SHORTCUT
&& ($page['shortcut'] ||
$shortcutMode)) {
759 if ($shortcutMode === self
::SHORTCUT_MODE_NONE
) {
760 // No shortcut_mode set, so target is directly set in $page['shortcut']
761 $searchField = 'uid';
762 $searchUid = (int)$page['shortcut'];
763 } elseif ($shortcutMode === self
::SHORTCUT_MODE_FIRST_SUBPAGE ||
$shortcutMode === self
::SHORTCUT_MODE_RANDOM_SUBPAGE
) {
764 // Check subpages - first subpage or random subpage
765 $searchField = 'pid';
766 // If a shortcut mode is set and no valid page is given to select subpags
767 // from use the actual page.
768 $searchUid = (int)$page['shortcut'] ?
: $page['uid'];
769 } elseif ($shortcutMode === self
::SHORTCUT_MODE_PARENT_PAGE
) {
770 // Shortcut to parent page
771 $searchField = 'uid';
772 $searchUid = $page['pid'];
778 $whereStatement = $searchField . '=' . $searchUid
779 . $this->where_hid_del
780 . $this->where_groupAccess
781 . ' ' . $additionalWhereClause;
783 $count = $this->getDatabaseConnection()->exec_SELECTcountRows(
792 } elseif ($dokType === self
::DOKTYPE_SHORTCUT
) {
793 // Neither shortcut target nor mode is set. Remove the page from the menu.
799 * Will find the page carrying the domain record matching the input domain.
800 * Might exit after sending a redirect-header IF a found domain record
801 * instructs to do so.
803 * @param string $domain Domain name to search for. Eg. "www.typo3.com". Typical the HTTP_HOST value.
804 * @param string $path Path for the current script in domain. Eg. "/somedir/subdir". Typ. supplied by \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('SCRIPT_NAME')
805 * @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')
806 * @return mixed If found, returns integer with page UID where found. Otherwise blank. Might exit if location-header is sent, see description.
807 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::findDomainRecord()
809 public function getDomainStartPage($domain, $path = '', $request_uri = '') {
810 $domain = explode(':', $domain);
811 $domain = strtolower(preg_replace('/\\.$/', '', $domain[0]));
812 // Removing extra trailing slashes
813 $path = trim(preg_replace('/\\/[^\\/]*$/', '', $path));
814 // Appending to domain string
816 $domain = preg_replace('/\\/*$/', '', $domain);
817 $res = $this->getDatabaseConnection()->exec_SELECTquery('pages.uid,sys_domain.redirectTo,sys_domain.redirectHttpStatusCode,sys_domain.prepend_params', 'pages,sys_domain', 'pages.uid=sys_domain.pid
818 AND sys_domain.hidden=0
819 AND (sys_domain.domainName=' . $this->getDatabaseConnection()->fullQuoteStr($domain, 'sys_domain') . ' OR sys_domain.domainName=' . $this->getDatabaseConnection()->fullQuoteStr(($domain . '/'), 'sys_domain') . ') ' . $this->where_hid_del
. $this->where_groupAccess
, '', '', 1);
820 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
821 $this->getDatabaseConnection()->sql_free_result($res);
823 if ($row['redirectTo']) {
824 $redirectUrl = $row['redirectTo'];
825 if ($row['prepend_params']) {
826 $redirectUrl = rtrim($redirectUrl, '/');
827 $prependStr = ltrim(substr($request_uri, strlen($path)), '/');
828 $redirectUrl .= '/' . $prependStr;
830 $statusCode = (int)$row['redirectHttpStatusCode'];
831 if ($statusCode && defined(HttpUtility
::class . '::HTTP_STATUS_' . $statusCode)) {
832 HttpUtility
::redirect($redirectUrl, constant(HttpUtility
::class . '::HTTP_STATUS_' . $statusCode));
834 HttpUtility
::redirect($redirectUrl, HttpUtility
::HTTP_STATUS_301
);
845 * Returns array with fields of the pages from here ($uid) and back to the root
847 * NOTICE: This function only takes deleted pages into account! So hidden,
848 * starttime and endtime restricted pages are included no matter what.
850 * Further: If any "recycler" page is found (doktype=255) then it will also block
853 * If you want more fields in the rootline records than default such can be added
854 * by listing them in $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']
856 * @param int $uid The page uid for which to seek back to the page tree root.
857 * @param string $MP Commalist of MountPoint parameters, eg. "1-2,3-4" etc. Normally this value comes from the GET var, MP
858 * @param bool $ignoreMPerrors If set, some errors related to Mount Points in root line are ignored.
860 * @throws \RuntimeException
861 * @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.
862 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageAndRootline()
864 public function getRootLine($uid, $MP = '', $ignoreMPerrors = FALSE) {
865 $rootline = GeneralUtility
::makeInstance(RootlineUtility
::class, $uid, $MP, $this);
867 return $rootline->get();
868 } catch (\RuntimeException
$ex) {
869 if ($ignoreMPerrors) {
870 $this->error_getRootLine
= $ex->getMessage();
871 if (substr($this->error_getRootLine
, -7) === 'uid -1.') {
872 $this->error_getRootLine_failPid
= -1;
875 /** @see \TYPO3\CMS\Core\Utility\RootlineUtility::getRecordArray */
876 } elseif ($ex->getCode() === 1343589451) {
884 * Creates a "path" string for the input root line array titles.
885 * Used for writing statistics.
887 * @param array $rl A rootline array!
888 * @param int $len The max length of each title from the rootline.
889 * @return string The path in the form "/page title/This is another pageti.../Another page
890 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
892 public function getPathFromRootline($rl, $len = 20) {
896 for ($a = 0; $a < $c; $a++
) {
897 if ($rl[$a]['uid']) {
898 $path .= '/' . GeneralUtility
::fixed_lgd_cs(strip_tags($rl[$a]['title']), $len);
906 * Returns the URL type for the input page row IF the doktype is 3 and not
909 * @param array $pagerow The page row to return URL type for
910 * @param bool $disable A flag to simply disable any output from here. - deprecated - don't use anymore.
911 * @return string|bool The URL type from $this->urltypes array. False if not found or disabled.
912 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::setExternalJumpUrl()
914 public function getExtURL($pagerow, $disable = FALSE) {
915 if ($disable !== FALSE) {
916 GeneralUtility
::deprecationLog('The disable option of PageRepository::getExtUrl() is deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8.');
919 if ((int)$pagerow['doktype'] === self
::DOKTYPE_LINK
) {
920 $redirectTo = $this->urltypes
[$pagerow['urltype']] . $pagerow['url'];
921 // If relative path, prefix Site URL:
922 $uI = parse_url($redirectTo);
923 // Relative path assumed now.
924 if (!$uI['scheme'] && $redirectTo[0] !== '/') {
925 $redirectTo = GeneralUtility
::getIndpEnv('TYPO3_SITE_URL') . $redirectTo;
933 * Returns MountPoint id for page
935 * Does a recursive search if the mounted page should be a mount page itself. It
936 * has a run-away break so it can't go into infinite loops.
938 * @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...)
939 * @param array|bool $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
940 * @param array $prevMountPids Array accumulating formerly tested page ids for mount points. Used for recursivity brake.
941 * @param int $firstPageUid The first page id.
942 * @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.
943 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
945 public function getMountPointInfo($pageId, $pageRec = FALSE, $prevMountPids = array(), $firstPageUid = 0) {
947 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
948 if (isset($this->cache_getMountPointInfo
[$pageId])) {
949 return $this->cache_getMountPointInfo
[$pageId];
951 // Get pageRec if not supplied:
952 if (!is_array($pageRec)) {
953 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol,t3ver_state', 'pages', 'uid=' . (int)$pageId . ' AND pages.deleted=0 AND pages.doktype<>255');
954 $pageRec = $this->getDatabaseConnection()->sql_fetch_assoc($res);
955 $this->getDatabaseConnection()->sql_free_result($res);
956 // Only look for version overlay if page record is not supplied; This assumes
957 // that the input record is overlaid with preview version, if any!
958 $this->versionOL('pages', $pageRec);
960 // Set first Page uid:
961 if (!$firstPageUid) {
962 $firstPageUid = $pageRec['uid'];
964 // Look for mount pid value plus other required circumstances:
965 $mount_pid = (int)$pageRec['mount_pid'];
966 if (is_array($pageRec) && (int)$pageRec['doktype'] === self
::DOKTYPE_MOUNTPOINT
&& $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, TRUE)) {
967 // Get the mount point record (to verify its general existence):
968 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol,t3ver_state', 'pages', 'uid=' . $mount_pid . ' AND pages.deleted=0 AND pages.doktype<>255');
969 $mountRec = $this->getDatabaseConnection()->sql_fetch_assoc($res);
970 $this->getDatabaseConnection()->sql_free_result($res);
971 $this->versionOL('pages', $mountRec);
972 if (is_array($mountRec)) {
973 // Look for recursive mount point:
974 $prevMountPids[] = $mount_pid;
975 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
976 // Return mount point information:
977 $result = $recursiveMountPid ?
: array(
978 'mount_pid' => $mount_pid,
979 'overlay' => $pageRec['mount_pid_ol'],
980 'MPvar' => $mount_pid . '-' . $firstPageUid,
981 'mount_point_rec' => $pageRec,
982 'mount_pid_rec' => $mountRec
985 // Means, there SHOULD have been a mount point, but there was none!
990 $this->cache_getMountPointInfo
[$pageId] = $result;
994 /********************************
996 * Selecting records in general
998 ********************************/
1001 * Checks if a record exists and is accessible.
1002 * The row is returned if everything's OK.
1004 * @param string $table The table name to search
1005 * @param int $uid The uid to look up in $table
1006 * @param bool|int $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
1007 * @return array|int Returns array (the record) if OK, otherwise blank/0 (zero)
1009 public function checkRecord($table, $uid, $checkPage = 0) {
1011 if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1012 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', $table, 'uid = ' . $uid . $this->enableFields($table));
1013 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
1014 $this->getDatabaseConnection()->sql_free_result($res);
1016 $this->versionOL($table, $row);
1017 if (is_array($row)) {
1019 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid', 'pages', 'uid=' . (int)$row['pid'] . $this->enableFields('pages'));
1020 $numRows = $this->getDatabaseConnection()->sql_num_rows($res);
1021 $this->getDatabaseConnection()->sql_free_result($res);
1037 * Returns record no matter what - except if record is deleted
1039 * @param string $table The table name to search
1040 * @param int $uid The uid to look up in $table
1041 * @param string $fields The fields to select, default is "*
1042 * @param bool $noWSOL If set, no version overlay is applied
1043 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
1044 * @see getPage_noCheck()
1046 public function getRawRecord($table, $uid, $fields = '*', $noWSOL = FALSE) {
1048 if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1049 $res = $this->getDatabaseConnection()->exec_SELECTquery($fields, $table, 'uid = ' . $uid . $this->deleteClause($table));
1050 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
1051 $this->getDatabaseConnection()->sql_free_result($res);
1054 $this->versionOL($table, $row);
1056 if (is_array($row)) {
1065 * Selects records based on matching a field (ei. other than UID) with a value
1067 * @param string $theTable The table name to search, eg. "pages" or "tt_content
1068 * @param string $theField The fieldname to match, eg. "uid" or "alias
1069 * @param string $theValue The value that fieldname must match, eg. "123" or "frontpage
1070 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
1071 * @param string $groupBy Optional GROUP BY field(s). If none, supply blank string.
1072 * @param string $orderBy Optional ORDER BY field(s). If none, supply blank string.
1073 * @param string $limit Optional LIMIT value ([begin,]max). If none, supply blank string.
1074 * @return mixed Returns array (the record) if found, otherwise nothing (void)
1076 public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
1077 if (is_array($GLOBALS['TCA'][$theTable])) {
1078 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', $theTable, $theField . '=' . $this->getDatabaseConnection()->fullQuoteStr($theValue, $theTable) . $this->deleteClause($theTable) . ' ' . $whereClause, $groupBy, $orderBy, $limit);
1080 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
1081 if (is_array($row)) {
1085 $this->getDatabaseConnection()->sql_free_result($res);
1086 if (!empty($rows)) {
1093 /********************************
1095 * Caching and standard clauses
1097 ********************************/
1100 * Returns data stored for the hash string in the cache "cache_hash"
1101 * Can be used to retrieved a cached value, array or object
1102 * Can be used from your frontend plugins if you like. It is also used to
1103 * store the parsed TypoScript template structures. You can call it directly
1104 * like PageRepository::getHash()
1106 * @param string $hash The hash-string which was used to store the data value
1107 * @return mixed The "data" from the cache
1108 * @see tslib_TStemplate::start(), storeHash()
1110 static public function getHash($hash) {
1111 $hashContent = NULL;
1112 /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $contentHashCache */
1113 $contentHashCache = GeneralUtility
::makeInstance(CacheManager
::class)->getCache('cache_hash');
1114 $cacheEntry = $contentHashCache->get($hash);
1116 $hashContent = $cacheEntry;
1118 return $hashContent;
1122 * Stores $data in the 'cache_hash' cache with the hash key, $hash
1123 * and visual/symbolic identification, $ident
1125 * Can be used from your frontend plugins if you like. You can call it
1126 * directly like PageRepository::storeHash()
1128 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1129 * @param mixed $data The data to store
1130 * @param string $ident Is just a textual identification in order to inform about the content!
1131 * @param int $lifetime The lifetime for the cache entry in seconds
1133 * @see tslib_TStemplate::start(), getHash()
1135 static public function storeHash($hash, $data, $ident, $lifetime = 0) {
1136 GeneralUtility
::makeInstance(CacheManager
::class)->getCache('cache_hash')->set($hash, $data, array('ident_' . $ident), (int)$lifetime);
1140 * Returns the "AND NOT deleted" clause for the tablename given IF
1141 * $GLOBALS['TCA'] configuration points to such a field.
1143 * @param string $table Tablename
1145 * @see enableFields()
1147 public function deleteClause($table) {
1148 return $GLOBALS['TCA'][$table]['ctrl']['delete'] ?
' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0' : '';
1152 * Returns a part of a WHERE clause which will filter out records with start/end
1153 * times or hidden/fe_groups fields set to values that should de-select them
1154 * according to the current time, preview settings or user login. Definitely a
1155 * frontend function.
1157 * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1158 * determines for each table which of these features applies to that table.
1160 * @param string $table Table name found in the $GLOBALS['TCA'] array
1161 * @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.
1162 * @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.
1163 * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
1164 * @throws \InvalidArgumentException
1165 * @return string The clause starting like " AND ...=... AND ...=...
1166 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields(), deleteClause()
1168 public function enableFields($table, $show_hidden = -1, $ignore_array = array(), $noVersionPreview = FALSE) {
1169 if ($show_hidden === -1 && is_object($this->getTypoScriptFrontendController())) {
1170 // If show_hidden was not set from outside and if TSFE is an object, set it
1171 // based on showHiddenPage and showHiddenRecords from TSFE
1172 $show_hidden = $table === 'pages' ?
$this->getTypoScriptFrontendController()->showHiddenPage
: $this->getTypoScriptFrontendController()->showHiddenRecords
;
1174 if ($show_hidden === -1) {
1177 // If show_hidden was not changed during the previous evaluation, do it here.
1178 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
1180 if (is_array($ctrl)) {
1181 // Delete field check:
1182 if ($ctrl['delete']) {
1183 $query .= ' AND ' . $table . '.' . $ctrl['delete'] . '=0';
1185 if ($ctrl['versioningWS']) {
1186 if (!$this->versioningPreview
) {
1187 // Filter out placeholder records (new/moved/deleted items)
1188 // in case we are NOT in a versioning preview (that means we are online!)
1189 $query .= ' AND ' . $table . '.t3ver_state<=' . new VersionState(VersionState
::DEFAULT_STATE
);
1190 } elseif ($table !== 'pages') {
1191 // show only records of live and of the current workspace
1192 // in case we are in a versioning preview
1193 $query .= ' AND (' .
1194 $table . '.t3ver_wsid=0 OR ' .
1195 $table . '.t3ver_wsid=' . (int)$this->versioningWorkspaceId
.
1199 // Filter out versioned records
1200 if (!$noVersionPreview && empty($ignore_array['pid'])) {
1201 $query .= ' AND ' . $table . '.pid<>-1';
1206 if (is_array($ctrl['enablecolumns'])) {
1207 // In case of versioning-preview, enableFields are ignored (checked in
1209 if (!$this->versioningPreview ||
!$ctrl['versioningWS'] ||
$noVersionPreview) {
1210 if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
1211 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1212 $query .= ' AND ' . $field . '=0';
1214 if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
1215 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1216 $query .= ' AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'];
1218 if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
1219 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1220 $query .= ' AND (' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
1222 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1223 $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1224 $query .= $this->getMultipleGroupsWhereClause($field, $table);
1226 // Call hook functions for additional enableColumns
1227 // It is used by the extension ingmar_accessctrl which enables assigning more
1228 // than one usergroup to content and page records
1229 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'])) {
1232 'show_hidden' => $show_hidden,
1233 'ignore_array' => $ignore_array,
1236 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] as $_funcRef) {
1237 $query .= GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1243 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);
1249 * Creating where-clause for checking group access to elements in enableFields
1252 * @param string $field Field with group list
1253 * @param string $table Table name
1254 * @return string AND sql-clause
1255 * @see enableFields()
1257 public function getMultipleGroupsWhereClause($field, $table) {
1258 $memberGroups = GeneralUtility
::intExplode(',', $this->getTypoScriptFrontendController()->gr_list
);
1259 $orChecks = array();
1260 // If the field is empty, then OK
1261 $orChecks[] = $field . '=\'\'';
1262 // If the field is NULL, then OK
1263 $orChecks[] = $field . ' IS NULL';
1264 // If the field contsains zero, then OK
1265 $orChecks[] = $field . '=\'0\'';
1266 foreach ($memberGroups as $value) {
1267 $orChecks[] = $this->getDatabaseConnection()->listQuery($field, $value, $table);
1269 return ' AND (' . implode(' OR ', $orChecks) . ')';
1272 /**********************
1274 * Versioning Preview
1276 **********************/
1279 * Finding online PID for offline version record
1281 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1282 * served which is not previewed by backend users!!!
1284 * Will look if the "pid" value of the input record is -1 (it is an offline
1285 * version) and if the table supports versioning; if so, it will translate the -1
1286 * PID into the PID of the original record.
1288 * Used whenever you are tracking something back, like making the root line.
1290 * Principle; Record offline! => Find online?
1292 * @param string $table Table name
1293 * @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.
1294 * @return void (Passed by ref).
1295 * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1297 public function fixVersioningPid($table, &$rr) {
1298 if ($this->versioningPreview
&& is_array($rr) && (int)$rr['pid'] === -1 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1301 // Have to hardcode it for "pages" table since TCA is not loaded at this moment!
1302 // Check values for t3ver_oid and t3ver_wsid:
1303 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1304 // If "t3ver_oid" is already a field, just set this:
1305 $oid = $rr['t3ver_oid'];
1306 $wsid = $rr['t3ver_wsid'];
1308 // Otherwise we have to expect "uid" to be in the record and look up based
1310 $newPidRec = $this->getRawRecord($table, $rr['uid'], 't3ver_oid,t3ver_wsid', TRUE);
1311 if (is_array($newPidRec)) {
1312 $oid = $newPidRec['t3ver_oid'];
1313 $wsid = $newPidRec['t3ver_wsid'];
1316 // If workspace ids matches and ID of current online version is found, look up
1317 // the PID value of that:
1318 if ($oid && ((int)$this->versioningWorkspaceId
=== 0 && $this->checkWorkspaceAccess($wsid) ||
(int)$wsid === (int)$this->versioningWorkspaceId
)) {
1319 $oidRec = $this->getRawRecord($table, $oid, 'pid', TRUE);
1320 if (is_array($oidRec)) {
1321 // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1322 // assumed that this is a "branch" type page and therefore the uid should be
1323 // kept (like in versionOL()). However if the page is NOT a branch version it
1324 // should not happen - but then again, direct access to that uid should not
1326 $rr['_ORIG_pid'] = $rr['pid'];
1327 $rr['pid'] = $oidRec['pid'];
1331 // Changing PID in case of moving pointer:
1332 if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1333 $rr['pid'] = $movePlhRec['pid'];
1338 * Versioning Preview Overlay
1340 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1341 * served which is not previewed by backend users!!!
1343 * Generally ALWAYS used when records are selected based on uid or pid. If
1344 * records are selected on other fields than uid or pid (eg. "email = ....") then
1345 * usage might produce undesired results and that should be evaluated on
1348 * Principle; Record online! => Find offline?
1350 * @param string $table Table name
1351 * @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!
1352 * @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)
1353 * @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!
1354 * @return void (Passed by ref).
1355 * @see fixVersioningPid(), BackendUtility::workspaceOL()
1357 public function versionOL($table, &$row, $unsetMovePointers = FALSE, $bypassEnableFieldsCheck = FALSE) {
1358 if ($this->versioningPreview
&& is_array($row)) {
1359 // will overlay any movePlhOL found with the real record, which in turn
1360 // will be overlaid with its workspace version if any.
1361 $movePldSwap = $this->movePlhOL($table, $row);
1362 // implode(',',array_keys($row)) = Using fields from original record to make
1363 // sure no additional fields are selected. This is best for eg. getPageOverlay()
1364 // Computed properties are excluded since those would lead to SQL errors.
1365 $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1366 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId
, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1367 if (is_array($wsAlt)) {
1368 // Always fix PID (like in fixVersioningPid() above). [This is usually not
1369 // the important factor for versioning OL]
1370 // Keep the old (-1) - indicates it was a version...
1371 $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1372 // Set in the online versions PID.
1373 $wsAlt['pid'] = $row['pid'];
1374 // For versions of single elements or page+content, preserve online UID and PID
1375 // (this will produce true "overlay" of element _content_, not any references)
1376 // For page+content the "_ORIG_uid" should actually be used as PID for selection
1377 // of tables with "versioning_followPages" enabled.
1378 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1379 $wsAlt['uid'] = $row['uid'];
1380 // Translate page alias as well so links are pointing to the _online_ page:
1381 if ($table === 'pages') {
1382 $wsAlt['alias'] = $row['alias'];
1384 // Changing input record to the workspace version alternative:
1386 // Check if it is deleted/new
1387 $rowVersionState = VersionState
::cast($row['t3ver_state']);
1389 $rowVersionState->equals(VersionState
::NEW_PLACEHOLDER
)
1390 ||
$rowVersionState->equals(VersionState
::DELETE_PLACEHOLDER
)
1392 // Unset record if it turned out to be deleted in workspace
1395 // Check if move-pointer in workspace (unless if a move-placeholder is the
1396 // reason why it appears!):
1397 // You have to specifically set $unsetMovePointers in order to clear these
1398 // because it is normally a display issue if it should be shown or not.
1400 ($rowVersionState->equals(VersionState
::MOVE_POINTER
)
1402 ) && $unsetMovePointers
1404 // Unset record if it turned out to be deleted in workspace
1408 // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1409 // (online version is dummy-representation)
1410 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1411 // enablefields for BOTH the version AND the online record deselects it. See
1412 // note for $bypassEnableFieldsCheck
1413 /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1414 $versionState = VersionState
::cast($row['t3ver_state']);
1415 if ($wsAlt <= -1 ||
$versionState->indicatesPlaceholder()) {
1416 // Unset record if it turned out to be "hidden"
1425 * Checks if record is a move-placeholder
1426 * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1427 * the pointed-to live record (and return TRUE) Used from versionOL
1429 * @param string $table Table name
1430 * @param array $row Row (passed by reference) - only online records...
1431 * @return bool TRUE if overlay is made.
1432 * @see BackendUtility::movePlhOl()
1434 public function movePlhOL($table, &$row) {
1435 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2
1436 && (int)VersionState
::cast($row['t3ver_state'])->equals(VersionState
::MOVE_PLACEHOLDER
)
1438 // Only for WS ver 2... (moving)
1439 // If t3ver_move_id is not found, then find it (but we like best if it is here)
1440 if (!isset($row['t3ver_move_id'])) {
1441 $moveIDRec = $this->getRawRecord($table, $row['uid'], 't3ver_move_id', TRUE);
1442 $moveID = $moveIDRec['t3ver_move_id'];
1444 $moveID = $row['t3ver_move_id'];
1446 // Find pointed-to record.
1448 $res = $this->getDatabaseConnection()->exec_SELECTquery(implode(',', array_keys($row)), $table, 'uid=' . (int)$moveID . $this->enableFields($table));
1449 $origRow = $this->getDatabaseConnection()->sql_fetch_assoc($res);
1450 $this->getDatabaseConnection()->sql_free_result($res);
1461 * Returns move placeholder of online (live) version
1463 * @param string $table Table name
1464 * @param int $uid Record UID of online version
1465 * @param string $fields Field list, default is *
1466 * @return array If found, the record, otherwise nothing.
1467 * @see BackendUtility::getMovePlaceholder()
1469 public function getMovePlaceholder($table, $uid, $fields = '*') {
1470 if ($this->versioningPreview
) {
1471 $workspace = (int)$this->versioningWorkspaceId
;
1472 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2 && $workspace !== 0) {
1473 // Select workspace version of record:
1474 $row = $this->getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, 'pid<>-1 AND
1475 t3ver_state=' . new VersionState(VersionState
::MOVE_PLACEHOLDER
) . ' AND
1476 t3ver_move_id=' . (int)$uid . ' AND
1477 t3ver_wsid=' . (int)$workspace . $this->deleteClause($table));
1478 if (is_array($row)) {
1487 * Select the version of a record for a workspace
1489 * @param int $workspace Workspace ID
1490 * @param string $table Table name to select from
1491 * @param int $uid Record uid for which to find workspace version.
1492 * @param string $fields Field list to select
1493 * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1494 * @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.
1495 * @see BackendUtility::getWorkspaceVersionOfRecord()
1497 public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = FALSE) {
1498 if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1499 $workspace = (int)$workspace;
1501 // Setting up enableFields for version record
1502 $enFields = $this->enableFields($table, -1, array(), TRUE);
1503 // Select workspace version of record, only testing for deleted.
1504 $newrow = $this->getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, 'pid=-1 AND
1505 t3ver_oid=' . $uid . ' AND
1506 t3ver_wsid=' . $workspace . $this->deleteClause($table));
1507 // If version found, check if it could have been selected with enableFields on
1509 if (is_array($newrow)) {
1510 if ($bypassEnableFieldsCheck ||
$this->getDatabaseConnection()->exec_SELECTgetSingleRow('uid', $table, 'pid=-1 AND
1511 t3ver_oid=' . $uid . ' AND
1512 t3ver_wsid=' . $workspace . $enFields)) {
1513 // Return offline version, tested for its enableFields.
1516 // Return -1 because offline version was de-selected due to its enableFields.
1520 // OK, so no workspace version was found. Then check if online version can be
1521 // selected with full enable fields and if so, return 1:
1522 if ($bypassEnableFieldsCheck ||
$this->getDatabaseConnection()->exec_SELECTgetSingleRow('uid', $table, 'uid=' . $uid . $enFields)) {
1523 // Means search was done, but no version found.
1526 // Return -2 because the online record was de-selected due to its enableFields.
1531 // No look up in database because versioning not enabled / or workspace not
1537 * Checks if user has access to workspace.
1539 * @param int $wsid Workspace ID
1540 * @return bool <code>TRUE</code> if has access
1542 public function checkWorkspaceAccess($wsid) {
1543 if (!$this->getBackendUser() ||
!ExtensionManagementUtility
::isLoaded('workspaces')) {
1546 if (isset($this->workspaceCache
[$wsid])) {
1547 $ws = $this->workspaceCache
[$wsid];
1550 // No $GLOBALS['TCA'] yet!
1551 $ws = $this->getDatabaseConnection()->exec_SELECTgetSingleRow('*', 'sys_workspace', 'uid=' . (int)$wsid . ' AND deleted=0');
1552 if (!is_array($ws)) {
1558 $ws = $this->getBackendUser()->checkWorkspace($ws);
1559 $this->workspaceCache
[$wsid] = $ws;
1561 return (string)$ws['_ACCESS'] !== '';
1565 * Gets file references for a given record field.
1567 * @param string $tableName Name of the table
1568 * @param string $fieldName Name of the field
1569 * @param array $element The parent element referencing to files
1572 public function getFileReferences($tableName, $fieldName, array $element) {
1573 /** @var $fileRepository FileRepository */
1574 $fileRepository = GeneralUtility
::makeInstance(FileRepository
::class);
1575 $currentId = !empty($element['uid']) ?
$element['uid'] : 0;
1577 // Fetch the references of the default element
1578 $references = $fileRepository->findByRelation($tableName, $fieldName, $currentId);
1580 $localizedId = NULL;
1581 if (isset($element['_LOCALIZED_UID'])) {
1582 $localizedId = $element['_LOCALIZED_UID'];
1583 } elseif (isset($element['_PAGES_OVERLAY_UID'])) {
1584 $localizedId = $element['_PAGES_OVERLAY_UID'];
1587 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['transForeignTable'])) {
1588 $tableName = $GLOBALS['TCA'][$tableName]['ctrl']['transForeignTable'];
1591 $isTableLocalizable = (
1592 !empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1593 && !empty($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1595 if ($isTableLocalizable && $localizedId !== NULL) {
1596 $localizedReferences = $fileRepository->findByRelation($tableName, $fieldName, $localizedId);
1597 $localizedReferencesValue = $localizedReferences ?
: '';
1598 if ($this->shouldFieldBeOverlaid($tableName, $fieldName, $localizedReferencesValue)) {
1599 $references = $localizedReferences;
1607 * Purges computed properties from database rows,
1608 * such as _ORIG_uid or _ORIG_pid for instance.
1613 protected function purgeComputedProperties(array $row) {
1614 foreach ($this->computedPropertyNames
as $computedPropertyName) {
1615 if (array_key_exists($computedPropertyName, $row)) {
1616 unset($row[$computedPropertyName]);
1623 * Determine if a field needs an overlay
1625 * @param string $table TCA tablename
1626 * @param string $field TCA fieldname
1627 * @param mixed $value Current value of the field
1628 * @return bool Returns TRUE if a given record field needs to be overlaid
1630 protected function shouldFieldBeOverlaid($table, $field, $value) {
1631 $l10n_mode = isset($GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode'])
1632 ?
$GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode']
1635 $shouldFieldBeOverlaid = TRUE;
1637 if ($l10n_mode === 'exclude') {
1638 $shouldFieldBeOverlaid = FALSE;
1639 } elseif ($l10n_mode === 'mergeIfNotBlank') {
1640 $checkValue = $value;
1642 // 0 values are considered blank when coming from a group field
1643 if (empty($value) && $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'group') {
1647 if ($checkValue === array() ||
!is_array($checkValue) && trim($checkValue) === '') {
1648 $shouldFieldBeOverlaid = FALSE;
1652 return $shouldFieldBeOverlaid;
1656 * Returns the database connection
1658 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1660 protected function getDatabaseConnection() {
1661 return $GLOBALS['TYPO3_DB'];
1665 * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
1667 protected function getTypoScriptFrontendController() {
1668 return $GLOBALS['TSFE'];
1672 * Returns the current BE user.
1674 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1676 protected function getBackendUser() {
1677 return $GLOBALS['BE_USER'];