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