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