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