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