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