[TASK] Deprecate $disable Option in PageRepository->getExtURL
[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 isset($rows[0]) ? $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 (empty($pagesInput)) {
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 (!empty($fieldArr)) {
377 if (!in_array('pid', $fieldArr, TRUE)) {
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 $overlays = array();
394 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
395 $this->versionOL('pages_language_overlay', $row);
396 if (is_array($row)) {
397 $row['_PAGES_OVERLAY'] = TRUE;
398 $row['_PAGES_OVERLAY_UID'] = $row['uid'];
399 $row['_PAGES_OVERLAY_LANGUAGE'] = $lUid;
400 $origUid = $row['pid'];
401 // Unset vital fields that are NOT allowed to be overlaid:
402 unset($row['uid']);
403 unset($row['pid']);
404 $overlays[$origUid] = $row;
405 }
406 }
407 $this->getDatabaseConnection()->sql_free_result($res);
408 }
409 }
410 // Create output:
411 $pagesOutput = array();
412 foreach ($pagesInput as $key => $origPage) {
413 if (is_array($origPage)) {
414 $pagesOutput[$key] = $origPage;
415 if (isset($overlays[$origPage['uid']])) {
416 // Overwrite the original field with the overlay
417 foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
418 if ($fieldName !== 'uid' && $fieldName !== 'pid') {
419 if ($this->shouldFieldBeOverlaid('pages_language_overlay', $fieldName, $fieldValue)) {
420 $pagesOutput[$key][$fieldName] = $fieldValue;
421 }
422 }
423 }
424 }
425 } else {
426 if (isset($overlays[$origPage])) {
427 $pagesOutput[$key] = $overlays[$origPage];
428 }
429 }
430 }
431 return $pagesOutput;
432 }
433
434 /**
435 * Creates language-overlay for records in general (where translation is found
436 * in records from the same table)
437 *
438 * @param string $table Table name
439 * @param array $row Record to overlay. Must containt uid, pid and $table]['ctrl']['languageField']
440 * @param int $sys_language_content Pointer to the sys_language uid for content on the site.
441 * @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned un-translated but unset (and return value is FALSE)
442 * @throws \UnexpectedValueException
443 * @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.
444 */
445 public function getRecordOverlay($table, $row, $sys_language_content, $OLmode = '') {
446 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'])) {
447 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] as $classRef) {
448 $hookObject = GeneralUtility::getUserObj($classRef);
449 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
450 throw new \UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881658);
451 }
452 $hookObject->getRecordOverlay_preProcess($table, $row, $sys_language_content, $OLmode, $this);
453 }
454 }
455 if ($row['uid'] > 0 && ($row['pid'] > 0 || in_array($table, $this->tableNamesAllowedOnRootLevel, TRUE))) {
456 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
457 if (!$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
458 // Will not be able to work with other tables (Just didn't implement it yet;
459 // Requires a scan over all tables [ctrl] part for first FIND the table that
460 // carries localization information for this table (which could even be more
461 // than a single table) and then use that. Could be implemented, but obviously
462 // takes a little more....) Will try to overlay a record only if the
463 // sys_language_content value is larger than zero.
464 if ($sys_language_content > 0) {
465 // Must be default language or [All], otherwise no overlaying:
466 if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] <= 0) {
467 // Select overlay record:
468 $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');
469 $olrow = $this->getDatabaseConnection()->sql_fetch_assoc($res);
470 $this->getDatabaseConnection()->sql_free_result($res);
471 $this->versionOL($table, $olrow);
472 // Merge record content by traversing all fields:
473 if (is_array($olrow)) {
474 if (isset($olrow['_ORIG_uid'])) {
475 $row['_ORIG_uid'] = $olrow['_ORIG_uid'];
476 }
477 if (isset($olrow['_ORIG_pid'])) {
478 $row['_ORIG_pid'] = $olrow['_ORIG_pid'];
479 }
480 foreach ($row as $fN => $fV) {
481 if ($fN !== 'uid' && $fN !== 'pid' && isset($olrow[$fN])) {
482 if ($this->shouldFieldBeOverlaid($table, $fN, $olrow[$fN])) {
483 $row[$fN] = $olrow[$fN];
484 }
485 } elseif ($fN === 'uid') {
486 $row['_LOCALIZED_UID'] = $olrow['uid'];
487 }
488 }
489 } elseif ($OLmode === 'hideNonTranslated' && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
490 // Unset, if non-translated records should be hidden. ONLY done if the source
491 // record really is default language and not [All] in which case it is allowed.
492 unset($row);
493 }
494 } elseif ($sys_language_content != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
495 unset($row);
496 }
497 } else {
498 // When default language is displayed, we never want to return a record carrying
499 // another language!
500 if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
501 unset($row);
502 }
503 }
504 }
505 }
506 }
507 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'])) {
508 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] as $classRef) {
509 $hookObject = GeneralUtility::getUserObj($classRef);
510 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
511 throw new \UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881659);
512 }
513 $hookObject->getRecordOverlay_postProcess($table, $row, $sys_language_content, $OLmode, $this);
514 }
515 }
516 return $row;
517 }
518
519 /************************************************
520 *
521 * Page related: Menu, Domain record, Root line
522 *
523 ************************************************/
524
525 /**
526 * Returns an array with pagerows for subpages with pid=$uid (which is pid
527 * here!). This is used for menus. If there are mount points in overlay mode
528 * the _MP_PARAM field is set to the corret MPvar.
529 *
530 * If the $uid being input does in itself require MPvars to define a correct
531 * rootline these must be handled externally to this function.
532 *
533 * @param int|int[] $uid The page id (or array of page ids) for which to fetch subpages (PID)
534 * @param string $fields List of fields to select. Default is "*" = all
535 * @param string $sortField The field to sort by. Default is "sorting
536 * @param string $addWhere Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
537 * @param bool $checkShortcuts Check if shortcuts exist, checks by default
538 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlayed localized fields, if any)
539 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageShortcut(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
540 * @see \TYPO3\CMS\WizardCrpages\Controller\CreatePagesWizardModuleFunctionController, \TYPO3\CMS\WizardSortpages\View\SortPagesWizardModuleFunction
541 */
542 public function getMenu($uid, $fields = '*', $sortField = 'sorting', $addWhere = '', $checkShortcuts = TRUE) {
543 $output = array();
544 $res = $this->getDatabaseConnection()->exec_SELECTquery(
545 $fields,
546 'pages',
547 'pid IN (' . implode(',', $this->getDatabaseConnection()->cleanIntArray((array)$uid)) . ')' . $this->where_hid_del
548 . $this->where_groupAccess . ' ' . $addWhere,
549 '',
550 $sortField
551 );
552 while (($row = $this->getDatabaseConnection()->sql_fetch_assoc($res))) {
553 $this->versionOL('pages', $row, TRUE);
554 if (is_array($row)) {
555 // Keep mount point:
556 $origUid = $row['uid'];
557 // $row MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields
558 // in it
559 $mount_info = $this->getMountPointInfo($origUid, $row);
560 // There is a valid mount point.
561 if (is_array($mount_info) && $mount_info['overlay']) {
562 // Using "getPage" is OK since we need the check for enableFields AND for type 2
563 // of mount pids we DO require a doktype < 200!
564 $mp_row = $this->getPage($mount_info['mount_pid']);
565 if (!empty($mp_row)) {
566 $row = $mp_row;
567 $row['_MP_PARAM'] = $mount_info['MPvar'];
568 } else {
569 unset($row);
570 }
571 }
572 // If shortcut, look up if the target exists and is currently visible
573 $doktype = (int)$row['doktype'];
574 $shortcutMode = (int)$row['shortcut_mode'];
575 if ($doktype === self::DOKTYPE_SHORTCUT && ($row['shortcut'] || $shortcutMode) && $checkShortcuts) {
576 if ($shortcutMode === 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 ($shortcutMode === self::SHORTCUT_MODE_FIRST_SUBPAGE || $shortcutMode === 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 ($shortcutMode === 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 ($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. - deprecated - don't use anymore.
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 = FALSE) {
725 if ($disable !== FALSE) {
726 GeneralUtility::deprecationLog('The disable option of PageRepository::getExtUrl() is deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8.');
727 return FALSE;
728 }
729 if ((int)$pagerow['doktype'] === self::DOKTYPE_LINK) {
730 $redirectTo = $this->urltypes[$pagerow['urltype']] . $pagerow['url'];
731 // If relative path, prefix Site URL:
732 $uI = parse_url($redirectTo);
733 // Relative path assumed now.
734 if (!$uI['scheme'] && $redirectTo[0] !== '/') {
735 $redirectTo = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $redirectTo;
736 }
737 return $redirectTo;
738 }
739 }
740
741 /**
742 * Returns MountPoint id for page
743 *
744 * Does a recursive search if the mounted page should be a mount page itself. It
745 * has a run-away break so it can't go into infinite loops.
746 *
747 * @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...)
748 * @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
749 * @param array $prevMountPids Array accumulating formerly tested page ids for mount points. Used for recursivity brake.
750 * @param int $firstPageUid The first page id.
751 * @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.
752 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
753 */
754 public function getMountPointInfo($pageId, $pageRec = FALSE, $prevMountPids = array(), $firstPageUid = 0) {
755 $result = FALSE;
756 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
757 if (isset($this->cache_getMountPointInfo[$pageId])) {
758 return $this->cache_getMountPointInfo[$pageId];
759 }
760 // Get pageRec if not supplied:
761 if (!is_array($pageRec)) {
762 $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');
763 $pageRec = $this->getDatabaseConnection()->sql_fetch_assoc($res);
764 $this->getDatabaseConnection()->sql_free_result($res);
765 // Only look for version overlay if page record is not supplied; This assumes
766 // that the input record is overlaid with preview version, if any!
767 $this->versionOL('pages', $pageRec);
768 }
769 // Set first Page uid:
770 if (!$firstPageUid) {
771 $firstPageUid = $pageRec['uid'];
772 }
773 // Look for mount pid value plus other required circumstances:
774 $mount_pid = (int)$pageRec['mount_pid'];
775 if (is_array($pageRec) && (int)$pageRec['doktype'] === self::DOKTYPE_MOUNTPOINT && $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, TRUE)) {
776 // Get the mount point record (to verify its general existence):
777 $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');
778 $mountRec = $this->getDatabaseConnection()->sql_fetch_assoc($res);
779 $this->getDatabaseConnection()->sql_free_result($res);
780 $this->versionOL('pages', $mountRec);
781 if (is_array($mountRec)) {
782 // Look for recursive mount point:
783 $prevMountPids[] = $mount_pid;
784 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
785 // Return mount point information:
786 $result = $recursiveMountPid ?: array(
787 'mount_pid' => $mount_pid,
788 'overlay' => $pageRec['mount_pid_ol'],
789 'MPvar' => $mount_pid . '-' . $firstPageUid,
790 'mount_point_rec' => $pageRec,
791 'mount_pid_rec' => $mountRec
792 );
793 } else {
794 // Means, there SHOULD have been a mount point, but there was none!
795 $result = -1;
796 }
797 }
798 }
799 $this->cache_getMountPointInfo[$pageId] = $result;
800 return $result;
801 }
802
803 /********************************
804 *
805 * Selecting records in general
806 *
807 ********************************/
808
809 /**
810 * Checks if a record exists and is accessible.
811 * The row is returned if everything's OK.
812 *
813 * @param string $table The table name to search
814 * @param int $uid The uid to look up in $table
815 * @param bool $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
816 * @return mixed Returns array (the record) if OK, otherwise blank/0 (zero)
817 */
818 public function checkRecord($table, $uid, $checkPage = 0) {
819 $uid = (int)$uid;
820 if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
821 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', $table, 'uid = ' . $uid . $this->enableFields($table));
822 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
823 $this->getDatabaseConnection()->sql_free_result($res);
824 if ($row) {
825 $this->versionOL($table, $row);
826 if (is_array($row)) {
827 if ($checkPage) {
828 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid', 'pages', 'uid=' . (int)$row['pid'] . $this->enableFields('pages'));
829 $numRows = $this->getDatabaseConnection()->sql_num_rows($res);
830 $this->getDatabaseConnection()->sql_free_result($res);
831 if ($numRows > 0) {
832 return $row;
833 } else {
834 return 0;
835 }
836 } else {
837 return $row;
838 }
839 }
840 }
841 }
842 }
843
844 /**
845 * Returns record no matter what - except if record is deleted
846 *
847 * @param string $table The table name to search
848 * @param int $uid The uid to look up in $table
849 * @param string $fields The fields to select, default is "*
850 * @param bool $noWSOL If set, no version overlay is applied
851 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
852 * @see getPage_noCheck()
853 */
854 public function getRawRecord($table, $uid, $fields = '*', $noWSOL = FALSE) {
855 $uid = (int)$uid;
856 // Excluding pages here so we can ask the function BEFORE TCA gets initialized.
857 // Support for this is followed up in deleteClause()...
858 if ((is_array($GLOBALS['TCA'][$table]) || $table === 'pages') && $uid > 0) {
859 $res = $this->getDatabaseConnection()->exec_SELECTquery($fields, $table, 'uid = ' . $uid . $this->deleteClause($table));
860 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
861 $this->getDatabaseConnection()->sql_free_result($res);
862 if ($row) {
863 if (!$noWSOL) {
864 $this->versionOL($table, $row);
865 }
866 if (is_array($row)) {
867 return $row;
868 }
869 }
870 }
871 }
872
873 /**
874 * Selects records based on matching a field (ei. other than UID) with a value
875 *
876 * @param string $theTable The table name to search, eg. "pages" or "tt_content
877 * @param string $theField The fieldname to match, eg. "uid" or "alias
878 * @param string $theValue The value that fieldname must match, eg. "123" or "frontpage
879 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
880 * @param string $groupBy Optional GROUP BY field(s). If none, supply blank string.
881 * @param string $orderBy Optional ORDER BY field(s). If none, supply blank string.
882 * @param string $limit Optional LIMIT value ([begin,]max). If none, supply blank string.
883 * @return mixed Returns array (the record) if found, otherwise nothing (void)
884 */
885 public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
886 if (is_array($GLOBALS['TCA'][$theTable])) {
887 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', $theTable, $theField . '=' . $this->getDatabaseConnection()->fullQuoteStr($theValue, $theTable) . $this->deleteClause($theTable) . ' ' . $whereClause, $groupBy, $orderBy, $limit);
888 $rows = array();
889 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
890 if (is_array($row)) {
891 $rows[] = $row;
892 }
893 }
894 $this->getDatabaseConnection()->sql_free_result($res);
895 if (!empty($rows)) {
896 return $rows;
897 }
898 }
899 }
900
901 /********************************
902 *
903 * Caching and standard clauses
904 *
905 ********************************/
906
907 /**
908 * Returns data stored for the hash string in the cache "cache_hash"
909 * Can be used to retrieved a cached value, array or object
910 * Can be used from your frontend plugins if you like. It is also used to
911 * store the parsed TypoScript template structures. You can call it directly
912 * like PageRepository::getHash()
913 *
914 * @param string $hash The hash-string which was used to store the data value
915 * @param int The expiration time (not used anymore)
916 * @return mixed The "data" from the cache
917 * @see tslib_TStemplate::start(), storeHash()
918 */
919 static public function getHash($hash, $expTime = 0) {
920 $hashContent = NULL;
921 $contentHashCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash');
922 $cacheEntry = $contentHashCache->get($hash);
923 if ($cacheEntry) {
924 $hashContent = $cacheEntry;
925 }
926 return $hashContent;
927 }
928
929 /**
930 * Stores $data in the 'cache_hash' cache with the hash key, $hash
931 * and visual/symbolic identification, $ident
932 *
933 * Can be used from your frontend plugins if you like. You can call it
934 * directly like PageRepository::storeHash()
935 *
936 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
937 * @param mixed $data The data to store
938 * @param string $ident Is just a textual identification in order to inform about the content!
939 * @param int $lifetime The lifetime for the cache entry in seconds
940 * @return void
941 * @see tslib_TStemplate::start(), getHash()
942 */
943 static public function storeHash($hash, $data, $ident, $lifetime = 0) {
944 GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($hash, $data, array('ident_' . $ident), (int)$lifetime);
945 }
946
947 /**
948 * Returns the "AND NOT deleted" clause for the tablename given IF
949 * $GLOBALS['TCA'] configuration points to such a field.
950 *
951 * @param string $table Tablename
952 * @return string
953 * @see enableFields()
954 */
955 public function deleteClause($table) {
956 // Hardcode for pages because TCA might not be loaded yet (early frontend
957 // initialization)
958 if ($table === 'pages') {
959 return ' AND pages.deleted=0';
960 } else {
961 return $GLOBALS['TCA'][$table]['ctrl']['delete'] ? ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0' : '';
962 }
963 }
964
965 /**
966 * Returns a part of a WHERE clause which will filter out records with start/end
967 * times or hidden/fe_groups fields set to values that should de-select them
968 * according to the current time, preview settings or user login. Definitely a
969 * frontend function.
970 *
971 * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
972 * determines for each table which of these features applies to that table.
973 *
974 * @param string $table Table name found in the $GLOBALS['TCA'] array
975 * @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.
976 * @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.
977 * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
978 * @throws \InvalidArgumentException
979 * @return string The clause starting like " AND ...=... AND ...=...
980 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields(), deleteClause()
981 */
982 public function enableFields($table, $show_hidden = -1, $ignore_array = array(), $noVersionPreview = FALSE) {
983 if ($show_hidden === -1 && is_object($this->getTypoScriptFrontendController())) {
984 // If show_hidden was not set from outside and if TSFE is an object, set it
985 // based on showHiddenPage and showHiddenRecords from TSFE
986 $show_hidden = $table === 'pages' ? $this->getTypoScriptFrontendController()->showHiddenPage : $this->getTypoScriptFrontendController()->showHiddenRecords;
987 }
988 if ($show_hidden === -1) {
989 $show_hidden = 0;
990 }
991 // If show_hidden was not changed during the previous evaluation, do it here.
992 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
993 $query = '';
994 if (is_array($ctrl)) {
995 // Delete field check:
996 if ($ctrl['delete']) {
997 $query .= ' AND ' . $table . '.' . $ctrl['delete'] . '=0';
998 }
999 if ($ctrl['versioningWS']) {
1000 if (!$this->versioningPreview) {
1001 // Filter out placeholder records (new/moved/deleted items)
1002 // in case we are NOT in a versioning preview (that means we are online!)
1003 $query .= ' AND ' . $table . '.t3ver_state<=' . new VersionState(VersionState::DEFAULT_STATE);
1004 } else {
1005 if ($table !== 'pages') {
1006 // show only records of live and of the current workspace
1007 // in case we are in a versioning preview
1008 $query .= ' AND (' .
1009 $table . '.t3ver_wsid=0 OR ' .
1010 $table . '.t3ver_wsid=' . (int)$this->versioningWorkspaceId .
1011 ')';
1012 }
1013 }
1014
1015 // Filter out versioned records
1016 if (!$noVersionPreview && empty($ignore_array['pid'])) {
1017 $query .= ' AND ' . $table . '.pid<>-1';
1018 }
1019 }
1020
1021 // Enable fields:
1022 if (is_array($ctrl['enablecolumns'])) {
1023 // In case of versioning-preview, enableFields are ignored (checked in
1024 // versionOL())
1025 if (!$this->versioningPreview || !$ctrl['versioningWS'] || $noVersionPreview) {
1026 if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
1027 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1028 $query .= ' AND ' . $field . '=0';
1029 }
1030 if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
1031 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1032 $query .= ' AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'];
1033 }
1034 if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
1035 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1036 $query .= ' AND (' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
1037 }
1038 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1039 $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1040 $query .= $this->getMultipleGroupsWhereClause($field, $table);
1041 }
1042 // Call hook functions for additional enableColumns
1043 // It is used by the extension ingmar_accessctrl which enables assigning more
1044 // than one usergroup to content and page records
1045 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'])) {
1046 $_params = array(
1047 'table' => $table,
1048 'show_hidden' => $show_hidden,
1049 'ignore_array' => $ignore_array,
1050 'ctrl' => $ctrl
1051 );
1052 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] as $_funcRef) {
1053 $query .= GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1054 }
1055 }
1056 }
1057 }
1058 } else {
1059 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);
1060 }
1061 return $query;
1062 }
1063
1064 /**
1065 * Creating where-clause for checking group access to elements in enableFields
1066 * function
1067 *
1068 * @param string $field Field with group list
1069 * @param string $table Table name
1070 * @return string AND sql-clause
1071 * @see enableFields()
1072 */
1073 public function getMultipleGroupsWhereClause($field, $table) {
1074 $memberGroups = GeneralUtility::intExplode(',', $this->getTypoScriptFrontendController()->gr_list);
1075 $orChecks = array();
1076 // If the field is empty, then OK
1077 $orChecks[] = $field . '=\'\'';
1078 // If the field is NULL, then OK
1079 $orChecks[] = $field . ' IS NULL';
1080 // If the field contsains zero, then OK
1081 $orChecks[] = $field . '=\'0\'';
1082 foreach ($memberGroups as $value) {
1083 $orChecks[] = $this->getDatabaseConnection()->listQuery($field, $value, $table);
1084 }
1085 return ' AND (' . implode(' OR ', $orChecks) . ')';
1086 }
1087
1088 /**********************
1089 *
1090 * Versioning Preview
1091 *
1092 **********************/
1093
1094 /**
1095 * Finding online PID for offline version record
1096 *
1097 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1098 * served which is not previewed by backend users!!!
1099 *
1100 * Will look if the "pid" value of the input record is -1 (it is an offline
1101 * version) and if the table supports versioning; if so, it will translate the -1
1102 * PID into the PID of the original record.
1103 *
1104 * Used whenever you are tracking something back, like making the root line.
1105 *
1106 * Principle; Record offline! => Find online?
1107 *
1108 * @param string $table Table name
1109 * @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.
1110 * @return void (Passed by ref).
1111 * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1112 */
1113 public function fixVersioningPid($table, &$rr) {
1114 if ($this->versioningPreview && is_array($rr) && (int)$rr['pid'] === -1 && ($table === 'pages' || $GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1115 // Have to hardcode it for "pages" table since TCA is not loaded at this moment!
1116 // Check values for t3ver_oid and t3ver_wsid:
1117 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1118 // If "t3ver_oid" is already a field, just set this:
1119 $oid = $rr['t3ver_oid'];
1120 $wsid = $rr['t3ver_wsid'];
1121 } else {
1122 // Otherwise we have to expect "uid" to be in the record and look up based
1123 // on this:
1124 $newPidRec = $this->getRawRecord($table, $rr['uid'], 't3ver_oid,t3ver_wsid', TRUE);
1125 if (is_array($newPidRec)) {
1126 $oid = $newPidRec['t3ver_oid'];
1127 $wsid = $newPidRec['t3ver_wsid'];
1128 }
1129 }
1130 // If workspace ids matches and ID of current online version is found, look up
1131 // the PID value of that:
1132 if ($oid && ((int)$this->versioningWorkspaceId === 0 && $this->checkWorkspaceAccess($wsid) || (int)$wsid === (int)$this->versioningWorkspaceId)) {
1133 $oidRec = $this->getRawRecord($table, $oid, 'pid', TRUE);
1134 if (is_array($oidRec)) {
1135 // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1136 // assumed that this is a "branch" type page and therefore the uid should be
1137 // kept (like in versionOL()). However if the page is NOT a branch version it
1138 // should not happen - but then again, direct access to that uid should not
1139 // happen!
1140 $rr['_ORIG_pid'] = $rr['pid'];
1141 $rr['pid'] = $oidRec['pid'];
1142 }
1143 }
1144 }
1145 // Changing PID in case of moving pointer:
1146 if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1147 $rr['pid'] = $movePlhRec['pid'];
1148 }
1149 }
1150
1151 /**
1152 * Versioning Preview Overlay
1153 *
1154 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1155 * served which is not previewed by backend users!!!
1156 *
1157 * Generally ALWAYS used when records are selected based on uid or pid. If
1158 * records are selected on other fields than uid or pid (eg. "email = ....") then
1159 * usage might produce undesired results and that should be evaluated on
1160 * individual basis.
1161 *
1162 * Principle; Record online! => Find offline?
1163 *
1164 * @param string $table Table name
1165 * @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!
1166 * @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)
1167 * @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!
1168 * @return void (Passed by ref).
1169 * @see fixVersioningPid(), BackendUtility::workspaceOL()
1170 */
1171 public function versionOL($table, &$row, $unsetMovePointers = FALSE, $bypassEnableFieldsCheck = FALSE) {
1172 if ($this->versioningPreview && is_array($row)) {
1173 // will overlay any movePlhOL found with the real record, which in turn
1174 // will be overlaid with its workspace version if any.
1175 $movePldSwap = $this->movePlhOL($table, $row);
1176 // implode(',',array_keys($row)) = Using fields from original record to make
1177 // sure no additional fields are selected. This is best for eg. getPageOverlay()
1178 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], implode(',', array_keys($row)), $bypassEnableFieldsCheck)) {
1179 if (is_array($wsAlt)) {
1180 // Always fix PID (like in fixVersioningPid() above). [This is usually not
1181 // the important factor for versioning OL]
1182 // Keep the old (-1) - indicates it was a version...
1183 $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1184 // Set in the online versions PID.
1185 $wsAlt['pid'] = $row['pid'];
1186 // For versions of single elements or page+content, preserve online UID and PID
1187 // (this will produce true "overlay" of element _content_, not any references)
1188 // For page+content the "_ORIG_uid" should actually be used as PID for selection
1189 // of tables with "versioning_followPages" enabled.
1190 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1191 $wsAlt['uid'] = $row['uid'];
1192 // Translate page alias as well so links are pointing to the _online_ page:
1193 if ($table === 'pages') {
1194 $wsAlt['alias'] = $row['alias'];
1195 }
1196 // Changing input record to the workspace version alternative:
1197 $row = $wsAlt;
1198 // Check if it is deleted/new
1199 $rowVersionState = VersionState::cast($row['t3ver_state']);
1200 if (
1201 $rowVersionState->equals(VersionState::NEW_PLACEHOLDER)
1202 || $rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)
1203 ) {
1204 // Unset record if it turned out to be deleted in workspace
1205 $row = FALSE;
1206 }
1207 // Check if move-pointer in workspace (unless if a move-placeholder is the
1208 // reason why it appears!):
1209 // You have to specifically set $unsetMovePointers in order to clear these
1210 // because it is normally a display issue if it should be shown or not.
1211 if (
1212 ($rowVersionState->equals(VersionState::MOVE_POINTER)
1213 && !$movePldSwap
1214 ) && $unsetMovePointers
1215 ) {
1216 // Unset record if it turned out to be deleted in workspace
1217 $row = FALSE;
1218 }
1219 } else {
1220 // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1221 // (online version is dummy-representation)
1222 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1223 // enablefields for BOTH the version AND the online record deselects it. See
1224 // note for $bypassEnableFieldsCheck
1225 if ($wsAlt <= -1 || VersionState::cast($row['t3ver_state'])->indicatesPlaceholder()) {
1226 // Unset record if it turned out to be "hidden"
1227 $row = FALSE;
1228 }
1229 }
1230 }
1231 }
1232 }
1233
1234 /**
1235 * Checks if record is a move-placeholder
1236 * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1237 * the pointed-to live record (and return TRUE) Used from versionOL
1238 *
1239 * @param string $table Table name
1240 * @param array $row Row (passed by reference) - only online records...
1241 * @return bool TRUE if overlay is made.
1242 * @see BackendUtility::movePlhOl()
1243 */
1244 public function movePlhOL($table, &$row) {
1245 if (
1246 ($table === 'pages'
1247 || (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2
1248 ) && (int)VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)
1249 ) {
1250 // Only for WS ver 2... (moving)
1251 // If t3ver_move_id is not found, then find it (but we like best if it is here)
1252 if (!isset($row['t3ver_move_id'])) {
1253 $moveIDRec = $this->getRawRecord($table, $row['uid'], 't3ver_move_id', TRUE);
1254 $moveID = $moveIDRec['t3ver_move_id'];
1255 } else {
1256 $moveID = $row['t3ver_move_id'];
1257 }
1258 // Find pointed-to record.
1259 if ($moveID) {
1260 $res = $this->getDatabaseConnection()->exec_SELECTquery(implode(',', array_keys($row)), $table, 'uid=' . (int)$moveID . $this->enableFields($table));
1261 $origRow = $this->getDatabaseConnection()->sql_fetch_assoc($res);
1262 $this->getDatabaseConnection()->sql_free_result($res);
1263 if ($origRow) {
1264 $row = $origRow;
1265 return TRUE;
1266 }
1267 }
1268 }
1269 return FALSE;
1270 }
1271
1272 /**
1273 * Returns move placeholder of online (live) version
1274 *
1275 * @param string $table Table name
1276 * @param int $uid Record UID of online version
1277 * @param string $fields Field list, default is *
1278 * @return array If found, the record, otherwise nothing.
1279 * @see BackendUtility::getMovePlaceholder()
1280 */
1281 public function getMovePlaceholder($table, $uid, $fields = '*') {
1282 if ($this->versioningPreview) {
1283 $workspace = (int)$this->versioningWorkspaceId;
1284 if (($table === 'pages' || (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) && $workspace !== 0) {
1285 // Select workspace version of record:
1286 $row = $this->getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, 'pid<>-1 AND
1287 t3ver_state=' . new VersionState(VersionState::MOVE_PLACEHOLDER) . ' AND
1288 t3ver_move_id=' . (int)$uid . ' AND
1289 t3ver_wsid=' . (int)$workspace . $this->deleteClause($table));
1290 if (is_array($row)) {
1291 return $row;
1292 }
1293 }
1294 }
1295 return FALSE;
1296 }
1297
1298 /**
1299 * Select the version of a record for a workspace
1300 *
1301 * @param int $workspace Workspace ID
1302 * @param string $table Table name to select from
1303 * @param int $uid Record uid for which to find workspace version.
1304 * @param string $fields Field list to select
1305 * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1306 * @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.
1307 * @see BackendUtility::getWorkspaceVersionOfRecord()
1308 */
1309 public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = FALSE) {
1310 if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1311 $workspace = (int)$workspace;
1312 $uid = (int)$uid;
1313 // Have to hardcode it for "pages" table since TCA is not loaded at this moment!
1314 // Setting up enableFields for version record:
1315 if ($table === 'pages') {
1316 $enFields = $this->versioningPreview_where_hid_del;
1317 } else {
1318 $enFields = $this->enableFields($table, -1, array(), TRUE);
1319 }
1320 // Select workspace version of record, only testing for deleted.
1321 $newrow = $this->getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, 'pid=-1 AND
1322 t3ver_oid=' . $uid . ' AND
1323 t3ver_wsid=' . $workspace . $this->deleteClause($table));
1324 // If version found, check if it could have been selected with enableFields on
1325 // as well:
1326 if (is_array($newrow)) {
1327 if ($bypassEnableFieldsCheck || $this->getDatabaseConnection()->exec_SELECTgetSingleRow('uid', $table, 'pid=-1 AND
1328 t3ver_oid=' . $uid . ' AND
1329 t3ver_wsid=' . $workspace . $enFields)) {
1330 // Return offline version, tested for its enableFields.
1331 return $newrow;
1332 } else {
1333 // Return -1 because offline version was de-selected due to its enableFields.
1334 return -1;
1335 }
1336 } else {
1337 // OK, so no workspace version was found. Then check if online version can be
1338 // selected with full enable fields and if so, return 1:
1339 if ($bypassEnableFieldsCheck || $this->getDatabaseConnection()->exec_SELECTgetSingleRow('uid', $table, 'uid=' . $uid . $enFields)) {
1340 // Means search was done, but no version found.
1341 return 1;
1342 } else {
1343 // Return -2 because the online record was de-selected due to its enableFields.
1344 return -2;
1345 }
1346 }
1347 }
1348 // No look up in database because versioning not enabled / or workspace not
1349 // offline
1350 return FALSE;
1351 }
1352
1353 /**
1354 * Checks if user has access to workspace.
1355 *
1356 * @param int $wsid Workspace ID
1357 * @return bool <code>TRUE</code> if has access
1358 */
1359 public function checkWorkspaceAccess($wsid) {
1360 if (!$GLOBALS['BE_USER'] || !ExtensionManagementUtility::isLoaded('workspaces')) {
1361 return FALSE;
1362 }
1363 if (isset($this->workspaceCache[$wsid])) {
1364 $ws = $this->workspaceCache[$wsid];
1365 } else {
1366 if ($wsid > 0) {
1367 // No $GLOBALS['TCA'] yet!
1368 $ws = $this->getDatabaseConnection()->exec_SELECTgetSingleRow('*', 'sys_workspace', 'uid=' . (int)$wsid . ' AND deleted=0');
1369 if (!is_array($ws)) {
1370 return FALSE;
1371 }
1372 } else {
1373 $ws = $wsid;
1374 }
1375 $ws = $GLOBALS['BE_USER']->checkWorkspace($ws);
1376 $this->workspaceCache[$wsid] = $ws;
1377 }
1378 return (string)$ws['_ACCESS'] !== '';
1379 }
1380
1381 /**
1382 * Gets file references for a given record field.
1383 *
1384 * @param string $tableName Name of the table
1385 * @param string $fieldName Name of the field
1386 * @param array $element The parent element referencing to files
1387 * @return array
1388 */
1389 public function getFileReferences($tableName, $fieldName, array $element) {
1390 /** @var $fileRepository FileRepository */
1391 $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
1392 $currentId = !empty($element['uid']) ? $element['uid'] : 0;
1393
1394 // Fetch the references of the default element
1395 $references = $fileRepository->findByRelation($tableName, $fieldName, $currentId);
1396
1397 $localizedId = NULL;
1398 if (isset($element['_LOCALIZED_UID'])) {
1399 $localizedId = $element['_LOCALIZED_UID'];
1400 } elseif (isset($element['_PAGES_OVERLAY_UID'])) {
1401 $localizedId = $element['_PAGES_OVERLAY_UID'];
1402 }
1403
1404 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['transForeignTable'])) {
1405 $tableName = $GLOBALS['TCA'][$tableName]['ctrl']['transForeignTable'];
1406 }
1407
1408 $isTableLocalizable = (
1409 !empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1410 && !empty($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1411 );
1412 if ($isTableLocalizable && $localizedId !== NULL) {
1413 $localizedReferences = $fileRepository->findByRelation($tableName, $fieldName, $localizedId);
1414 $localizedReferencesValue = $localizedReferences ?: '';
1415 if ($this->shouldFieldBeOverlaid($tableName, $fieldName, $localizedReferencesValue)) {
1416 $references = $localizedReferences;
1417 }
1418 }
1419
1420 return $references;
1421 }
1422
1423 /**
1424 * Determine if a field needs an overlay
1425 *
1426 * @param string $table TCA tablename
1427 * @param string $field TCA fieldname
1428 * @param mixed $value Current value of the field
1429 * @return bool Returns TRUE if a given record field needs to be overlaid
1430 */
1431 protected function shouldFieldBeOverlaid($table, $field, $value) {
1432 $l10n_mode = isset($GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode'])
1433 ? $GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode']
1434 : '';
1435
1436 $shouldFieldBeOverlaid = TRUE;
1437
1438 if ($l10n_mode === 'exclude') {
1439 $shouldFieldBeOverlaid = FALSE;
1440 } elseif ($l10n_mode === 'mergeIfNotBlank') {
1441 $checkValue = $value;
1442
1443 // 0 values are considered blank when coming from a group field
1444 if (empty($value) && $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'group') {
1445 $checkValue = '';
1446 }
1447
1448 if ($checkValue === array() || !is_array($checkValue) && trim($checkValue) === '') {
1449 $shouldFieldBeOverlaid = FALSE;
1450 }
1451 }
1452
1453 return $shouldFieldBeOverlaid;
1454 }
1455
1456 /**
1457 * Returns the database connection
1458 *
1459 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1460 */
1461 protected function getDatabaseConnection() {
1462 return $GLOBALS['TYPO3_DB'];
1463 }
1464
1465 /**
1466 * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
1467 */
1468 protected function getTypoScriptFrontendController() {
1469 return $GLOBALS['TSFE'];
1470 }
1471
1472 }