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