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