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