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