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