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