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