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