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