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