[TASK] Deprecate "noWSOL" in PageRepository->getRecordRaw
[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 = null)
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 !== null) {
1146 GeneralUtility::deprecationLog('The fourth parameter of PageRepository->getRawRecord() has been deprecated, use a SQL statement directly. The parameter will be removed in TYPO3 v10.');
1147 }
1148 // @deprecated - remove this if-clause in TYPO3 v10
1149 if (!$noWSOL) {
1150 $this->versionOL($table, $row);
1151 }
1152 if (is_array($row)) {
1153 return $row;
1154 }
1155 }
1156 }
1157 return 0;
1158 }
1159
1160 /**
1161 * Selects records based on matching a field (ei. other than UID) with a value
1162 *
1163 * @param string $theTable The table name to search, eg. "pages" or "tt_content
1164 * @param string $theField The fieldname to match, eg. "uid" or "alias
1165 * @param string $theValue The value that fieldname must match, eg. "123" or "frontpage
1166 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
1167 * @param string $groupBy Optional GROUP BY field(s). If none, supply blank string.
1168 * @param string $orderBy Optional ORDER BY field(s). If none, supply blank string.
1169 * @param string $limit Optional LIMIT value ([begin,]max). If none, supply blank string.
1170 * @return mixed Returns array (the record) if found, otherwise nothing (void)
1171 */
1172 public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
1173 {
1174 if (is_array($GLOBALS['TCA'][$theTable])) {
1175 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($theTable);
1176 $queryBuilder->getRestrictions()
1177 ->removeAll()
1178 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1179
1180 $queryBuilder->select('*')
1181 ->from($theTable)
1182 ->where($queryBuilder->expr()->eq($theField, $queryBuilder->createNamedParameter($theValue)));
1183
1184 if ($whereClause !== '') {
1185 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($whereClause));
1186 }
1187
1188 if ($groupBy !== '') {
1189 $queryBuilder->groupBy(QueryHelper::parseGroupBy($groupBy));
1190 }
1191
1192 if ($orderBy !== '') {
1193 foreach (QueryHelper::parseOrderBy($orderBy) as $orderPair) {
1194 list($fieldName, $order) = $orderPair;
1195 $queryBuilder->addOrderBy($fieldName, $order);
1196 }
1197 }
1198
1199 if ($limit !== '') {
1200 if (strpos($limit, ',')) {
1201 $limitOffsetAndMax = GeneralUtility::intExplode(',', $limit);
1202 $queryBuilder->setFirstResult((int)$limitOffsetAndMax[0]);
1203 $queryBuilder->setMaxResults((int)$limitOffsetAndMax[1]);
1204 } else {
1205 $queryBuilder->setMaxResults((int)$limit);
1206 }
1207 }
1208
1209 $rows = $queryBuilder->execute()->fetchAll();
1210
1211 if (!empty($rows)) {
1212 return $rows;
1213 }
1214 }
1215 return null;
1216 }
1217
1218 /********************************
1219 *
1220 * Standard clauses
1221 *
1222 ********************************/
1223
1224 /**
1225 * Returns the "AND NOT deleted" clause for the tablename given IF
1226 * $GLOBALS['TCA'] configuration points to such a field.
1227 *
1228 * @param string $table Tablename
1229 * @return string
1230 * @see enableFields()
1231 */
1232 public function deleteClause($table)
1233 {
1234 return $GLOBALS['TCA'][$table]['ctrl']['delete'] ? ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0' : '';
1235 }
1236
1237 /**
1238 * Returns a part of a WHERE clause which will filter out records with start/end
1239 * times or hidden/fe_groups fields set to values that should de-select them
1240 * according to the current time, preview settings or user login. Definitely a
1241 * frontend function.
1242 *
1243 * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1244 * determines for each table which of these features applies to that table.
1245 *
1246 * @param string $table Table name found in the $GLOBALS['TCA'] array
1247 * @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.
1248 * @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.
1249 * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
1250 * @throws \InvalidArgumentException
1251 * @return string The clause starting like " AND ...=... AND ...=...
1252 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields(), deleteClause()
1253 */
1254 public function enableFields($table, $show_hidden = -1, $ignore_array = [], $noVersionPreview = false)
1255 {
1256 if ($show_hidden === -1 && is_object($this->getTypoScriptFrontendController())) {
1257 // If show_hidden was not set from outside and if TSFE is an object, set it
1258 // based on showHiddenPage and showHiddenRecords from TSFE
1259 $show_hidden = $table === 'pages' || $table === 'pages_language_overlay'
1260 ? $this->getTypoScriptFrontendController()->showHiddenPage
1261 : $this->getTypoScriptFrontendController()->showHiddenRecords;
1262 }
1263 if ($show_hidden === -1) {
1264 $show_hidden = 0;
1265 }
1266 // If show_hidden was not changed during the previous evaluation, do it here.
1267 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
1268 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1269 ->getQueryBuilderForTable($table)
1270 ->expr();
1271 $constraints = [];
1272 if (is_array($ctrl)) {
1273 // Delete field check:
1274 if ($ctrl['delete']) {
1275 $constraints[] = $expressionBuilder->eq($table . '.' . $ctrl['delete'], 0);
1276 }
1277 if ($ctrl['versioningWS']) {
1278 if (!$this->versioningPreview) {
1279 // Filter out placeholder records (new/moved/deleted items)
1280 // in case we are NOT in a versioning preview (that means we are online!)
1281 $constraints[] = $expressionBuilder->lte(
1282 $table . '.t3ver_state',
1283 new VersionState(VersionState::DEFAULT_STATE)
1284 );
1285 } elseif ($table !== 'pages') {
1286 // show only records of live and of the current workspace
1287 // in case we are in a versioning preview
1288 $constraints[] = $expressionBuilder->orX(
1289 $expressionBuilder->eq($table . '.t3ver_wsid', 0),
1290 $expressionBuilder->eq($table . '.t3ver_wsid', (int)$this->versioningWorkspaceId)
1291 );
1292 }
1293
1294 // Filter out versioned records
1295 if (!$noVersionPreview && empty($ignore_array['pid'])) {
1296 $constraints[] = $expressionBuilder->neq($table . '.pid', -1);
1297 }
1298 }
1299
1300 // Enable fields:
1301 if (is_array($ctrl['enablecolumns'])) {
1302 // In case of versioning-preview, enableFields are ignored (checked in
1303 // versionOL())
1304 if (!$this->versioningPreview || !$ctrl['versioningWS'] || $noVersionPreview) {
1305 if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
1306 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1307 $constraints[] = $expressionBuilder->eq($field, 0);
1308 }
1309 if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
1310 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1311 $constraints[] = $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']);
1312 }
1313 if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
1314 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1315 $constraints[] = $expressionBuilder->orX(
1316 $expressionBuilder->eq($field, 0),
1317 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
1318 );
1319 }
1320 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1321 $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1322 $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1323 $this->getMultipleGroupsWhereClause($field, $table)
1324 );
1325 }
1326 // Call hook functions for additional enableColumns
1327 // It is used by the extension ingmar_accessctrl which enables assigning more
1328 // than one usergroup to content and page records
1329 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'])) {
1330 $_params = [
1331 'table' => $table,
1332 'show_hidden' => $show_hidden,
1333 'ignore_array' => $ignore_array,
1334 'ctrl' => $ctrl
1335 ];
1336 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] as $_funcRef) {
1337 $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1338 GeneralUtility::callUserFunction($_funcRef, $_params, $this)
1339 );
1340 }
1341 }
1342 }
1343 }
1344 } else {
1345 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);
1346 }
1347
1348 return empty($constraints) ? '' : ' AND ' . $expressionBuilder->andX(...$constraints);
1349 }
1350
1351 /**
1352 * Creating where-clause for checking group access to elements in enableFields
1353 * function
1354 *
1355 * @param string $field Field with group list
1356 * @param string $table Table name
1357 * @return string AND sql-clause
1358 * @see enableFields()
1359 */
1360 public function getMultipleGroupsWhereClause($field, $table)
1361 {
1362 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1363 ->getQueryBuilderForTable($table)
1364 ->expr();
1365 $memberGroups = GeneralUtility::intExplode(',', $this->getTypoScriptFrontendController()->gr_list);
1366 $orChecks = [];
1367 // If the field is empty, then OK
1368 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal(''));
1369 // If the field is NULL, then OK
1370 $orChecks[] = $expressionBuilder->isNull($field);
1371 // If the field contains zero, then OK
1372 $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal('0'));
1373 foreach ($memberGroups as $value) {
1374 $orChecks[] = $expressionBuilder->inSet($field, $expressionBuilder->literal($value));
1375 }
1376
1377 return' AND (' . $expressionBuilder->orX(...$orChecks) . ')';
1378 }
1379
1380 /**********************
1381 *
1382 * Versioning Preview
1383 *
1384 **********************/
1385
1386 /**
1387 * Finding online PID for offline version record
1388 *
1389 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1390 * served which is not previewed by backend users!!!
1391 *
1392 * Will look if the "pid" value of the input record is -1 (it is an offline
1393 * version) and if the table supports versioning; if so, it will translate the -1
1394 * PID into the PID of the original record.
1395 *
1396 * Used whenever you are tracking something back, like making the root line.
1397 *
1398 * Principle; Record offline! => Find online?
1399 *
1400 * @param string $table Table name
1401 * @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.
1402 * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1403 */
1404 public function fixVersioningPid($table, &$rr)
1405 {
1406 if ($this->versioningPreview && is_array($rr) && (int)$rr['pid'] === -1 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1407 $oid = 0;
1408 $wsid = 0;
1409 // Check values for t3ver_oid and t3ver_wsid:
1410 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1411 // If "t3ver_oid" is already a field, just set this:
1412 $oid = $rr['t3ver_oid'];
1413 $wsid = $rr['t3ver_wsid'];
1414 } else {
1415 // Otherwise we have to expect "uid" to be in the record and look up based
1416 // on this:
1417 $uid = (int)$rr['uid'];
1418 if ($uid > 0) {
1419 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1420 $queryBuilder->getRestrictions()
1421 ->removeAll()
1422 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1423 $newPidRec = $queryBuilder->select('t3ver_oid', 't3ver_wsid')
1424 ->from($table)
1425 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1426 ->execute()
1427 ->fetch();
1428
1429 if (is_array($newPidRec)) {
1430 $oid = $newPidRec['t3ver_oid'];
1431 $wsid = $newPidRec['t3ver_wsid'];
1432 }
1433 }
1434 }
1435 // If workspace ids matches and ID of current online version is found, look up
1436 // the PID value of that:
1437 if ($oid && ((int)$this->versioningWorkspaceId === 0 && $this->checkWorkspaceAccess($wsid) || (int)$wsid === (int)$this->versioningWorkspaceId)) {
1438 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1439 $queryBuilder->getRestrictions()
1440 ->removeAll()
1441 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1442 $oidRec = $queryBuilder->select('pid')
1443 ->from($table)
1444 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($oid, \PDO::PARAM_INT)))
1445 ->execute()
1446 ->fetch();
1447
1448 if (is_array($oidRec)) {
1449 // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1450 // assumed that this is a "branch" type page and therefore the uid should be
1451 // kept (like in versionOL()). However if the page is NOT a branch version it
1452 // should not happen - but then again, direct access to that uid should not
1453 // happen!
1454 $rr['_ORIG_pid'] = $rr['pid'];
1455 $rr['pid'] = $oidRec['pid'];
1456 }
1457 }
1458 }
1459 // Changing PID in case of moving pointer:
1460 if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1461 $rr['pid'] = $movePlhRec['pid'];
1462 }
1463 }
1464
1465 /**
1466 * Versioning Preview Overlay
1467 *
1468 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1469 * served which is not previewed by backend users!!!
1470 *
1471 * Generally ALWAYS used when records are selected based on uid or pid. If
1472 * records are selected on other fields than uid or pid (eg. "email = ....") then
1473 * usage might produce undesired results and that should be evaluated on
1474 * individual basis.
1475 *
1476 * Principle; Record online! => Find offline?
1477 *
1478 * @param string $table Table name
1479 * @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!
1480 * @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)
1481 * @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!
1482 * @see fixVersioningPid(), BackendUtility::workspaceOL()
1483 */
1484 public function versionOL($table, &$row, $unsetMovePointers = false, $bypassEnableFieldsCheck = false)
1485 {
1486 if ($this->versioningPreview && is_array($row)) {
1487 // will overlay any movePlhOL found with the real record, which in turn
1488 // will be overlaid with its workspace version if any.
1489 $movePldSwap = $this->movePlhOL($table, $row);
1490 // implode(',',array_keys($row)) = Using fields from original record to make
1491 // sure no additional fields are selected. This is best for eg. getPageOverlay()
1492 // Computed properties are excluded since those would lead to SQL errors.
1493 $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1494 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1495 if (is_array($wsAlt)) {
1496 // Always fix PID (like in fixVersioningPid() above). [This is usually not
1497 // the important factor for versioning OL]
1498 // Keep the old (-1) - indicates it was a version...
1499 $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1500 // Set in the online versions PID.
1501 $wsAlt['pid'] = $row['pid'];
1502 // For versions of single elements or page+content, preserve online UID and PID
1503 // (this will produce true "overlay" of element _content_, not any references)
1504 // For page+content the "_ORIG_uid" should actually be used as PID for selection.
1505 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1506 $wsAlt['uid'] = $row['uid'];
1507 // Translate page alias as well so links are pointing to the _online_ page:
1508 if ($table === 'pages') {
1509 $wsAlt['alias'] = $row['alias'];
1510 }
1511 // Changing input record to the workspace version alternative:
1512 $row = $wsAlt;
1513 // Check if it is deleted/new
1514 $rowVersionState = VersionState::cast($row['t3ver_state']);
1515 if (
1516 $rowVersionState->equals(VersionState::NEW_PLACEHOLDER)
1517 || $rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)
1518 ) {
1519 // Unset record if it turned out to be deleted in workspace
1520 $row = false;
1521 }
1522 // Check if move-pointer in workspace (unless if a move-placeholder is the
1523 // reason why it appears!):
1524 // You have to specifically set $unsetMovePointers in order to clear these
1525 // because it is normally a display issue if it should be shown or not.
1526 if (
1527 ($rowVersionState->equals(VersionState::MOVE_POINTER)
1528 && !$movePldSwap
1529 ) && $unsetMovePointers
1530 ) {
1531 // Unset record if it turned out to be deleted in workspace
1532 $row = false;
1533 }
1534 } else {
1535 // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1536 // (online version is dummy-representation)
1537 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1538 // enablefields for BOTH the version AND the online record deselects it. See
1539 // note for $bypassEnableFieldsCheck
1540 /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1541 $versionState = VersionState::cast($row['t3ver_state']);
1542 if ($wsAlt <= -1 || $versionState->indicatesPlaceholder()) {
1543 // Unset record if it turned out to be "hidden"
1544 $row = false;
1545 }
1546 }
1547 }
1548 }
1549 }
1550
1551 /**
1552 * Checks if record is a move-placeholder
1553 * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1554 * the pointed-to live record (and return TRUE) Used from versionOL
1555 *
1556 * @param string $table Table name
1557 * @param array $row Row (passed by reference) - only online records...
1558 * @return bool TRUE if overlay is made.
1559 * @see BackendUtility::movePlhOl()
1560 */
1561 public function movePlhOL($table, &$row)
1562 {
1563 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])
1564 && (int)VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)
1565 ) {
1566 $moveID = 0;
1567 // If t3ver_move_id is not found, then find it (but we like best if it is here)
1568 if (!isset($row['t3ver_move_id'])) {
1569 if ((int)$row['uid'] > 0) {
1570 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1571 $queryBuilder->getRestrictions()
1572 ->removeAll()
1573 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1574 $moveIDRec = $queryBuilder->select('t3ver_move_id')
1575 ->from($table)
1576 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)))
1577 ->execute()
1578 ->fetch();
1579
1580 if (is_array($moveIDRec)) {
1581 $moveID = $moveIDRec['t3ver_move_id'];
1582 }
1583 }
1584 } else {
1585 $moveID = $row['t3ver_move_id'];
1586 }
1587 // Find pointed-to record.
1588 if ($moveID) {
1589 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1590 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1591 $origRow = $queryBuilder->select(...array_keys($this->purgeComputedProperties($row)))
1592 ->from($table)
1593 ->where(
1594 $queryBuilder->expr()->eq(
1595 'uid',
1596 $queryBuilder->createNamedParameter($moveID, \PDO::PARAM_INT)
1597 )
1598 )
1599 ->setMaxResults(1)
1600 ->execute()
1601 ->fetch();
1602
1603 if ($origRow) {
1604 $row = $origRow;
1605 return true;
1606 }
1607 }
1608 }
1609 return false;
1610 }
1611
1612 /**
1613 * Returns move placeholder of online (live) version
1614 *
1615 * @param string $table Table name
1616 * @param int $uid Record UID of online version
1617 * @param string $fields Field list, default is *
1618 * @return array If found, the record, otherwise nothing.
1619 * @see BackendUtility::getMovePlaceholder()
1620 */
1621 public function getMovePlaceholder($table, $uid, $fields = '*')
1622 {
1623 if ($this->versioningPreview) {
1624 $workspace = (int)$this->versioningWorkspaceId;
1625 if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) && $workspace !== 0) {
1626 // Select workspace version of record:
1627 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1628 $queryBuilder->getRestrictions()
1629 ->removeAll()
1630 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1631
1632 $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1633 ->from($table)
1634 ->where(
1635 $queryBuilder->expr()->neq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1636 $queryBuilder->expr()->eq(
1637 't3ver_state',
1638 $queryBuilder->createNamedParameter(
1639 new VersionState(VersionState::MOVE_PLACEHOLDER),
1640 \PDO::PARAM_INT
1641 )
1642 ),
1643 $queryBuilder->expr()->eq(
1644 't3ver_move_id',
1645 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1646 ),
1647 $queryBuilder->expr()->eq(
1648 't3ver_wsid',
1649 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1650 )
1651 )
1652 ->setMaxResults(1)
1653 ->execute()
1654 ->fetch();
1655
1656 if (is_array($row)) {
1657 return $row;
1658 }
1659 }
1660 }
1661 return false;
1662 }
1663
1664 /**
1665 * Select the version of a record for a workspace
1666 *
1667 * @param int $workspace Workspace ID
1668 * @param string $table Table name to select from
1669 * @param int $uid Record uid for which to find workspace version.
1670 * @param string $fields Field list to select
1671 * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1672 * @return mixed If found, return record, otherwise other value: Returns 1 if version was sought for but not found, returns -1/-2 if record (offline/online) existed but had enableFields that would disable it. Returns FALSE if not in workspace or no versioning for record. Notice, that the enablefields of the online record is also tested.
1673 * @see BackendUtility::getWorkspaceVersionOfRecord()
1674 */
1675 public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = false)
1676 {
1677 if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1678 $workspace = (int)$workspace;
1679 $uid = (int)$uid;
1680 // Select workspace version of record, only testing for deleted.
1681 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1682 $queryBuilder->getRestrictions()
1683 ->removeAll()
1684 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1685
1686 $newrow = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1687 ->from($table)
1688 ->where(
1689 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1690 $queryBuilder->expr()->eq(
1691 't3ver_oid',
1692 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1693 ),
1694 $queryBuilder->expr()->eq(
1695 't3ver_wsid',
1696 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1697 )
1698 )
1699 ->setMaxResults(1)
1700 ->execute()
1701 ->fetch();
1702
1703 // If version found, check if it could have been selected with enableFields on
1704 // as well:
1705 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1706 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1707 // Remove the frontend workspace restriction because we are testing a version record
1708 $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction::class);
1709 $queryBuilder->select('uid')
1710 ->from($table)
1711 ->setMaxResults(1);
1712
1713 if (is_array($newrow)) {
1714 $queryBuilder->where(
1715 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1716 $queryBuilder->expr()->eq(
1717 't3ver_oid',
1718 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1719 ),
1720 $queryBuilder->expr()->eq(
1721 't3ver_wsid',
1722 $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1723 )
1724 );
1725 if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1726 // Return offline version, tested for its enableFields.
1727 return $newrow;
1728 } else {
1729 // Return -1 because offline version was de-selected due to its enableFields.
1730 return -1;
1731 }
1732 } else {
1733 // OK, so no workspace version was found. Then check if online version can be
1734 // selected with full enable fields and if so, return 1:
1735 $queryBuilder->where(
1736 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
1737 );
1738 if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1739 // Means search was done, but no version found.
1740 return 1;
1741 } else {
1742 // Return -2 because the online record was de-selected due to its enableFields.
1743 return -2;
1744 }
1745 }
1746 }
1747 // No look up in database because versioning not enabled / or workspace not
1748 // offline
1749 return false;
1750 }
1751
1752 /**
1753 * Checks if user has access to workspace.
1754 *
1755 * @param int $wsid Workspace ID
1756 * @return bool <code>TRUE</code> if has access
1757 */
1758 public function checkWorkspaceAccess($wsid)
1759 {
1760 if (!$this->getBackendUser() || !ExtensionManagementUtility::isLoaded('workspaces')) {
1761 return false;
1762 }
1763 if (isset($this->workspaceCache[$wsid])) {
1764 $ws = $this->workspaceCache[$wsid];
1765 } else {
1766 if ($wsid > 0) {
1767 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1768 ->getQueryBuilderForTable('sys_workspace');
1769 $queryBuilder->getRestrictions()->removeAll();
1770 $ws = $queryBuilder->select('*')
1771 ->from('sys_workspace')
1772 ->where(
1773 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($wsid, \PDO::PARAM_INT)),
1774 $queryBuilder->expr()->eq('deleted', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1775 )
1776 ->execute()
1777 ->fetch();
1778 if (!is_array($ws)) {
1779 return false;
1780 }
1781 } else {
1782 $ws = $wsid;
1783 }
1784 $ws = $this->getBackendUser()->checkWorkspace($ws);
1785 $this->workspaceCache[$wsid] = $ws;
1786 }
1787 return (string)$ws['_ACCESS'] !== '';
1788 }
1789
1790 /**
1791 * Gets file references for a given record field.
1792 *
1793 * @param string $tableName Name of the table
1794 * @param string $fieldName Name of the field
1795 * @param array $element The parent element referencing to files
1796 * @return array
1797 */
1798 public function getFileReferences($tableName, $fieldName, array $element)
1799 {
1800 /** @var $fileRepository FileRepository */
1801 $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
1802 $currentId = !empty($element['uid']) ? $element['uid'] : 0;
1803
1804 // Fetch the references of the default element
1805 try {
1806 $references = $fileRepository->findByRelation($tableName, $fieldName, $currentId);
1807 } catch (FileDoesNotExistException $e) {
1808 /**
1809 * We just catch the exception here
1810 * Reasoning: There is nothing an editor or even admin could do
1811 */
1812 return [];
1813 } catch (\InvalidArgumentException $e) {
1814 /**
1815 * The storage does not exist anymore
1816 * Log the exception message for admins as they maybe can restore the storage
1817 */
1818 $logMessage = $e->getMessage() . ' (table: "' . $tableName . '", fieldName: "' . $fieldName . '", currentId: ' . $currentId . ')';
1819 GeneralUtility::sysLog($logMessage, 'core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1820 return [];
1821 }
1822
1823 $localizedId = null;
1824 if (isset($element['_LOCALIZED_UID'])) {
1825 $localizedId = $element['_LOCALIZED_UID'];
1826 } elseif (isset($element['_PAGES_OVERLAY_UID'])) {
1827 $localizedId = $element['_PAGES_OVERLAY_UID'];
1828 }
1829
1830 if ($tableName === 'pages') {
1831 $tableName = 'pages_language_overlay';
1832 }
1833
1834 $isTableLocalizable = (
1835 !empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1836 && !empty($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1837 );
1838 if ($isTableLocalizable && $localizedId !== null) {
1839 $localizedReferences = $fileRepository->findByRelation($tableName, $fieldName, $localizedId);
1840 $references = $localizedReferences;
1841 }
1842
1843 return $references;
1844 }
1845
1846 /**
1847 * Purges computed properties from database rows,
1848 * such as _ORIG_uid or _ORIG_pid for instance.
1849 *
1850 * @param array $row
1851 * @return array
1852 */
1853 protected function purgeComputedProperties(array $row)
1854 {
1855 foreach ($this->computedPropertyNames as $computedPropertyName) {
1856 if (array_key_exists($computedPropertyName, $row)) {
1857 unset($row[$computedPropertyName]);
1858 }
1859 }
1860 return $row;
1861 }
1862
1863 /**
1864 * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
1865 */
1866 protected function getTypoScriptFrontendController()
1867 {
1868 return $GLOBALS['TSFE'];
1869 }
1870
1871 /**
1872 * Returns the current BE user.
1873 *
1874 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1875 */
1876 protected function getBackendUser()
1877 {
1878 return $GLOBALS['BE_USER'];
1879 }
1880 }