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 Psr\Log\LoggerAwareInterface
;
18 use Psr\Log\LoggerAwareTrait
;
19 use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait
;
20 use TYPO3\CMS\Core\Database\Connection
;
21 use TYPO3\CMS\Core\Database\ConnectionPool
;
22 use TYPO3\CMS\Core\Database\Query\QueryHelper
;
23 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction
;
24 use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer
;
25 use TYPO3\CMS\Core\Database\Query\Restriction\FrontendWorkspaceRestriction
;
26 use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException
;
27 use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException
;
28 use TYPO3\CMS\Core\Resource\FileRepository
;
29 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility
;
30 use TYPO3\CMS\Core\Utility\GeneralUtility
;
31 use TYPO3\CMS\Core\Utility\RootlineUtility
;
32 use TYPO3\CMS\Core\Versioning\VersionState
;
35 * Page functions, a lot of sql/pages-related functions
37 * Mainly used in the frontend but also in some cases in the backend. It's
38 * important to set the right $where_hid_del in the object so that the
39 * functions operate properly
40 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
42 class PageRepository
implements LoggerAwareInterface
45 use PublicPropertyDeprecationTrait
;
48 * List of all deprecated public properties
51 protected $deprecatedPublicProperties = [
52 'versioningPreview' => 'Using $versioningPreview of class PageRepository is discouraged, just use versioningWorkspaceId to determine if a workspace should be previewed.',
53 'workspaceCache' => 'Using $workspaceCache of class PageRepository from the outside is discouraged, as this only reflects a local runtime cache.',
54 'error_getRootLine' => 'Using $error_getRootLine of class PageRepository from the outside is deprecated as this property only exists for legacy reasons.',
55 'error_getRootLine_failPid' => 'Using $error_getRootLine_failPid of class PageRepository from the outside is deprecated as this property only exists for legacy reasons.',
59 * This is not the final clauses. There will normally be conditions for the
60 * hidden, starttime and endtime fields as well. You MUST initialize the object
61 * by the init() function
65 public $where_hid_del = ' AND pages.deleted=0';
68 * Clause for fe_group access
72 public $where_groupAccess = '';
77 public $sys_language_uid = 0;
80 * If TRUE, versioning preview of other record versions is allowed. THIS MUST
81 * ONLY BE SET IF the page is not cached and truly previewed by a backend
85 * @deprecated since TYPO3 v9.3, will be removed in TYPO3 v10. As $versioningWorkspaceId now indicates what records to fetch.
87 protected $versioningPreview = false
;
90 * Workspace ID for preview
91 * If > 0, versioning preview of other record versions is allowed. THIS MUST
92 * ONLY BE SET IF the page is not cached and truly previewed by a backend
97 public $versioningWorkspaceId = 0;
102 protected $workspaceCache = [];
105 * Error string set by getRootLine()
109 protected $error_getRootLine = '';
112 * Error uid set by getRootLine()
116 protected $error_getRootLine_failPid = 0;
121 protected $cache_getPage = [];
126 protected $cache_getPage_noCheck = [];
131 protected $cache_getPageIdFromAlias = [];
136 protected $cache_getMountPointInfo = [];
141 protected $tableNamesAllowedOnRootLevel = [
147 * Computed properties that are added to database rows.
151 protected $computedPropertyNames = [
157 '_PAGES_OVERLAY_UID',
158 '_PAGES_OVERLAY_LANGUAGE',
162 * Named constants for "magic numbers" of the field doktype
164 const DOKTYPE_DEFAULT
= 1;
165 const DOKTYPE_LINK
= 3;
166 const DOKTYPE_SHORTCUT
= 4;
167 const DOKTYPE_BE_USER_SECTION
= 6;
168 const DOKTYPE_MOUNTPOINT
= 7;
169 const DOKTYPE_SPACER
= 199;
170 const DOKTYPE_SYSFOLDER
= 254;
171 const DOKTYPE_RECYCLER
= 255;
174 * Named constants for "magic numbers" of the field shortcut_mode
176 const SHORTCUT_MODE_NONE
= 0;
177 const SHORTCUT_MODE_FIRST_SUBPAGE
= 1;
178 const SHORTCUT_MODE_RANDOM_SUBPAGE
= 2;
179 const SHORTCUT_MODE_PARENT_PAGE
= 3;
182 * init() MUST be run directly after creating a new template-object
183 * This sets the internal variable $this->where_hid_del to the correct where
184 * clause for page records taking deleted/hidden/starttime/endtime/t3ver_state
187 * @param bool $show_hidden If $show_hidden is TRUE, the hidden-field is ignored!! Normally this should be FALSE. Is used for previewing.
188 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id(), \TYPO3\CMS\Tstemplate\Controller\TemplateAnalyzerModuleFunctionController::initialize_editor()
190 public function init($show_hidden)
192 $this->where_groupAccess
= '';
194 if ($this->versioningWorkspaceId
) {
195 // For version previewing, make sure that enable-fields are not
196 // de-selecting hidden pages - we need versionOL() to unset them only
197 // if the overlay record instructs us to.
198 // Clear where_hid_del and restrict to live and current workspaces
199 $expressionBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
200 ->getQueryBuilderForTable('pages')
202 $this->where_hid_del
= ' AND ' . $expressionBuilder->andX(
203 $expressionBuilder->eq('pages.deleted', 0),
204 $expressionBuilder->orX(
205 $expressionBuilder->eq('pages.t3ver_wsid', 0),
206 $expressionBuilder->eq('pages.t3ver_wsid', (int)$this->versioningWorkspaceId
)
210 // add starttime / endtime, and check for hidden/deleted
211 // Filter out new/deleted place-holder pages in case we are NOT in a
212 // versioning preview (that means we are online!)
213 $this->where_hid_del
= $this->enableFields('pages', $show_hidden, ['fe_group' => true
], true
);
215 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self
::class]['init'] ?? false
)) {
216 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self
::class]['init'] as $classRef) {
217 $hookObject = GeneralUtility
::makeInstance($classRef);
218 if (!$hookObject instanceof PageRepositoryInitHookInterface
) {
219 throw new \
UnexpectedValueException($classRef . ' must implement interface ' . PageRepositoryInitHookInterface
::class, 1379579812);
221 $hookObject->init_postProcess($this);
226 /**************************
228 * Selecting page records
230 **************************/
233 * Loads the full page record for the given page ID.
235 * The page record is either served from a first-level cache or loaded from the
236 * database. If no page can be found, an empty array is returned.
238 * Language overlay and versioning overlay are applied. Mount Point
239 * handling is not done, an overlaid Mount Point is not replaced.
241 * The result is conditioned by the public properties where_groupAccess
242 * and where_hid_del that are preset by the init() method.
244 * @see PageRepository::where_groupAccess
245 * @see PageRepository::where_hid_del
246 * @see PageRepository::init()
248 * By default the usergroup access check is enabled. Use the second method argument
249 * to disable the usergroup access check.
251 * The given UID can be preprocessed by registering a hook class that is
252 * implementing the PageRepositoryGetPageHookInterface into the configuration array
253 * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'].
255 * @param int $uid The page id to look up
256 * @param bool $disableGroupAccessCheck set to true to disable group access check
257 * @return array The resulting page record with overlays or empty array
258 * @throws \UnexpectedValueException
259 * @see PageRepository::getPage_noCheck()
261 public function getPage($uid, $disableGroupAccessCheck = false
)
263 // Hook to manipulate the page uid for special overlay handling
264 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'] ??
[] as $className) {
265 $hookObject = GeneralUtility
::makeInstance($className);
266 if (!$hookObject instanceof PageRepositoryGetPageHookInterface
) {
267 throw new \
UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageHookInterface
::class, 1251476766);
269 $hookObject->getPage_preProcess($uid, $disableGroupAccessCheck, $this);
275 $disableGroupAccessCheck ?
'' : $this->where_groupAccess
,
276 $this->where_hid_del
,
277 $this->sys_language_uid
281 if (is_array($this->cache_getPage
[$uid][$cacheKey])) {
282 return $this->cache_getPage
[$uid][$cacheKey];
285 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
286 $queryBuilder->getRestrictions()->removeAll();
287 $queryBuilder->select('*')
290 $queryBuilder->expr()->eq('uid', (int)$uid),
291 QueryHelper
::stripLogicalOperatorPrefix($this->where_hid_del
)
294 if (!$disableGroupAccessCheck) {
295 $queryBuilder->andWhere(QueryHelper
::stripLogicalOperatorPrefix($this->where_groupAccess
));
298 $row = $queryBuilder->execute()->fetch();
300 $this->versionOL('pages', $row);
301 if (is_array($row)) {
302 $result = $this->getPageOverlay($row);
305 $this->cache_getPage
[$uid][$cacheKey] = $result;
310 * Return the $row for the page with uid = $uid WITHOUT checking for
311 * ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
313 * @param int $uid The page id to look up
314 * @return array The page row with overlaid localized fields. Empty array if no page.
317 public function getPage_noCheck($uid)
319 if ($this->cache_getPage_noCheck
[$uid]) {
320 return $this->cache_getPage_noCheck
[$uid];
323 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
324 $queryBuilder->getRestrictions()
326 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
327 $row = $queryBuilder->select('*')
329 ->where($queryBuilder->expr()->eq('uid', (int)$uid))
335 $this->versionOL('pages', $row);
336 if (is_array($row)) {
337 $result = $this->getPageOverlay($row);
340 $this->cache_getPage_noCheck
[$uid] = $result;
345 * Returns the $row of the first web-page in the tree (for the default menu...)
347 * @param int $uid The page id for which to fetch first subpages (PID)
348 * @return mixed If found: The page record (with overlaid localized fields, if any). If NOT found: blank value (not array!)
349 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
351 public function getFirstWebPage($uid)
354 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
355 $queryBuilder->getRestrictions()->removeAll();
356 $row = $queryBuilder->select('*')
359 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)),
360 QueryHelper
::stripLogicalOperatorPrefix($this->where_hid_del
),
361 QueryHelper
::stripLogicalOperatorPrefix($this->where_groupAccess
)
369 $this->versionOL('pages', $row);
370 if (is_array($row)) {
371 $output = $this->getPageOverlay($row);
378 * Returns a pagerow for the page with alias $alias
380 * @param string $alias The alias to look up the page uid for.
381 * @return int Returns page uid (int) if found, otherwise 0 (zero)
382 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::checkAndSetAlias(), ContentObjectRenderer::typoLink()
384 public function getPageIdFromAlias($alias)
386 $alias = strtolower($alias);
387 if ($this->cache_getPageIdFromAlias
[$alias]) {
388 return $this->cache_getPageIdFromAlias
[$alias];
390 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
391 $queryBuilder->getRestrictions()
393 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
395 $row = $queryBuilder->select('uid')
398 $queryBuilder->expr()->eq('alias', $queryBuilder->createNamedParameter($alias, \PDO
::PARAM_STR
)),
399 // "AND pid>=0" because of versioning (means that aliases sent MUST be online!)
400 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO
::PARAM_INT
))
407 $this->cache_getPageIdFromAlias
[$alias] = $row['uid'];
410 $this->cache_getPageIdFromAlias
[$alias] = 0;
415 * Returns the relevant page overlay record fields
417 * @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 OVERLAID before the page record is returned.
418 * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
419 * @throws \UnexpectedValueException
420 * @return array Page row which is overlaid with language_overlay record (or the overlay record alone)
422 public function getPageOverlay($pageInput, $lUid = -1)
424 $rows = $this->getPagesOverlay([$pageInput], $lUid);
425 // Always an array in return
426 return $rows[0] ??
[];
430 * Returns the relevant page overlay record fields
432 * @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 OVERLAID before the page records are returned.
433 * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
434 * @throws \UnexpectedValueException
435 * @return array Page rows which are overlaid with language_overlay record.
436 * If the input was an array of integers, missing records are not
437 * included. If the input were page rows, untranslated pages
440 public function getPagesOverlay(array $pagesInput, $lUid = -1)
442 if (empty($pagesInput)) {
447 $lUid = $this->sys_language_uid
;
450 foreach ($pagesInput as &$origPage) {
451 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'] ??
[] as $className) {
452 $hookObject = GeneralUtility
::makeInstance($className);
453 if (!$hookObject instanceof PageRepositoryGetPageOverlayHookInterface
) {
454 throw new \
UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageOverlayHookInterface
::class, 1269878881);
456 $hookObject->getPageOverlay_preProcess($origPage, $lUid, $this);
460 // If language UID is different from zero, do overlay:
464 $origPage = reset($pagesInput);
465 foreach ($pagesInput as $origPage) {
466 if (is_array($origPage)) {
467 // Was the whole record
468 $page_ids[] = $origPage['uid'];
471 $page_ids[] = $origPage;
474 // NOTE regarding the query restrictions
475 // Currently the showHiddenRecords of TSFE set will allow
476 // page translation records to be selected as they are
477 // child-records of a page.
478 // However you may argue that the showHiddenField flag should
479 // determine this. But that's not how it's done right now.
480 // Selecting overlay record:
481 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
482 ->getQueryBuilderForTable('pages');
483 $queryBuilder->setRestrictions(GeneralUtility
::makeInstance(FrontendRestrictionContainer
::class));
484 $result = $queryBuilder->select('*')
487 $queryBuilder->expr()->in(
488 $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
489 $queryBuilder->createNamedParameter($page_ids, Connection
::PARAM_INT_ARRAY
)
491 $queryBuilder->expr()->eq(
492 $GLOBALS['TCA']['pages']['ctrl']['languageField'],
493 $queryBuilder->createNamedParameter($lUid, \PDO
::PARAM_INT
)
499 while ($row = $result->fetch()) {
500 $this->versionOL('pages', $row);
501 if (is_array($row)) {
502 $row['_PAGES_OVERLAY'] = true
;
503 $row['_PAGES_OVERLAY_UID'] = $row['uid'];
504 $row['_PAGES_OVERLAY_LANGUAGE'] = $lUid;
505 $origUid = $row[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
506 // Unset vital fields that are NOT allowed to be overlaid:
509 $overlays[$origUid] = $row;
515 foreach ($pagesInput as $key => $origPage) {
516 if (is_array($origPage)) {
517 $pagesOutput[$key] = $origPage;
518 if (isset($overlays[$origPage['uid']])) {
519 // Overwrite the original field with the overlay
520 foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
521 if ($fieldName !== 'uid' && $fieldName !== 'pid') {
522 $pagesOutput[$key][$fieldName] = $fieldValue;
527 if (isset($overlays[$origPage])) {
528 $pagesOutput[$key] = $overlays[$origPage];
536 * Creates language-overlay for records in general (where translation is found
537 * in records from the same table)
539 * @param string $table Table name
540 * @param array $row Record to overlay. Must contain uid, pid and $table]['ctrl']['languageField']
541 * @param int $sys_language_content Pointer to the sys_language uid for content on the site.
542 * @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned un-translated but unset (and return value is FALSE)
543 * @throws \UnexpectedValueException
544 * @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.
546 public function getRecordOverlay($table, $row, $sys_language_content, $OLmode = '')
548 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ??
[] as $className) {
549 $hookObject = GeneralUtility
::makeInstance($className);
550 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface
) {
551 throw new \
UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface
::class, 1269881658);
553 $hookObject->getRecordOverlay_preProcess($table, $row, $sys_language_content, $OLmode, $this);
555 if ($row['uid'] > 0 && ($row['pid'] > 0 ||
in_array($table, $this->tableNamesAllowedOnRootLevel
, true
))) {
556 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
557 // Return record for ALL languages untouched
558 // TODO: Fix call stack to prevent this situation in the first place
559 if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] !== -1) {
560 // Will not be able to work with other tables (Just didn't implement it yet;
561 // Requires a scan over all tables [ctrl] part for first FIND the table that
562 // carries localization information for this table (which could even be more
563 // than a single table) and then use that. Could be implemented, but obviously
564 // takes a little more....) Will try to overlay a record only if the
565 // sys_language_content value is larger than zero.
566 if ($sys_language_content > 0) {
567 // Must be default language, otherwise no overlaying
568 if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
569 // Select overlay record:
570 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
571 ->getQueryBuilderForTable($table);
572 $queryBuilder->setRestrictions(
573 GeneralUtility
::makeInstance(FrontendRestrictionContainer
::class)
575 $olrow = $queryBuilder->select('*')
578 $queryBuilder->expr()->eq(
580 $queryBuilder->createNamedParameter($row['pid'], \PDO
::PARAM_INT
)
582 $queryBuilder->expr()->eq(
583 $GLOBALS['TCA'][$table]['ctrl']['languageField'],
584 $queryBuilder->createNamedParameter($sys_language_content, \PDO
::PARAM_INT
)
586 $queryBuilder->expr()->eq(
587 $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
588 $queryBuilder->createNamedParameter($row['uid'], \PDO
::PARAM_INT
)
595 $this->versionOL($table, $olrow);
596 // Merge record content by traversing all fields:
597 if (is_array($olrow)) {
598 if (isset($olrow['_ORIG_uid'])) {
599 $row['_ORIG_uid'] = $olrow['_ORIG_uid'];
601 if (isset($olrow['_ORIG_pid'])) {
602 $row['_ORIG_pid'] = $olrow['_ORIG_pid'];
604 foreach ($row as $fN => $fV) {
605 if ($fN !== 'uid' && $fN !== 'pid' && isset($olrow[$fN])) {
606 $row[$fN] = $olrow[$fN];
607 } elseif ($fN === 'uid') {
608 $row['_LOCALIZED_UID'] = $olrow['uid'];
611 } elseif ($OLmode === 'hideNonTranslated' && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
612 // Unset, if non-translated records should be hidden. ONLY done if the source
613 // record really is default language and not [All] in which case it is allowed.
616 } elseif ($sys_language_content != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
620 // When default language is displayed, we never want to return a record carrying
622 if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
629 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ??
[] as $className) {
630 $hookObject = GeneralUtility
::makeInstance($className);
631 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface
) {
632 throw new \
UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface
::class, 1269881659);
634 $hookObject->getRecordOverlay_postProcess($table, $row, $sys_language_content, $OLmode, $this);
639 /************************************************
641 * Page related: Menu, Domain record, Root line
643 ************************************************/
646 * Returns an array with page rows for subpages of a certain page ID. This is used for menus in the frontend.
647 * If there are mount points in overlay mode the _MP_PARAM field is set to the correct MPvar.
649 * If the $pageId being input does in itself require MPvars to define a correct
650 * rootline these must be handled externally to this function.
652 * @param int|int[] $pageId The page id (or array of page ids) for which to fetch subpages (PID)
653 * @param string $fields List of fields to select. Default is "*" = all
654 * @param string $sortField The field to sort by. Default is "sorting
655 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
656 * @param bool $checkShortcuts Check if shortcuts exist, checks by default
657 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
658 * @see self::getPageShortcut(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
660 public function getMenu($pageId, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true
)
662 return $this->getSubpagesForPages((array)$pageId, $fields, $sortField, $additionalWhereClause, $checkShortcuts);
666 * Returns an array with page-rows for pages with uid in $pageIds.
668 * This is used for menus. If there are mount points in overlay mode
669 * the _MP_PARAM field is set to the correct MPvar.
671 * @param int[] $pageIds Array of page ids to fetch
672 * @param string $fields List of fields to select. Default is "*" = all
673 * @param string $sortField The field to sort by. Default is "sorting"
674 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
675 * @param bool $checkShortcuts Check if shortcuts exist, checks by default
676 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
678 public function getMenuForPages(array $pageIds, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true
)
680 return $this->getSubpagesForPages($pageIds, $fields, $sortField, $additionalWhereClause, $checkShortcuts, false
);
684 * Loads page records either by PIDs or by UIDs.
686 * By default the subpages of the given page IDs are loaded (as the method name suggests). If $parentPages is set
687 * to FALSE, the page records for the given page IDs are loaded directly.
689 * Concerning the rationale, please see these two other methods:
691 * @see PageRepository::getMenu()
692 * @see PageRepository::getMenuForPages()
694 * Version and language overlay are applied to the loaded records.
696 * If a record is a mount point in overlay mode, the the overlaying page record is returned in place of the
697 * record. The record is enriched by the field _MP_PARAM containing the mount point mapping for the mount
700 * The query can be customized by setting fields, sorting and additional WHERE clauses. If additional WHERE
701 * clauses are given, the clause must start with an operator, i.e: "AND title like '%blabla%'".
703 * The keys of the returned page records are the page UIDs.
705 * CAUTION: In case of an overlaid mount point, it is the original UID.
707 * @param int[] $pageIds PIDs or UIDs to load records for
708 * @param string $fields fields to select
709 * @param string $sortField the field to sort by
710 * @param string $additionalWhereClause optional additional WHERE clause
711 * @param bool $checkShortcuts whether to check if shortcuts exist
712 * @param bool $parentPages Switch to load pages (false) or child pages (true).
713 * @return array page records
715 * @see self::getPageShortcut()
716 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
718 protected function getSubpagesForPages(
720 string $fields = '*',
721 string $sortField = 'sorting',
722 string $additionalWhereClause = '',
723 bool
$checkShortcuts = true
,
724 bool
$parentPages = true
726 $relationField = $parentPages ?
'pid' : 'uid';
727 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
728 $queryBuilder->getRestrictions()->removeAll();
730 $res = $queryBuilder->select(...GeneralUtility
::trimExplode(',', $fields, true
))
733 $queryBuilder->expr()->in(
735 $queryBuilder->createNamedParameter($pageIds, Connection
::PARAM_INT_ARRAY
)
737 $queryBuilder->expr()->eq(
738 $GLOBALS['TCA']['pages']['ctrl']['languageField'],
739 $queryBuilder->createNamedParameter(0, \PDO
::PARAM_INT
)
741 QueryHelper
::stripLogicalOperatorPrefix($this->where_hid_del
),
742 QueryHelper
::stripLogicalOperatorPrefix($this->where_groupAccess
),
743 QueryHelper
::stripLogicalOperatorPrefix($additionalWhereClause)
746 if (!empty($sortField)) {
747 $orderBy = QueryHelper
::parseOrderBy($sortField);
748 foreach ($orderBy as $order) {
749 $res->orderBy(...$order);
752 $result = $res->execute();
755 while ($page = $result->fetch()) {
756 $originalUid = $page['uid'];
758 // Versioning Preview Overlay
759 $this->versionOL('pages', $page, true
);
760 // Skip if page got disabled due to version overlay
761 // (might be delete or move placeholder)
766 // Add a mount point parameter if needed
767 $page = $this->addMountPointParameterToPage((array)$page);
769 // If shortcut, look up if the target exists and is currently visible
770 if ($checkShortcuts) {
771 $page = $this->checkValidShortcutOfPage((array)$page, $additionalWhereClause);
774 // If the page still is there, we add it to the output
776 $pages[$originalUid] = $page;
780 // Finally load language overlays
781 return $this->getPagesOverlay($pages);
785 * Replaces the given page record with mounted page if required
787 * If the given page record is a mount point in overlay mode, the page
788 * record is replaced by the record of the overlaying page. The overlay
789 * record is enriched by setting the mount point mapping into the field
790 * _MP_PARAM as string for example '23-14'.
792 * In all other cases the given page record is returned as is.
794 * @todo Find a better name. The current doesn't hit the point.
796 * @param array $page The page record to handle.
797 * @return array The given page record or it's replacement.
799 protected function addMountPointParameterToPage(array $page): array
805 // $page MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
806 $mountPointInfo = $this->getMountPointInfo($page['uid'], $page);
808 // There is a valid mount point in overlay mode.
809 if (is_array($mountPointInfo) && $mountPointInfo['overlay']) {
811 // Using "getPage" is OK since we need the check for enableFields AND for type 2
812 // of mount pids we DO require a doktype < 200!
813 $mountPointPage = $this->getPage($mountPointInfo['mount_pid']);
815 if (!empty($mountPointPage)) {
816 $page = $mountPointPage;
817 $page['_MP_PARAM'] = $mountPointInfo['MPvar'];
826 * If shortcut, look up if the target exists and is currently visible
828 * @param array $page The page to check
829 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
832 protected function checkValidShortcutOfPage(array $page, $additionalWhereClause)
838 $dokType = (int)$page['doktype'];
839 $shortcutMode = (int)$page['shortcut_mode'];
841 if ($dokType === self
::DOKTYPE_SHORTCUT
&& ($page['shortcut'] ||
$shortcutMode)) {
842 if ($shortcutMode === self
::SHORTCUT_MODE_NONE
) {
843 // No shortcut_mode set, so target is directly set in $page['shortcut']
844 $searchField = 'uid';
845 $searchUid = (int)$page['shortcut'];
846 } elseif ($shortcutMode === self
::SHORTCUT_MODE_FIRST_SUBPAGE ||
$shortcutMode === self
::SHORTCUT_MODE_RANDOM_SUBPAGE
) {
847 // Check subpages - first subpage or random subpage
848 $searchField = 'pid';
849 // If a shortcut mode is set and no valid page is given to select subpags
850 // from use the actual page.
851 $searchUid = (int)$page['shortcut'] ?
: $page['uid'];
852 } elseif ($shortcutMode === self
::SHORTCUT_MODE_PARENT_PAGE
) {
853 // Shortcut to parent page
854 $searchField = 'uid';
855 $searchUid = $page['pid'];
861 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
862 $queryBuilder->getRestrictions()->removeAll();
863 $count = $queryBuilder->count('uid')
866 $queryBuilder->expr()->eq(
868 $queryBuilder->createNamedParameter($searchUid, \PDO
::PARAM_INT
)
870 QueryHelper
::stripLogicalOperatorPrefix($this->where_hid_del
),
871 QueryHelper
::stripLogicalOperatorPrefix($this->where_groupAccess
),
872 QueryHelper
::stripLogicalOperatorPrefix($additionalWhereClause)
880 } elseif ($dokType === self
::DOKTYPE_SHORTCUT
) {
881 // Neither shortcut target nor mode is set. Remove the page from the menu.
888 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
890 * @param int $shortcutFieldValue The value of the "shortcut" field from the pages record
891 * @param int $shortcutMode The shortcut mode: 1 will select first subpage, 2 a random subpage, 3 the parent page; default is the page pointed to by $SC
892 * @param int $thisUid The current page UID of the page which is a shortcut
893 * @param int $iteration Safety feature which makes sure that the function is calling itself recursively max 20 times (since this function can find shortcuts to other shortcuts to other shortcuts...)
894 * @param array $pageLog An array filled with previous page uids tested by the function - new page uids are evaluated against this to avoid going in circles.
895 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
897 * @throws \RuntimeException
898 * @throws ShortcutTargetPageNotFoundException
899 * @return mixed Returns the page record of the page that the shortcut pointed to.
901 * @see getPageAndRootline()
903 public function getPageShortcut($shortcutFieldValue, $shortcutMode, $thisUid, $iteration = 20, $pageLog = [], $disableGroupCheck = false
)
905 $idArray = GeneralUtility
::intExplode(',', $shortcutFieldValue);
906 // Find $page record depending on shortcut mode:
907 switch ($shortcutMode) {
908 case self
::SHORTCUT_MODE_FIRST_SUBPAGE
:
909 case self
::SHORTCUT_MODE_RANDOM_SUBPAGE
:
910 $pageArray = $this->getMenu($idArray[0] ?
: $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . self
::DOKTYPE_BE_USER_SECTION
);
912 if ($shortcutMode == self
::SHORTCUT_MODE_RANDOM_SUBPAGE
&& !empty($pageArray)) {
913 $pO = (int)rand(0, count($pageArray) - 1);
917 foreach ($pageArray as $pV) {
925 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. However, this page has no accessible subpages.';
926 throw new ShortcutTargetPageNotFoundException($message, 1301648328);
929 case self
::SHORTCUT_MODE_PARENT_PAGE
:
930 $parent = $this->getPage($idArray[0] ?
: $thisUid, $disableGroupCheck);
931 $page = $this->getPage($parent['pid'], $disableGroupCheck);
933 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. However, the parent page is not accessible.';
934 throw new ShortcutTargetPageNotFoundException($message, 1301648358);
938 $page = $this->getPage($idArray[0], $disableGroupCheck);
940 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
941 throw new ShortcutTargetPageNotFoundException($message, 1301648404);
944 // Check if short cut page was a shortcut itself, if so look up recursively:
945 if ($page['doktype'] == self
::DOKTYPE_SHORTCUT
) {
946 if (!in_array($page['uid'], $pageLog) && $iteration > 0) {
947 $pageLog[] = $page['uid'];
948 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $iteration - 1, $pageLog, $disableGroupCheck);
950 $pageLog[] = $page['uid'];
951 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
952 $this->logger
->error($message);
953 throw new \
RuntimeException($message, 1294587212);
956 // Return resulting page:
961 * Will find the page carrying the domain record matching the input domain.
963 * @param string $domain Domain name to search for. Eg. "www.typo3.com". Typical the HTTP_HOST value.
964 * @param string $path Path for the current script in domain. Eg. "/somedir/subdir". Typ. supplied by \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('SCRIPT_NAME')
965 * @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')
966 * @return mixed If found, returns integer with page UID where found. Otherwise blank. Might exit if location-header is sent, see description.
967 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::findDomainRecord()
968 * @deprecated will be removed in TYPO3 v10.0.
970 public function getDomainStartPage($domain, $path = '', $request_uri = '')
972 trigger_error('This method will be removed in TYPO3 v10.0. As the SiteResolver middleware resolves the domain start page.', E_USER_DEPRECATED
);
973 $domain = explode(':', $domain);
974 $domain = strtolower(preg_replace('/\\.$/', '', $domain[0]));
975 // Removing extra trailing slashes
976 $path = trim(preg_replace('/\\/[^\\/]*$/', '', $path));
977 // Appending to domain string
979 $domain = preg_replace('/\\/*$/', '', $domain);
980 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
981 $queryBuilder->getRestrictions()->removeAll();
989 $queryBuilder->expr()->eq('pages.uid', $queryBuilder->quoteIdentifier('sys_domain.pid')),
990 $queryBuilder->expr()->eq(
992 $queryBuilder->createNamedParameter(0, \PDO
::PARAM_INT
)
994 $queryBuilder->expr()->orX(
995 $queryBuilder->expr()->eq(
996 'sys_domain.domainName',
997 $queryBuilder->createNamedParameter($domain, \PDO
::PARAM_STR
)
999 $queryBuilder->expr()->eq(
1000 'sys_domain.domainName',
1001 $queryBuilder->createNamedParameter($domain . '/', \PDO
::PARAM_STR
)
1004 QueryHelper
::stripLogicalOperatorPrefix($this->where_hid_del
),
1005 QueryHelper
::stripLogicalOperatorPrefix($this->where_groupAccess
)
1018 * Returns array with fields of the pages from here ($uid) and back to the root
1020 * NOTICE: This function only takes deleted pages into account! So hidden,
1021 * starttime and endtime restricted pages are included no matter what.
1023 * Further: If any "recycler" page is found (doktype=255) then it will also block
1026 * If you want more fields in the rootline records than default such can be added
1027 * by listing them in $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']
1029 * @param int $uid The page uid for which to seek back to the page tree root.
1030 * @param string $MP Commalist of MountPoint parameters, eg. "1-2,3-4" etc. Normally this value comes from the GET var, MP
1031 * @param bool $ignoreMPerrors If set, some errors related to Mount Points in root line are ignored.
1032 * @throws \Exception
1033 * @throws \RuntimeException
1034 * @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.
1035 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageAndRootline()
1037 public function getRootLine($uid, $MP = '', $ignoreMPerrors = null
)
1039 if ($ignoreMPerrors !== null
) {
1040 trigger_error('The third argument in PageRepository::getRootline() will be removed in TYPO3 v10.0. Use a try/catch block around this method to catch any mount point errors, if necessary', E_USER_DEPRECATED
);
1042 $ignoreMPerrors = false
;
1044 $rootline = GeneralUtility
::makeInstance(RootlineUtility
::class, $uid, $MP, $this);
1046 return $rootline->get();
1047 } catch (\RuntimeException
$ex) {
1048 if ($ignoreMPerrors) {
1049 $this->error_getRootLine
= $ex->getMessage();
1050 if (substr($this->error_getRootLine
, -7) === 'uid -1.') {
1051 $this->error_getRootLine_failPid
= -1;
1055 if ($ex->getCode() === 1343589451) {
1056 /** @see \TYPO3\CMS\Core\Utility\RootlineUtility::getRecordArray */
1064 * Returns the redirect URL for the input page row IF the doktype is set to 3.
1066 * @param array $pagerow The page row to return URL type for
1067 * @return string|bool The URL from based on the data from "pages:url". False if not found.
1068 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initializeRedirectUrlHandlers()
1070 public function getExtURL($pagerow)
1072 if ((int)$pagerow['doktype'] === self
::DOKTYPE_LINK
) {
1073 $redirectTo = $pagerow['url'];
1074 $uI = parse_url($redirectTo);
1075 // If relative path, prefix Site URL
1076 // If it's a valid email without protocol, add "mailto:"
1077 if (!($uI['scheme'] ?? false
)) {
1078 if (GeneralUtility
::validEmail($redirectTo)) {
1079 $redirectTo = 'mailto:' . $redirectTo;
1080 } elseif ($redirectTo[0] !== '/') {
1081 $redirectTo = GeneralUtility
::getIndpEnv('TYPO3_SITE_URL') . $redirectTo;
1090 * Returns a MountPoint array for the specified page
1092 * Does a recursive search if the mounted page should be a mount page
1097 * Recursive mount points are not supported by all parts of the core.
1098 * The usage is discouraged. They may be removed from this method.
1100 * @see: https://decisions.typo3.org/t/supporting-or-prohibiting-recursive-mount-points/165/3
1102 * An array will be returned if mount pages are enabled, the correct
1103 * doktype (7) is set for page and there IS a mount_pid with a valid
1106 * The optional page record must contain at least uid, pid, doktype,
1107 * mount_pid,mount_pid_ol. If it is not supplied it will be looked up by
1108 * the system at additional costs for the lookup.
1110 * Returns FALSE if no mount point was found, "-1" if there should have been
1111 * one, but no connection to it, otherwise an array with information
1112 * about mount pid and modes.
1114 * @param int $pageId Page id to do the lookup for.
1115 * @param array|bool $pageRec Optional page record for the given page.
1116 * @param array $prevMountPids Internal register to prevent lookup cycles.
1117 * @param int $firstPageUid The first page id.
1118 * @return mixed Mount point array or failure flags (-1, false).
1119 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
1121 public function getMountPointInfo($pageId, $pageRec = false
, $prevMountPids = [], $firstPageUid = 0)
1124 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
1125 if (isset($this->cache_getMountPointInfo
[$pageId])) {
1126 return $this->cache_getMountPointInfo
[$pageId];
1128 // Get pageRec if not supplied:
1129 if (!is_array($pageRec)) {
1130 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
1131 $queryBuilder->getRestrictions()
1133 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1135 $pageRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
1138 $queryBuilder->expr()->eq(
1140 $queryBuilder->createNamedParameter($pageId, \PDO
::PARAM_INT
)
1142 $queryBuilder->expr()->neq(
1144 $queryBuilder->createNamedParameter(255, \PDO
::PARAM_INT
)
1150 // Only look for version overlay if page record is not supplied; This assumes
1151 // that the input record is overlaid with preview version, if any!
1152 $this->versionOL('pages', $pageRec);
1154 // Set first Page uid:
1155 if (!$firstPageUid) {
1156 $firstPageUid = $pageRec['uid'];
1158 // Look for mount pid value plus other required circumstances:
1159 $mount_pid = (int)$pageRec['mount_pid'];
1160 if (is_array($pageRec) && (int)$pageRec['doktype'] === self
::DOKTYPE_MOUNTPOINT
&& $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, true
)) {
1161 // Get the mount point record (to verify its general existence):
1162 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('pages');
1163 $queryBuilder->getRestrictions()
1165 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1167 $mountRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
1170 $queryBuilder->expr()->eq(
1172 $queryBuilder->createNamedParameter($mount_pid, \PDO
::PARAM_INT
)
1174 $queryBuilder->expr()->neq(
1176 $queryBuilder->createNamedParameter(255, \PDO
::PARAM_INT
)
1182 $this->versionOL('pages', $mountRec);
1183 if (is_array($mountRec)) {
1184 // Look for recursive mount point:
1185 $prevMountPids[] = $mount_pid;
1186 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
1187 // Return mount point information:
1188 $result = $recursiveMountPid ?
: [
1189 'mount_pid' => $mount_pid,
1190 'overlay' => $pageRec['mount_pid_ol'],
1191 'MPvar' => $mount_pid . '-' . $firstPageUid,
1192 'mount_point_rec' => $pageRec,
1193 'mount_pid_rec' => $mountRec
1196 // Means, there SHOULD have been a mount point, but there was none!
1201 $this->cache_getMountPointInfo
[$pageId] = $result;
1205 /********************************
1207 * Selecting records in general
1209 ********************************/
1212 * Checks if a record exists and is accessible.
1213 * The row is returned if everything's OK.
1215 * @param string $table The table name to search
1216 * @param int $uid The uid to look up in $table
1217 * @param bool|int $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
1218 * @return array|int Returns array (the record) if OK, otherwise blank/0 (zero)
1220 public function checkRecord($table, $uid, $checkPage = 0)
1223 if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1224 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1225 $queryBuilder->setRestrictions(GeneralUtility
::makeInstance(FrontendRestrictionContainer
::class));
1226 $row = $queryBuilder->select('*')
1228 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)))
1233 $this->versionOL($table, $row);
1234 if (is_array($row)) {
1236 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1237 ->getQueryBuilderForTable('pages');
1238 $queryBuilder->setRestrictions(GeneralUtility
::makeInstance(FrontendRestrictionContainer
::class));
1239 $numRows = (int)$queryBuilder->count('*')
1242 $queryBuilder->expr()->eq(
1244 $queryBuilder->createNamedParameter($row['pid'], \PDO
::PARAM_INT
)
1262 * Returns record no matter what - except if record is deleted
1264 * @param string $table The table name to search
1265 * @param int $uid The uid to look up in $table
1266 * @param string $fields The fields to select, default is "*
1267 * @param bool $noWSOL If set, no version overlay is applied
1268 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
1269 * @see getPage_noCheck()
1271 public function getRawRecord($table, $uid, $fields = '*', $noWSOL = null
)
1274 if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1275 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1276 $queryBuilder->getRestrictions()
1278 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1279 $row = $queryBuilder->select(...GeneralUtility
::trimExplode(',', $fields, true
))
1281 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)))
1286 if ($noWSOL !== null
) {
1287 trigger_error('The fourth parameter of PageRepository->getRawRecord() has been deprecated, use a SQL statement directly. The parameter will be removed in TYPO3 v10.', E_USER_DEPRECATED
);
1289 // @deprecated - remove this if-clause in TYPO3 v10
1291 $this->versionOL($table, $row);
1293 if (is_array($row)) {
1302 * Selects records based on matching a field (ei. other than UID) with a value
1304 * @param string $theTable The table name to search, eg. "pages" or "tt_content
1305 * @param string $theField The fieldname to match, eg. "uid" or "alias
1306 * @param string $theValue The value that fieldname must match, eg. "123" or "frontpage
1307 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
1308 * @param string $groupBy Optional GROUP BY field(s). If none, supply blank string.
1309 * @param string $orderBy Optional ORDER BY field(s). If none, supply blank string.
1310 * @param string $limit Optional LIMIT value ([begin,]max). If none, supply blank string.
1311 * @return mixed Returns array (the record) if found, otherwise nothing (void)
1313 public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
1315 if (is_array($GLOBALS['TCA'][$theTable])) {
1316 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($theTable);
1317 $queryBuilder->getRestrictions()
1319 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1321 $queryBuilder->select('*')
1323 ->where($queryBuilder->expr()->eq($theField, $queryBuilder->createNamedParameter($theValue)));
1325 if ($whereClause !== '') {
1326 $queryBuilder->andWhere(QueryHelper
::stripLogicalOperatorPrefix($whereClause));
1329 if ($groupBy !== '') {
1330 $queryBuilder->groupBy(QueryHelper
::parseGroupBy($groupBy));
1333 if ($orderBy !== '') {
1334 foreach (QueryHelper
::parseOrderBy($orderBy) as $orderPair) {
1335 list($fieldName, $order) = $orderPair;
1336 $queryBuilder->addOrderBy($fieldName, $order);
1340 if ($limit !== '') {
1341 if (strpos($limit, ',')) {
1342 $limitOffsetAndMax = GeneralUtility
::intExplode(',', $limit);
1343 $queryBuilder->setFirstResult((int)$limitOffsetAndMax[0]);
1344 $queryBuilder->setMaxResults((int)$limitOffsetAndMax[1]);
1346 $queryBuilder->setMaxResults((int)$limit);
1350 $rows = $queryBuilder->execute()->fetchAll();
1352 if (!empty($rows)) {
1359 /********************************
1363 ********************************/
1366 * Returns the "AND NOT deleted" clause for the tablename given IF
1367 * $GLOBALS['TCA'] configuration points to such a field.
1369 * @param string $table Tablename
1371 * @see enableFields()
1372 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use QueryBuilders' Restrictions directly instead.
1374 public function deleteClause($table)
1376 trigger_error('The delete clause can be applied via the DeletedRestrictions via QueryBuilder, this method will be removed in TYPO3 v10.0', E_USER_DEPRECATED
);
1377 return $GLOBALS['TCA'][$table]['ctrl']['delete'] ?
' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0' : '';
1381 * Returns a part of a WHERE clause which will filter out records with start/end
1382 * times or hidden/fe_groups fields set to values that should de-select them
1383 * according to the current time, preview settings or user login. Definitely a
1384 * frontend function.
1386 * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1387 * determines for each table which of these features applies to that table.
1389 * @param string $table Table name found in the $GLOBALS['TCA'] array
1390 * @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.
1391 * @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.
1392 * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
1393 * @throws \InvalidArgumentException
1394 * @return string The clause starting like " AND ...=... AND ...=...
1395 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields()
1397 public function enableFields($table, $show_hidden = -1, $ignore_array = [], $noVersionPreview = false
)
1399 if ($show_hidden === -1 && is_object($this->getTypoScriptFrontendController())) {
1400 // If show_hidden was not set from outside and if TSFE is an object, set it
1401 // based on showHiddenPage and showHiddenRecords from TSFE
1402 $show_hidden = $table === 'pages'
1403 ?
$this->getTypoScriptFrontendController()->showHiddenPage
1404 : $this->getTypoScriptFrontendController()->showHiddenRecords
;
1406 if ($show_hidden === -1) {
1409 // If show_hidden was not changed during the previous evaluation, do it here.
1410 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
1411 $expressionBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1412 ->getQueryBuilderForTable($table)
1415 if (is_array($ctrl)) {
1416 // Delete field check:
1417 if ($ctrl['delete']) {
1418 $constraints[] = $expressionBuilder->eq($table . '.' . $ctrl['delete'], 0);
1420 if ($ctrl['versioningWS']) {
1421 if (!$this->versioningWorkspaceId
) {
1422 // Filter out placeholder records (new/moved/deleted items)
1423 // in case we are NOT in a versioning preview (that means we are online!)
1424 $constraints[] = $expressionBuilder->lte(
1425 $table . '.t3ver_state',
1426 new VersionState(VersionState
::DEFAULT_STATE
)
1428 } elseif ($table !== 'pages') {
1429 // show only records of live and of the current workspace
1430 // in case we are in a versioning preview
1431 $constraints[] = $expressionBuilder->orX(
1432 $expressionBuilder->eq($table . '.t3ver_wsid', 0),
1433 $expressionBuilder->eq($table . '.t3ver_wsid', (int)$this->versioningWorkspaceId
)
1437 // Filter out versioned records
1438 if (!$noVersionPreview && empty($ignore_array['pid'])) {
1439 $constraints[] = $expressionBuilder->neq($table . '.pid', -1);
1444 if (is_array($ctrl['enablecolumns'])) {
1445 // In case of versioning-preview, enableFields are ignored (checked in
1447 if (!$this->versioningWorkspaceId ||
!$ctrl['versioningWS'] ||
$noVersionPreview) {
1448 if (($ctrl['enablecolumns']['disabled'] ?? false
) && !$show_hidden && !($ignore_array['disabled'] ?? false
)) {
1449 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1450 $constraints[] = $expressionBuilder->eq($field, 0);
1452 if (($ctrl['enablecolumns']['starttime'] ?? false
) && !($ignore_array['starttime'] ?? false
)) {
1453 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1454 $constraints[] = $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']);
1456 if (($ctrl['enablecolumns']['endtime'] ?? false
) && !($ignore_array['endtime'] ?? false
)) {
1457 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1458 $constraints[] = $expressionBuilder->orX(
1459 $expressionBuilder->eq($field, 0),
1460 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
1463 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1464 $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1465 $constraints[] = QueryHelper
::stripLogicalOperatorPrefix(
1466 $this->getMultipleGroupsWhereClause($field, $table)
1469 // Call hook functions for additional enableColumns
1470 // It is used by the extension ingmar_accessctrl which enables assigning more
1471 // than one usergroup to content and page records
1474 'show_hidden' => $show_hidden,
1475 'ignore_array' => $ignore_array,
1478 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] ??
[] as $_funcRef) {
1479 $constraints[] = QueryHelper
::stripLogicalOperatorPrefix(
1480 GeneralUtility
::callUserFunction($_funcRef, $_params, $this)
1486 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);
1489 return empty($constraints) ?
'' : ' AND ' . $expressionBuilder->andX(...$constraints);
1493 * Creating where-clause for checking group access to elements in enableFields
1496 * @param string $field Field with group list
1497 * @param string $table Table name
1498 * @return string AND sql-clause
1499 * @see enableFields()
1501 public function getMultipleGroupsWhereClause($field, $table)
1503 $expressionBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1504 ->getQueryBuilderForTable($table)
1506 $memberGroups = GeneralUtility
::intExplode(',', $this->getTypoScriptFrontendController()->gr_list
);
1508 // If the field is empty, then OK
1509 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal(''));
1510 // If the field is NULL, then OK
1511 $orChecks[] = $expressionBuilder->isNull($field);
1512 // If the field contains zero, then OK
1513 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal('0'));
1514 foreach ($memberGroups as $value) {
1515 $orChecks[] = $expressionBuilder->inSet($field, $expressionBuilder->literal($value));
1518 return' AND (' . $expressionBuilder->orX(...$orChecks) . ')';
1521 /**********************
1523 * Versioning Preview
1525 **********************/
1528 * Finding online PID for offline version record
1530 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1531 * served which is not previewed by backend users!!!
1533 * Will look if the "pid" value of the input record is -1 (it is an offline
1534 * version) and if the table supports versioning; if so, it will translate the -1
1535 * PID into the PID of the original record.
1537 * Used whenever you are tracking something back, like making the root line.
1539 * Principle; Record offline! => Find online?
1541 * @param string $table Table name
1542 * @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.
1543 * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1545 public function fixVersioningPid($table, &$rr)
1547 if ($this->versioningWorkspaceId
&& is_array($rr) && (int)$rr['pid'] === -1 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1550 // Check values for t3ver_oid and t3ver_wsid:
1551 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1552 // If "t3ver_oid" is already a field, just set this:
1553 $oid = $rr['t3ver_oid'];
1554 $wsid = $rr['t3ver_wsid'];
1556 // Otherwise we have to expect "uid" to be in the record and look up based
1558 $uid = (int)$rr['uid'];
1560 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1561 $queryBuilder->getRestrictions()
1563 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1564 $newPidRec = $queryBuilder->select('t3ver_oid', 't3ver_wsid')
1566 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)))
1570 if (is_array($newPidRec)) {
1571 $oid = $newPidRec['t3ver_oid'];
1572 $wsid = $newPidRec['t3ver_wsid'];
1576 // If workspace ids matches and ID of current online version is found, look up
1577 // the PID value of that:
1578 if ($oid && ((int)$this->versioningWorkspaceId
=== 0 && $this->checkWorkspaceAccess($wsid) ||
(int)$wsid === (int)$this->versioningWorkspaceId
)) {
1579 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1580 $queryBuilder->getRestrictions()
1582 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1583 $oidRec = $queryBuilder->select('pid')
1585 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($oid, \PDO
::PARAM_INT
)))
1589 if (is_array($oidRec)) {
1590 // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1591 // assumed that this is a "branch" type page and therefore the uid should be
1592 // kept (like in versionOL()). However if the page is NOT a branch version it
1593 // should not happen - but then again, direct access to that uid should not
1595 $rr['_ORIG_pid'] = $rr['pid'];
1596 $rr['pid'] = $oidRec['pid'];
1600 // Changing PID in case of moving pointer:
1601 if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1602 $rr['pid'] = $movePlhRec['pid'];
1607 * Versioning Preview Overlay
1609 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1610 * served which is not previewed by backend users!!!
1612 * Generally ALWAYS used when records are selected based on uid or pid. If
1613 * records are selected on other fields than uid or pid (eg. "email = ....") then
1614 * usage might produce undesired results and that should be evaluated on
1617 * Principle; Record online! => Find offline?
1619 * @param string $table Table name
1620 * @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!
1621 * @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)
1622 * @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!
1623 * @see fixVersioningPid(), BackendUtility::workspaceOL()
1625 public function versionOL($table, &$row, $unsetMovePointers = false
, $bypassEnableFieldsCheck = false
)
1627 if ($this->versioningWorkspaceId
&& is_array($row)) {
1628 // will overlay any movePlhOL found with the real record, which in turn
1629 // will be overlaid with its workspace version if any.
1630 $movePldSwap = $this->movePlhOL($table, $row);
1631 // implode(',',array_keys($row)) = Using fields from original record to make
1632 // sure no additional fields are selected. This is best for eg. getPageOverlay()
1633 // Computed properties are excluded since those would lead to SQL errors.
1634 $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1635 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId
, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1636 if (is_array($wsAlt)) {
1637 // Always fix PID (like in fixVersioningPid() above). [This is usually not
1638 // the important factor for versioning OL]
1639 // Keep the old (-1) - indicates it was a version...
1640 $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1641 // Set in the online versions PID.
1642 $wsAlt['pid'] = $row['pid'];
1643 // For versions of single elements or page+content, preserve online UID and PID
1644 // (this will produce true "overlay" of element _content_, not any references)
1645 // For page+content the "_ORIG_uid" should actually be used as PID for selection.
1646 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1647 $wsAlt['uid'] = $row['uid'];
1648 // Translate page alias as well so links are pointing to the _online_ page:
1649 if ($table === 'pages') {
1650 $wsAlt['alias'] = $row['alias'];
1652 // Changing input record to the workspace version alternative:
1654 // Check if it is deleted/new
1655 $rowVersionState = VersionState
::cast($row['t3ver_state']);
1657 $rowVersionState->equals(VersionState
::NEW_PLACEHOLDER
)
1658 ||
$rowVersionState->equals(VersionState
::DELETE_PLACEHOLDER
)
1660 // Unset record if it turned out to be deleted in workspace
1663 // Check if move-pointer in workspace (unless if a move-placeholder is the
1664 // reason why it appears!):
1665 // You have to specifically set $unsetMovePointers in order to clear these
1666 // because it is normally a display issue if it should be shown or not.
1669 $rowVersionState->equals(VersionState
::MOVE_POINTER
)
1671 ) && $unsetMovePointers
1673 // Unset record if it turned out to be deleted in workspace
1677 // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1678 // (online version is dummy-representation)
1679 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1680 // enablefields for BOTH the version AND the online record deselects it. See
1681 // note for $bypassEnableFieldsCheck
1682 /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1683 $versionState = VersionState
::cast($row['t3ver_state']);
1684 if ($wsAlt <= -1 ||
$versionState->indicatesPlaceholder()) {
1685 // Unset record if it turned out to be "hidden"
1694 * Checks if record is a move-placeholder
1695 * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1696 * the pointed-to live record (and return TRUE) Used from versionOL
1698 * @param string $table Table name
1699 * @param array $row Row (passed by reference) - only online records...
1700 * @return bool TRUE if overlay is made.
1701 * @see BackendUtility::movePlhOl()
1703 public function movePlhOL($table, &$row)
1705 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])
1706 && (int)VersionState
::cast($row['t3ver_state'])->equals(VersionState
::MOVE_PLACEHOLDER
)
1709 // If t3ver_move_id is not found, then find it (but we like best if it is here)
1710 if (!isset($row['t3ver_move_id'])) {
1711 if ((int)$row['uid'] > 0) {
1712 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1713 $queryBuilder->getRestrictions()
1715 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1716 $moveIDRec = $queryBuilder->select('t3ver_move_id')
1718 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($row['uid'], \PDO
::PARAM_INT
)))
1722 if (is_array($moveIDRec)) {
1723 $moveID = $moveIDRec['t3ver_move_id'];
1727 $moveID = $row['t3ver_move_id'];
1729 // Find pointed-to record.
1731 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1732 $queryBuilder->setRestrictions(GeneralUtility
::makeInstance(FrontendRestrictionContainer
::class));
1733 $origRow = $queryBuilder->select(...array_keys($this->purgeComputedProperties($row)))
1736 $queryBuilder->expr()->eq(
1738 $queryBuilder->createNamedParameter($moveID, \PDO
::PARAM_INT
)
1755 * Returns move placeholder of online (live) version
1757 * @param string $table Table name
1758 * @param int $uid Record UID of online version
1759 * @param string $fields Field list, default is *
1760 * @return array If found, the record, otherwise nothing.
1761 * @see BackendUtility::getMovePlaceholder()
1763 public function getMovePlaceholder($table, $uid, $fields = '*')
1765 $workspace = (int)$this->versioningWorkspaceId
;
1766 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) && $workspace !== 0) {
1767 // Select workspace version of record:
1768 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1769 $queryBuilder->getRestrictions()
1771 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1773 $row = $queryBuilder->select(...GeneralUtility
::trimExplode(',', $fields, true
))
1776 $queryBuilder->expr()->neq('pid', $queryBuilder->createNamedParameter(-1, \PDO
::PARAM_INT
)),
1777 $queryBuilder->expr()->eq(
1779 $queryBuilder->createNamedParameter(
1780 (string)VersionState
::cast(VersionState
::MOVE_PLACEHOLDER
),
1784 $queryBuilder->expr()->eq(
1786 $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)
1788 $queryBuilder->expr()->eq(
1790 $queryBuilder->createNamedParameter($workspace, \PDO
::PARAM_INT
)
1797 if (is_array($row)) {
1805 * Select the version of a record for a workspace
1807 * @param int $workspace Workspace ID
1808 * @param string $table Table name to select from
1809 * @param int $uid Record uid for which to find workspace version.
1810 * @param string $fields Field list to select
1811 * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1812 * @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.
1813 * @see BackendUtility::getWorkspaceVersionOfRecord()
1815 public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = false
)
1817 if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1818 $workspace = (int)$workspace;
1820 // Select workspace version of record, only testing for deleted.
1821 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1822 $queryBuilder->getRestrictions()
1824 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1826 $newrow = $queryBuilder->select(...GeneralUtility
::trimExplode(',', $fields, true
))
1829 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO
::PARAM_INT
)),
1830 $queryBuilder->expr()->eq(
1832 $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)
1834 $queryBuilder->expr()->eq(
1836 $queryBuilder->createNamedParameter($workspace, \PDO
::PARAM_INT
)
1843 // If version found, check if it could have been selected with enableFields on
1845 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
1846 $queryBuilder->setRestrictions(GeneralUtility
::makeInstance(FrontendRestrictionContainer
::class));
1847 // Remove the frontend workspace restriction because we are testing a version record
1848 $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction
::class);
1849 $queryBuilder->select('uid')
1853 if (is_array($newrow)) {
1854 $queryBuilder->where(
1855 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO
::PARAM_INT
)),
1856 $queryBuilder->expr()->eq(
1858 $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)
1860 $queryBuilder->expr()->eq(
1862 $queryBuilder->createNamedParameter($workspace, \PDO
::PARAM_INT
)
1865 if ($bypassEnableFieldsCheck ||
$queryBuilder->execute()->fetchColumn()) {
1866 // Return offline version, tested for its enableFields.
1869 // Return -1 because offline version was de-selected due to its enableFields.
1872 // OK, so no workspace version was found. Then check if online version can be
1873 // selected with full enable fields and if so, return 1:
1874 $queryBuilder->where(
1875 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
))
1877 if ($bypassEnableFieldsCheck ||
$queryBuilder->execute()->fetchColumn()) {
1878 // Means search was done, but no version found.
1881 // Return -2 because the online record was de-selected due to its enableFields.
1884 // No look up in database because versioning not enabled / or workspace not
1890 * Checks if user has access to workspace.
1892 * @param int $wsid Workspace ID
1893 * @return bool true if the backend user has access to a certain workspace
1895 public function checkWorkspaceAccess($wsid)
1897 if (!$this->getBackendUser() ||
!ExtensionManagementUtility
::isLoaded('workspaces')) {
1900 if (!isset($this->workspaceCache
[$wsid])) {
1901 $this->workspaceCache
[$wsid] = $this->getBackendUser()->checkWorkspace($wsid);
1903 return (string)$this->workspaceCache
[$wsid]['_ACCESS'] !== '';
1907 * Gets file references for a given record field.
1909 * @param string $tableName Name of the table
1910 * @param string $fieldName Name of the field
1911 * @param array $element The parent element referencing to files
1914 public function getFileReferences($tableName, $fieldName, array $element)
1916 /** @var $fileRepository FileRepository */
1917 $fileRepository = GeneralUtility
::makeInstance(FileRepository
::class);
1918 $currentId = !empty($element['uid']) ?
$element['uid'] : 0;
1920 // Fetch the references of the default element
1922 $references = $fileRepository->findByRelation($tableName, $fieldName, $currentId);
1923 } catch (FileDoesNotExistException
$e) {
1925 * We just catch the exception here
1926 * Reasoning: There is nothing an editor or even admin could do
1929 } catch (\InvalidArgumentException
$e) {
1931 * The storage does not exist anymore
1932 * Log the exception message for admins as they maybe can restore the storage
1934 $logMessage = $e->getMessage() . ' (table: "' . $tableName . '", fieldName: "' . $fieldName . '", currentId: ' . $currentId . ')';
1935 $this->logger
->error($logMessage, ['exception' => $e]);
1939 $localizedId = null
;
1940 if (isset($element['_LOCALIZED_UID'])) {
1941 $localizedId = $element['_LOCALIZED_UID'];
1942 } elseif (isset($element['_PAGES_OVERLAY_UID'])) {
1943 $localizedId = $element['_PAGES_OVERLAY_UID'];
1946 $isTableLocalizable = (
1947 !empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1948 && !empty($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1950 if ($isTableLocalizable && $localizedId !== null
) {
1951 $localizedReferences = $fileRepository->findByRelation($tableName, $fieldName, $localizedId);
1952 $references = $localizedReferences;
1959 * Purges computed properties from database rows,
1960 * such as _ORIG_uid or _ORIG_pid for instance.
1965 protected function purgeComputedProperties(array $row)
1967 foreach ($this->computedPropertyNames
as $computedPropertyName) {
1968 if (array_key_exists($computedPropertyName, $row)) {
1969 unset($row[$computedPropertyName]);
1976 * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
1978 protected function getTypoScriptFrontendController()
1980 return $GLOBALS['TSFE'];
1984 * Returns the current BE user.
1986 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1988 protected function getBackendUser()
1990 return $GLOBALS['BE_USER'];