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