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