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