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