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