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