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