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