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