a67b4443adc1eb4ef693c5f644403d9ad32b97dd
[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 * Add the mount point parameter to the page if needed
735 *
736 * @param array $page The page to check
737 * @return array
738 */
739 protected function addMountPointParameterToPage(array $page)
740 {
741 if (empty($page)) {
742 return [];
743 }
744
745 // $page MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
746 $mountPointInfo = $this->getMountPointInfo($page['uid'], $page);
747
748 // There is a valid mount point.
749 if (is_array($mountPointInfo) && $mountPointInfo['overlay']) {
750
751 // Using "getPage" is OK since we need the check for enableFields AND for type 2
752 // of mount pids we DO require a doktype < 200!
753 $mountPointPage = $this->getPage($mountPointInfo['mount_pid']);
754
755 if (!empty($mountPointPage)) {
756 $page = $mountPointPage;
757 $page['_MP_PARAM'] = $mountPointInfo['MPvar'];
758 } else {
759 $page = [];
760 }
761 }
762 return $page;
763 }
764
765 /**
766 * If shortcut, look up if the target exists and is currently visible
767 *
768 * @param array $page The page to check
769 * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
770 * @return array
771 */
772 protected function checkValidShortcutOfPage(array $page, $additionalWhereClause)
773 {
774 if (empty($page)) {
775 return [];
776 }
777
778 $dokType = (int)$page['doktype'];
779 $shortcutMode = (int)$page['shortcut_mode'];
780
781 if ($dokType === self::DOKTYPE_SHORTCUT && ($page['shortcut'] || $shortcutMode)) {
782 if ($shortcutMode === self::SHORTCUT_MODE_NONE) {
783 // No shortcut_mode set, so target is directly set in $page['shortcut']
784 $searchField = 'uid';
785 $searchUid = (int)$page['shortcut'];
786 } elseif ($shortcutMode === self::SHORTCUT_MODE_FIRST_SUBPAGE || $shortcutMode === self::SHORTCUT_MODE_RANDOM_SUBPAGE) {
787 // Check subpages - first subpage or random subpage
788 $searchField = 'pid';
789 // If a shortcut mode is set and no valid page is given to select subpags
790 // from use the actual page.
791 $searchUid = (int)$page['shortcut'] ?: $page['uid'];
792 } elseif ($shortcutMode === self::SHORTCUT_MODE_PARENT_PAGE) {
793 // Shortcut to parent page
794 $searchField = 'uid';
795 $searchUid = $page['pid'];
796 } else {
797 $searchField = '';
798 $searchUid = 0;
799 }
800
801 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
802 $queryBuilder->getRestrictions()->removeAll();
803 $count = $queryBuilder->count('uid')
804 ->from('pages')
805 ->where(
806 $queryBuilder->expr()->eq(
807 $searchField,
808 $queryBuilder->createNamedParameter($searchUid, \PDO::PARAM_INT)
809 ),
810 QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
811 QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
812 QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
813 )
814 ->execute()
815 ->fetchColumn();
816
817 if (!$count) {
818 $page = [];
819 }
820 } elseif ($dokType === self::DOKTYPE_SHORTCUT) {
821 // Neither shortcut target nor mode is set. Remove the page from the menu.
822 $page = [];
823 }
824 return $page;
825 }
826 /**
827 * Will find the page carrying the domain record matching the input domain.
828 * Might exit after sending a redirect-header IF a found domain record
829 * instructs to do so.
830 *
831 * @param string $domain Domain name to search for. Eg. "www.typo3.com". Typical the HTTP_HOST value.
832 * @param string $path Path for the current script in domain. Eg. "/somedir/subdir". Typ. supplied by \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('SCRIPT_NAME')
833 * @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')
834 * @return mixed If found, returns integer with page UID where found. Otherwise blank. Might exit if location-header is sent, see description.
835 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::findDomainRecord()
836 */
837 public function getDomainStartPage($domain, $path = '', $request_uri = '')
838 {
839 $domain = explode(':', $domain);
840 $domain = strtolower(preg_replace('/\\.$/', '', $domain[0]));
841 // Removing extra trailing slashes
842 $path = trim(preg_replace('/\\/[^\\/]*$/', '', $path));
843 // Appending to domain string
844 $domain .= $path;
845 $domain = preg_replace('/\\/*$/', '', $domain);
846 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
847 $queryBuilder->getRestrictions()->removeAll();
848 $row = $queryBuilder
849 ->select(
850 'pages.uid',
851 'sys_domain.redirectTo',
852 'sys_domain.redirectHttpStatusCode',
853 'sys_domain.prepend_params'
854 )
855 ->from('pages')
856 ->from('sys_domain')
857 ->where(
858 $queryBuilder->expr()->eq('pages.uid', $queryBuilder->quoteIdentifier('sys_domain.pid')),
859 $queryBuilder->expr()->eq(
860 'sys_domain.hidden',
861 $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
862 ),
863 $queryBuilder->expr()->orX(
864 $queryBuilder->expr()->eq(
865 'sys_domain.domainName',
866 $queryBuilder->createNamedParameter($domain, \PDO::PARAM_STR)
867 ),
868 $queryBuilder->expr()->eq(
869 'sys_domain.domainName',
870 $queryBuilder->createNamedParameter($domain . '/', \PDO::PARAM_STR)
871 )
872 ),
873 QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
874 QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess)
875 )
876 ->setMaxResults(1)
877 ->execute()
878 ->fetch();
879
880 if (!$row) {
881 return '';
882 }
883
884 if ($row['redirectTo']) {
885 $redirectUrl = $row['redirectTo'];
886 if ($row['prepend_params']) {
887 $redirectUrl = rtrim($redirectUrl, '/');
888 $prependStr = ltrim(substr($request_uri, strlen($path)), '/');
889 $redirectUrl .= '/' . $prependStr;
890 }
891 $statusCode = (int)$row['redirectHttpStatusCode'];
892 if ($statusCode && defined(HttpUtility::class . '::HTTP_STATUS_' . $statusCode)) {
893 HttpUtility::redirect($redirectUrl, constant(HttpUtility::class . '::HTTP_STATUS_' . $statusCode));
894 } else {
895 HttpUtility::redirect($redirectUrl, HttpUtility::HTTP_STATUS_301);
896 }
897 die;
898 } else {
899 return $row['uid'];
900 }
901 }
902
903 /**
904 * Returns array with fields of the pages from here ($uid) and back to the root
905 *
906 * NOTICE: This function only takes deleted pages into account! So hidden,
907 * starttime and endtime restricted pages are included no matter what.
908 *
909 * Further: If any "recycler" page is found (doktype=255) then it will also block
910 * for the rootline)
911 *
912 * If you want more fields in the rootline records than default such can be added
913 * by listing them in $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']
914 *
915 * @param int $uid The page uid for which to seek back to the page tree root.
916 * @param string $MP Commalist of MountPoint parameters, eg. "1-2,3-4" etc. Normally this value comes from the GET var, MP
917 * @param bool $ignoreMPerrors If set, some errors related to Mount Points in root line are ignored.
918 * @throws \Exception
919 * @throws \RuntimeException
920 * @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.
921 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageAndRootline()
922 */
923 public function getRootLine($uid, $MP = '', $ignoreMPerrors = false)
924 {
925 $rootline = GeneralUtility::makeInstance(RootlineUtility::class, $uid, $MP, $this);
926 try {
927 return $rootline->get();
928 } catch (\RuntimeException $ex) {
929 if ($ignoreMPerrors) {
930 $this->error_getRootLine = $ex->getMessage();
931 if (substr($this->error_getRootLine, -7) === 'uid -1.') {
932 $this->error_getRootLine_failPid = -1;
933 }
934 return [];
935 /** @see \TYPO3\CMS\Core\Utility\RootlineUtility::getRecordArray */
936 } elseif ($ex->getCode() === 1343589451) {
937 return [];
938 }
939 throw $ex;
940 }
941 }
942
943 /**
944 * Returns the URL type for the input page row IF the doktype is set to 3.
945 *
946 * @param array $pagerow The page row to return URL type for
947 * @return string|bool The URL from based on the data from "urltype" and "url". False if not found.
948 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initializeRedirectUrlHandlers()
949 */
950 public function getExtURL($pagerow)
951 {
952 if ((int)$pagerow['doktype'] === self::DOKTYPE_LINK) {
953 $redirectTo = $this->urltypes[$pagerow['urltype']] . $pagerow['url'];
954 // If relative path, prefix Site URL:
955 $uI = parse_url($redirectTo);
956 // Relative path assumed now.
957 if (!$uI['scheme'] && $redirectTo[0] !== '/') {
958 $redirectTo = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $redirectTo;
959 }
960 return $redirectTo;
961 }
962 return false;
963 }
964
965 /**
966 * Returns MountPoint id for page
967 *
968 * Does a recursive search if the mounted page should be a mount page itself. It
969 * has a run-away break so it can't go into infinite loops.
970 *
971 * @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...)
972 * @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
973 * @param array $prevMountPids Array accumulating formerly tested page ids for mount points. Used for recursivity brake.
974 * @param int $firstPageUid The first page id.
975 * @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.
976 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
977 */
978 public function getMountPointInfo($pageId, $pageRec = false, $prevMountPids = [], $firstPageUid = 0)
979 {
980 $result = false;
981 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
982 if (isset($this->cache_getMountPointInfo[$pageId])) {
983 return $this->cache_getMountPointInfo[$pageId];
984 }
985 // Get pageRec if not supplied:
986 if (!is_array($pageRec)) {
987 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
988 $queryBuilder->getRestrictions()
989 ->removeAll()
990 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
991
992 $pageRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
993 ->from('pages')
994 ->where(
995 $queryBuilder->expr()->eq(
996 'uid',
997 $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
998 ),
999 $queryBuilder->expr()->neq(
1000 'doktype',
1001 $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
1002 )
1003 )
1004 ->execute()
1005 ->fetch();
1006
1007 // Only look for version overlay if page record is not supplied; This assumes
1008 // that the input record is overlaid with preview version, if any!
1009 $this->versionOL('pages', $pageRec);
1010 }
1011 // Set first Page uid:
1012 if (!$firstPageUid) {
1013 $firstPageUid = $pageRec['uid'];
1014 }
1015 // Look for mount pid value plus other required circumstances:
1016 $mount_pid = (int)$pageRec['mount_pid'];
1017 if (is_array($pageRec) && (int)$pageRec['doktype'] === self::DOKTYPE_MOUNTPOINT && $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, true)) {
1018 // Get the mount point record (to verify its general existence):
1019 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1020 $queryBuilder->getRestrictions()
1021 ->removeAll()
1022 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1023
1024 $mountRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
1025 ->from('pages')
1026 ->where(
1027 $queryBuilder->expr()->eq(
1028 'uid',
1029 $queryBuilder->createNamedParameter($mount_pid, \PDO::PARAM_INT)
1030 ),
1031 $queryBuilder->expr()->neq(
1032 'doktype',
1033 $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
1034 )
1035 )
1036 ->execute()
1037 ->fetch();
1038
1039 $this->versionOL('pages', $mountRec);
1040 if (is_array($mountRec)) {
1041 // Look for recursive mount point:
1042 $prevMountPids[] = $mount_pid;
1043 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
1044 // Return mount point information:
1045 $result = $recursiveMountPid ?: [
1046 'mount_pid' => $mount_pid,
1047 'overlay' => $pageRec['mount_pid_ol'],
1048 'MPvar' => $mount_pid . '-' . $firstPageUid,
1049 'mount_point_rec' => $pageRec,
1050 'mount_pid_rec' => $mountRec
1051 ];
1052 } else {
1053 // Means, there SHOULD have been a mount point, but there was none!
1054 $result = -1;
1055 }
1056 }
1057 }
1058 $this->cache_getMountPointInfo[$pageId] = $result;
1059 return $result;
1060 }
1061
1062 /********************************
1063 *
1064 * Selecting records in general
1065 *
1066 ********************************/
1067
1068 /**
1069 * Checks if a record exists and is accessible.
1070 * The row is returned if everything's OK.
1071 *
1072 * @param string $table The table name to search
1073 * @param int $uid The uid to look up in $table
1074 * @param bool|int $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
1075 * @return array|int Returns array (the record) if OK, otherwise blank/0 (zero)
1076 */
1077 public function checkRecord($table, $uid, $checkPage = 0)
1078 {
1079 $uid = (int)$uid;
1080 if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1081 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1082 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1083 $row = $queryBuilder->select('*')
1084 ->from($table)
1085 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1086 ->execute()
1087 ->fetch();
1088
1089 if ($row) {
1090 $this->versionOL($table, $row);
1091 if (is_array($row)) {
1092 if ($checkPage) {
1093 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1094 ->getQueryBuilderForTable('pages');
1095 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1096 $numRows = (int)$queryBuilder->count('*')
1097 ->from('pages')
1098 ->where(
1099 $queryBuilder->expr()->eq(
1100 'uid',
1101 $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
1102 )
1103 )
1104 ->execute()
1105 ->fetchColumn();
1106 if ($numRows > 0) {
1107 return $row;
1108 } else {
1109 return 0;
1110 }
1111 } else {
1112 return $row;
1113 }
1114 }
1115 }
1116 }
1117 return 0;
1118 }
1119
1120 /**
1121 * Returns record no matter what - except if record is deleted
1122 *
1123 * @param string $table The table name to search
1124 * @param int $uid The uid to look up in $table
1125 * @param string $fields The fields to select, default is "*
1126 * @param bool $noWSOL If set, no version overlay is applied
1127 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
1128 * @see getPage_noCheck()
1129 */
1130 public function getRawRecord($table, $uid, $fields = '*', $noWSOL = false)
1131 {
1132 $uid = (int)$uid;
1133 if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1134 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1135 $queryBuilder->getRestrictions()
1136 ->removeAll()
1137 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1138 $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1139 ->from($table)
1140 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1141 ->execute()
1142 ->fetch();
1143
1144 if ($row) {
1145 if (!$noWSOL) {
1146 $this->versionOL($table, $row);
1147 }
1148 if (is_array($row)) {
1149 return $row;
1150 }
1151 }
1152 }
1153 return 0;
1154 }
1155
1156 /**
1157 * Selects records based on matching a field (ei. other than UID) with a value
1158 *
1159 * @param string $theTable The table name to search, eg. "pages" or "tt_content
1160 * @param string $theField The fieldname to match, eg. "uid" or "alias
1161 * @param string $theValue The value that fieldname must match, eg. "123" or "frontpage
1162 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
1163 * @param string $groupBy Optional GROUP BY field(s). If none, supply blank string.
1164 * @param string $orderBy Optional ORDER BY field(s). If none, supply blank string.
1165 * @param string $limit Optional LIMIT value ([begin,]max). If none, supply blank string.
1166 * @return mixed Returns array (the record) if found, otherwise nothing (void)
1167 */
1168 public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
1169 {
1170 if (is_array($GLOBALS['TCA'][$theTable])) {
1171 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($theTable);
1172 $queryBuilder->getRestrictions()
1173 ->removeAll()
1174 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1175
1176 $queryBuilder->select('*')
1177 ->from($theTable)
1178 ->where($queryBuilder->expr()->eq($theField, $queryBuilder->createNamedParameter($theValue)));
1179
1180 if ($whereClause !== '') {
1181 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($whereClause));
1182 }
1183
1184 if ($groupBy !== '') {
1185 $queryBuilder->groupBy(QueryHelper::parseGroupBy($groupBy));
1186 }
1187
1188 if ($orderBy !== '') {
1189 foreach (QueryHelper::parseOrderBy($orderBy) as $orderPair) {
1190 list($fieldName, $order) = $orderPair;
1191 $queryBuilder->addOrderBy($fieldName, $order);
1192 }
1193 }
1194
1195 if ($limit !== '') {
1196 if (strpos($limit, ',')) {
1197 $limitOffsetAndMax = GeneralUtility::intExplode(',', $limit);
1198 $queryBuilder->setFirstResult((int)$limitOffsetAndMax[0]);
1199 $queryBuilder->setMaxResults((int)$limitOffsetAndMax[1]);
1200 } else {
1201 $queryBuilder->setMaxResults((int)$limit);
1202 }
1203 }
1204
1205 $rows = $queryBuilder->execute()->fetchAll();
1206
1207 if (!empty($rows)) {
1208 return $rows;
1209 }
1210 }
1211 return null;
1212 }
1213
1214 /********************************
1215 *
1216 * Standard clauses
1217 *
1218 ********************************/
1219
1220 /**
1221 * Returns the "AND NOT deleted" clause for the tablename given IF
1222 * $GLOBALS['TCA'] configuration points to such a field.
1223 *
1224 * @param string $table Tablename
1225 * @return string
1226 * @see enableFields()
1227 */
1228 public function deleteClause($table)
1229 {
1230 return $GLOBALS['TCA'][$table]['ctrl']['delete'] ? ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0' : '';
1231 }
1232
1233 /**
1234 * Returns a part of a WHERE clause which will filter out records with start/end
1235 * times or hidden/fe_groups fields set to values that should de-select them
1236 * according to the current time, preview settings or user login. Definitely a
1237 * frontend function.
1238 *
1239 * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1240 * determines for each table which of these features applies to that table.
1241 *
1242 * @param string $table Table name found in the $GLOBALS['TCA'] array
1243 * @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.
1244 * @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.
1245 * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
1246 * @throws \InvalidArgumentException
1247 * @return string The clause starting like " AND ...=... AND ...=...
1248 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields(), deleteClause()
1249 */
1250 public function enableFields($table, $show_hidden = -1, $ignore_array = [], $noVersionPreview = false)
1251 {
1252 if ($show_hidden === -1 && is_object($this->getTypoScriptFrontendController())) {
1253 // If show_hidden was not set from outside and if TSFE is an object, set it
1254 // based on showHiddenPage and showHiddenRecords from TSFE
1255 $show_hidden = $table === 'pages' || $table === 'pages_language_overlay'
1256 ? $this->getTypoScriptFrontendController()->showHiddenPage
1257 : $this->getTypoScriptFrontendController()->showHiddenRecords;
1258 }
1259 if ($show_hidden === -1) {
1260 $show_hidden = 0;
1261 }
1262 // If show_hidden was not changed during the previous evaluation, do it here.
1263 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
1264 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1265 ->getQueryBuilderForTable($table)
1266 ->expr();
1267 $constraints = [];
1268 if (is_array($ctrl)) {
1269 // Delete field check:
1270 if ($ctrl['delete']) {
1271 $constraints[] = $expressionBuilder->eq($table . '.' . $ctrl['delete'], 0);
1272 }
1273 if ($ctrl['versioningWS']) {
1274 if (!$this->versioningPreview) {
1275 // Filter out placeholder records (new/moved/deleted items)
1276 // in case we are NOT in a versioning preview (that means we are online!)
1277 $constraints[] = $expressionBuilder->lte(
1278 $table . '.t3ver_state',
1279 new VersionState(VersionState::DEFAULT_STATE)
1280 );
1281 } elseif ($table !== 'pages') {
1282 // show only records of live and of the current workspace
1283 // in case we are in a versioning preview
1284 $constraints[] = $expressionBuilder->orX(
1285 $expressionBuilder->eq($table . '.t3ver_wsid', 0),
1286 $expressionBuilder->eq($table . '.t3ver_wsid', (int)$this->versioningWorkspaceId)
1287 );
1288 }
1289
1290 // Filter out versioned records
1291 if (!$noVersionPreview && empty($ignore_array['pid'])) {
1292 $constraints[] = $expressionBuilder->neq($table . '.pid', -1);
1293 }
1294 }
1295
1296 // Enable fields:
1297 if (is_array($ctrl['enablecolumns'])) {
1298 // In case of versioning-preview, enableFields are ignored (checked in
1299 // versionOL())
1300 if (!$this->versioningPreview || !$ctrl['versioningWS'] || $noVersionPreview) {
1301 if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
1302 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1303 $constraints[] = $expressionBuilder->eq($field, 0);
1304 }
1305 if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
1306 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1307 $constraints[] = $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']);
1308 }
1309 if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
1310 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1311 $constraints[] = $expressionBuilder->orX(
1312 $expressionBuilder->eq($field, 0),
1313 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
1314 );
1315 }
1316 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1317 $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1318 $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1319 $this->getMultipleGroupsWhereClause($field, $table)
1320 );
1321 }
1322 // Call hook functions for additional enableColumns
1323 // It is used by the extension ingmar_accessctrl which enables assigning more
1324 // than one usergroup to content and page records
1325 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'])) {
1326 $_params = [
1327 'table' => $table,
1328 'show_hidden' => $show_hidden,
1329 'ignore_array' => $ignore_array,
1330 'ctrl' => $ctrl
1331 ];
1332 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] as $_funcRef) {
1333 $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1334 GeneralUtility::callUserFunction($_funcRef, $_params, $this)
1335 );
1336 }
1337 }
1338 }
1339 }
1340 } else {
1341 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);
1342 }
1343
1344 return empty($constraints) ? '' : ' AND ' . $expressionBuilder->andX(...$constraints);
1345 }
1346
1347 /**
1348 * Creating where-clause for checking group access to elements in enableFields
1349 * function
1350 *
1351 * @param string $field Field with group list
1352 * @param string $table Table name
1353 * @return string AND sql-clause
1354 * @see enableFields()
1355 */
1356 public function getMultipleGroupsWhereClause($field, $table)
1357 {
1358 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1359 ->getQueryBuilderForTable($table)
1360 ->expr();
1361 $memberGroups = GeneralUtility::intExplode(',', $this->getTypoScriptFrontendController()->gr_list);
1362 $orChecks = [];
1363 // If the field is empty, then OK
1364 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal(''));
1365 // If the field is NULL, then OK
1366 $orChecks[] = $expressionBuilder->isNull($field);
1367 // If the field contains zero, then OK
1368 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal('0'));
1369 foreach ($memberGroups as $value) {
1370 $orChecks[] = $expressionBuilder->inSet($field, $expressionBuilder->literal($value));
1371 }
1372
1373 return' AND (' . $expressionBuilder->orX(...$orChecks) . ')';
1374 }
1375
1376 /**********************
1377 *
1378 * Versioning Preview
1379 *
1380 **********************/
1381
1382 /**
1383 * Finding online PID for offline version record
1384 *
1385 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1386 * served which is not previewed by backend users!!!
1387 *
1388 * Will look if the "pid" value of the input record is -1 (it is an offline
1389 * version) and if the table supports versioning; if so, it will translate the -1
1390 * PID into the PID of the original record.
1391 *
1392 * Used whenever you are tracking something back, like making the root line.
1393 *
1394 * Principle; Record offline! => Find online?
1395 *
1396 * @param string $table Table name
1397 * @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.
1398 * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1399 */
1400 public function fixVersioningPid($table, &$rr)
1401 {
1402 if ($this->versioningPreview && is_array($rr) && (int)$rr['pid'] === -1 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1403 $oid = 0;
1404 $wsid = 0;
1405 // Check values for t3ver_oid and t3ver_wsid:
1406 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1407 // If "t3ver_oid" is already a field, just set this:
1408 $oid = $rr['t3ver_oid'];
1409 $wsid = $rr['t3ver_wsid'];
1410 } else {
1411 // Otherwise we have to expect "uid" to be in the record and look up based
1412 // on this:
1413 $newPidRec = $this->getRawRecord($table, $rr['uid'], 't3ver_oid,t3ver_wsid', true);
1414 if (is_array($newPidRec)) {
1415 $oid = $newPidRec['t3ver_oid'];
1416 $wsid = $newPidRec['t3ver_wsid'];
1417 }
1418 }
1419 // If workspace ids matches and ID of current online version is found, look up
1420 // the PID value of that:
1421 if ($oid && ((int)$this->versioningWorkspaceId === 0 && $this->checkWorkspaceAccess($wsid) || (int)$wsid === (int)$this->versioningWorkspaceId)) {
1422 $oidRec = $this->getRawRecord($table, $oid, 'pid', true);
1423 if (is_array($oidRec)) {
1424 // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1425 // assumed that this is a "branch" type page and therefore the uid should be
1426 // kept (like in versionOL()). However if the page is NOT a branch version it
1427 // should not happen - but then again, direct access to that uid should not
1428 // happen!
1429 $rr['_ORIG_pid'] = $rr['pid'];
1430 $rr['pid'] = $oidRec['pid'];
1431 }
1432 }
1433 }
1434 // Changing PID in case of moving pointer:
1435 if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1436 $rr['pid'] = $movePlhRec['pid'];
1437 }
1438 }
1439
1440 /**
1441 * Versioning Preview Overlay
1442 *
1443 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1444 * served which is not previewed by backend users!!!
1445 *
1446 * Generally ALWAYS used when records are selected based on uid or pid. If
1447 * records are selected on other fields than uid or pid (eg. "email = ....") then
1448 * usage might produce undesired results and that should be evaluated on
1449 * individual basis.
1450 *
1451 * Principle; Record online! => Find offline?
1452 *
1453 * @param string $table Table name
1454 * @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!
1455 * @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)
1456 * @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!
1457 * @see fixVersioningPid(), BackendUtility::workspaceOL()
1458 */
1459 public function versionOL($table, &$row, $unsetMovePointers = false, $bypassEnableFieldsCheck = false)
1460 {
1461 if ($this->versioningPreview && is_array($row)) {
1462 // will overlay any movePlhOL found with the real record, which in turn
1463 // will be overlaid with its workspace version if any.
1464 $movePldSwap = $this->movePlhOL($table, $row);
1465 // implode(',',array_keys($row)) = Using fields from original record to make
1466 // sure no additional fields are selected. This is best for eg. getPageOverlay()
1467 // Computed properties are excluded since those would lead to SQL errors.
1468 $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1469 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1470 if (is_array($wsAlt)) {
1471 // Always fix PID (like in fixVersioningPid() above). [This is usually not
1472 // the important factor for versioning OL]
1473 // Keep the old (-1) - indicates it was a version...
1474 $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1475 // Set in the online versions PID.
1476 $wsAlt['pid'] = $row['pid'];
1477 // For versions of single elements or page+content, preserve online UID and PID
1478 // (this will produce true "overlay" of element _content_, not any references)
1479 // For page+content the "_ORIG_uid" should actually be used as PID for selection.
1480 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1481 $wsAlt['uid'] = $row['uid'];
1482 // Translate page alias as well so links are pointing to the _online_ page:
1483 if ($table === 'pages') {
1484 $wsAlt['alias'] = $row['alias'];
1485 }
1486 // Changing input record to the workspace version alternative:
1487 $row = $wsAlt;
1488 // Check if it is deleted/new
1489 $rowVersionState = VersionState::cast($row['t3ver_state']);
1490 if (
1491 $rowVersionState->equals(VersionState::NEW_PLACEHOLDER)
1492 || $rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)
1493 ) {
1494 // Unset record if it turned out to be deleted in workspace
1495 $row = false;
1496 }
1497 // Check if move-pointer in workspace (unless if a move-placeholder is the
1498 // reason why it appears!):
1499 // You have to specifically set $unsetMovePointers in order to clear these
1500 // because it is normally a display issue if it should be shown or not.
1501 if (
1502 ($rowVersionState->equals(VersionState::MOVE_POINTER)
1503 && !$movePldSwap
1504 ) && $unsetMovePointers
1505 ) {
1506 // Unset record if it turned out to be deleted in workspace
1507 $row = false;
1508 }
1509 } else {
1510 // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1511 // (online version is dummy-representation)
1512 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1513 // enablefields for BOTH the version AND the online record deselects it. See
1514 // note for $bypassEnableFieldsCheck
1515 /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1516 $versionState = VersionState::cast($row['t3ver_state']);
1517 if ($wsAlt <= -1 || $versionState->indicatesPlaceholder()) {
1518 // Unset record if it turned out to be "hidden"
1519 $row = false;
1520 }
1521 }
1522 }
1523 }
1524 }
1525
1526 /**
1527 * Checks if record is a move-placeholder
1528 * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1529 * the pointed-to live record (and return TRUE) Used from versionOL
1530 *
1531 * @param string $table Table name
1532 * @param array $row Row (passed by reference) - only online records...
1533 * @return bool TRUE if overlay is made.
1534 * @see BackendUtility::movePlhOl()
1535 */
1536 public function movePlhOL($table, &$row)
1537 {
1538 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])
1539 && (int)VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)
1540 ) {
1541 // If t3ver_move_id is not found, then find it (but we like best if it is here)
1542 if (!isset($row['t3ver_move_id'])) {
1543 $moveIDRec = $this->getRawRecord($table, $row['uid'], 't3ver_move_id', true);
1544 $moveID = $moveIDRec['t3ver_move_id'];
1545 } else {
1546 $moveID = $row['t3ver_move_id'];
1547 }
1548 // Find pointed-to record.
1549 if ($moveID) {
1550 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1551 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1552 $origRow = $queryBuilder->select(...array_keys($this->purgeComputedProperties($row)))
1553 ->from($table)
1554 ->where(
1555 $queryBuilder->expr()->eq(
1556 'uid',
1557 $queryBuilder->createNamedParameter($moveID, \PDO::PARAM_INT)
1558 )
1559 )
1560 ->setMaxResults(1)
1561 ->execute()
1562 ->fetch();
1563
1564 if ($origRow) {
1565 $row = $origRow;
1566 return true;
1567 }
1568 }
1569 }
1570 return false;
1571 }
1572
1573 /**
1574 * Returns move placeholder of online (live) version
1575 *
1576 * @param string $table Table name
1577 * @param int $uid Record UID of online version
1578 * @param string $fields Field list, default is *
1579 * @return array If found, the record, otherwise nothing.
1580 * @see BackendUtility::getMovePlaceholder()
1581 */
1582 public function getMovePlaceholder($table, $uid, $fields = '*')
1583 {
1584 if ($this->versioningPreview) {
1585 $workspace = (int)$this->versioningWorkspaceId;
1586 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) && $workspace !== 0) {
1587 // Select workspace version of record:
1588 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1589 $queryBuilder->getRestrictions()
1590 ->removeAll()
1591 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1592
1593 $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1594 ->from($table)
1595 ->where(
1596 $queryBuilder->expr()->neq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1597 $queryBuilder->expr()->eq(
1598 't3ver_state',
1599 $queryBuilder->createNamedParameter(
1600 new VersionState(VersionState::MOVE_PLACEHOLDER),
1601 \PDO::PARAM_INT
1602 )
1603 ),
1604 $queryBuilder->expr()->eq(
1605 't3ver_move_id',
1606 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1607 ),
1608 $queryBuilder->expr()->eq(
1609 't3ver_wsid',
1610 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1611 )
1612 )
1613 ->setMaxResults(1)
1614 ->execute()
1615 ->fetch();
1616
1617 if (is_array($row)) {
1618 return $row;
1619 }
1620 }
1621 }
1622 return false;
1623 }
1624
1625 /**
1626 * Select the version of a record for a workspace
1627 *
1628 * @param int $workspace Workspace ID
1629 * @param string $table Table name to select from
1630 * @param int $uid Record uid for which to find workspace version.
1631 * @param string $fields Field list to select
1632 * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1633 * @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.
1634 * @see BackendUtility::getWorkspaceVersionOfRecord()
1635 */
1636 public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = false)
1637 {
1638 if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1639 $workspace = (int)$workspace;
1640 $uid = (int)$uid;
1641 // Select workspace version of record, only testing for deleted.
1642 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1643 $queryBuilder->getRestrictions()
1644 ->removeAll()
1645 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1646
1647 $newrow = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1648 ->from($table)
1649 ->where(
1650 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1651 $queryBuilder->expr()->eq(
1652 't3ver_oid',
1653 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1654 ),
1655 $queryBuilder->expr()->eq(
1656 't3ver_wsid',
1657 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1658 )
1659 )
1660 ->setMaxResults(1)
1661 ->execute()
1662 ->fetch();
1663
1664 // If version found, check if it could have been selected with enableFields on
1665 // as well:
1666 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1667 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1668 // Remove the frontend workspace restriction because we are testing a version record
1669 $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction::class);
1670 $queryBuilder->select('uid')
1671 ->from($table)
1672 ->setMaxResults(1);
1673
1674 if (is_array($newrow)) {
1675 $queryBuilder->where(
1676 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1677 $queryBuilder->expr()->eq(
1678 't3ver_oid',
1679 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1680 ),
1681 $queryBuilder->expr()->eq(
1682 't3ver_wsid',
1683 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1684 )
1685 );
1686 if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1687 // Return offline version, tested for its enableFields.
1688 return $newrow;
1689 } else {
1690 // Return -1 because offline version was de-selected due to its enableFields.
1691 return -1;
1692 }
1693 } else {
1694 // OK, so no workspace version was found. Then check if online version can be
1695 // selected with full enable fields and if so, return 1:
1696 $queryBuilder->where(
1697 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
1698 );
1699 if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1700 // Means search was done, but no version found.
1701 return 1;
1702 } else {
1703 // Return -2 because the online record was de-selected due to its enableFields.
1704 return -2;
1705 }
1706 }
1707 }
1708 // No look up in database because versioning not enabled / or workspace not
1709 // offline
1710 return false;
1711 }
1712
1713 /**
1714 * Checks if user has access to workspace.
1715 *
1716 * @param int $wsid Workspace ID
1717 * @return bool <code>TRUE</code> if has access
1718 */
1719 public function checkWorkspaceAccess($wsid)
1720 {
1721 if (!$this->getBackendUser() || !ExtensionManagementUtility::isLoaded('workspaces')) {
1722 return false;
1723 }
1724 if (isset($this->workspaceCache[$wsid])) {
1725 $ws = $this->workspaceCache[$wsid];
1726 } else {
1727 if ($wsid > 0) {
1728 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1729 ->getQueryBuilderForTable('sys_workspace');
1730 $queryBuilder->getRestrictions()->removeAll();
1731 $ws = $queryBuilder->select('*')
1732 ->from('sys_workspace')
1733 ->where(
1734 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($wsid, \PDO::PARAM_INT)),
1735 $queryBuilder->expr()->eq('deleted', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1736 )
1737 ->execute()
1738 ->fetch();
1739 if (!is_array($ws)) {
1740 return false;
1741 }
1742 } else {
1743 $ws = $wsid;
1744 }
1745 $ws = $this->getBackendUser()->checkWorkspace($ws);
1746 $this->workspaceCache[$wsid] = $ws;
1747 }
1748 return (string)$ws['_ACCESS'] !== '';
1749 }
1750
1751 /**
1752 * Gets file references for a given record field.
1753 *
1754 * @param string $tableName Name of the table
1755 * @param string $fieldName Name of the field
1756 * @param array $element The parent element referencing to files
1757 * @return array
1758 */
1759 public function getFileReferences($tableName, $fieldName, array $element)
1760 {
1761 /** @var $fileRepository FileRepository */
1762 $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
1763 $currentId = !empty($element['uid']) ? $element['uid'] : 0;
1764
1765 // Fetch the references of the default element
1766 try {
1767 $references = $fileRepository->findByRelation($tableName, $fieldName, $currentId);
1768 } catch (FileDoesNotExistException $e) {
1769 /**
1770 * We just catch the exception here
1771 * Reasoning: There is nothing an editor or even admin could do
1772 */
1773 return [];
1774 } catch (\InvalidArgumentException $e) {
1775 /**
1776 * The storage does not exist anymore
1777 * Log the exception message for admins as they maybe can restore the storage
1778 */
1779 $logMessage = $e->getMessage() . ' (table: "' . $tableName . '", fieldName: "' . $fieldName . '", currentId: ' . $currentId . ')';
1780 GeneralUtility::sysLog($logMessage, 'core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1781 return [];
1782 }
1783
1784 $localizedId = null;
1785 if (isset($element['_LOCALIZED_UID'])) {
1786 $localizedId = $element['_LOCALIZED_UID'];
1787 } elseif (isset($element['_PAGES_OVERLAY_UID'])) {
1788 $localizedId = $element['_PAGES_OVERLAY_UID'];
1789 }
1790
1791 if ($tableName === 'pages') {
1792 $tableName = 'pages_language_overlay';
1793 }
1794
1795 $isTableLocalizable = (
1796 !empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1797 && !empty($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1798 );
1799 if ($isTableLocalizable && $localizedId !== null) {
1800 $localizedReferences = $fileRepository->findByRelation($tableName, $fieldName, $localizedId);
1801 $references = $localizedReferences;
1802 }
1803
1804 return $references;
1805 }
1806
1807 /**
1808 * Purges computed properties from database rows,
1809 * such as _ORIG_uid or _ORIG_pid for instance.
1810 *
1811 * @param array $row
1812 * @return array
1813 */
1814 protected function purgeComputedProperties(array $row)
1815 {
1816 foreach ($this->computedPropertyNames as $computedPropertyName) {
1817 if (array_key_exists($computedPropertyName, $row)) {
1818 unset($row[$computedPropertyName]);
1819 }
1820 }
1821 return $row;
1822 }
1823
1824 /**
1825 * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
1826 */
1827 protected function getTypoScriptFrontendController()
1828 {
1829 return $GLOBALS['TSFE'];
1830 }
1831
1832 /**
1833 * Returns the current BE user.
1834 *
1835 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1836 */
1837 protected function getBackendUser()
1838 {
1839 return $GLOBALS['BE_USER'];
1840 }
1841 }