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