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