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