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