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