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