[!!!][TASK] Remove deprecated code from PageRepository
[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 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initializeRedirectUrlHandlers()
942 */
943 public function getExtURL($pagerow)
944 {
945 if ((int)$pagerow['doktype'] === self::DOKTYPE_LINK) {
946 $redirectTo = $pagerow['url'];
947 $uI = parse_url($redirectTo);
948 // If relative path, prefix Site URL
949 // If it's a valid email without protocol, add "mailto:"
950 if (!($uI['scheme'] ?? false)) {
951 if (GeneralUtility::validEmail($redirectTo)) {
952 $redirectTo = 'mailto:' . $redirectTo;
953 } elseif ($redirectTo[0] !== '/') {
954 $redirectTo = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $redirectTo;
955 }
956 }
957 return $redirectTo;
958 }
959 return false;
960 }
961
962 /**
963 * Returns a MountPoint array for the specified page
964 *
965 * Does a recursive search if the mounted page should be a mount page
966 * itself.
967 *
968 * Note:
969 *
970 * Recursive mount points are not supported by all parts of the core.
971 * The usage is discouraged. They may be removed from this method.
972 *
973 * @see: https://decisions.typo3.org/t/supporting-or-prohibiting-recursive-mount-points/165/3
974 *
975 * An array will be returned if mount pages are enabled, the correct
976 * doktype (7) is set for page and there IS a mount_pid with a valid
977 * record.
978 *
979 * The optional page record must contain at least uid, pid, doktype,
980 * mount_pid,mount_pid_ol. If it is not supplied it will be looked up by
981 * the system at additional costs for the lookup.
982 *
983 * Returns FALSE if no mount point was found, "-1" if there should have been
984 * one, but no connection to it, otherwise an array with information
985 * about mount pid and modes.
986 *
987 * @param int $pageId Page id to do the lookup for.
988 * @param array|bool $pageRec Optional page record for the given page.
989 * @param array $prevMountPids Internal register to prevent lookup cycles.
990 * @param int $firstPageUid The first page id.
991 * @return mixed Mount point array or failure flags (-1, false).
992 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
993 */
994 public function getMountPointInfo($pageId, $pageRec = false, $prevMountPids = [], $firstPageUid = 0)
995 {
996 if (!$GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
997 return false;
998 }
999 $cacheIdentifier = 'PageRepository_getMountPointInfo_' . $pageId;
1000 $cache = $this->getRuntimeCache();
1001 if ($cache->has($cacheIdentifier)) {
1002 return $cache->get($cacheIdentifier);
1003 }
1004 $result = false;
1005 // Get pageRec if not supplied:
1006 if (!is_array($pageRec)) {
1007 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1008 $queryBuilder->getRestrictions()
1009 ->removeAll()
1010 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1011
1012 $pageRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
1013 ->from('pages')
1014 ->where(
1015 $queryBuilder->expr()->eq(
1016 'uid',
1017 $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
1018 ),
1019 $queryBuilder->expr()->neq(
1020 'doktype',
1021 $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
1022 )
1023 )
1024 ->execute()
1025 ->fetch();
1026
1027 // Only look for version overlay if page record is not supplied; This assumes
1028 // that the input record is overlaid with preview version, if any!
1029 $this->versionOL('pages', $pageRec);
1030 }
1031 // Set first Page uid:
1032 if (!$firstPageUid) {
1033 $firstPageUid = $pageRec['uid'];
1034 }
1035 // Look for mount pid value plus other required circumstances:
1036 $mount_pid = (int)$pageRec['mount_pid'];
1037 if (is_array($pageRec) && (int)$pageRec['doktype'] === self::DOKTYPE_MOUNTPOINT && $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, true)) {
1038 // Get the mount point record (to verify its general existence):
1039 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1040 $queryBuilder->getRestrictions()
1041 ->removeAll()
1042 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1043
1044 $mountRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
1045 ->from('pages')
1046 ->where(
1047 $queryBuilder->expr()->eq(
1048 'uid',
1049 $queryBuilder->createNamedParameter($mount_pid, \PDO::PARAM_INT)
1050 ),
1051 $queryBuilder->expr()->neq(
1052 'doktype',
1053 $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
1054 )
1055 )
1056 ->execute()
1057 ->fetch();
1058
1059 $this->versionOL('pages', $mountRec);
1060 if (is_array($mountRec)) {
1061 // Look for recursive mount point:
1062 $prevMountPids[] = $mount_pid;
1063 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
1064 // Return mount point information:
1065 $result = $recursiveMountPid ?: [
1066 'mount_pid' => $mount_pid,
1067 'overlay' => $pageRec['mount_pid_ol'],
1068 'MPvar' => $mount_pid . '-' . $firstPageUid,
1069 'mount_point_rec' => $pageRec,
1070 'mount_pid_rec' => $mountRec
1071 ];
1072 } else {
1073 // Means, there SHOULD have been a mount point, but there was none!
1074 $result = -1;
1075 }
1076 }
1077 $cache->set($cacheIdentifier, $result);
1078 return $result;
1079 }
1080
1081 /********************************
1082 *
1083 * Selecting records in general
1084 *
1085 ********************************/
1086
1087 /**
1088 * Checks if a record exists and is accessible.
1089 * The row is returned if everything's OK.
1090 *
1091 * @param string $table The table name to search
1092 * @param int $uid The uid to look up in $table
1093 * @param bool|int $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
1094 * @return array|int Returns array (the record) if OK, otherwise blank/0 (zero)
1095 */
1096 public function checkRecord($table, $uid, $checkPage = 0)
1097 {
1098 $uid = (int)$uid;
1099 if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1100 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1101 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1102 $row = $queryBuilder->select('*')
1103 ->from($table)
1104 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1105 ->execute()
1106 ->fetch();
1107
1108 if ($row) {
1109 $this->versionOL($table, $row);
1110 if (is_array($row)) {
1111 if ($checkPage) {
1112 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1113 ->getQueryBuilderForTable('pages');
1114 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1115 $numRows = (int)$queryBuilder->count('*')
1116 ->from('pages')
1117 ->where(
1118 $queryBuilder->expr()->eq(
1119 'uid',
1120 $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
1121 )
1122 )
1123 ->execute()
1124 ->fetchColumn();
1125 if ($numRows > 0) {
1126 return $row;
1127 }
1128 return 0;
1129 }
1130 return $row;
1131 }
1132 }
1133 }
1134 return 0;
1135 }
1136
1137 /**
1138 * Returns record no matter what - except if record is deleted
1139 *
1140 * @param string $table The table name to search
1141 * @param int $uid The uid to look up in $table
1142 * @param string $fields The fields to select, default is "*
1143 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
1144 * @see getPage_noCheck()
1145 */
1146 public function getRawRecord($table, $uid, $fields = '*')
1147 {
1148 $uid = (int)$uid;
1149 if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1150 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1151 $queryBuilder->getRestrictions()
1152 ->removeAll()
1153 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1154 $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1155 ->from($table)
1156 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1157 ->execute()
1158 ->fetch();
1159
1160 if ($row) {
1161 $this->versionOL($table, $row);
1162 if (is_array($row)) {
1163 return $row;
1164 }
1165 }
1166 }
1167 return 0;
1168 }
1169
1170 /********************************
1171 *
1172 * Standard clauses
1173 *
1174 ********************************/
1175
1176 /**
1177 * Returns a part of a WHERE clause which will filter out records with start/end
1178 * times or hidden/fe_groups fields set to values that should de-select them
1179 * according to the current time, preview settings or user login. Definitely a
1180 * frontend function.
1181 *
1182 * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1183 * determines for each table which of these features applies to that table.
1184 *
1185 * @param string $table Table name found in the $GLOBALS['TCA'] array
1186 * @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.
1187 * @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.
1188 * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
1189 * @throws \InvalidArgumentException
1190 * @return string The clause starting like " AND ...=... AND ...=...
1191 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields()
1192 */
1193 public function enableFields($table, $show_hidden = -1, $ignore_array = [], $noVersionPreview = false)
1194 {
1195 if ($show_hidden === -1) {
1196 // If show_hidden was not set from outside, use the current context
1197 $show_hidden = (int)$this->context->getPropertyFromAspect('visibility', $table === 'pages' ? 'includeHiddenPages' : 'includeHiddenContent', false);
1198 }
1199 // If show_hidden was not changed during the previous evaluation, do it here.
1200 $ctrl = $GLOBALS['TCA'][$table]['ctrl'] ?? null;
1201 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1202 ->getQueryBuilderForTable($table)
1203 ->expr();
1204 $constraints = [];
1205 if (is_array($ctrl)) {
1206 // Delete field check:
1207 if ($ctrl['delete']) {
1208 $constraints[] = $expressionBuilder->eq($table . '.' . $ctrl['delete'], 0);
1209 }
1210 if ($ctrl['versioningWS'] ?? false) {
1211 if (!$this->versioningWorkspaceId > 0) {
1212 // Filter out placeholder records (new/moved/deleted items)
1213 // in case we are NOT in a versioning preview (that means we are online!)
1214 $constraints[] = $expressionBuilder->lte(
1215 $table . '.t3ver_state',
1216 new VersionState(VersionState::DEFAULT_STATE)
1217 );
1218 } elseif ($table !== 'pages') {
1219 // show only records of live and of the current workspace
1220 // in case we are in a versioning preview
1221 $constraints[] = $expressionBuilder->orX(
1222 $expressionBuilder->eq($table . '.t3ver_wsid', 0),
1223 $expressionBuilder->eq($table . '.t3ver_wsid', (int)$this->versioningWorkspaceId)
1224 );
1225 }
1226
1227 // Filter out versioned records
1228 if (!$noVersionPreview && empty($ignore_array['pid'])) {
1229 $constraints[] = $expressionBuilder->neq($table . '.pid', -1);
1230 }
1231 }
1232
1233 // Enable fields:
1234 if (is_array($ctrl['enablecolumns'])) {
1235 // In case of versioning-preview, enableFields are ignored (checked in
1236 // versionOL())
1237 if ($this->versioningWorkspaceId <= 0 || !$ctrl['versioningWS'] || $noVersionPreview) {
1238 if (($ctrl['enablecolumns']['disabled'] ?? false) && !$show_hidden && !($ignore_array['disabled'] ?? false)) {
1239 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1240 $constraints[] = $expressionBuilder->eq($field, 0);
1241 }
1242 if (($ctrl['enablecolumns']['starttime'] ?? false) && !($ignore_array['starttime'] ?? false)) {
1243 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1244 $constraints[] = $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']);
1245 }
1246 if (($ctrl['enablecolumns']['endtime'] ?? false) && !($ignore_array['endtime'] ?? false)) {
1247 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1248 $constraints[] = $expressionBuilder->orX(
1249 $expressionBuilder->eq($field, 0),
1250 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
1251 );
1252 }
1253 if (($ctrl['enablecolumns']['fe_group'] ?? false) && !($ignore_array['fe_group'] ?? false)) {
1254 $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1255 $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1256 $this->getMultipleGroupsWhereClause($field, $table)
1257 );
1258 }
1259 // Call hook functions for additional enableColumns
1260 // It is used by the extension ingmar_accessctrl which enables assigning more
1261 // than one usergroup to content and page records
1262 $_params = [
1263 'table' => $table,
1264 'show_hidden' => $show_hidden,
1265 'ignore_array' => $ignore_array,
1266 'ctrl' => $ctrl
1267 ];
1268 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] ?? [] as $_funcRef) {
1269 $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1270 GeneralUtility::callUserFunction($_funcRef, $_params, $this)
1271 );
1272 }
1273 }
1274 }
1275 } else {
1276 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);
1277 }
1278
1279 return empty($constraints) ? '' : ' AND ' . $expressionBuilder->andX(...$constraints);
1280 }
1281
1282 /**
1283 * Creating where-clause for checking group access to elements in enableFields
1284 * function
1285 *
1286 * @param string $field Field with group list
1287 * @param string $table Table name
1288 * @return string AND sql-clause
1289 * @see enableFields()
1290 */
1291 public function getMultipleGroupsWhereClause($field, $table)
1292 {
1293 if (!$this->context->hasAspect('frontend.user')) {
1294 return '';
1295 }
1296 /** @var UserAspect $userAspect */
1297 $userAspect = $this->context->getAspect('frontend.user');
1298 $memberGroups = $userAspect->getGroupIds();
1299
1300 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1301 ->getQueryBuilderForTable($table)
1302 ->expr();
1303 $orChecks = [];
1304 // If the field is empty, then OK
1305 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal(''));
1306 // If the field is NULL, then OK
1307 $orChecks[] = $expressionBuilder->isNull($field);
1308 // If the field contains zero, then OK
1309 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal('0'));
1310 foreach ($memberGroups as $value) {
1311 $orChecks[] = $expressionBuilder->inSet($field, $expressionBuilder->literal($value));
1312 }
1313
1314 return' AND (' . $expressionBuilder->orX(...$orChecks) . ')';
1315 }
1316
1317 /**********************
1318 *
1319 * Versioning Preview
1320 *
1321 **********************/
1322
1323 /**
1324 * Finding online PID for offline version record
1325 *
1326 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1327 * served which is not previewed by backend users!!!
1328 *
1329 * Will look if the "pid" value of the input record is -1 (it is an offline
1330 * version) and if the table supports versioning; if so, it will translate the -1
1331 * PID into the PID of the original record.
1332 *
1333 * Used whenever you are tracking something back, like making the root line.
1334 *
1335 * Principle; Record offline! => Find online?
1336 *
1337 * @param string $table Table name
1338 * @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.
1339 * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1340 */
1341 public function fixVersioningPid($table, &$rr)
1342 {
1343 if ($this->versioningWorkspaceId > 0 && is_array($rr) && (int)$rr['pid'] === -1 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1344 $oid = 0;
1345 $wsid = 0;
1346 // Check values for t3ver_oid and t3ver_wsid:
1347 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1348 // If "t3ver_oid" is already a field, just set this:
1349 $oid = $rr['t3ver_oid'];
1350 $wsid = $rr['t3ver_wsid'];
1351 } else {
1352 // Otherwise we have to expect "uid" to be in the record and look up based
1353 // on this:
1354 $uid = (int)$rr['uid'];
1355 if ($uid > 0) {
1356 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1357 $queryBuilder->getRestrictions()
1358 ->removeAll()
1359 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1360 $newPidRec = $queryBuilder->select('t3ver_oid', 't3ver_wsid')
1361 ->from($table)
1362 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1363 ->execute()
1364 ->fetch();
1365
1366 if (is_array($newPidRec)) {
1367 $oid = $newPidRec['t3ver_oid'];
1368 $wsid = $newPidRec['t3ver_wsid'];
1369 }
1370 }
1371 }
1372 // If workspace ids matches and ID of current online version is found, look up
1373 // the PID value of that:
1374 if ($oid && (int)$wsid === (int)$this->versioningWorkspaceId) {
1375 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1376 $queryBuilder->getRestrictions()
1377 ->removeAll()
1378 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1379 $oidRec = $queryBuilder->select('pid')
1380 ->from($table)
1381 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($oid, \PDO::PARAM_INT)))
1382 ->execute()
1383 ->fetch();
1384
1385 if (is_array($oidRec)) {
1386 // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1387 // assumed that this is a "branch" type page and therefore the uid should be
1388 // kept (like in versionOL()). However if the page is NOT a branch version it
1389 // should not happen - but then again, direct access to that uid should not
1390 // happen!
1391 $rr['_ORIG_pid'] = $rr['pid'];
1392 $rr['pid'] = $oidRec['pid'];
1393 }
1394 }
1395 }
1396 // Changing PID in case of moving pointer:
1397 if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1398 $rr['pid'] = $movePlhRec['pid'];
1399 }
1400 }
1401
1402 /**
1403 * Versioning Preview Overlay
1404 *
1405 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1406 * served which is not previewed by backend users!!!
1407 *
1408 * Generally ALWAYS used when records are selected based on uid or pid. If
1409 * records are selected on other fields than uid or pid (eg. "email = ....") then
1410 * usage might produce undesired results and that should be evaluated on
1411 * individual basis.
1412 *
1413 * Principle; Record online! => Find offline?
1414 *
1415 * @param string $table Table name
1416 * @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!
1417 * @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)
1418 * @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!
1419 * @see fixVersioningPid(), BackendUtility::workspaceOL()
1420 */
1421 public function versionOL($table, &$row, $unsetMovePointers = false, $bypassEnableFieldsCheck = false)
1422 {
1423 if ($this->versioningWorkspaceId > 0 && is_array($row)) {
1424 // will overlay any movePlhOL found with the real record, which in turn
1425 // will be overlaid with its workspace version if any.
1426 $movePldSwap = $this->movePlhOL($table, $row);
1427 // implode(',',array_keys($row)) = Using fields from original record to make
1428 // sure no additional fields are selected. This is best for eg. getPageOverlay()
1429 // Computed properties are excluded since those would lead to SQL errors.
1430 $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1431 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1432 if (is_array($wsAlt)) {
1433 // Always fix PID (like in fixVersioningPid() above). [This is usually not
1434 // the important factor for versioning OL]
1435 // Keep the old (-1) - indicates it was a version...
1436 $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1437 // Set in the online versions PID.
1438 $wsAlt['pid'] = $row['pid'];
1439 // For versions of single elements or page+content, preserve online UID and PID
1440 // (this will produce true "overlay" of element _content_, not any references)
1441 // For page+content the "_ORIG_uid" should actually be used as PID for selection.
1442 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1443 $wsAlt['uid'] = $row['uid'];
1444 // Translate page alias as well so links are pointing to the _online_ page:
1445 if ($table === 'pages') {
1446 $wsAlt['alias'] = $row['alias'];
1447 }
1448 // Changing input record to the workspace version alternative:
1449 $row = $wsAlt;
1450 // Check if it is deleted/new
1451 $rowVersionState = VersionState::cast($row['t3ver_state'] ?? null);
1452 if (
1453 $rowVersionState->equals(VersionState::NEW_PLACEHOLDER)
1454 || $rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)
1455 ) {
1456 // Unset record if it turned out to be deleted in workspace
1457 $row = false;
1458 }
1459 // Check if move-pointer in workspace (unless if a move-placeholder is the
1460 // reason why it appears!):
1461 // You have to specifically set $unsetMovePointers in order to clear these
1462 // because it is normally a display issue if it should be shown or not.
1463 if (
1464 (
1465 $rowVersionState->equals(VersionState::MOVE_POINTER)
1466 && !$movePldSwap
1467 ) && $unsetMovePointers
1468 ) {
1469 // Unset record if it turned out to be deleted in workspace
1470 $row = false;
1471 }
1472 } else {
1473 // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1474 // (online version is dummy-representation)
1475 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1476 // enablefields for BOTH the version AND the online record deselects it. See
1477 // note for $bypassEnableFieldsCheck
1478 /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1479 $versionState = VersionState::cast($row['t3ver_state']);
1480 if ($wsAlt <= -1 || $versionState->indicatesPlaceholder()) {
1481 // Unset record if it turned out to be "hidden"
1482 $row = false;
1483 }
1484 }
1485 }
1486 }
1487 }
1488
1489 /**
1490 * Checks if record is a move-placeholder
1491 * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1492 * the pointed-to live record (and return TRUE) Used from versionOL
1493 *
1494 * @param string $table Table name
1495 * @param array $row Row (passed by reference) - only online records...
1496 * @return bool TRUE if overlay is made.
1497 * @see BackendUtility::movePlhOl()
1498 */
1499 protected function movePlhOL($table, &$row)
1500 {
1501 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])
1502 && (int)VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)
1503 ) {
1504 $moveID = 0;
1505 // If t3ver_move_id is not found, then find it (but we like best if it is here)
1506 if (!isset($row['t3ver_move_id'])) {
1507 if ((int)$row['uid'] > 0) {
1508 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1509 $queryBuilder->getRestrictions()
1510 ->removeAll()
1511 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1512 $moveIDRec = $queryBuilder->select('t3ver_move_id')
1513 ->from($table)
1514 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)))
1515 ->execute()
1516 ->fetch();
1517
1518 if (is_array($moveIDRec)) {
1519 $moveID = $moveIDRec['t3ver_move_id'];
1520 }
1521 }
1522 } else {
1523 $moveID = $row['t3ver_move_id'];
1524 }
1525 // Find pointed-to record.
1526 if ($moveID) {
1527 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1528 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1529 $origRow = $queryBuilder->select(...array_keys($this->purgeComputedProperties($row)))
1530 ->from($table)
1531 ->where(
1532 $queryBuilder->expr()->eq(
1533 'uid',
1534 $queryBuilder->createNamedParameter($moveID, \PDO::PARAM_INT)
1535 )
1536 )
1537 ->setMaxResults(1)
1538 ->execute()
1539 ->fetch();
1540
1541 if ($origRow) {
1542 $row = $origRow;
1543 return true;
1544 }
1545 }
1546 }
1547 return false;
1548 }
1549
1550 /**
1551 * Returns move placeholder of online (live) version
1552 *
1553 * @param string $table Table name
1554 * @param int $uid Record UID of online version
1555 * @param string $fields Field list, default is *
1556 * @return array If found, the record, otherwise nothing.
1557 * @see BackendUtility::getMovePlaceholder()
1558 */
1559 protected function getMovePlaceholder($table, $uid, $fields = '*')
1560 {
1561 $workspace = (int)$this->versioningWorkspaceId;
1562 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) && $workspace > 0) {
1563 // Select workspace version of record:
1564 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1565 $queryBuilder->getRestrictions()
1566 ->removeAll()
1567 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1568
1569 $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1570 ->from($table)
1571 ->where(
1572 $queryBuilder->expr()->neq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1573 $queryBuilder->expr()->eq(
1574 't3ver_state',
1575 $queryBuilder->createNamedParameter(
1576 (string)VersionState::cast(VersionState::MOVE_PLACEHOLDER),
1577 \PDO::PARAM_INT
1578 )
1579 ),
1580 $queryBuilder->expr()->eq(
1581 't3ver_move_id',
1582 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1583 ),
1584 $queryBuilder->expr()->eq(
1585 't3ver_wsid',
1586 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1587 )
1588 )
1589 ->setMaxResults(1)
1590 ->execute()
1591 ->fetch();
1592
1593 if (is_array($row)) {
1594 return $row;
1595 }
1596 }
1597 return false;
1598 }
1599
1600 /**
1601 * Select the version of a record for a workspace
1602 *
1603 * @param int $workspace Workspace ID
1604 * @param string $table Table name to select from
1605 * @param int $uid Record uid for which to find workspace version.
1606 * @param string $fields Field list to select
1607 * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1608 * @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.
1609 * @see BackendUtility::getWorkspaceVersionOfRecord()
1610 */
1611 public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = false)
1612 {
1613 if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1614 $workspace = (int)$workspace;
1615 $uid = (int)$uid;
1616 // Select workspace version of record, only testing for deleted.
1617 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1618 $queryBuilder->getRestrictions()
1619 ->removeAll()
1620 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1621
1622 $newrow = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1623 ->from($table)
1624 ->where(
1625 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1626 $queryBuilder->expr()->eq(
1627 't3ver_oid',
1628 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1629 ),
1630 $queryBuilder->expr()->eq(
1631 't3ver_wsid',
1632 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1633 )
1634 )
1635 ->setMaxResults(1)
1636 ->execute()
1637 ->fetch();
1638
1639 // If version found, check if it could have been selected with enableFields on
1640 // as well:
1641 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1642 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1643 // Remove the frontend workspace restriction because we are testing a version record
1644 $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction::class);
1645 $queryBuilder->select('uid')
1646 ->from($table)
1647 ->setMaxResults(1);
1648
1649 if (is_array($newrow)) {
1650 $queryBuilder->where(
1651 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1652 $queryBuilder->expr()->eq(
1653 't3ver_oid',
1654 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1655 ),
1656 $queryBuilder->expr()->eq(
1657 't3ver_wsid',
1658 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1659 )
1660 );
1661 if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1662 // Return offline version, tested for its enableFields.
1663 return $newrow;
1664 }
1665 // Return -1 because offline version was de-selected due to its enableFields.
1666 return -1;
1667 }
1668 // OK, so no workspace version was found. Then check if online version can be
1669 // selected with full enable fields and if so, return 1:
1670 $queryBuilder->where(
1671 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
1672 );
1673 if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1674 // Means search was done, but no version found.
1675 return 1;
1676 }
1677 // Return -2 because the online record was de-selected due to its enableFields.
1678 return -2;
1679 }
1680 // No look up in database because versioning not enabled / or workspace not
1681 // offline
1682 return false;
1683 }
1684
1685 /**
1686 * Purges computed properties from database rows,
1687 * such as _ORIG_uid or _ORIG_pid for instance.
1688 *
1689 * @param array $row
1690 * @return array
1691 */
1692 protected function purgeComputedProperties(array $row)
1693 {
1694 foreach ($this->computedPropertyNames as $computedPropertyName) {
1695 if (array_key_exists($computedPropertyName, $row)) {
1696 unset($row[$computedPropertyName]);
1697 }
1698 }
1699 return $row;
1700 }
1701
1702 /**
1703 * @return VariableFrontend
1704 */
1705 protected function getRuntimeCache(): VariableFrontend
1706 {
1707 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
1708 }
1709 }