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