a18bf61934432d502d235d5501b5a688ba69b895
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Page / PageRepository.php
1 <?php
2 namespace TYPO3\CMS\Frontend\Page;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Cache\CacheManager;
18 use TYPO3\CMS\Core\Resource\FileRepository;
19 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21 use TYPO3\CMS\Core\Utility\HttpUtility;
22 use TYPO3\CMS\Core\Utility\RootlineUtility;
23 use TYPO3\CMS\Core\Versioning\VersionState;
24
25 /**
26 * Page functions, a lot of sql/pages-related functions
27 *
28 * Mainly used in the frontend but also in some cases in the backend. It's
29 * important to set the right $where_hid_del in the object so that the
30 * functions operate properly
31 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
32 */
33 class PageRepository {
34
35 /**
36 * @var array
37 */
38 public $urltypes = array('', 'http://', 'ftp://', 'mailto:', 'https://');
39
40 /**
41 * This is not the final clauses. There will normally be conditions for the
42 * hidden, starttime and endtime fields as well. You MUST initialize the object
43 * by the init() function
44 *
45 * @var string
46 */
47 public $where_hid_del = ' AND pages.deleted=0';
48
49 /**
50 * Clause for fe_group access
51 *
52 * @var string
53 */
54 public $where_groupAccess = '';
55
56 /**
57 * @var int
58 */
59 public $sys_language_uid = 0;
60
61 /**
62 * If TRUE, versioning preview of other record versions is allowed. THIS MUST
63 * ONLY BE SET IF the page is not cached and truely previewed by a backend
64 * user!!!
65 *
66 * @var bool
67 */
68 public $versioningPreview = FALSE;
69
70 /**
71 * Workspace ID for preview
72 *
73 * @var int
74 */
75 public $versioningWorkspaceId = 0;
76
77 /**
78 * @var array
79 */
80 public $workspaceCache = array();
81
82 /**
83 * Error string set by getRootLine()
84 *
85 * @var string
86 */
87 public $error_getRootLine = '';
88
89 /**
90 * Error uid set by getRootLine()
91 *
92 * @var int
93 */
94 public $error_getRootLine_failPid = 0;
95
96 /**
97 * @var array
98 */
99 protected $cache_getRootLine = array();
100
101 /**
102 * @var array
103 */
104 protected $cache_getPage = array();
105
106 /**
107 * @var array
108 */
109 protected $cache_getPage_noCheck = array();
110
111 /**
112 * @var array
113 */
114 protected $cache_getPageIdFromAlias = array();
115
116 /**
117 * @var array
118 */
119 protected $cache_getMountPointInfo = array();
120
121 /**
122 * @var array
123 */
124 protected $tableNamesAllowedOnRootLevel = array(
125 'sys_file_metadata',
126 'sys_category',
127 );
128
129 /**
130 * Named constants for "magic numbers" of the field doktype
131 */
132 const DOKTYPE_DEFAULT = 1;
133 const DOKTYPE_LINK = 3;
134 const DOKTYPE_SHORTCUT = 4;
135 const DOKTYPE_BE_USER_SECTION = 6;
136 const DOKTYPE_MOUNTPOINT = 7;
137 const DOKTYPE_SPACER = 199;
138 const DOKTYPE_SYSFOLDER = 254;
139 const DOKTYPE_RECYCLER = 255;
140
141 /**
142 * Named constants for "magic numbers" of the field shortcut_mode
143 */
144 const SHORTCUT_MODE_NONE = 0;
145 const SHORTCUT_MODE_FIRST_SUBPAGE = 1;
146 const SHORTCUT_MODE_RANDOM_SUBPAGE = 2;
147 const SHORTCUT_MODE_PARENT_PAGE = 3;
148
149 /**
150 * init() MUST be run directly after creating a new template-object
151 * This sets the internal variable $this->where_hid_del to the correct where
152 * clause for page records taking deleted/hidden/starttime/endtime/t3ver_state
153 * into account
154 *
155 * @param bool $show_hidden If $show_hidden is TRUE, the hidden-field is ignored!! Normally this should be FALSE. Is used for previewing.
156 * @return void
157 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id(), \TYPO3\CMS\Tstemplate\Controller\TemplateAnalyzerModuleFunctionController::initialize_editor()
158 */
159 public function init($show_hidden) {
160 $this->where_groupAccess = '';
161
162 if ($this->versioningPreview) {
163 // For version previewing, make sure that enable-fields are not
164 // de-selecting hidden pages - we need versionOL() to unset them only
165 // if the overlay record instructs us to.
166 // Clear where_hid_del and restrict to live and current workspaces
167 $this->where_hid_del = ' AND pages.deleted=0 AND (pages.t3ver_wsid=0 OR pages.t3ver_wsid=' . (int)$this->versioningWorkspaceId . ')';
168 } else {
169 // add starttime / endtime, and check for hidden/deleted
170 // Filter out new/deleted place-holder pages in case we are NOT in a
171 // versioning preview (that means we are online!)
172 $this->where_hid_del = $this->enableFields('pages', $show_hidden, array('fe_group' => TRUE), TRUE);
173 }
174 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][PageRepository::class]['init'])) {
175 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][PageRepository::class]['init'] as $classRef) {
176 $hookObject = GeneralUtility::makeInstance($classRef);
177 if (!$hookObject instanceof PageRepositoryInitHookInterface) {
178 throw new \UnexpectedValueException($hookObject . ' must implement interface TYPO3\\CMS\\Frontend\\Page\\PageRepositoryInitHookInterface', 1379579812);
179 }
180 $hookObject->init_postProcess($this);
181 }
182 }
183 }
184
185 /**************************
186 *
187 * Selecting page records
188 *
189 **************************/
190
191 /**
192 * Returns the $row for the page with uid = $uid (observing ->where_hid_del)
193 * Any pages_language_overlay will be applied before the result is returned.
194 * If no page is found an empty array is returned.
195 *
196 * @param int $uid The page id to look up.
197 * @param bool $disableGroupAccessCheck If set, the check for group access is disabled. VERY rarely used
198 * @throws \UnexpectedValueException
199 * @return array The page row with overlayed localized fields. Empty it no page.
200 * @see getPage_noCheck()
201 */
202 public function getPage($uid, $disableGroupAccessCheck = FALSE) {
203 // Hook to manipulate the page uid for special overlay handling
204 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'])) {
205 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'] as $classRef) {
206 $hookObject = GeneralUtility::getUserObj($classRef);
207 if (!$hookObject instanceof PageRepositoryGetPageHookInterface) {
208 throw new \UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetPageHookInterface::class, 1251476766);
209 }
210 $hookObject->getPage_preProcess($uid, $disableGroupAccessCheck, $this);
211 }
212 }
213 $accessCheck = $disableGroupAccessCheck ? '' : $this->where_groupAccess;
214 $cacheKey = md5($accessCheck . '-' . $this->where_hid_del . '-' . $this->sys_language_uid);
215 if (is_array($this->cache_getPage[$uid][$cacheKey])) {
216 return $this->cache_getPage[$uid][$cacheKey];
217 }
218 $result = array();
219 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'pages', 'uid=' . (int)$uid . $this->where_hid_del . $accessCheck);
220 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
221 $this->getDatabaseConnection()->sql_free_result($res);
222 if ($row) {
223 $this->versionOL('pages', $row);
224 if (is_array($row)) {
225 $result = $this->getPageOverlay($row);
226 }
227 }
228 $this->cache_getPage[$uid][$cacheKey] = $result;
229 return $result;
230 }
231
232 /**
233 * Return the $row for the page with uid = $uid WITHOUT checking for
234 * ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
235 *
236 * @param int $uid The page id to look up
237 * @return array The page row with overlayed localized fields. Empty array if no page.
238 * @see getPage()
239 */
240 public function getPage_noCheck($uid) {
241 if ($this->cache_getPage_noCheck[$uid]) {
242 return $this->cache_getPage_noCheck[$uid];
243 }
244 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'pages', 'uid=' . (int)$uid . $this->deleteClause('pages'));
245 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
246 $this->getDatabaseConnection()->sql_free_result($res);
247 $result = array();
248 if ($row) {
249 $this->versionOL('pages', $row);
250 if (is_array($row)) {
251 $result = $this->getPageOverlay($row);
252 }
253 }
254 $this->cache_getPage_noCheck[$uid] = $result;
255 return $result;
256 }
257
258 /**
259 * Returns the $row of the first web-page in the tree (for the default menu...)
260 *
261 * @param int $uid The page id for which to fetch first subpages (PID)
262 * @return mixed If found: The page record (with overlayed localized fields, if any). If NOT found: blank value (not array!)
263 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
264 */
265 public function getFirstWebPage($uid) {
266 $output = '';
267 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'pages', 'pid=' . (int)$uid . $this->where_hid_del . $this->where_groupAccess, '', 'sorting', '1');
268 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
269 $this->getDatabaseConnection()->sql_free_result($res);
270 if ($row) {
271 $this->versionOL('pages', $row);
272 if (is_array($row)) {
273 $output = $this->getPageOverlay($row);
274 }
275 }
276 return $output;
277 }
278
279 /**
280 * Returns a pagerow for the page with alias $alias
281 *
282 * @param string $alias The alias to look up the page uid for.
283 * @return int Returns page uid (int) if found, otherwise 0 (zero)
284 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::checkAndSetAlias(), ContentObjectRenderer::typoLink()
285 */
286 public function getPageIdFromAlias($alias) {
287 $alias = strtolower($alias);
288 if ($this->cache_getPageIdFromAlias[$alias]) {
289 return $this->cache_getPageIdFromAlias[$alias];
290 }
291 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid', 'pages', 'alias=' . $this->getDatabaseConnection()->fullQuoteStr($alias, 'pages') . ' AND pid>=0 AND pages.deleted=0');
292 // "AND pid>=0" because of versioning (means that aliases sent MUST be online!)
293 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
294 $this->getDatabaseConnection()->sql_free_result($res);
295 if ($row) {
296 $this->cache_getPageIdFromAlias[$alias] = $row['uid'];
297 return $row['uid'];
298 }
299 $this->cache_getPageIdFromAlias[$alias] = 0;
300 return 0;
301 }
302
303 /**
304 * Returns the relevant page overlay record fields
305 *
306 * @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.
307 * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
308 * @throws \UnexpectedValueException
309 * @return array Page row which is overlayed with language_overlay record (or the overlay record alone)
310 */
311 public function getPageOverlay($pageInput, $lUid = -1) {
312 $rows = $this->getPagesOverlay(array($pageInput), $lUid);
313 // Always an array in return
314 return isset($rows[0]) ? $rows[0] : array();
315 }
316
317 /**
318 * Returns the relevant page overlay record fields
319 *
320 * @param array $pagesInput Array of integers or array of arrays. If each value is an integer, it's the pids of the pageOverlay records and thus the page overlay records are returned. If each value is an array, it's page-records and based on this page records the language records are found and OVERLAYED before the page records are returned.
321 * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
322 * @throws \UnexpectedValueException
323 * @return array Page rows which are overlayed with language_overlay record.
324 * If the input was an array of integers, missing records are not
325 * included. If the input were page rows, untranslated pages
326 * are returned.
327 */
328 public function getPagesOverlay(array $pagesInput, $lUid = -1) {
329 if (empty($pagesInput)) {
330 return array();
331 }
332 // Initialize:
333 if ($lUid < 0) {
334 $lUid = $this->sys_language_uid;
335 }
336 $row = NULL;
337 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'])) {
338 foreach ($pagesInput as $origPage) {
339 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'] as $classRef) {
340 $hookObject = GeneralUtility::getUserObj($classRef);
341 if (!$hookObject instanceof PageRepositoryGetPageOverlayHookInterface) {
342 throw new \UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetPageOverlayHookInterface::class, 1269878881);
343 }
344 $hookObject->getPageOverlay_preProcess($origPage, $lUid, $this);
345 }
346 }
347 }
348 // If language UID is different from zero, do overlay:
349 if ($lUid) {
350 $fieldArr = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['pageOverlayFields'], TRUE);
351 $page_ids = array();
352
353 $origPage = reset($pagesInput);
354 if (is_array($origPage)) {
355 // Make sure that only fields which exist in the first incoming record are overlaid!
356 $fieldArr = array_intersect($fieldArr, array_keys($origPage));
357 }
358 foreach ($pagesInput as $origPage) {
359 if (is_array($origPage)) {
360 // Was the whole record
361 $page_ids[] = $origPage['uid'];
362 } else {
363 // Was the id
364 $page_ids[] = $origPage;
365 }
366 }
367 if (!empty($fieldArr)) {
368 if (!in_array('pid', $fieldArr, TRUE)) {
369 $fieldArr[] = 'pid';
370 }
371 // NOTE to enabledFields('pages_language_overlay'):
372 // Currently the showHiddenRecords of TSFE set will allow
373 // pages_language_overlay records to be selected as they are
374 // child-records of a page.
375 // However you may argue that the showHiddenField flag should
376 // determine this. But that's not how it's done right now.
377 // Selecting overlay record:
378 $res = $this->getDatabaseConnection()->exec_SELECTquery(
379 implode(',', $fieldArr),
380 'pages_language_overlay',
381 'pid IN(' . implode(',', $this->getDatabaseConnection()->cleanIntArray($page_ids)) . ')'
382 . ' AND sys_language_uid=' . (int)$lUid . $this->enableFields('pages_language_overlay')
383 );
384 $overlays = array();
385 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
386 $this->versionOL('pages_language_overlay', $row);
387 if (is_array($row)) {
388 $row['_PAGES_OVERLAY'] = TRUE;
389 $row['_PAGES_OVERLAY_UID'] = $row['uid'];
390 $row['_PAGES_OVERLAY_LANGUAGE'] = $lUid;
391 $origUid = $row['pid'];
392 // Unset vital fields that are NOT allowed to be overlaid:
393 unset($row['uid']);
394 unset($row['pid']);
395 $overlays[$origUid] = $row;
396 }
397 }
398 $this->getDatabaseConnection()->sql_free_result($res);
399 }
400 }
401 // Create output:
402 $pagesOutput = array();
403 foreach ($pagesInput as $key => $origPage) {
404 if (is_array($origPage)) {
405 $pagesOutput[$key] = $origPage;
406 if (isset($overlays[$origPage['uid']])) {
407 // Overwrite the original field with the overlay
408 foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
409 if ($fieldName !== 'uid' && $fieldName !== 'pid') {
410 if ($this->shouldFieldBeOverlaid('pages_language_overlay', $fieldName, $fieldValue)) {
411 $pagesOutput[$key][$fieldName] = $fieldValue;
412 }
413 }
414 }
415 }
416 } else {
417 if (isset($overlays[$origPage])) {
418 $pagesOutput[$key] = $overlays[$origPage];
419 }
420 }
421 }
422 return $pagesOutput;
423 }
424
425 /**
426 * Creates language-overlay for records in general (where translation is found
427 * in records from the same table)
428 *
429 * @param string $table Table name
430 * @param array $row Record to overlay. Must containt uid, pid and $table]['ctrl']['languageField']
431 * @param int $sys_language_content Pointer to the sys_language uid for content on the site.
432 * @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned un-translated but unset (and return value is FALSE)
433 * @throws \UnexpectedValueException
434 * @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.
435 */
436 public function getRecordOverlay($table, $row, $sys_language_content, $OLmode = '') {
437 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'])) {
438 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] as $classRef) {
439 $hookObject = GeneralUtility::getUserObj($classRef);
440 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
441 throw new \UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881658);
442 }
443 $hookObject->getRecordOverlay_preProcess($table, $row, $sys_language_content, $OLmode, $this);
444 }
445 }
446 if ($row['uid'] > 0 && ($row['pid'] > 0 || in_array($table, $this->tableNamesAllowedOnRootLevel, TRUE))) {
447 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
448 if (!$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
449 // Will not be able to work with other tables (Just didn't implement it yet;
450 // Requires a scan over all tables [ctrl] part for first FIND the table that
451 // carries localization information for this table (which could even be more
452 // than a single table) and then use that. Could be implemented, but obviously
453 // takes a little more....) Will try to overlay a record only if the
454 // sys_language_content value is larger than zero.
455 if ($sys_language_content > 0) {
456 // Must be default language or [All], otherwise no overlaying:
457 if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] <= 0) {
458 // Select overlay record:
459 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', $table, 'pid=' . (int)$row['pid'] . ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '=' . (int)$sys_language_content . ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . '=' . (int)$row['uid'] . $this->enableFields($table), '', '', '1');
460 $olrow = $this->getDatabaseConnection()->sql_fetch_assoc($res);
461 $this->getDatabaseConnection()->sql_free_result($res);
462 $this->versionOL($table, $olrow);
463 // Merge record content by traversing all fields:
464 if (is_array($olrow)) {
465 if (isset($olrow['_ORIG_uid'])) {
466 $row['_ORIG_uid'] = $olrow['_ORIG_uid'];
467 }
468 if (isset($olrow['_ORIG_pid'])) {
469 $row['_ORIG_pid'] = $olrow['_ORIG_pid'];
470 }
471 foreach ($row as $fN => $fV) {
472 if ($fN !== 'uid' && $fN !== 'pid' && isset($olrow[$fN])) {
473 if ($this->shouldFieldBeOverlaid($table, $fN, $olrow[$fN])) {
474 $row[$fN] = $olrow[$fN];
475 }
476 } elseif ($fN === 'uid') {
477 $row['_LOCALIZED_UID'] = $olrow['uid'];
478 }
479 }
480 } elseif ($OLmode === 'hideNonTranslated' && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
481 // Unset, if non-translated records should be hidden. ONLY done if the source
482 // record really is default language and not [All] in which case it is allowed.
483 unset($row);
484 }
485 } elseif ($sys_language_content != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
486 unset($row);
487 }
488 } else {
489 // When default language is displayed, we never want to return a record carrying
490 // another language!
491 if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
492 unset($row);
493 }
494 }
495 }
496 }
497 }
498 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'])) {
499 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] as $classRef) {
500 $hookObject = GeneralUtility::getUserObj($classRef);
501 if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
502 throw new \UnexpectedValueException('$hookObject must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881659);
503 }
504 $hookObject->getRecordOverlay_postProcess($table, $row, $sys_language_content, $OLmode, $this);
505 }
506 }
507 return $row;
508 }
509
510 /************************************************
511 *
512 * Page related: Menu, Domain record, Root line
513 *
514 ************************************************/
515
516 /**
517 * Returns an array with pagerows for subpages with pid=$uid (which is pid
518 * here!). This is used for menus. If there are mount points in overlay mode
519 * the _MP_PARAM field is set to the corret MPvar.
520 *
521 * If the $uid being input does in itself require MPvars to define a correct
522 * rootline these must be handled externally to this function.
523 *
524 * @param int|int[] $uid The page id (or array of page ids) for which to fetch subpages (PID)
525 * @param string $fields List of fields to select. Default is "*" = all
526 * @param string $sortField The field to sort by. Default is "sorting
527 * @param string $addWhere Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
528 * @param bool $checkShortcuts Check if shortcuts exist, checks by default
529 * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlayed localized fields, if any)
530 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageShortcut(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
531 * @see \TYPO3\CMS\WizardCrpages\Controller\CreatePagesWizardModuleFunctionController, \TYPO3\CMS\WizardSortpages\View\SortPagesWizardModuleFunction
532 */
533 public function getMenu($uid, $fields = '*', $sortField = 'sorting', $addWhere = '', $checkShortcuts = TRUE) {
534 $output = array();
535 $res = $this->getDatabaseConnection()->exec_SELECTquery(
536 $fields,
537 'pages',
538 'pid IN (' . implode(',', $this->getDatabaseConnection()->cleanIntArray((array)$uid)) . ')' . $this->where_hid_del
539 . $this->where_groupAccess . ' ' . $addWhere,
540 '',
541 $sortField
542 );
543 while (($row = $this->getDatabaseConnection()->sql_fetch_assoc($res))) {
544 $this->versionOL('pages', $row, TRUE);
545 if (is_array($row)) {
546 // Keep mount point:
547 $origUid = $row['uid'];
548 // $row MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields
549 // in it
550 $mount_info = $this->getMountPointInfo($origUid, $row);
551 // There is a valid mount point.
552 if (is_array($mount_info) && $mount_info['overlay']) {
553 // Using "getPage" is OK since we need the check for enableFields AND for type 2
554 // of mount pids we DO require a doktype < 200!
555 $mp_row = $this->getPage($mount_info['mount_pid']);
556 if (!empty($mp_row)) {
557 $row = $mp_row;
558 $row['_MP_PARAM'] = $mount_info['MPvar'];
559 } else {
560 unset($row);
561 }
562 }
563 // If shortcut, look up if the target exists and is currently visible
564 $doktype = (int)$row['doktype'];
565 $shortcutMode = (int)$row['shortcut_mode'];
566 if ($doktype === self::DOKTYPE_SHORTCUT && ($row['shortcut'] || $shortcutMode) && $checkShortcuts) {
567 if ($shortcutMode === self::SHORTCUT_MODE_NONE) {
568 // No shortcut_mode set, so target is directly set in $row['shortcut']
569 $searchField = 'uid';
570 $searchUid = (int)$row['shortcut'];
571 } elseif ($shortcutMode === self::SHORTCUT_MODE_FIRST_SUBPAGE || $shortcutMode === self::SHORTCUT_MODE_RANDOM_SUBPAGE) {
572 // Check subpages - first subpage or random subpage
573 $searchField = 'pid';
574 // If a shortcut mode is set and no valid page is given to select subpags
575 // from use the actual page.
576 $searchUid = (int)$row['shortcut'] ?: $row['uid'];
577 } elseif ($shortcutMode === self::SHORTCUT_MODE_PARENT_PAGE) {
578 // Shortcut to parent page
579 $searchField = 'uid';
580 $searchUid = $row['pid'];
581 }
582 $count = $this->getDatabaseConnection()->exec_SELECTcountRows('uid', 'pages', $searchField . '=' . $searchUid . $this->where_hid_del . $this->where_groupAccess . ' ' . $addWhere);
583 if (!$count) {
584 unset($row);
585 }
586 } elseif ($doktype === self::DOKTYPE_SHORTCUT && $checkShortcuts) {
587 // Neither shortcut target nor mode is set. Remove the page from the menu.
588 unset($row);
589 }
590 if (is_array($row)) {
591 $output[$origUid] = $row;
592 }
593 }
594 }
595 $this->getDatabaseConnection()->sql_free_result($res);
596 // Finally load language overlays
597 return $this->getPagesOverlay($output);
598 }
599
600 /**
601 * Will find the page carrying the domain record matching the input domain.
602 * Might exit after sending a redirect-header IF a found domain record
603 * instructs to do so.
604 *
605 * @param string $domain Domain name to search for. Eg. "www.typo3.com". Typical the HTTP_HOST value.
606 * @param string $path Path for the current script in domain. Eg. "/somedir/subdir". Typ. supplied by \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('SCRIPT_NAME')
607 * @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')
608 * @return mixed If found, returns integer with page UID where found. Otherwise blank. Might exit if location-header is sent, see description.
609 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::findDomainRecord()
610 */
611 public function getDomainStartPage($domain, $path = '', $request_uri = '') {
612 $domain = explode(':', $domain);
613 $domain = strtolower(preg_replace('/\\.$/', '', $domain[0]));
614 // Removing extra trailing slashes
615 $path = trim(preg_replace('/\\/[^\\/]*$/', '', $path));
616 // Appending to domain string
617 $domain .= $path;
618 $domain = preg_replace('/\\/*$/', '', $domain);
619 $res = $this->getDatabaseConnection()->exec_SELECTquery('pages.uid,sys_domain.redirectTo,sys_domain.redirectHttpStatusCode,sys_domain.prepend_params', 'pages,sys_domain', 'pages.uid=sys_domain.pid
620 AND sys_domain.hidden=0
621 AND (sys_domain.domainName=' . $this->getDatabaseConnection()->fullQuoteStr($domain, 'sys_domain') . ' OR sys_domain.domainName=' . $this->getDatabaseConnection()->fullQuoteStr(($domain . '/'), 'sys_domain') . ') ' . $this->where_hid_del . $this->where_groupAccess, '', '', 1);
622 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
623 $this->getDatabaseConnection()->sql_free_result($res);
624 if ($row) {
625 if ($row['redirectTo']) {
626 $redirectUrl = $row['redirectTo'];
627 if ($row['prepend_params']) {
628 $redirectUrl = rtrim($redirectUrl, '/');
629 $prependStr = ltrim(substr($request_uri, strlen($path)), '/');
630 $redirectUrl .= '/' . $prependStr;
631 }
632 $statusCode = (int)$row['redirectHttpStatusCode'];
633 if ($statusCode && defined(HttpUtility::class . '::HTTP_STATUS_' . $statusCode)) {
634 HttpUtility::redirect($redirectUrl, constant(HttpUtility::class . '::HTTP_STATUS_' . $statusCode));
635 } else {
636 HttpUtility::redirect($redirectUrl, HttpUtility::HTTP_STATUS_301);
637 }
638 die;
639 } else {
640 return $row['uid'];
641 }
642 }
643 }
644
645 /**
646 * Returns array with fields of the pages from here ($uid) and back to the root
647 *
648 * NOTICE: This function only takes deleted pages into account! So hidden,
649 * starttime and endtime restricted pages are included no matter what.
650 *
651 * Further: If any "recycler" page is found (doktype=255) then it will also block
652 * for the rootline)
653 *
654 * If you want more fields in the rootline records than default such can be added
655 * by listing them in $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']
656 *
657 * @param int $uid The page uid for which to seek back to the page tree root.
658 * @param string $MP Commalist of MountPoint parameters, eg. "1-2,3-4" etc. Normally this value comes from the GET var, MP
659 * @param bool $ignoreMPerrors If set, some errors related to Mount Points in root line are ignored.
660 * @throws \Exception
661 * @throws \RuntimeException
662 * @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.
663 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageAndRootline()
664 */
665 public function getRootLine($uid, $MP = '', $ignoreMPerrors = FALSE) {
666 $rootline = GeneralUtility::makeInstance(RootlineUtility::class, $uid, $MP, $this);
667 try {
668 return $rootline->get();
669 } catch (\RuntimeException $ex) {
670 if ($ignoreMPerrors) {
671 $this->error_getRootLine = $ex->getMessage();
672 if (substr($this->error_getRootLine, -7) === 'uid -1.') {
673 $this->error_getRootLine_failPid = -1;
674 }
675 return array();
676 /** @see \TYPO3\CMS\Core\Utility\RootlineUtility::getRecordArray */
677 } elseif ($ex->getCode() === 1343589451) {
678 return array();
679 }
680 throw $ex;
681 }
682 }
683
684 /**
685 * Creates a "path" string for the input root line array titles.
686 * Used for writing statistics.
687 *
688 * @param array $rl A rootline array!
689 * @param int $len The max length of each title from the rootline.
690 * @return string The path in the form "/page title/This is another pageti.../Another page
691 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
692 */
693 public function getPathFromRootline($rl, $len = 20) {
694 if (is_array($rl)) {
695 $c = count($rl);
696 $path = '';
697 for ($a = 0; $a < $c; $a++) {
698 if ($rl[$a]['uid']) {
699 $path .= '/' . GeneralUtility::fixed_lgd_cs(strip_tags($rl[$a]['title']), $len);
700 }
701 }
702 return $path;
703 }
704 }
705
706 /**
707 * Returns the URL type for the input page row IF the doktype is 3 and not
708 * disabled.
709 *
710 * @param array $pagerow The page row to return URL type for
711 * @param bool $disable A flag to simply disable any output from here. - deprecated - don't use anymore.
712 * @return string The URL type from $this->urltypes array. False if not found or disabled.
713 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::setExternalJumpUrl()
714 */
715 public function getExtURL($pagerow, $disable = FALSE) {
716 if ($disable !== FALSE) {
717 GeneralUtility::deprecationLog('The disable option of PageRepository::getExtUrl() is deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8.');
718 return FALSE;
719 }
720 if ((int)$pagerow['doktype'] === self::DOKTYPE_LINK) {
721 $redirectTo = $this->urltypes[$pagerow['urltype']] . $pagerow['url'];
722 // If relative path, prefix Site URL:
723 $uI = parse_url($redirectTo);
724 // Relative path assumed now.
725 if (!$uI['scheme'] && $redirectTo[0] !== '/') {
726 $redirectTo = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $redirectTo;
727 }
728 return $redirectTo;
729 }
730 }
731
732 /**
733 * Returns MountPoint id for page
734 *
735 * Does a recursive search if the mounted page should be a mount page itself. It
736 * has a run-away break so it can't go into infinite loops.
737 *
738 * @param int $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...)
739 * @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
740 * @param array $prevMountPids Array accumulating formerly tested page ids for mount points. Used for recursivity brake.
741 * @param int $firstPageUid The first page id.
742 * @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.
743 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
744 */
745 public function getMountPointInfo($pageId, $pageRec = FALSE, $prevMountPids = array(), $firstPageUid = 0) {
746 $result = FALSE;
747 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
748 if (isset($this->cache_getMountPointInfo[$pageId])) {
749 return $this->cache_getMountPointInfo[$pageId];
750 }
751 // Get pageRec if not supplied:
752 if (!is_array($pageRec)) {
753 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol,t3ver_state', 'pages', 'uid=' . (int)$pageId . ' AND pages.deleted=0 AND pages.doktype<>255');
754 $pageRec = $this->getDatabaseConnection()->sql_fetch_assoc($res);
755 $this->getDatabaseConnection()->sql_free_result($res);
756 // Only look for version overlay if page record is not supplied; This assumes
757 // that the input record is overlaid with preview version, if any!
758 $this->versionOL('pages', $pageRec);
759 }
760 // Set first Page uid:
761 if (!$firstPageUid) {
762 $firstPageUid = $pageRec['uid'];
763 }
764 // Look for mount pid value plus other required circumstances:
765 $mount_pid = (int)$pageRec['mount_pid'];
766 if (is_array($pageRec) && (int)$pageRec['doktype'] === self::DOKTYPE_MOUNTPOINT && $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, TRUE)) {
767 // Get the mount point record (to verify its general existence):
768 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol,t3ver_state', 'pages', 'uid=' . $mount_pid . ' AND pages.deleted=0 AND pages.doktype<>255');
769 $mountRec = $this->getDatabaseConnection()->sql_fetch_assoc($res);
770 $this->getDatabaseConnection()->sql_free_result($res);
771 $this->versionOL('pages', $mountRec);
772 if (is_array($mountRec)) {
773 // Look for recursive mount point:
774 $prevMountPids[] = $mount_pid;
775 $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
776 // Return mount point information:
777 $result = $recursiveMountPid ?: array(
778 'mount_pid' => $mount_pid,
779 'overlay' => $pageRec['mount_pid_ol'],
780 'MPvar' => $mount_pid . '-' . $firstPageUid,
781 'mount_point_rec' => $pageRec,
782 'mount_pid_rec' => $mountRec
783 );
784 } else {
785 // Means, there SHOULD have been a mount point, but there was none!
786 $result = -1;
787 }
788 }
789 }
790 $this->cache_getMountPointInfo[$pageId] = $result;
791 return $result;
792 }
793
794 /********************************
795 *
796 * Selecting records in general
797 *
798 ********************************/
799
800 /**
801 * Checks if a record exists and is accessible.
802 * The row is returned if everything's OK.
803 *
804 * @param string $table The table name to search
805 * @param int $uid The uid to look up in $table
806 * @param bool $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
807 * @return mixed Returns array (the record) if OK, otherwise blank/0 (zero)
808 */
809 public function checkRecord($table, $uid, $checkPage = 0) {
810 $uid = (int)$uid;
811 if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
812 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', $table, 'uid = ' . $uid . $this->enableFields($table));
813 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
814 $this->getDatabaseConnection()->sql_free_result($res);
815 if ($row) {
816 $this->versionOL($table, $row);
817 if (is_array($row)) {
818 if ($checkPage) {
819 $res = $this->getDatabaseConnection()->exec_SELECTquery('uid', 'pages', 'uid=' . (int)$row['pid'] . $this->enableFields('pages'));
820 $numRows = $this->getDatabaseConnection()->sql_num_rows($res);
821 $this->getDatabaseConnection()->sql_free_result($res);
822 if ($numRows > 0) {
823 return $row;
824 } else {
825 return 0;
826 }
827 } else {
828 return $row;
829 }
830 }
831 }
832 }
833 }
834
835 /**
836 * Returns record no matter what - except if record is deleted
837 *
838 * @param string $table The table name to search
839 * @param int $uid The uid to look up in $table
840 * @param string $fields The fields to select, default is "*
841 * @param bool $noWSOL If set, no version overlay is applied
842 * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
843 * @see getPage_noCheck()
844 */
845 public function getRawRecord($table, $uid, $fields = '*', $noWSOL = FALSE) {
846 $uid = (int)$uid;
847 if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
848 $res = $this->getDatabaseConnection()->exec_SELECTquery($fields, $table, 'uid = ' . $uid . $this->deleteClause($table));
849 $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
850 $this->getDatabaseConnection()->sql_free_result($res);
851 if ($row) {
852 if (!$noWSOL) {
853 $this->versionOL($table, $row);
854 }
855 if (is_array($row)) {
856 return $row;
857 }
858 }
859 }
860 }
861
862 /**
863 * Selects records based on matching a field (ei. other than UID) with a value
864 *
865 * @param string $theTable The table name to search, eg. "pages" or "tt_content
866 * @param string $theField The fieldname to match, eg. "uid" or "alias
867 * @param string $theValue The value that fieldname must match, eg. "123" or "frontpage
868 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
869 * @param string $groupBy Optional GROUP BY field(s). If none, supply blank string.
870 * @param string $orderBy Optional ORDER BY field(s). If none, supply blank string.
871 * @param string $limit Optional LIMIT value ([begin,]max). If none, supply blank string.
872 * @return mixed Returns array (the record) if found, otherwise nothing (void)
873 */
874 public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
875 if (is_array($GLOBALS['TCA'][$theTable])) {
876 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', $theTable, $theField . '=' . $this->getDatabaseConnection()->fullQuoteStr($theValue, $theTable) . $this->deleteClause($theTable) . ' ' . $whereClause, $groupBy, $orderBy, $limit);
877 $rows = array();
878 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
879 if (is_array($row)) {
880 $rows[] = $row;
881 }
882 }
883 $this->getDatabaseConnection()->sql_free_result($res);
884 if (!empty($rows)) {
885 return $rows;
886 }
887 }
888 }
889
890 /********************************
891 *
892 * Caching and standard clauses
893 *
894 ********************************/
895
896 /**
897 * Returns data stored for the hash string in the cache "cache_hash"
898 * Can be used to retrieved a cached value, array or object
899 * Can be used from your frontend plugins if you like. It is also used to
900 * store the parsed TypoScript template structures. You can call it directly
901 * like PageRepository::getHash()
902 *
903 * @param string $hash The hash-string which was used to store the data value
904 * @param int The expiration time (not used anymore)
905 * @return mixed The "data" from the cache
906 * @see tslib_TStemplate::start(), storeHash()
907 */
908 static public function getHash($hash, $expTime = 0) {
909 $hashContent = NULL;
910 $contentHashCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash');
911 $cacheEntry = $contentHashCache->get($hash);
912 if ($cacheEntry) {
913 $hashContent = $cacheEntry;
914 }
915 return $hashContent;
916 }
917
918 /**
919 * Stores $data in the 'cache_hash' cache with the hash key, $hash
920 * and visual/symbolic identification, $ident
921 *
922 * Can be used from your frontend plugins if you like. You can call it
923 * directly like PageRepository::storeHash()
924 *
925 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
926 * @param mixed $data The data to store
927 * @param string $ident Is just a textual identification in order to inform about the content!
928 * @param int $lifetime The lifetime for the cache entry in seconds
929 * @return void
930 * @see tslib_TStemplate::start(), getHash()
931 */
932 static public function storeHash($hash, $data, $ident, $lifetime = 0) {
933 GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($hash, $data, array('ident_' . $ident), (int)$lifetime);
934 }
935
936 /**
937 * Returns the "AND NOT deleted" clause for the tablename given IF
938 * $GLOBALS['TCA'] configuration points to such a field.
939 *
940 * @param string $table Tablename
941 * @return string
942 * @see enableFields()
943 */
944 public function deleteClause($table) {
945 return $GLOBALS['TCA'][$table]['ctrl']['delete'] ? ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0' : '';
946 }
947
948 /**
949 * Returns a part of a WHERE clause which will filter out records with start/end
950 * times or hidden/fe_groups fields set to values that should de-select them
951 * according to the current time, preview settings or user login. Definitely a
952 * frontend function.
953 *
954 * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
955 * determines for each table which of these features applies to that table.
956 *
957 * @param string $table Table name found in the $GLOBALS['TCA'] array
958 * @param int $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.
959 * @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.
960 * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
961 * @throws \InvalidArgumentException
962 * @return string The clause starting like " AND ...=... AND ...=...
963 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields(), deleteClause()
964 */
965 public function enableFields($table, $show_hidden = -1, $ignore_array = array(), $noVersionPreview = FALSE) {
966 if ($show_hidden === -1 && is_object($this->getTypoScriptFrontendController())) {
967 // If show_hidden was not set from outside and if TSFE is an object, set it
968 // based on showHiddenPage and showHiddenRecords from TSFE
969 $show_hidden = $table === 'pages' ? $this->getTypoScriptFrontendController()->showHiddenPage : $this->getTypoScriptFrontendController()->showHiddenRecords;
970 }
971 if ($show_hidden === -1) {
972 $show_hidden = 0;
973 }
974 // If show_hidden was not changed during the previous evaluation, do it here.
975 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
976 $query = '';
977 if (is_array($ctrl)) {
978 // Delete field check:
979 if ($ctrl['delete']) {
980 $query .= ' AND ' . $table . '.' . $ctrl['delete'] . '=0';
981 }
982 if ($ctrl['versioningWS']) {
983 if (!$this->versioningPreview) {
984 // Filter out placeholder records (new/moved/deleted items)
985 // in case we are NOT in a versioning preview (that means we are online!)
986 $query .= ' AND ' . $table . '.t3ver_state<=' . new VersionState(VersionState::DEFAULT_STATE);
987 } elseif ($table !== 'pages') {
988 // show only records of live and of the current workspace
989 // in case we are in a versioning preview
990 $query .= ' AND (' .
991 $table . '.t3ver_wsid=0 OR ' .
992 $table . '.t3ver_wsid=' . (int)$this->versioningWorkspaceId .
993 ')';
994 }
995
996 // Filter out versioned records
997 if (!$noVersionPreview && empty($ignore_array['pid'])) {
998 $query .= ' AND ' . $table . '.pid<>-1';
999 }
1000 }
1001
1002 // Enable fields:
1003 if (is_array($ctrl['enablecolumns'])) {
1004 // In case of versioning-preview, enableFields are ignored (checked in
1005 // versionOL())
1006 if (!$this->versioningPreview || !$ctrl['versioningWS'] || $noVersionPreview) {
1007 if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
1008 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1009 $query .= ' AND ' . $field . '=0';
1010 }
1011 if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
1012 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1013 $query .= ' AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'];
1014 }
1015 if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
1016 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1017 $query .= ' AND (' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
1018 }
1019 if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1020 $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1021 $query .= $this->getMultipleGroupsWhereClause($field, $table);
1022 }
1023 // Call hook functions for additional enableColumns
1024 // It is used by the extension ingmar_accessctrl which enables assigning more
1025 // than one usergroup to content and page records
1026 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'])) {
1027 $_params = array(
1028 'table' => $table,
1029 'show_hidden' => $show_hidden,
1030 'ignore_array' => $ignore_array,
1031 'ctrl' => $ctrl
1032 );
1033 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] as $_funcRef) {
1034 $query .= GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1035 }
1036 }
1037 }
1038 }
1039 } else {
1040 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);
1041 }
1042 return $query;
1043 }
1044
1045 /**
1046 * Creating where-clause for checking group access to elements in enableFields
1047 * function
1048 *
1049 * @param string $field Field with group list
1050 * @param string $table Table name
1051 * @return string AND sql-clause
1052 * @see enableFields()
1053 */
1054 public function getMultipleGroupsWhereClause($field, $table) {
1055 $memberGroups = GeneralUtility::intExplode(',', $this->getTypoScriptFrontendController()->gr_list);
1056 $orChecks = array();
1057 // If the field is empty, then OK
1058 $orChecks[] = $field . '=\'\'';
1059 // If the field is NULL, then OK
1060 $orChecks[] = $field . ' IS NULL';
1061 // If the field contsains zero, then OK
1062 $orChecks[] = $field . '=\'0\'';
1063 foreach ($memberGroups as $value) {
1064 $orChecks[] = $this->getDatabaseConnection()->listQuery($field, $value, $table);
1065 }
1066 return ' AND (' . implode(' OR ', $orChecks) . ')';
1067 }
1068
1069 /**********************
1070 *
1071 * Versioning Preview
1072 *
1073 **********************/
1074
1075 /**
1076 * Finding online PID for offline version record
1077 *
1078 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1079 * served which is not previewed by backend users!!!
1080 *
1081 * Will look if the "pid" value of the input record is -1 (it is an offline
1082 * version) and if the table supports versioning; if so, it will translate the -1
1083 * PID into the PID of the original record.
1084 *
1085 * Used whenever you are tracking something back, like making the root line.
1086 *
1087 * Principle; Record offline! => Find online?
1088 *
1089 * @param string $table Table name
1090 * @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.
1091 * @return void (Passed by ref).
1092 * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1093 */
1094 public function fixVersioningPid($table, &$rr) {
1095 if ($this->versioningPreview && is_array($rr) && (int)$rr['pid'] === -1 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1096 // Have to hardcode it for "pages" table since TCA is not loaded at this moment!
1097 // Check values for t3ver_oid and t3ver_wsid:
1098 if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1099 // If "t3ver_oid" is already a field, just set this:
1100 $oid = $rr['t3ver_oid'];
1101 $wsid = $rr['t3ver_wsid'];
1102 } else {
1103 // Otherwise we have to expect "uid" to be in the record and look up based
1104 // on this:
1105 $newPidRec = $this->getRawRecord($table, $rr['uid'], 't3ver_oid,t3ver_wsid', TRUE);
1106 if (is_array($newPidRec)) {
1107 $oid = $newPidRec['t3ver_oid'];
1108 $wsid = $newPidRec['t3ver_wsid'];
1109 }
1110 }
1111 // If workspace ids matches and ID of current online version is found, look up
1112 // the PID value of that:
1113 if ($oid && ((int)$this->versioningWorkspaceId === 0 && $this->checkWorkspaceAccess($wsid) || (int)$wsid === (int)$this->versioningWorkspaceId)) {
1114 $oidRec = $this->getRawRecord($table, $oid, 'pid', TRUE);
1115 if (is_array($oidRec)) {
1116 // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1117 // assumed that this is a "branch" type page and therefore the uid should be
1118 // kept (like in versionOL()). However if the page is NOT a branch version it
1119 // should not happen - but then again, direct access to that uid should not
1120 // happen!
1121 $rr['_ORIG_pid'] = $rr['pid'];
1122 $rr['pid'] = $oidRec['pid'];
1123 }
1124 }
1125 }
1126 // Changing PID in case of moving pointer:
1127 if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1128 $rr['pid'] = $movePlhRec['pid'];
1129 }
1130 }
1131
1132 /**
1133 * Versioning Preview Overlay
1134 *
1135 * ONLY active when backend user is previewing records. MUST NEVER affect a site
1136 * served which is not previewed by backend users!!!
1137 *
1138 * Generally ALWAYS used when records are selected based on uid or pid. If
1139 * records are selected on other fields than uid or pid (eg. "email = ....") then
1140 * usage might produce undesired results and that should be evaluated on
1141 * individual basis.
1142 *
1143 * Principle; Record online! => Find offline?
1144 *
1145 * @param string $table Table name
1146 * @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!
1147 * @param bool $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)
1148 * @param bool $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!
1149 * @return void (Passed by ref).
1150 * @see fixVersioningPid(), BackendUtility::workspaceOL()
1151 */
1152 public function versionOL($table, &$row, $unsetMovePointers = FALSE, $bypassEnableFieldsCheck = FALSE) {
1153 if ($this->versioningPreview && is_array($row)) {
1154 // will overlay any movePlhOL found with the real record, which in turn
1155 // will be overlaid with its workspace version if any.
1156 $movePldSwap = $this->movePlhOL($table, $row);
1157 // implode(',',array_keys($row)) = Using fields from original record to make
1158 // sure no additional fields are selected. This is best for eg. getPageOverlay()
1159 if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], implode(',', array_keys($row)), $bypassEnableFieldsCheck)) {
1160 if (is_array($wsAlt)) {
1161 // Always fix PID (like in fixVersioningPid() above). [This is usually not
1162 // the important factor for versioning OL]
1163 // Keep the old (-1) - indicates it was a version...
1164 $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1165 // Set in the online versions PID.
1166 $wsAlt['pid'] = $row['pid'];
1167 // For versions of single elements or page+content, preserve online UID and PID
1168 // (this will produce true "overlay" of element _content_, not any references)
1169 // For page+content the "_ORIG_uid" should actually be used as PID for selection
1170 // of tables with "versioning_followPages" enabled.
1171 $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1172 $wsAlt['uid'] = $row['uid'];
1173 // Translate page alias as well so links are pointing to the _online_ page:
1174 if ($table === 'pages') {
1175 $wsAlt['alias'] = $row['alias'];
1176 }
1177 // Changing input record to the workspace version alternative:
1178 $row = $wsAlt;
1179 // Check if it is deleted/new
1180 $rowVersionState = VersionState::cast($row['t3ver_state']);
1181 if (
1182 $rowVersionState->equals(VersionState::NEW_PLACEHOLDER)
1183 || $rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)
1184 ) {
1185 // Unset record if it turned out to be deleted in workspace
1186 $row = FALSE;
1187 }
1188 // Check if move-pointer in workspace (unless if a move-placeholder is the
1189 // reason why it appears!):
1190 // You have to specifically set $unsetMovePointers in order to clear these
1191 // because it is normally a display issue if it should be shown or not.
1192 if (
1193 ($rowVersionState->equals(VersionState::MOVE_POINTER)
1194 && !$movePldSwap
1195 ) && $unsetMovePointers
1196 ) {
1197 // Unset record if it turned out to be deleted in workspace
1198 $row = FALSE;
1199 }
1200 } else {
1201 // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1202 // (online version is dummy-representation)
1203 // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1204 // enablefields for BOTH the version AND the online record deselects it. See
1205 // note for $bypassEnableFieldsCheck
1206 if ($wsAlt <= -1 || VersionState::cast($row['t3ver_state'])->indicatesPlaceholder()) {
1207 // Unset record if it turned out to be "hidden"
1208 $row = FALSE;
1209 }
1210 }
1211 }
1212 }
1213 }
1214
1215 /**
1216 * Checks if record is a move-placeholder
1217 * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1218 * the pointed-to live record (and return TRUE) Used from versionOL
1219 *
1220 * @param string $table Table name
1221 * @param array $row Row (passed by reference) - only online records...
1222 * @return bool TRUE if overlay is made.
1223 * @see BackendUtility::movePlhOl()
1224 */
1225 public function movePlhOL($table, &$row) {
1226 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2
1227 && (int)VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)
1228 ) {
1229 // Only for WS ver 2... (moving)
1230 // If t3ver_move_id is not found, then find it (but we like best if it is here)
1231 if (!isset($row['t3ver_move_id'])) {
1232 $moveIDRec = $this->getRawRecord($table, $row['uid'], 't3ver_move_id', TRUE);
1233 $moveID = $moveIDRec['t3ver_move_id'];
1234 } else {
1235 $moveID = $row['t3ver_move_id'];
1236 }
1237 // Find pointed-to record.
1238 if ($moveID) {
1239 $res = $this->getDatabaseConnection()->exec_SELECTquery(implode(',', array_keys($row)), $table, 'uid=' . (int)$moveID . $this->enableFields($table));
1240 $origRow = $this->getDatabaseConnection()->sql_fetch_assoc($res);
1241 $this->getDatabaseConnection()->sql_free_result($res);
1242 if ($origRow) {
1243 $row = $origRow;
1244 return TRUE;
1245 }
1246 }
1247 }
1248 return FALSE;
1249 }
1250
1251 /**
1252 * Returns move placeholder of online (live) version
1253 *
1254 * @param string $table Table name
1255 * @param int $uid Record UID of online version
1256 * @param string $fields Field list, default is *
1257 * @return array If found, the record, otherwise nothing.
1258 * @see BackendUtility::getMovePlaceholder()
1259 */
1260 public function getMovePlaceholder($table, $uid, $fields = '*') {
1261 if ($this->versioningPreview) {
1262 $workspace = (int)$this->versioningWorkspaceId;
1263 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2 && $workspace !== 0) {
1264 // Select workspace version of record:
1265 $row = $this->getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, 'pid<>-1 AND
1266 t3ver_state=' . new VersionState(VersionState::MOVE_PLACEHOLDER) . ' AND
1267 t3ver_move_id=' . (int)$uid . ' AND
1268 t3ver_wsid=' . (int)$workspace . $this->deleteClause($table));
1269 if (is_array($row)) {
1270 return $row;
1271 }
1272 }
1273 }
1274 return FALSE;
1275 }
1276
1277 /**
1278 * Select the version of a record for a workspace
1279 *
1280 * @param int $workspace Workspace ID
1281 * @param string $table Table name to select from
1282 * @param int $uid Record uid for which to find workspace version.
1283 * @param string $fields Field list to select
1284 * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1285 * @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.
1286 * @see BackendUtility::getWorkspaceVersionOfRecord()
1287 */
1288 public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = FALSE) {
1289 if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1290 $workspace = (int)$workspace;
1291 $uid = (int)$uid;
1292 // Setting up enableFields for version record
1293 $enFields = $this->enableFields($table, -1, array(), TRUE);
1294 // Select workspace version of record, only testing for deleted.
1295 $newrow = $this->getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, 'pid=-1 AND
1296 t3ver_oid=' . $uid . ' AND
1297 t3ver_wsid=' . $workspace . $this->deleteClause($table));
1298 // If version found, check if it could have been selected with enableFields on
1299 // as well:
1300 if (is_array($newrow)) {
1301 if ($bypassEnableFieldsCheck || $this->getDatabaseConnection()->exec_SELECTgetSingleRow('uid', $table, 'pid=-1 AND
1302 t3ver_oid=' . $uid . ' AND
1303 t3ver_wsid=' . $workspace . $enFields)) {
1304 // Return offline version, tested for its enableFields.
1305 return $newrow;
1306 } else {
1307 // Return -1 because offline version was de-selected due to its enableFields.
1308 return -1;
1309 }
1310 } else {
1311 // OK, so no workspace version was found. Then check if online version can be
1312 // selected with full enable fields and if so, return 1:
1313 if ($bypassEnableFieldsCheck || $this->getDatabaseConnection()->exec_SELECTgetSingleRow('uid', $table, 'uid=' . $uid . $enFields)) {
1314 // Means search was done, but no version found.
1315 return 1;
1316 } else {
1317 // Return -2 because the online record was de-selected due to its enableFields.
1318 return -2;
1319 }
1320 }
1321 }
1322 // No look up in database because versioning not enabled / or workspace not
1323 // offline
1324 return FALSE;
1325 }
1326
1327 /**
1328 * Checks if user has access to workspace.
1329 *
1330 * @param int $wsid Workspace ID
1331 * @return bool <code>TRUE</code> if has access
1332 */
1333 public function checkWorkspaceAccess($wsid) {
1334 if (!$GLOBALS['BE_USER'] || !ExtensionManagementUtility::isLoaded('workspaces')) {
1335 return FALSE;
1336 }
1337 if (isset($this->workspaceCache[$wsid])) {
1338 $ws = $this->workspaceCache[$wsid];
1339 } else {
1340 if ($wsid > 0) {
1341 // No $GLOBALS['TCA'] yet!
1342 $ws = $this->getDatabaseConnection()->exec_SELECTgetSingleRow('*', 'sys_workspace', 'uid=' . (int)$wsid . ' AND deleted=0');
1343 if (!is_array($ws)) {
1344 return FALSE;
1345 }
1346 } else {
1347 $ws = $wsid;
1348 }
1349 $ws = $GLOBALS['BE_USER']->checkWorkspace($ws);
1350 $this->workspaceCache[$wsid] = $ws;
1351 }
1352 return (string)$ws['_ACCESS'] !== '';
1353 }
1354
1355 /**
1356 * Gets file references for a given record field.
1357 *
1358 * @param string $tableName Name of the table
1359 * @param string $fieldName Name of the field
1360 * @param array $element The parent element referencing to files
1361 * @return array
1362 */
1363 public function getFileReferences($tableName, $fieldName, array $element) {
1364 /** @var $fileRepository FileRepository */
1365 $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
1366 $currentId = !empty($element['uid']) ? $element['uid'] : 0;
1367
1368 // Fetch the references of the default element
1369 $references = $fileRepository->findByRelation($tableName, $fieldName, $currentId);
1370
1371 $localizedId = NULL;
1372 if (isset($element['_LOCALIZED_UID'])) {
1373 $localizedId = $element['_LOCALIZED_UID'];
1374 } elseif (isset($element['_PAGES_OVERLAY_UID'])) {
1375 $localizedId = $element['_PAGES_OVERLAY_UID'];
1376 }
1377
1378 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['transForeignTable'])) {
1379 $tableName = $GLOBALS['TCA'][$tableName]['ctrl']['transForeignTable'];
1380 }
1381
1382 $isTableLocalizable = (
1383 !empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1384 && !empty($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1385 );
1386 if ($isTableLocalizable && $localizedId !== NULL) {
1387 $localizedReferences = $fileRepository->findByRelation($tableName, $fieldName, $localizedId);
1388 $localizedReferencesValue = $localizedReferences ?: '';
1389 if ($this->shouldFieldBeOverlaid($tableName, $fieldName, $localizedReferencesValue)) {
1390 $references = $localizedReferences;
1391 }
1392 }
1393
1394 return $references;
1395 }
1396
1397 /**
1398 * Determine if a field needs an overlay
1399 *
1400 * @param string $table TCA tablename
1401 * @param string $field TCA fieldname
1402 * @param mixed $value Current value of the field
1403 * @return bool Returns TRUE if a given record field needs to be overlaid
1404 */
1405 protected function shouldFieldBeOverlaid($table, $field, $value) {
1406 $l10n_mode = isset($GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode'])
1407 ? $GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode']
1408 : '';
1409
1410 $shouldFieldBeOverlaid = TRUE;
1411
1412 if ($l10n_mode === 'exclude') {
1413 $shouldFieldBeOverlaid = FALSE;
1414 } elseif ($l10n_mode === 'mergeIfNotBlank') {
1415 $checkValue = $value;
1416
1417 // 0 values are considered blank when coming from a group field
1418 if (empty($value) && $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'group') {
1419 $checkValue = '';
1420 }
1421
1422 if ($checkValue === array() || !is_array($checkValue) && trim($checkValue) === '') {
1423 $shouldFieldBeOverlaid = FALSE;
1424 }
1425 }
1426
1427 return $shouldFieldBeOverlaid;
1428 }
1429
1430 /**
1431 * Returns the database connection
1432 *
1433 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1434 */
1435 protected function getDatabaseConnection() {
1436 return $GLOBALS['TYPO3_DB'];
1437 }
1438
1439 /**
1440 * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
1441 */
1442 protected function getTypoScriptFrontendController() {
1443 return $GLOBALS['TSFE'];
1444 }
1445
1446 }