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