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