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