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