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