1<?php
2
3/*
4 * This file is part of the TYPO3 CMS project.
5 *
6 * It is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU General Public License, either version 2
8 * of the License, or any later version.
9 *
10 * For the full copyright and license information, please read the
11 * LICENSE.txt file that was distributed with this source code.
12 *
13 * The TYPO3 project - inspiring people to share!
14 */
15
16namespace TYPO3\CMS\Core\Domain\Repository;
17
18use Psr\Log\LoggerAwareInterface;
19use Psr\Log\LoggerAwareTrait;
20use TYPO3\CMS\Core\Cache\CacheManager;
21use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
22use TYPO3\CMS\Core\Context\Context;
23use TYPO3\CMS\Core\Context\Exception\AspectNotFoundException;
24use TYPO3\CMS\Core\Context\LanguageAspect;
25use TYPO3\CMS\Core\Context\UserAspect;
26use TYPO3\CMS\Core\Database\Connection;
27use TYPO3\CMS\Core\Database\ConnectionPool;
28use TYPO3\CMS\Core\Database\Query\QueryHelper;
29use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
30use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
31use TYPO3\CMS\Core\Database\Query\Restriction\FrontendGroupRestriction;
32use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
33use TYPO3\CMS\Core\Database\Query\Restriction\FrontendWorkspaceRestriction;
34use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
35use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
36use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
37use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
38use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
39use TYPO3\CMS\Core\Type\Bitmask\PageTranslationVisibility;
40use TYPO3\CMS\Core\Utility\GeneralUtility;
41use TYPO3\CMS\Core\Utility\MathUtility;
42use TYPO3\CMS\Core\Versioning\VersionState;
43
44/**
45 * Page functions, a lot of sql/pages-related functions
46 *
47 * Mainly used in the frontend but also in some cases in the backend. It's
48 * important to set the right $where_hid_del in the object so that the
49 * functions operate properly
50 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
51 */
52class PageRepository implements LoggerAwareInterface
53{
54    use LoggerAwareTrait;
55
56    /**
57     * This is not the final clauses. There will normally be conditions for the
58     * hidden, starttime and endtime fields as well. You MUST initialize the object
59     * by the init() function
60     *
61     * @var string
62     */
63    public $where_hid_del = ' AND pages.deleted=0';
64
65    /**
66     * Clause for fe_group access
67     *
68     * @var string
69     */
70    public $where_groupAccess = '';
71
72    /**
73     * Can be migrated away later to use context API directly.
74     *
75     * @var int
76     */
77    protected $sys_language_uid = 0;
78
79    /**
80     * Can be migrated away later to use context API directly.
81     * Workspace ID for preview
82     * If > 0, versioning preview of other record versions is allowed. THIS MUST
83     * ONLY BE SET IF the page is not cached and truly previewed by a backend
84     * user!
85     *
86     * @var int
87     */
88    protected $versioningWorkspaceId = 0;
89
90    /**
91     * Computed properties that are added to database rows.
92     *
93     * @var array
94     */
95    protected $computedPropertyNames = [
96        '_LOCALIZED_UID',
97        '_MP_PARAM',
98        '_ORIG_uid',
99        '_ORIG_pid',
100        '_SHORTCUT_ORIGINAL_PAGE_UID',
101        '_PAGES_OVERLAY',
102        '_PAGES_OVERLAY_UID',
103        '_PAGES_OVERLAY_LANGUAGE',
104        '_PAGES_OVERLAY_REQUESTEDLANGUAGE',
105    ];
106
107    /**
108     * Named constants for "magic numbers" of the field doktype
109     */
110    const DOKTYPE_DEFAULT = 1;
111    const DOKTYPE_LINK = 3;
112    const DOKTYPE_SHORTCUT = 4;
113    const DOKTYPE_BE_USER_SECTION = 6;
114    const DOKTYPE_MOUNTPOINT = 7;
115    const DOKTYPE_SPACER = 199;
116    const DOKTYPE_SYSFOLDER = 254;
117    const DOKTYPE_RECYCLER = 255;
118
119    /**
120     * Named constants for "magic numbers" of the field shortcut_mode
121     */
122    const SHORTCUT_MODE_NONE = 0;
123    const SHORTCUT_MODE_FIRST_SUBPAGE = 1;
124    const SHORTCUT_MODE_RANDOM_SUBPAGE = 2;
125    const SHORTCUT_MODE_PARENT_PAGE = 3;
126
127    /**
128     * @var Context
129     */
130    protected $context;
131
132    /**
133     * PageRepository constructor to set the base context, this will effectively remove the necessity for
134     * setting properties from the outside.
135     *
136     * @param Context $context
137     */
138    public function __construct(Context $context = null)
139    {
140        $this->context = $context ?? GeneralUtility::makeInstance(Context::class);
141        $this->versioningWorkspaceId = $this->context->getPropertyFromAspect('workspace', 'id');
142        // Only set up the where clauses for pages when TCA is set. This usually happens only in tests.
143        // Once all tests are written very well, this can be removed again
144        if (isset($GLOBALS['TCA']['pages'])) {
145            $this->init($this->context->getPropertyFromAspect('visibility', 'includeHiddenPages'));
146            $this->where_groupAccess = $this->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
147            $this->sys_language_uid = (int)$this->context->getPropertyFromAspect('language', 'id', 0);
148        }
149    }
150
151    /**
152     * init() MUST be run directly after creating a new template-object
153     * This sets the internal variable $this->where_hid_del to the correct where
154     * clause for page records taking deleted/hidden/starttime/endtime/t3ver_state
155     * into account
156     *
157     * @param bool $show_hidden If $show_hidden is TRUE, the hidden-field is ignored!! Normally this should be FALSE. Is used for previewing.
158     * @internal
159     */
160    protected function init($show_hidden)
161    {
162        $this->where_groupAccess = '';
163        // As PageRepository may be used multiple times during the frontend request, and may
164        // actually be used before the usergroups have been resolved, self::getMultipleGroupsWhereClause()
165        // and the hook in ->enableFields() need to be reconsidered when the usergroup state changes.
166        // When something changes in the context, a second runtime cache entry is built.
167        // However, the PageRepository is generally in use for generating e.g. hundreds of links, so they would all use
168        // the same cache identifier.
169        $userAspect = $this->context->getAspect('frontend.user');
170        $frontendUserIdentifier = 'user_' . (int)$userAspect->get('id') . '_groups_' . md5(implode(',', $userAspect->getGroupIds()));
171
172        // We need to respect the date aspect as we might have subrequests with a different time (e.g. backend preview links)
173        $dateTimeIdentifier = $this->context->getAspect('date')->get('timestamp');
174
175        $cache = $this->getRuntimeCache();
176        $cacheIdentifier = 'PageRepository_hidDelWhere' . ($show_hidden ? 'ShowHidden' : '') . '_' . (int)$this->versioningWorkspaceId . '_' . $frontendUserIdentifier . '_' . $dateTimeIdentifier;
177        $cacheEntry = $cache->get($cacheIdentifier);
178        if ($cacheEntry) {
179            $this->where_hid_del = $cacheEntry;
180        } else {
181            $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
182                ->getQueryBuilderForTable('pages')
183                ->expr();
184            if ($this->versioningWorkspaceId > 0) {
185                // For version previewing, make sure that enable-fields are not
186                // de-selecting hidden pages - we need versionOL() to unset them only
187                // if the overlay record instructs us to.
188                // Clear where_hid_del and restrict to live and current workspaces
189                $this->where_hid_del = ' AND ' . $expressionBuilder->andX(
190                    $expressionBuilder->eq('pages.deleted', 0),
191                    $expressionBuilder->orX(
192                        $expressionBuilder->eq('pages.t3ver_wsid', 0),
193                        $expressionBuilder->eq('pages.t3ver_wsid', (int)$this->versioningWorkspaceId)
194                    ),
195                    $expressionBuilder->neq('pages.doktype', self::DOKTYPE_RECYCLER)
196                );
197            } else {
198                // add starttime / endtime, and check for hidden/deleted
199                // Filter out new/deleted place-holder pages in case we are NOT in a
200                // versioning preview (that means we are online!)
201                $this->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
202                    QueryHelper::stripLogicalOperatorPrefix(
203                        $this->enableFields('pages', (int)$show_hidden, ['fe_group' => true])
204                    ),
205                    $expressionBuilder->neq('pages.doktype', self::DOKTYPE_RECYCLER)
206                );
207            }
208            $cache->set($cacheIdentifier, $this->where_hid_del);
209        }
210
211        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'] ?? false)) {
212            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'] as $classRef) {
213                $hookObject = GeneralUtility::makeInstance($classRef);
214                if (!$hookObject instanceof PageRepositoryInitHookInterface) {
215                    throw new \UnexpectedValueException($classRef . ' must implement interface ' . PageRepositoryInitHookInterface::class, 1379579812);
216                }
217                $hookObject->init_postProcess($this);
218            }
219        }
220    }
221
222    /**************************
223     *
224     * Selecting page records
225     *
226     **************************/
227
228    /**
229     * Loads the full page record for the given page ID.
230     *
231     * The page record is either served from a first-level cache or loaded from the
232     * database. If no page can be found, an empty array is returned.
233     *
234     * Language overlay and versioning overlay are applied. Mount Point
235     * handling is not done, an overlaid Mount Point is not replaced.
236     *
237     * The result is conditioned by the public properties where_groupAccess
238     * and where_hid_del that are preset by the init() method.
239     *
240     * @see PageRepository::where_groupAccess
241     * @see PageRepository::where_hid_del
242     *
243     * By default the usergroup access check is enabled. Use the second method argument
244     * to disable the usergroup access check.
245     *
246     * The given UID can be preprocessed by registering a hook class that is
247     * implementing the PageRepositoryGetPageHookInterface into the configuration array
248     * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'].
249     *
250     * @param int $uid The page id to look up
251     * @param bool $disableGroupAccessCheck set to true to disable group access check
252     * @return array The resulting page record with overlays or empty array
253     * @throws \UnexpectedValueException
254     * @see PageRepository::getPage_noCheck()
255     */
256    public function getPage($uid, $disableGroupAccessCheck = false)
257    {
258        // Hook to manipulate the page uid for special overlay handling
259        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'] ?? [] as $className) {
260            $hookObject = GeneralUtility::makeInstance($className);
261            if (!$hookObject instanceof PageRepositoryGetPageHookInterface) {
262                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageHookInterface::class, 1251476766);
263            }
264            $hookObject->getPage_preProcess($uid, $disableGroupAccessCheck, $this);
265        }
266        $cacheIdentifier = 'PageRepository_getPage_' . md5(
267            implode(
268                '-',
269                [
270                    $uid,
271                    $disableGroupAccessCheck ? '' : $this->where_groupAccess,
272                    $this->where_hid_del,
273                    $this->sys_language_uid,
274                ]
275            )
276        );
277        $cache = $this->getRuntimeCache();
278        $cacheEntry = $cache->get($cacheIdentifier);
279        if (is_array($cacheEntry)) {
280            return $cacheEntry;
281        }
282        $result = [];
283        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
284        $queryBuilder->getRestrictions()->removeAll();
285        $queryBuilder->select('*')
286            ->from('pages')
287            ->where(
288                $queryBuilder->expr()->eq('uid', (int)$uid),
289                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del)
290            );
291
292        $originalWhereGroupAccess = '';
293        if (!$disableGroupAccessCheck) {
294            $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess));
295        } else {
296            $originalWhereGroupAccess = $this->where_groupAccess;
297            $this->where_groupAccess = '';
298        }
299
300        $row = $queryBuilder->executeQuery()->fetchAssociative();
301        if ($row) {
302            $this->versionOL('pages', $row);
303            if (is_array($row)) {
304                $result = $this->getPageOverlay($row);
305            }
306        }
307
308        if ($disableGroupAccessCheck) {
309            $this->where_groupAccess = $originalWhereGroupAccess;
310        }
311
312        $cache->set($cacheIdentifier, $result);
313        return $result;
314    }
315
316    /**
317     * Return the $row for the page with uid = $uid WITHOUT checking for
318     * ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
319     *
320     * @param int $uid The page id to look up
321     * @return array The page row with overlaid localized fields. Empty array if no page.
322     * @see getPage()
323     */
324    public function getPage_noCheck($uid)
325    {
326        $cache = $this->getRuntimeCache();
327        $cacheIdentifier = 'PageRepository_getPage_noCheck_' . $uid . '_' . $this->sys_language_uid . '_' . $this->versioningWorkspaceId;
328        $cacheEntry = $cache->get($cacheIdentifier);
329        if ($cacheEntry !== false) {
330            return $cacheEntry;
331        }
332
333        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
334        $queryBuilder->getRestrictions()
335            ->removeAll()
336            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
337        $row = $queryBuilder->select('*')
338            ->from('pages')
339            ->where($queryBuilder->expr()->eq('uid', (int)$uid))
340            ->executeQuery()
341            ->fetchAssociative();
342
343        $result = [];
344        if ($row) {
345            $this->versionOL('pages', $row);
346            if (is_array($row)) {
347                $result = $this->getPageOverlay($row);
348            }
349        }
350        $cache->set($cacheIdentifier, $result);
351        return $result;
352    }
353
354    /**
355     * Master helper method to overlay a record to a language.
356     *
357     * Be aware that for pages the languageId is taken, and for all other records the contentId.
358     * This might change through a feature switch in the future.
359     *
360     * @param string $table the name of the table, should be a TCA table with localization enabled
361     * @param array $row the current (full-fletched) record.
362     * @return array|null
363     */
364    public function getLanguageOverlay(string $table, array $row)
365    {
366        // table is not localizable, so return directly
367        if (!isset($GLOBALS['TCA'][$table]['ctrl']['languageField'])) {
368            return $row;
369        }
370        try {
371            /** @var LanguageAspect $languageAspect */
372            $languageAspect = $this->context->getAspect('language');
373            if ($languageAspect->doOverlays()) {
374                if ($table === 'pages') {
375                    return $this->getPageOverlay($row, $languageAspect->getId());
376                }
377                return $this->getRecordOverlay(
378                    $table,
379                    $row,
380                    $languageAspect->getContentId(),
381                    $languageAspect->getOverlayType() === $languageAspect::OVERLAYS_MIXED ? '1' : 'hideNonTranslated'
382                );
383            }
384        } catch (AspectNotFoundException $e) {
385            // no overlays
386        }
387        return $row;
388    }
389
390    /**
391     * Returns the relevant page overlay record fields
392     *
393     * @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.
394     * @param int $languageUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
395     * @throws \UnexpectedValueException
396     * @return array Page row which is overlaid with language_overlay record (or the overlay record alone)
397     */
398    public function getPageOverlay($pageInput, $languageUid = null)
399    {
400        $rows = $this->getPagesOverlay([$pageInput], $languageUid);
401        // Always an array in return
402        return $rows[0] ?? [];
403    }
404
405    /**
406     * Returns the relevant page overlay record fields
407     *
408     * @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.
409     * @param int $languageUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
410     * @throws \UnexpectedValueException
411     * @return array Page rows which are overlaid with language_overlay record.
412     *               If the input was an array of integers, missing records are not
413     *               included. If the input were page rows, untranslated pages
414     *               are returned.
415     */
416    public function getPagesOverlay(array $pagesInput, $languageUid = null)
417    {
418        if (empty($pagesInput)) {
419            return [];
420        }
421        if ($languageUid === null) {
422            $languageUid = $this->sys_language_uid;
423        }
424        foreach ($pagesInput as &$origPage) {
425            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'] ?? [] as $className) {
426                $hookObject = GeneralUtility::makeInstance($className);
427                if (!$hookObject instanceof PageRepositoryGetPageOverlayHookInterface) {
428                    throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageOverlayHookInterface::class, 1269878881);
429                }
430                $hookObject->getPageOverlay_preProcess($origPage, $languageUid, $this);
431            }
432        }
433        unset($origPage);
434
435        $overlays = [];
436        // If language UID is different from zero, do overlay:
437        if ($languageUid) {
438            $languageUids = array_merge([$languageUid], $this->getLanguageFallbackChain(null));
439
440            $pageIds = [];
441            foreach ($pagesInput as $origPage) {
442                if (is_array($origPage)) {
443                    // Was the whole record
444                    $pageIds[] = (int)($origPage['uid'] ?? 0);
445                } else {
446                    // Was the id
447                    $pageIds[] = (int)$origPage;
448                }
449            }
450            $overlays = $this->getPageOverlaysForLanguageUids($pageIds, $languageUids);
451        }
452
453        // Create output:
454        $pagesOutput = [];
455        foreach ($pagesInput as $key => $origPage) {
456            if (is_array($origPage)) {
457                $pagesOutput[$key] = $origPage;
458                if (isset($origPage['uid'], $overlays[$origPage['uid']])) {
459                    // Overwrite the original field with the overlay
460                    foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
461                        if ($fieldName !== 'uid' && $fieldName !== 'pid') {
462                            $pagesOutput[$key][$fieldName] = $fieldValue;
463                        }
464                    }
465                }
466            } else {
467                if (isset($overlays[$origPage])) {
468                    $pagesOutput[$key] = $overlays[$origPage];
469                }
470            }
471        }
472        return $pagesOutput;
473    }
474
475    /**
476     * Checks whether the passed (translated or default language) page is accessible with the given language settings.
477     *
478     * @param array $page the page translation record or the page in the default language
479     * @param LanguageAspect $languageAspect
480     * @return bool true if the given page translation record is suited for the given language ID
481     * @internal
482     */
483    public function isPageSuitableForLanguage(array $page, LanguageAspect $languageAspect): bool
484    {
485        $languageUid = $languageAspect->getId();
486        // Checks if the default language version can be shown
487        // Block page is set, if l18n_cfg allows plus: 1) Either default language or 2) another language but NO overlay record set for page!
488        $pageTranslationVisibility = new PageTranslationVisibility((int)($page['l18n_cfg'] ?? 0));
489        if ((!$languageUid || !($page['_PAGES_OVERLAY'] ?? false))
490            && $pageTranslationVisibility->shouldBeHiddenInDefaultLanguage()
491        ) {
492            return false;
493        }
494        if ($languageUid > 0 && $pageTranslationVisibility->shouldHideTranslationIfNoTranslatedRecordExists()) {
495            if (!($page['_PAGES_OVERLAY'] ?? false) || (int)($page['_PAGES_OVERLAY_LANGUAGE'] ?? 0) !== $languageUid) {
496                return false;
497            }
498        } elseif ($languageUid > 0) {
499            $languageUids = array_merge([$languageUid], $this->getLanguageFallbackChain($languageAspect));
500            return in_array((int)($page['sys_language_uid'] ?? 0), $languageUids, true);
501        }
502        return true;
503    }
504
505    /**
506     * Returns the cleaned fallback chain from the current language aspect, if there is one.
507     *
508     * @param LanguageAspect|null $languageAspect
509     * @return int[]
510     */
511    protected function getLanguageFallbackChain(?LanguageAspect $languageAspect): array
512    {
513        $languageAspect = $languageAspect ?? $this->context->getAspect('language');
514        return array_filter($languageAspect->getFallbackChain(), static function ($item) {
515            return MathUtility::canBeInterpretedAsInteger($item);
516        });
517    }
518
519    /**
520     * Returns the first match of overlays for pages in the passed languages.
521     *
522     * NOTE regarding the query restrictions:
523     * Currently the visibility aspect within the FrontendRestrictionContainer will allow
524     * page translation records to be selected as they are child-records of a page.
525     * However you may argue that the visibility flag should determine this.
526     * But that's not how it's done right now.
527     *
528     * @param array $pageUids
529     * @param array $languageUids uid of sys_language, please note that the order is important here.
530     * @return array
531     */
532    protected function getPageOverlaysForLanguageUids(array $pageUids, array $languageUids): array
533    {
534        // Remove default language ("0")
535        $languageUids = array_filter($languageUids);
536        $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'];
537        $overlays = [];
538
539        foreach ($pageUids as $pageId) {
540            // Create a map based on the order of values in $languageUids. Those entries reflect the order of the language + fallback chain.
541            // We can't work with database ordering since there is no common SQL clause to order by e.g. [7, 1, 2].
542            $orderedListByLanguages = array_flip($languageUids);
543
544            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
545            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
546            // Because "fe_group" is an exclude field, so it is synced between overlays, the group restriction is removed for language overlays of pages
547            $queryBuilder->getRestrictions()->removeByType(FrontendGroupRestriction::class);
548            $result = $queryBuilder->select('*')
549                ->from('pages')
550                ->where(
551                    $queryBuilder->expr()->eq(
552                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
553                        $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
554                    ),
555                    $queryBuilder->expr()->in(
556                        $GLOBALS['TCA']['pages']['ctrl']['languageField'],
557                        $queryBuilder->createNamedParameter($languageUids, Connection::PARAM_INT_ARRAY)
558                    )
559                )
560                ->executeQuery();
561
562            // Create a list of rows ordered by values in $languageUids
563            while ($row = $result->fetchAssociative()) {
564                $orderedListByLanguages[$row[$languageField]] = $row;
565            }
566
567            foreach ($orderedListByLanguages as $languageUid => $row) {
568                if (!is_array($row)) {
569                    continue;
570                }
571
572                // Found a result for the current language id
573                $this->versionOL('pages', $row);
574                if (is_array($row)) {
575                    $row['_PAGES_OVERLAY'] = true;
576                    $row['_PAGES_OVERLAY_UID'] = $row['uid'];
577                    $row['_PAGES_OVERLAY_LANGUAGE'] = $languageUid;
578                    $row['_PAGES_OVERLAY_REQUESTEDLANGUAGE'] = $languageUids[0];
579                    // Unset vital fields that are NOT allowed to be overlaid:
580                    unset($row['uid'], $row['pid']);
581                    $overlays[$pageId] = $row;
582
583                    // Language fallback found, stop querying further languages
584                    break;
585                }
586            }
587        }
588
589        return $overlays;
590    }
591
592    /**
593     * Creates language-overlay for records in general (where translation is found
594     * in records from the same table)
595     *
596     * @param string $table Table name
597     * @param array $row Record to overlay. Must contain uid, pid and $table]['ctrl']['languageField']
598     * @param int $sys_language_content Pointer to the sys_language uid for content on the site.
599     * @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned  un-translated but unset (and return value is NULL)
600     * @throws \UnexpectedValueException
601     * @return mixed Returns the input record, possibly overlaid with a translation.  But if $OLmode is "hideNonTranslated" then it will return NULL if no translation is found.
602     */
603    public function getRecordOverlay($table, $row, $sys_language_content, $OLmode = '')
604    {
605        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ?? [] as $className) {
606            $hookObject = GeneralUtility::makeInstance($className);
607            if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
608                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881658);
609            }
610            $hookObject->getRecordOverlay_preProcess($table, $row, $sys_language_content, $OLmode, $this);
611        }
612
613        $tableControl = $GLOBALS['TCA'][$table]['ctrl'] ?? [];
614
615        if (!empty($tableControl['languageField'])
616            // Return record for ALL languages untouched
617            // @todo: Fix call stack to prevent this situation in the first place
618            && (int)$row[$tableControl['languageField']] !== -1
619            && !empty($tableControl['transOrigPointerField'])
620            && $row['uid'] > 0
621            && ($row['pid'] > 0 || in_array($tableControl['rootLevel'] ?? false, [true, 1, -1], true))) {
622            // Will try to overlay a record only if the sys_language_content value is larger than zero.
623            if ($sys_language_content > 0) {
624                // Must be default language, otherwise no overlaying
625                if ((int)$row[$tableControl['languageField']] === 0) {
626                    // Select overlay record:
627                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
628                        ->getQueryBuilderForTable($table);
629                    $queryBuilder->setRestrictions(
630                        GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context)
631                    );
632                    if ($this->versioningWorkspaceId > 0) {
633                        // If not in live workspace, remove query based "enable fields" checks, it will be done in versionOL()
634                        // @see functional workspace test createLocalizedNotHiddenWorkspaceContentHiddenInLive()
635                        $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
636                        $queryBuilder->getRestrictions()->removeByType(StartTimeRestriction::class);
637                        $queryBuilder->getRestrictions()->removeByType(EndTimeRestriction::class);
638                        // We remove the FrontendWorkspaceRestriction in this case, because we need to get the LIVE record
639                        // of the language record before doing the version overlay of the language again. WorkspaceRestriction
640                        // does this for us, PLUS we need to ensure to get a possible LIVE record first (that's why
641                        // the "orderBy" query is there, so the LIVE record is found first), as there might only be a
642                        // versioned record (e.g. new version) or both (common for modifying, moving etc).
643                        if ($this->hasTableWorkspaceSupport($table)) {
644                            $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction::class);
645                            $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->versioningWorkspaceId));
646                            $queryBuilder->orderBy('t3ver_wsid', 'ASC');
647                        }
648                    }
649
650                    $pid = $row['pid'];
651                    // When inside a workspace, the already versioned $row of the default language is coming in
652                    // For moved versioned records, the PID MIGHT be different. However, the idea of this function is
653                    // to get the language overlay of the LIVE default record, and afterwards get the versioned record
654                    // the found (live) language record again, see the versionOL() call a few lines below.
655                    // This means, we need to modify the $pid value for moved records, as they might be on a different
656                    // page and use the PID of the LIVE version.
657                    if (isset($row['_ORIG_pid']) && $this->hasTableWorkspaceSupport($table) && VersionState::cast($row['t3ver_state'] ?? 0)->equals(VersionState::MOVE_POINTER)) {
658                        $pid = $row['_ORIG_pid'];
659                    }
660                    $olrow = $queryBuilder->select('*')
661                        ->from($table)
662                        ->where(
663                            $queryBuilder->expr()->eq(
664                                'pid',
665                                $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
666                            ),
667                            $queryBuilder->expr()->eq(
668                                $tableControl['languageField'],
669                                $queryBuilder->createNamedParameter($sys_language_content, \PDO::PARAM_INT)
670                            ),
671                            $queryBuilder->expr()->eq(
672                                $tableControl['transOrigPointerField'],
673                                $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)
674                            )
675                        )
676                        ->setMaxResults(1)
677                        ->executeQuery()
678                        ->fetchAssociative();
679
680                    $this->versionOL($table, $olrow);
681                    // Merge record content by traversing all fields:
682                    if (is_array($olrow)) {
683                        if (isset($olrow['_ORIG_uid'])) {
684                            $row['_ORIG_uid'] = $olrow['_ORIG_uid'];
685                        }
686                        if (isset($olrow['_ORIG_pid'])) {
687                            $row['_ORIG_pid'] = $olrow['_ORIG_pid'];
688                        }
689                        foreach ($row as $fN => $fV) {
690                            if ($fN !== 'uid' && $fN !== 'pid' && isset($olrow[$fN])) {
691                                $row[$fN] = $olrow[$fN];
692                            } elseif ($fN === 'uid') {
693                                $row['_LOCALIZED_UID'] = $olrow['uid'];
694                            }
695                        }
696                    } elseif ($OLmode === 'hideNonTranslated' && (int)$row[$tableControl['languageField']] === 0) {
697                        // Unset, if non-translated records should be hidden. ONLY done if the source
698                        // record really is default language and not [All] in which case it is allowed.
699                        $row = null;
700                    }
701                } elseif ($sys_language_content != $row[$tableControl['languageField']]) {
702                    $row = null;
703                }
704            } else {
705                // When default language is displayed, we never want to return a record carrying
706                // another language!
707                if ($row[$tableControl['languageField']] > 0) {
708                    $row = null;
709                }
710            }
711        }
712
713        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ?? [] as $className) {
714            $hookObject = GeneralUtility::makeInstance($className);
715            if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
716                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881659);
717            }
718            $hookObject->getRecordOverlay_postProcess($table, $row, $sys_language_content, $OLmode, $this);
719        }
720
721        return $row;
722    }
723
724    /************************************************
725     *
726     * Page related: Menu, Domain record, Root line
727     *
728     ************************************************/
729
730    /**
731     * Returns an array with page rows for subpages of a certain page ID. This is used for menus in the frontend.
732     * If there are mount points in overlay mode the _MP_PARAM field is set to the correct MPvar.
733     *
734     * If the $pageId being input does in itself require MPvars to define a correct
735     * rootline these must be handled externally to this function.
736     *
737     * @param int|int[] $pageId The page id (or array of page ids) for which to fetch subpages (PID)
738     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
739     *                       contains the `uid` field. It's mandatory for further processing of the result row.
740     * @param string $sortField The field to sort by. Default is "sorting
741     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
742     * @param bool $checkShortcuts Check if shortcuts exist, checks by default
743     * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
744     * @see getPageShortcut()
745     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
746     */
747    public function getMenu($pageId, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
748    {
749        // @todo: Restricting $fields to a list like 'uid, title' here, leads to issues from methods like
750        //        getSubpagesForPages() which access keys like 'doktype'. This is odd, select field list
751        //        should be handled better here, probably at least containing fields that are used in the
752        //        sub methods. In the end, it might be easier to drop argument $fields altogether and
753        //        always select * ?
754        return $this->getSubpagesForPages((array)$pageId, $fields, $sortField, $additionalWhereClause, $checkShortcuts);
755    }
756
757    /**
758     * Returns an array with page-rows for pages with uid in $pageIds.
759     *
760     * This is used for menus. If there are mount points in overlay mode
761     * the _MP_PARAM field is set to the correct MPvar.
762     *
763     * @param int[] $pageIds Array of page ids to fetch
764     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
765     *                       contains the `uid` field. It's mandatory for further processing of the result row.
766     * @param string $sortField The field to sort by. Default is "sorting"
767     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
768     * @param bool $checkShortcuts Check if shortcuts exist, checks by default
769     * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
770     */
771    public function getMenuForPages(array $pageIds, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
772    {
773        return $this->getSubpagesForPages($pageIds, $fields, $sortField, $additionalWhereClause, $checkShortcuts, false);
774    }
775
776    /**
777     * Loads page records either by PIDs or by UIDs.
778     *
779     * By default the subpages of the given page IDs are loaded (as the method name suggests). If $parentPages is set
780     * to FALSE, the page records for the given page IDs are loaded directly.
781     *
782     * Concerning the rationale, please see these two other methods:
783     *
784     * @see PageRepository::getMenu()
785     * @see PageRepository::getMenuForPages()
786     *
787     * Version and language overlay are applied to the loaded records.
788     *
789     * If a record is a mount point in overlay mode, the the overlaying page record is returned in place of the
790     * record. The record is enriched by the field _MP_PARAM containing the mount point mapping for the mount
791     * point.
792     *
793     * The query can be customized by setting fields, sorting and additional WHERE clauses. If additional WHERE
794     * clauses are given, the clause must start with an operator, i.e: "AND title like '%some text%'".
795     *
796     * The keys of the returned page records are the page UIDs.
797     *
798     * CAUTION: In case of an overlaid mount point, it is the original UID.
799     *
800     * @param int[] $pageIds PIDs or UIDs to load records for
801     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
802     *                       contains the `uid` field. It's mandatory for further processing of the result row.
803     * @param string $sortField the field to sort by
804     * @param string $additionalWhereClause optional additional WHERE clause
805     * @param bool $checkShortcuts whether to check if shortcuts exist
806     * @param bool $parentPages Switch to load pages (false) or child pages (true).
807     * @return array page records
808     *
809     * @see self::getPageShortcut()
810     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
811     */
812    protected function getSubpagesForPages(
813        array $pageIds,
814        string $fields = '*',
815        string $sortField = 'sorting',
816        string $additionalWhereClause = '',
817        bool $checkShortcuts = true,
818        bool $parentPages = true
819    ): array {
820        $relationField = $parentPages ? 'pid' : 'uid';
821        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
822        $queryBuilder->getRestrictions()
823            ->removeAll()
824            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->versioningWorkspaceId));
825
826        $res = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
827            ->from('pages')
828            ->where(
829                $queryBuilder->expr()->in(
830                    $relationField,
831                    $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
832                ),
833                $queryBuilder->expr()->eq(
834                    $GLOBALS['TCA']['pages']['ctrl']['languageField'],
835                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
836                ),
837                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
838                QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
839                QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
840            );
841
842        if (!empty($sortField)) {
843            $orderBy = QueryHelper::parseOrderBy($sortField);
844            foreach ($orderBy as $order) {
845                $res->addOrderBy($order[0], $order[1] ?? 'ASC');
846            }
847        }
848        $result = $res->executeQuery();
849
850        $pages = [];
851        while ($page = $result->fetchAssociative()) {
852            $originalUid = $page['uid'];
853
854            // Versioning Preview Overlay
855            $this->versionOL('pages', $page, true);
856            // Skip if page got disabled due to version overlay (might be delete placeholder)
857            if (empty($page)) {
858                continue;
859            }
860
861            // Add a mount point parameter if needed
862            $page = $this->addMountPointParameterToPage((array)$page);
863
864            // If shortcut, look up if the target exists and is currently visible
865            if ($checkShortcuts) {
866                $page = $this->checkValidShortcutOfPage((array)$page, $additionalWhereClause);
867            }
868
869            // If the page still is there, we add it to the output
870            if (!empty($page)) {
871                $pages[$originalUid] = $page;
872            }
873        }
874
875        // Finally load language overlays
876        return $this->getPagesOverlay($pages);
877    }
878
879    /**
880     * Replaces the given page record with mounted page if required
881     *
882     * If the given page record is a mount point in overlay mode, the page
883     * record is replaced by the record of the overlaying page. The overlay
884     * record is enriched by setting the mount point mapping into the field
885     * _MP_PARAM as string for example '23-14'.
886     *
887     * In all other cases the given page record is returned as is.
888     *
889     * @todo Find a better name. The current doesn't hit the point.
890     *
891     * @param array $page The page record to handle.
892     * @return array The given page record or it's replacement.
893     */
894    protected function addMountPointParameterToPage(array $page): array
895    {
896        if (empty($page)) {
897            return [];
898        }
899
900        // $page MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
901        $mountPointInfo = $this->getMountPointInfo($page['uid'], $page);
902
903        // There is a valid mount point in overlay mode.
904        if (is_array($mountPointInfo) && $mountPointInfo['overlay']) {
905
906            // Using "getPage" is OK since we need the check for enableFields AND for type 2
907            // of mount pids we DO require a doktype < 200!
908            $mountPointPage = $this->getPage($mountPointInfo['mount_pid']);
909
910            if (!empty($mountPointPage)) {
911                $page = $mountPointPage;
912                $page['_MP_PARAM'] = $mountPointInfo['MPvar'];
913            } else {
914                $page = [];
915            }
916        }
917        return $page;
918    }
919
920    /**
921     * If shortcut, look up if the target exists and is currently visible
922     *
923     * @param array $page The page to check
924     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
925     * @return array
926     */
927    protected function checkValidShortcutOfPage(array $page, $additionalWhereClause)
928    {
929        if (empty($page)) {
930            return [];
931        }
932
933        $dokType = (int)$page['doktype'];
934        $shortcutMode = (int)$page['shortcut_mode'];
935
936        if ($dokType === self::DOKTYPE_SHORTCUT && ($page['shortcut'] || $shortcutMode)) {
937            if ($shortcutMode === self::SHORTCUT_MODE_NONE) {
938                // No shortcut_mode set, so target is directly set in $page['shortcut']
939                $searchField = 'uid';
940                $searchUid = (int)$page['shortcut'];
941            } elseif ($shortcutMode === self::SHORTCUT_MODE_FIRST_SUBPAGE || $shortcutMode === self::SHORTCUT_MODE_RANDOM_SUBPAGE) {
942                // Check subpages - first subpage or random subpage
943                $searchField = 'pid';
944                // If a shortcut mode is set and no valid page is given to select subpages
945                // from use the actual page.
946                $searchUid = (int)$page['shortcut'] ?: $page['uid'];
947            } elseif ($shortcutMode === self::SHORTCUT_MODE_PARENT_PAGE) {
948                // Shortcut to parent page
949                $searchField = 'uid';
950                $searchUid = $page['pid'];
951            } else {
952                $searchField = '';
953                $searchUid = 0;
954            }
955
956            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
957            $queryBuilder->getRestrictions()->removeAll();
958            $count = $queryBuilder->count('uid')
959                ->from('pages')
960                ->where(
961                    $queryBuilder->expr()->eq(
962                        $searchField,
963                        $queryBuilder->createNamedParameter($searchUid, \PDO::PARAM_INT)
964                    ),
965                    QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
966                    QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
967                    QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
968                )
969                ->executeQuery()
970                ->fetchOne();
971
972            if (!$count) {
973                $page = [];
974            }
975        } elseif ($dokType === self::DOKTYPE_SHORTCUT) {
976            // Neither shortcut target nor mode is set. Remove the page from the menu.
977            $page = [];
978        }
979        return $page;
980    }
981
982    /**
983     * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
984     *
985     * @param string $shortcutFieldValue The value of the "shortcut" field from the pages record
986     * @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
987     * @param int $thisUid The current page UID of the page which is a shortcut
988     * @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...)
989     * @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.
990     * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
991     * @param bool $resolveRandomPageShortcuts If true (default) this will also resolve shortcut to random subpages. In case of linking from a page to a shortcut page, we do not want to cache the "random" logic.
992     *
993     * @throws \RuntimeException
994     * @throws ShortcutTargetPageNotFoundException
995     * @return mixed Returns the page record of the page that the shortcut pointed to. If $resolveRandomPageShortcuts = false, and the shortcut page is configured to point to a random shortcut then an empty array is returned
996     * @internal
997     * @see getPageAndRootline()
998     */
999    public function getPageShortcut($shortcutFieldValue, $shortcutMode, $thisUid, $iteration = 20, $pageLog = [], $disableGroupCheck = false, bool $resolveRandomPageShortcuts = true)
1000    {
1001        $idArray = GeneralUtility::intExplode(',', $shortcutFieldValue);
1002        if ($resolveRandomPageShortcuts === false && (int)$shortcutMode === self::SHORTCUT_MODE_RANDOM_SUBPAGE) {
1003            return [];
1004        }
1005        // Find $page record depending on shortcut mode:
1006        switch ($shortcutMode) {
1007            case self::SHORTCUT_MODE_FIRST_SUBPAGE:
1008            case self::SHORTCUT_MODE_RANDOM_SUBPAGE:
1009                $excludedDoktypes = [
1010                    self::DOKTYPE_SPACER,
1011                    self::DOKTYPE_SYSFOLDER,
1012                    self::DOKTYPE_RECYCLER,
1013                    self::DOKTYPE_BE_USER_SECTION,
1014                ];
1015                $savedWhereGroupAccess = '';
1016                // "getMenu()" does not allow to hand over $disableGroupCheck, for this reason it is manually disabled and re-enabled afterwards.
1017                if ($disableGroupCheck) {
1018                    $savedWhereGroupAccess = $this->where_groupAccess;
1019                    $this->where_groupAccess = '';
1020                }
1021                $pageArray = $this->getMenu($idArray[0] ?: $thisUid, '*', 'sorting', 'AND pages.doktype NOT IN (' . implode(', ', $excludedDoktypes) . ')');
1022                if ($disableGroupCheck) {
1023                    $this->where_groupAccess = $savedWhereGroupAccess;
1024                }
1025                $pO = 0;
1026                if ($shortcutMode == self::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1027                    $pO = (int)random_int(0, count($pageArray) - 1);
1028                }
1029                $c = 0;
1030                $page = [];
1031                foreach ($pageArray as $pV) {
1032                    if ($c === $pO) {
1033                        $page = $pV;
1034                        break;
1035                    }
1036                    $c++;
1037                }
1038                if (empty($page)) {
1039                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. However, this page has no accessible subpages.';
1040                    throw new ShortcutTargetPageNotFoundException($message, 1301648328);
1041                }
1042                break;
1043            case self::SHORTCUT_MODE_PARENT_PAGE:
1044                $parent = $this->getPage($idArray[0] ?: $thisUid, $disableGroupCheck);
1045                $page = $this->getPage($parent['pid'], $disableGroupCheck);
1046                if (empty($page)) {
1047                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. However, the parent page is not accessible.';
1048                    throw new ShortcutTargetPageNotFoundException($message, 1301648358);
1049                }
1050                break;
1051            default:
1052                $page = $this->getPage($idArray[0], $disableGroupCheck);
1053                if (empty($page)) {
1054                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1055                    throw new ShortcutTargetPageNotFoundException($message, 1301648404);
1056                }
1057        }
1058        // Check if short cut page was a shortcut itself, if so look up recursively:
1059        if ((int)$page['doktype'] === self::DOKTYPE_SHORTCUT) {
1060            if (!in_array($page['uid'], $pageLog) && $iteration > 0) {
1061                $pageLog[] = $page['uid'];
1062                $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $iteration - 1, $pageLog, $disableGroupCheck);
1063            } else {
1064                $pageLog[] = $page['uid'];
1065                $this->logger->error('Page shortcuts were looping in uids {uids}', ['uids' => implode(', ', array_values($pageLog))]);
1066                throw new \RuntimeException('Page shortcuts were looping in uids: ' . implode(', ', array_values($pageLog)), 1294587212);
1067            }
1068        }
1069        // Return resulting page:
1070        return $page;
1071    }
1072
1073    /**
1074     * Check if page is a shortcut, then resolve the target page directly.
1075     * This is a better method than "getPageShortcut()" and should be used instead, as this automatically checks for $page records
1076     * and returns the shortcut pages directly.
1077     *
1078     * This method also provides a runtime cache around resolving the shortcut resolving, in order to speed up link generation
1079     * to the same shortcut page.
1080     *
1081     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageAndRootline()
1082     */
1083    public function resolveShortcutPage(array $page, bool $resolveRandomSubpages = false, bool $disableGroupAccessCheck = false): array
1084    {
1085        if ((int)($page['doktype'] ?? 0) !== self::DOKTYPE_SHORTCUT) {
1086            return $page;
1087        }
1088        $shortcutMode = (int)($page['shortcut_mode'] ?? self::SHORTCUT_MODE_NONE);
1089        $shortcutTarget = (string)($page['shortcut'] ?? '');
1090
1091        $cacheIdentifier = 'shortcuts_resolved_' . ($disableGroupAccessCheck ? '1' : '0') . '_' . $page['uid'] . '_' . $this->sys_language_uid . '_' . $page['sys_language_uid'];
1092        // Only use the runtime cache if we do not support the random subpages functionality
1093        if ($resolveRandomSubpages === false) {
1094            $cachedResult = $this->getRuntimeCache()->get($cacheIdentifier);
1095            if (is_array($cachedResult)) {
1096                return $cachedResult;
1097            }
1098        }
1099        $shortcut = $this->getPageShortcut(
1100            $shortcutTarget,
1101            $shortcutMode,
1102            $page['uid'],
1103            20,
1104            [],
1105            $disableGroupAccessCheck,
1106            $resolveRandomSubpages
1107        );
1108        if (!empty($shortcut)) {
1109            $page = $shortcut;
1110            $page['_SHORTCUT_ORIGINAL_PAGE_UID'] = $page['uid'];
1111        }
1112
1113        if ($resolveRandomSubpages === false) {
1114            $this->getRuntimeCache()->set($cacheIdentifier, $page);
1115        }
1116
1117        return $page;
1118    }
1119    /**
1120     * Returns the redirect URL for the input page row IF the doktype is set to 3.
1121     *
1122     * @param array $pagerow The page row to return URL type for
1123     * @return string|bool The URL from based on the data from "pages:url". False if not found.
1124     */
1125    public function getExtURL($pagerow)
1126    {
1127        if ((int)$pagerow['doktype'] === self::DOKTYPE_LINK) {
1128            $redirectTo = $pagerow['url'];
1129            $uI = parse_url($redirectTo);
1130            // If relative path, prefix Site URL
1131            // If it's a valid email without protocol, add "mailto:"
1132            if (!($uI['scheme'] ?? false)) {
1133                if (GeneralUtility::validEmail($redirectTo)) {
1134                    $redirectTo = 'mailto:' . $redirectTo;
1135                } elseif ($redirectTo[0] !== '/') {
1136                    $redirectTo = $GLOBALS['TYPO3_REQUEST']->getAttribute('normalizedParams')->getSiteUrl() . $redirectTo;
1137                }
1138            }
1139            return $redirectTo;
1140        }
1141        return false;
1142    }
1143
1144    /**
1145     * Returns a MountPoint array for the specified page
1146     *
1147     * Does a recursive search if the mounted page should be a mount page
1148     * itself.
1149     *
1150     * Note:
1151     *
1152     * Recursive mount points are not supported by all parts of the core.
1153     * The usage is discouraged. They may be removed from this method.
1154     *
1155     * @see https://decisions.typo3.org/t/supporting-or-prohibiting-recursive-mount-points/165/3
1156     *
1157     * An array will be returned if mount pages are enabled, the correct
1158     * doktype (7) is set for page and there IS a mount_pid with a valid
1159     * record.
1160     *
1161     * The optional page record must contain at least uid, pid, doktype,
1162     * mount_pid,mount_pid_ol. If it is not supplied it will be looked up by
1163     * the system at additional costs for the lookup.
1164     *
1165     * Returns FALSE if no mount point was found, "-1" if there should have been
1166     * one, but no connection to it, otherwise an array with information
1167     * about mount pid and modes.
1168     *
1169     * @param int $pageId Page id to do the lookup for.
1170     * @param array|bool $pageRec Optional page record for the given page.
1171     * @param array $prevMountPids Internal register to prevent lookup cycles.
1172     * @param int $firstPageUid The first page id.
1173     * @return mixed Mount point array or failure flags (-1, false).
1174     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
1175     */
1176    public function getMountPointInfo($pageId, $pageRec = false, $prevMountPids = [], $firstPageUid = 0)
1177    {
1178        if (!$GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
1179            return false;
1180        }
1181        $cacheIdentifier = 'PageRepository_getMountPointInfo_' . $pageId;
1182        $cache = $this->getRuntimeCache();
1183        if ($cache->has($cacheIdentifier)) {
1184            return $cache->get($cacheIdentifier);
1185        }
1186        $result = false;
1187        // Get pageRec if not supplied:
1188        if (!is_array($pageRec)) {
1189            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1190            $queryBuilder->getRestrictions()
1191                ->removeAll()
1192                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1193
1194            $pageRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state', 'l10n_parent')
1195                ->from('pages')
1196                ->where(
1197                    $queryBuilder->expr()->eq(
1198                        'uid',
1199                        $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
1200                    ),
1201                    $queryBuilder->expr()->neq(
1202                        'doktype',
1203                        $queryBuilder->createNamedParameter(self::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1204                    )
1205                )
1206                ->executeQuery()
1207                ->fetchAssociative();
1208
1209            // Only look for version overlay if page record is not supplied; This assumes
1210            // that the input record is overlaid with preview version, if any!
1211            $this->versionOL('pages', $pageRec);
1212        }
1213        // Set first Page uid:
1214        if (!$firstPageUid) {
1215            $firstPageUid = (int)($pageRec['l10n_parent'] ?? false) ?: $pageRec['uid'] ?? 0;
1216        }
1217        // Look for mount pid value plus other required circumstances:
1218        $mount_pid = (int)($pageRec['mount_pid'] ?? 0);
1219        $doktype = (int)($pageRec['doktype'] ?? 0);
1220        if (is_array($pageRec) && $doktype === self::DOKTYPE_MOUNTPOINT && $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, true)) {
1221            // Get the mount point record (to verify its general existence):
1222            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1223            $queryBuilder->getRestrictions()
1224                ->removeAll()
1225                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1226
1227            $mountRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state', 'l10n_parent')
1228                ->from('pages')
1229                ->where(
1230                    $queryBuilder->expr()->eq(
1231                        'uid',
1232                        $queryBuilder->createNamedParameter($mount_pid, \PDO::PARAM_INT)
1233                    ),
1234                    $queryBuilder->expr()->neq(
1235                        'doktype',
1236                        $queryBuilder->createNamedParameter(self::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1237                    )
1238                )
1239                ->executeQuery()
1240                ->fetchAssociative();
1241
1242            $this->versionOL('pages', $mountRec);
1243            if (is_array($mountRec)) {
1244                // Look for recursive mount point:
1245                $prevMountPids[] = $mount_pid;
1246                $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
1247                // Return mount point information:
1248                $result = $recursiveMountPid ?: [
1249                    'mount_pid' => $mount_pid,
1250                    'overlay' => $pageRec['mount_pid_ol'],
1251                    'MPvar' => $mount_pid . '-' . $firstPageUid,
1252                    'mount_point_rec' => $pageRec,
1253                    'mount_pid_rec' => $mountRec,
1254                ];
1255            } else {
1256                // Means, there SHOULD have been a mount point, but there was none!
1257                $result = -1;
1258            }
1259        }
1260        $cache->set($cacheIdentifier, $result);
1261        return $result;
1262    }
1263
1264    /**
1265     * Removes Page UID numbers from the input array which are not available due to QueryRestrictions
1266     * This is also very helpful to add a custom RestrictionContainer to add custom Restrictions such as "bad doktypes" e.g. RECYCLER doktypes
1267     *
1268     * @param int[] $pageIds Array of Page UID numbers to check
1269     * @param QueryRestrictionContainerInterface|null $restrictionContainer
1270     * @return int[] Returns the array of remaining page UID numbers
1271     */
1272    public function filterAccessiblePageIds(array $pageIds, QueryRestrictionContainerInterface $restrictionContainer = null): array
1273    {
1274        if ($pageIds === []) {
1275            return [];
1276        }
1277        $validPageIds = [];
1278        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1279        if ($restrictionContainer instanceof QueryRestrictionContainerInterface) {
1280            $queryBuilder->setRestrictions($restrictionContainer);
1281        } else {
1282            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
1283        }
1284        $statement = $queryBuilder->select('uid')
1285            ->from('pages')
1286            ->where(
1287                $queryBuilder->expr()->in(
1288                    'uid',
1289                    $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
1290                )
1291            )
1292            ->executeQuery();
1293        while ($row = $statement->fetchAssociative()) {
1294            $validPageIds[] = (int)$row['uid'];
1295        }
1296        return $validPageIds;
1297    }
1298    /********************************
1299     *
1300     * Selecting records in general
1301     *
1302     ********************************/
1303
1304    /**
1305     * Checks if a record exists and is accessible.
1306     * The row is returned if everything's OK.
1307     *
1308     * @param string $table The table name to search
1309     * @param int $uid The uid to look up in $table
1310     * @param bool|int $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
1311     * @return array|int Returns array (the record) if OK, otherwise blank/0 (zero)
1312     */
1313    public function checkRecord($table, $uid, $checkPage = 0)
1314    {
1315        $uid = (int)$uid;
1316        if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1317            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1318            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
1319            $row = $queryBuilder->select('*')
1320                ->from($table)
1321                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1322                ->executeQuery()
1323                ->fetchAssociative();
1324
1325            if ($row) {
1326                $this->versionOL($table, $row);
1327                if (is_array($row)) {
1328                    if ($checkPage) {
1329                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1330                            ->getQueryBuilderForTable('pages');
1331                        $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
1332                        $numRows = (int)$queryBuilder->count('*')
1333                            ->from('pages')
1334                            ->where(
1335                                $queryBuilder->expr()->eq(
1336                                    'uid',
1337                                    $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
1338                                )
1339                            )
1340                            ->executeQuery()
1341                            ->fetchOne();
1342                        if ($numRows > 0) {
1343                            return $row;
1344                        }
1345                        return 0;
1346                    }
1347                    return $row;
1348                }
1349            }
1350        }
1351        return 0;
1352    }
1353
1354    /**
1355     * Returns record no matter what - except if record is deleted
1356     *
1357     * @param string $table The table name to search
1358     * @param int $uid The uid to look up in $table
1359     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
1360     *                       contains the `uid` field. It's mandatory for further processing of the result row.
1361     * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
1362     * @see getPage_noCheck()
1363     */
1364    public function getRawRecord($table, $uid, $fields = '*')
1365    {
1366        $uid = (int)$uid;
1367        if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1368            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1369            $queryBuilder->getRestrictions()
1370                ->removeAll()
1371                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1372            $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1373                ->from($table)
1374                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1375                ->executeQuery()
1376                ->fetchAssociative();
1377
1378            if ($row) {
1379                $this->versionOL($table, $row);
1380                if (is_array($row)) {
1381                    return $row;
1382                }
1383            }
1384        }
1385        return 0;
1386    }
1387
1388    /********************************
1389     *
1390     * Standard clauses
1391     *
1392     ********************************/
1393
1394    /**
1395     * Returns a part of a WHERE clause which will filter out records with start/end
1396     * times or hidden/fe_groups fields set to values that should de-select them
1397     * according to the current time, preview settings or user login. Definitely a
1398     * frontend function.
1399     *
1400     * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1401     * determines for each table which of these features applies to that table.
1402     *
1403     * @param string $table Table name found in the $GLOBALS['TCA'] array
1404     * @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.
1405     * @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.
1406     * @throws \InvalidArgumentException
1407     * @return string The clause starting like " AND ...=... AND ...=...
1408     */
1409    public function enableFields($table, $show_hidden = -1, $ignore_array = [])
1410    {
1411        if ($show_hidden === -1) {
1412            // If show_hidden was not set from outside, use the current context
1413            $show_hidden = (int)$this->context->getPropertyFromAspect('visibility', $table === 'pages' ? 'includeHiddenPages' : 'includeHiddenContent', false);
1414        }
1415        // If show_hidden was not changed during the previous evaluation, do it here.
1416        $ctrl = $GLOBALS['TCA'][$table]['ctrl'] ?? null;
1417        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1418            ->getQueryBuilderForTable($table)
1419            ->expr();
1420        $constraints = [];
1421        if (is_array($ctrl)) {
1422            // Delete field check:
1423            if ($ctrl['delete'] ?? false) {
1424                $constraints[] = $expressionBuilder->eq($table . '.' . $ctrl['delete'], 0);
1425            }
1426            if ($this->hasTableWorkspaceSupport($table)) {
1427                // this should work exactly as WorkspaceRestriction and WorkspaceRestriction should be used instead
1428                if ($this->versioningWorkspaceId === 0) {
1429                    // Filter out placeholder records (new/deleted items)
1430                    // in case we are NOT in a version preview (that means we are online!)
1431                    $constraints[] = $expressionBuilder->lte(
1432                        $table . '.t3ver_state',
1433                        new VersionState(VersionState::DEFAULT_STATE)
1434                    );
1435                    $constraints[] = $expressionBuilder->eq($table . '.t3ver_wsid', 0);
1436                } else {
1437                    // show only records of live and of the current workspace
1438                    // in case we are in a versioning preview
1439                    $constraints[] = $expressionBuilder->orX(
1440                        $expressionBuilder->eq($table . '.t3ver_wsid', 0),
1441                        $expressionBuilder->eq($table . '.t3ver_wsid', (int)$this->versioningWorkspaceId)
1442                    );
1443                }
1444
1445                // Filter out versioned records
1446                if (empty($ignore_array['pid'])) {
1447                    // Always filter out versioned records that have an "offline" record
1448                    $constraints[] = $expressionBuilder->orX(
1449                        $expressionBuilder->eq($table . '.t3ver_oid', 0),
1450                        $expressionBuilder->eq($table . '.t3ver_state', VersionState::MOVE_POINTER)
1451                    );
1452                }
1453            }
1454
1455            // Enable fields:
1456            if (is_array($ctrl['enablecolumns'] ?? false)) {
1457                // In case of versioning-preview, enableFields are ignored (checked in
1458                // versionOL())
1459                if ($this->versioningWorkspaceId === 0 || !$this->hasTableWorkspaceSupport($table)) {
1460                    if (($ctrl['enablecolumns']['disabled'] ?? false) && !$show_hidden && !($ignore_array['disabled'] ?? false)) {
1461                        $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1462                        $constraints[] = $expressionBuilder->eq($field, 0);
1463                    }
1464                    if (($ctrl['enablecolumns']['starttime'] ?? false) && !($ignore_array['starttime'] ?? false)) {
1465                        $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1466                        $constraints[] = $expressionBuilder->lte(
1467                            $field,
1468                            $this->context->getPropertyFromAspect('date', 'accessTime', 0)
1469                        );
1470                    }
1471                    if (($ctrl['enablecolumns']['endtime'] ?? false) && !($ignore_array['endtime'] ?? false)) {
1472                        $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1473                        $constraints[] = $expressionBuilder->orX(
1474                            $expressionBuilder->eq($field, 0),
1475                            $expressionBuilder->gt(
1476                                $field,
1477                                $this->context->getPropertyFromAspect('date', 'accessTime', 0)
1478                            )
1479                        );
1480                    }
1481                    if (($ctrl['enablecolumns']['fe_group'] ?? false) && !($ignore_array['fe_group'] ?? false)) {
1482                        $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1483                        $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1484                            $this->getMultipleGroupsWhereClause($field, $table)
1485                        );
1486                    }
1487                    // Call hook functions for additional enableColumns
1488                    // It is used by the extension ingmar_accessctrl which enables assigning more
1489                    // than one usergroup to content and page records
1490                    $_params = [
1491                        'table' => $table,
1492                        'show_hidden' => $show_hidden,
1493                        'ignore_array' => $ignore_array,
1494                        'ctrl' => $ctrl,
1495                    ];
1496                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] ?? [] as $_funcRef) {
1497                        $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1498                            GeneralUtility::callUserFunction($_funcRef, $_params, $this)
1499                        );
1500                    }
1501                }
1502            }
1503        } else {
1504            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);
1505        }
1506
1507        return empty($constraints) ? '' : ' AND ' . $expressionBuilder->andX(...$constraints);
1508    }
1509
1510    /**
1511     * Creating where-clause for checking group access to elements in enableFields
1512     * function
1513     *
1514     * @param string $field Field with group list
1515     * @param string $table Table name
1516     * @return string AND sql-clause
1517     * @see enableFields()
1518     */
1519    public function getMultipleGroupsWhereClause($field, $table)
1520    {
1521        if (!$this->context->hasAspect('frontend.user')) {
1522            return '';
1523        }
1524        /** @var UserAspect $userAspect */
1525        $userAspect = $this->context->getAspect('frontend.user');
1526        $memberGroups = $userAspect->getGroupIds();
1527        $cache = $this->getRuntimeCache();
1528        $cacheIdentifier = 'PageRepository_groupAccessWhere_' . md5($field . '_' . $table . '_' . implode('_', $memberGroups));
1529        $cacheEntry = $cache->get($cacheIdentifier);
1530        if ($cacheEntry) {
1531            return $cacheEntry;
1532        }
1533
1534        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1535            ->getQueryBuilderForTable($table)
1536            ->expr();
1537        $orChecks = [];
1538        // If the field is empty, then OK
1539        $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal(''));
1540        // If the field is NULL, then OK
1541        $orChecks[] = $expressionBuilder->isNull($field);
1542        // If the field contains zero, then OK
1543        $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal('0'));
1544        foreach ($memberGroups as $value) {
1545            $orChecks[] = $expressionBuilder->inSet($field, $expressionBuilder->literal($value));
1546        }
1547
1548        $accessGroupWhere = ' AND (' . $expressionBuilder->orX(...$orChecks) . ')';
1549        $cache->set($cacheIdentifier, $accessGroupWhere);
1550        return $accessGroupWhere;
1551    }
1552
1553    /**********************
1554     *
1555     * Versioning Preview
1556     *
1557     **********************/
1558
1559    /**
1560     * Finding online PID for offline version record
1561     *
1562     * ONLY active when backend user is previewing records. MUST NEVER affect a site
1563     * served which is not previewed by backend users!!!
1564     *
1565     * What happens in this method:
1566     * If a record was moved in a workspace, the records' PID might be different. This is only reason
1567     * nowadays why this method exists.
1568     *
1569     * This is checked:
1570     * 1. If the record has a "online pendant" (t3ver_oid > 0), it overrides the "pid" with the one from the online version.
1571     * 2. If a record is a live version, check if there is a moved version in this workspace, and override the LIVE version with the new moved "pid" value.
1572     *
1573     * Used whenever you are tracking something back, like making the root line.
1574     *
1575     * Principle; Record offline! => Find online?
1576     *
1577     * @param string $table Table name
1578     * @param array $rr Record array passed by reference. As minimum, "pid" and "uid" fields must exist! Having "t3ver_state" and "t3ver_wsid" is nice and will save you a DB query.
1579     * @see BackendUtility::fixVersioningPid()
1580     * @see versionOL()
1581     * @deprecated will be removed in TYPO3 v12, use versionOL() directly to achieve the same result.
1582     */
1583    public function fixVersioningPid($table, &$rr)
1584    {
1585        trigger_error('PageRepository->fixVersioningPid() will be removed in TYPO3 v12, use PageRepository->versionOL() instead.', E_USER_DEPRECATED);
1586        if ($this->versioningWorkspaceId <= 0) {
1587            return;
1588        }
1589        if (!is_array($rr)) {
1590            return;
1591        }
1592        if (!$this->hasTableWorkspaceSupport($table)) {
1593            return;
1594        }
1595        $uid = (int)$rr['uid'];
1596        $workspaceId = 0;
1597        $versionState = null;
1598        // Check values for t3ver_state and t3ver_wsid
1599        if (isset($rr['t3ver_wsid']) && isset($rr['t3ver_state'])) {
1600            // If "t3ver_state" is already a field, just set the needed values
1601            $workspaceId = (int)$rr['t3ver_wsid'];
1602            $versionState = (int)$rr['t3ver_state'];
1603        } elseif ($uid > 0) {
1604            // Otherwise we have to expect "uid" to be in the record and look up based
1605            // on this:
1606            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1607            $queryBuilder->getRestrictions()
1608                ->removeAll()
1609                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1610            $newPidRec = $queryBuilder->select('t3ver_wsid', 't3ver_state')
1611                ->from($table)
1612                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1613                ->execute()
1614                ->fetchAssociative();
1615
1616            if (is_array($newPidRec)) {
1617                $workspaceId = (int)$newPidRec['t3ver_wsid'];
1618                $versionState = (int)$newPidRec['t3ver_state'];
1619            }
1620        }
1621
1622        // Workspace does not match, so this is skipped
1623        if ($workspaceId !== (int)$this->versioningWorkspaceId) {
1624            return;
1625        }
1626        // Changing PID in case there is a move pointer
1627        // This happens if the $uid is still a live version but the overlay happened (via t3ver_oid) and the t3ver_state was
1628        // Changed to MOVE_POINTER. This logic happens in versionOL(), where the "pid" of the live version is kept.
1629        if ($versionState === VersionState::MOVE_POINTER && $movedPageId = $this->getMovedPidOfVersionedRecord($table, $uid)) {
1630            $rr['_ORIG_pid'] = $rr['pid'];
1631            $rr['pid'] = $movedPageId;
1632        }
1633    }
1634
1635    /**
1636     * Versioning Preview Overlay
1637     *
1638     * ONLY active when backend user is previewing records. MUST NEVER affect a site
1639     * served which is not previewed by backend users!!!
1640     *
1641     * Generally ALWAYS used when records are selected based on uid or pid. If
1642     * records are selected on other fields than uid or pid (eg. "email = ....") then
1643     * usage might produce undesired results and that should be evaluated on
1644     * individual basis.
1645     *
1646     * Principle; Record online! => Find offline?
1647     *
1648     * @param string $table Table name
1649     * @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!
1650     * @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)
1651     * @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!
1652     * @see fixVersioningPid()
1653     * @see BackendUtility::workspaceOL()
1654     */
1655    public function versionOL($table, &$row, $unsetMovePointers = false, $bypassEnableFieldsCheck = false)
1656    {
1657        if ($this->versioningWorkspaceId > 0 && is_array($row)) {
1658            // implode(',',array_keys($row)) = Using fields from original record to make
1659            // sure no additional fields are selected. This is best for eg. getPageOverlay()
1660            // Computed properties are excluded since those would lead to SQL errors.
1661            $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1662            // will overlay any incoming moved record with the live record, which in turn
1663            // will be overlaid with its workspace version again to fetch both PID fields.
1664            $incomingRecordIsAMoveVersion = (int)($row['t3ver_oid'] ?? 0) > 0 && (int)($row['t3ver_state'] ?? 0) === VersionState::MOVE_POINTER;
1665            if ($incomingRecordIsAMoveVersion) {
1666                // Fetch the live version again if the given $row is a move pointer, so we know the original PID
1667                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1668                $queryBuilder->getRestrictions()
1669                    ->removeAll()
1670                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1671                $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fieldNames, true))
1672                    ->from($table)
1673                    ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$row['t3ver_oid'], \PDO::PARAM_INT)))
1674                    ->executeQuery()
1675                    ->fetchAssociative();
1676            }
1677            if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1678                if (is_array($wsAlt)) {
1679                    $rowVersionState = VersionState::cast($wsAlt['t3ver_state'] ?? null);
1680                    if ($rowVersionState->equals(VersionState::MOVE_POINTER)) {
1681                        // For move pointers, store the actual live PID in the _ORIG_pid
1682                        // The only place where PID is actually different in a workspace
1683                        $wsAlt['_ORIG_pid'] = $row['pid'];
1684                    }
1685                    // For versions of single elements or page+content, preserve online UID
1686                    // (this will produce true "overlay" of element _content_, not any references)
1687                    // For new versions there is no online counterpart
1688                    if (!$rowVersionState->equals(VersionState::NEW_PLACEHOLDER)) {
1689                        $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1690                    }
1691                    $wsAlt['uid'] = $row['uid'];
1692                    // Changing input record to the workspace version alternative:
1693                    $row = $wsAlt;
1694                    // Unset record if it turned out to be deleted in workspace
1695                    if ($rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)) {
1696                        $row = false;
1697                    }
1698                    // Check if move-pointer in workspace (unless if a move-placeholder is the
1699                    // reason why it appears!):
1700                    // You have to specifically set $unsetMovePointers in order to clear these
1701                    // because it is normally a display issue if it should be shown or not.
1702                    if ($rowVersionState->equals(VersionState::MOVE_POINTER) && !$incomingRecordIsAMoveVersion && $unsetMovePointers) {
1703                        // Unset record if it turned out to be deleted in workspace
1704                        $row = false;
1705                    }
1706                } else {
1707                    // No version found, then check if online version is dummy-representation
1708                    // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1709                    // enablefields for BOTH the version AND the online record deselects it. See
1710                    // note for $bypassEnableFieldsCheck
1711                    /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1712                    $versionState = VersionState::cast($row['t3ver_state'] ?? 0);
1713                    if ($wsAlt <= -1 || $versionState->indicatesPlaceholder()) {
1714                        // Unset record if it turned out to be "hidden"
1715                        $row = false;
1716                    }
1717                }
1718            }
1719        }
1720    }
1721
1722    /**
1723     * Returns the PID of the new (moved) location within a version, when a $liveUid is given.
1724     *
1725     * Please note: This is only performed within a workspace.
1726     * This was previously stored in the move placeholder's PID, but move pointer's PID and move placeholder's PID
1727     * are the same since TYPO3 v10, so the MOVE_POINTER is queried.
1728     *
1729     * @param string $table Table name
1730     * @param int $liveUid Record UID of online version
1731     * @return int|null If found, the Page ID of the moved record, otherwise null.
1732     */
1733    protected function getMovedPidOfVersionedRecord(string $table, int $liveUid): ?int
1734    {
1735        if ($this->versioningWorkspaceId <= 0) {
1736            return null;
1737        }
1738        if (!$this->hasTableWorkspaceSupport($table)) {
1739            return null;
1740        }
1741        // Select workspace version of record
1742        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1743        $queryBuilder->getRestrictions()
1744            ->removeAll()
1745            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1746
1747        $row = $queryBuilder->select('pid')
1748            ->from($table)
1749            ->where(
1750                $queryBuilder->expr()->eq(
1751                    't3ver_state',
1752                    $queryBuilder->createNamedParameter(
1753                        (string)VersionState::cast(VersionState::MOVE_POINTER),
1754                        \PDO::PARAM_INT
1755                    )
1756                ),
1757                $queryBuilder->expr()->eq(
1758                    't3ver_oid',
1759                    $queryBuilder->createNamedParameter($liveUid, \PDO::PARAM_INT)
1760                ),
1761                $queryBuilder->expr()->eq(
1762                    't3ver_wsid',
1763                    $queryBuilder->createNamedParameter($this->versioningWorkspaceId, \PDO::PARAM_INT)
1764                )
1765            )
1766            ->setMaxResults(1)
1767            ->execute()
1768            ->fetchAssociative();
1769
1770        if (is_array($row)) {
1771            return (int)$row['pid'];
1772        }
1773        return null;
1774    }
1775
1776    /**
1777     * Select the version of a record for a workspace
1778     *
1779     * @param int $workspace Workspace ID
1780     * @param string $table Table name to select from
1781     * @param int $uid Record uid for which to find workspace version.
1782     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
1783     *                       contains the `uid` field. It's mandatory for further processing of the result row.
1784     * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1785     * @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.
1786     * @see BackendUtility::getWorkspaceVersionOfRecord()
1787     */
1788    public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = false)
1789    {
1790        if ($workspace !== 0 && $this->hasTableWorkspaceSupport($table)) {
1791            $workspace = (int)$workspace;
1792            $uid = (int)$uid;
1793            // Select workspace version of record, only testing for deleted.
1794            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1795            $queryBuilder->getRestrictions()
1796                ->removeAll()
1797                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1798
1799            $newrow = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1800                ->from($table)
1801                ->where(
1802                    $queryBuilder->expr()->eq(
1803                        't3ver_wsid',
1804                        $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1805                    ),
1806                    $queryBuilder->expr()->orX(
1807                    // t3ver_state=1 does not contain a t3ver_oid, and returns itself
1808                        $queryBuilder->expr()->andX(
1809                            $queryBuilder->expr()->eq(
1810                                'uid',
1811                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1812                            ),
1813                            $queryBuilder->expr()->eq(
1814                                't3ver_state',
1815                                $queryBuilder->createNamedParameter(VersionState::NEW_PLACEHOLDER, \PDO::PARAM_INT)
1816                            )
1817                        ),
1818                        $queryBuilder->expr()->eq(
1819                            't3ver_oid',
1820                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1821                        )
1822                    )
1823                )
1824                ->setMaxResults(1)
1825                ->executeQuery()
1826                ->fetchAssociative();
1827
1828            // If version found, check if it could have been selected with enableFields on
1829            // as well:
1830            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1831            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
1832            // Remove the frontend workspace restriction because we are testing a version record
1833            $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction::class);
1834            $queryBuilder->select('uid')
1835                ->from($table)
1836                ->setMaxResults(1);
1837
1838            if (is_array($newrow)) {
1839                $queryBuilder->where(
1840                    $queryBuilder->expr()->eq(
1841                        't3ver_wsid',
1842                        $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1843                    ),
1844                    $queryBuilder->expr()->orX(
1845                    // t3ver_state=1 does not contain a t3ver_oid, and returns itself
1846                        $queryBuilder->expr()->andX(
1847                            $queryBuilder->expr()->eq(
1848                                'uid',
1849                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1850                            ),
1851                            $queryBuilder->expr()->eq(
1852                                't3ver_state',
1853                                $queryBuilder->createNamedParameter(VersionState::NEW_PLACEHOLDER, \PDO::PARAM_INT)
1854                            )
1855                        ),
1856                        $queryBuilder->expr()->eq(
1857                            't3ver_oid',
1858                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1859                        )
1860                    )
1861                );
1862                if ($bypassEnableFieldsCheck || $queryBuilder->executeQuery()->fetchOne()) {
1863                    // Return offline version, tested for its enableFields.
1864                    return $newrow;
1865                }
1866                // Return -1 because offline version was de-selected due to its enableFields.
1867                return -1;
1868            }
1869            // OK, so no workspace version was found. Then check if online version can be
1870            // selected with full enable fields and if so, return 1:
1871            $queryBuilder->where(
1872                $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
1873            );
1874            if ($bypassEnableFieldsCheck || $queryBuilder->executeQuery()->fetchOne()) {
1875                // Means search was done, but no version found.
1876                return 1;
1877            }
1878            // Return -2 because the online record was de-selected due to its enableFields.
1879            return -2;
1880        }
1881        // No look up in database because versioning not enabled / or workspace not
1882        // offline
1883        return false;
1884    }
1885
1886    /**
1887     * Purges computed properties from database rows,
1888     * such as _ORIG_uid or _ORIG_pid for instance.
1889     *
1890     * @param array $row
1891     * @return array
1892     */
1893    protected function purgeComputedProperties(array $row)
1894    {
1895        foreach ($this->computedPropertyNames as $computedPropertyName) {
1896            if (array_key_exists($computedPropertyName, $row)) {
1897                unset($row[$computedPropertyName]);
1898            }
1899        }
1900        return $row;
1901    }
1902
1903    /**
1904     * @return VariableFrontend
1905     */
1906    protected function getRuntimeCache(): VariableFrontend
1907    {
1908        return GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
1909    }
1910
1911    protected function hasTableWorkspaceSupport(string $tableName): bool
1912    {
1913        return !empty($GLOBALS['TCA'][$tableName]['ctrl']['versioningWS']);
1914    }
1915}
1916