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