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