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