[BUGFIX] Prevent exception due to missing id in the language menu
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / ContentObject / Menu / AbstractMenuContentObject.php
1 <?php
2 namespace TYPO3\CMS\Frontend\ContentObject\Menu;
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\Database\DatabaseConnection;
19 use TYPO3\CMS\Core\Database\RelationHandler;
20 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
21 use TYPO3\CMS\Core\TypoScript\TemplateService;
22 use TYPO3\CMS\Core\Utility\ArrayUtility;
23 use TYPO3\CMS\Core\Utility\GeneralUtility;
24 use TYPO3\CMS\Core\Utility\MathUtility;
25 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
26 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
27 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
28 use TYPO3\CMS\Frontend\Page\PageRepository;
29
30 /**
31 * Generating navigation/menus from TypoScript
32 *
33 * The HMENU content object uses this (or more precisely one of the extension classes).
34 * Among others the class generates an array of menu items. Thereafter functions from the subclasses are called.
35 * The class is always used through extension classes (like GraphicalMenuContentObject or TextMenuContentObject).
36 */
37 abstract class AbstractMenuContentObject
38 {
39 /**
40 * tells you which menu number this is. This is important when getting data from the setup
41 *
42 * @var int
43 */
44 public $menuNumber = 1;
45
46 /**
47 * 0 = rootFolder
48 *
49 * @var int
50 */
51 public $entryLevel = 0;
52
53 /**
54 * The doktype-number that defines a spacer
55 *
56 * @var string
57 */
58 public $spacerIDList = '199';
59
60 /**
61 * Doktypes that define which should not be included in a menu
62 *
63 * @var string
64 */
65 public $doktypeExcludeList = '6';
66
67 /**
68 * @var int[]
69 */
70 public $alwaysActivePIDlist = [];
71
72 /**
73 * @var string
74 */
75 public $imgNamePrefix = 'img';
76
77 /**
78 * @var int
79 */
80 public $imgNameNotRandom = 0;
81
82 /**
83 * @var bool
84 */
85 public $debug = 0;
86
87 /**
88 * Loaded with the parent cObj-object when a new HMENU is made
89 *
90 * @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
91 */
92 public $parent_cObj = null;
93
94 /**
95 * @var string
96 */
97 public $GMENU_fixKey = 'gmenu';
98
99 /**
100 * accumulation of mount point data
101 *
102 * @var string[]
103 */
104 public $MP_array = [];
105
106 /**
107 * HMENU configuration
108 *
109 * @var array
110 */
111 public $conf = [];
112
113 /**
114 * xMENU configuration (TMENU, GMENU etc)
115 *
116 * @var array
117 */
118 public $mconf = [];
119
120 /**
121 * @var \TYPO3\CMS\Core\TypoScript\TemplateService
122 */
123 public $tmpl = null;
124
125 /**
126 * @var \TYPO3\CMS\Frontend\Page\PageRepository
127 */
128 public $sys_page = null;
129
130 /**
131 * The base page-id of the menu.
132 *
133 * @var int
134 */
135 public $id;
136
137 /**
138 * Holds the page uid of the NEXT page in the root line from the page pointed to by entryLevel;
139 * Used to expand the menu automatically if in a certain root line.
140 *
141 * @var string
142 */
143 public $nextActive;
144
145 /**
146 * The array of menuItems which is built
147 *
148 * @var array[]
149 */
150 public $menuArr;
151
152 /**
153 * @var string
154 */
155 public $hash;
156
157 /**
158 * @var array
159 */
160 public $result = [];
161
162 /**
163 * Is filled with an array of page uid numbers + RL parameters which are in the current
164 * root line (used to evaluate whether a menu item is in active state)
165 *
166 * @var string
167 */
168 public $rL_uidRegister = '';
169
170 /**
171 * @var string
172 */
173 public $INPfixMD5;
174
175 /**
176 * @var mixed[]
177 */
178 public $I;
179
180 /**
181 * @var string
182 */
183 public $WMresult;
184
185 /**
186 * @var string
187 */
188 public $WMfreezePrefix;
189
190 /**
191 * @var int
192 */
193 public $WMmenuItems;
194
195 /**
196 * @var array[]
197 */
198 public $WMsubmenuObjSuffixes;
199
200 /**
201 * @var string
202 */
203 public $WMextraScript;
204
205 /**
206 * @var ContentObjectRenderer
207 */
208 public $WMcObj = null;
209
210 /**
211 * Can be set to contain menu item arrays for sub-levels.
212 *
213 * @var string
214 */
215 public $alternativeMenuTempArray = '';
216
217 /**
218 * Will be 'id' in XHTML-mode
219 *
220 * @var string
221 */
222 public $nameAttribute = 'name';
223
224 /**
225 * TRUE to use cHash in generated link (normally only for the language
226 * selector and if parameters exist in the URL).
227 *
228 * @var bool
229 */
230 protected $useCacheHash = false;
231
232 /**
233 * The initialization of the object. This just sets some internal variables.
234 *
235 * @param TemplateService $tmpl The $this->getTypoScriptFrontendController()->tmpl object
236 * @param PageRepository $sys_page The $this->getTypoScriptFrontendController()->sys_page object
237 * @param int|string $id A starting point page id. This should probably be blank since the 'entryLevel' value will be used then.
238 * @param array $conf The TypoScript configuration for the HMENU cObject
239 * @param int $menuNumber Menu number; 1,2,3. Should probably be 1
240 * @param string $objSuffix Submenu Object suffix. This offers submenus a way to use alternative configuration for specific positions in the menu; By default "1 = TMENU" would use "1." for the TMENU configuration, but if this string is set to eg. "a" then "1a." would be used for configuration instead (while "1 = " is still used for the overall object definition of "TMENU")
241 * @return bool Returns TRUE on success
242 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::HMENU()
243 */
244 public function start($tmpl, $sys_page, $id, $conf, $menuNumber, $objSuffix = '')
245 {
246 $tsfe = $this->getTypoScriptFrontendController();
247 // Init:
248 $this->conf = $conf;
249 $this->menuNumber = $menuNumber;
250 $this->mconf = $conf[$this->menuNumber . $objSuffix . '.'];
251 $this->debug = $tsfe->debug;
252 $this->WMcObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
253 // In XHTML and HTML5 there is no "name" attribute anymore
254 switch ($tsfe->xhtmlDoctype) {
255 case 'xhtml_strict':
256 // intended fall-through
257 case 'xhtml_11':
258 // intended fall-through
259 case 'xhtml_2':
260 // intended fall-through
261 case 'html5':
262 // intended fall-through
263 case '':
264 // empty means that it's HTML5 by default
265 $this->nameAttribute = 'id';
266 break;
267 default:
268 $this->nameAttribute = 'name';
269 }
270 // Sets the internal vars. $tmpl MUST be the template-object. $sys_page MUST be the sys_page object
271 if ($this->conf[$this->menuNumber . $objSuffix] && is_object($tmpl) && is_object($sys_page)) {
272 $this->tmpl = $tmpl;
273 $this->sys_page = $sys_page;
274 // alwaysActivePIDlist initialized:
275 if (trim($this->conf['alwaysActivePIDlist']) || isset($this->conf['alwaysActivePIDlist.'])) {
276 if (isset($this->conf['alwaysActivePIDlist.'])) {
277 $this->conf['alwaysActivePIDlist'] = $this->parent_cObj->stdWrap(
278 $this->conf['alwaysActivePIDlist'],
279 $this->conf['alwaysActivePIDlist.']
280 );
281 }
282 $this->alwaysActivePIDlist = GeneralUtility::intExplode(',', $this->conf['alwaysActivePIDlist']);
283 }
284 // 'not in menu' doktypes
285 if ($this->conf['excludeDoktypes']) {
286 $this->doktypeExcludeList = $this->getDatabaseConnection()->cleanIntList($this->conf['excludeDoktypes']);
287 }
288 // EntryLevel
289 $this->entryLevel = $this->parent_cObj->getKey(
290 isset($conf['entryLevel.']) ? $this->parent_cObj->stdWrap(
291 $conf['entryLevel'],
292 $conf['entryLevel.']
293 ) : $conf['entryLevel'],
294 $this->tmpl->rootLine
295 );
296 // Set parent page: If $id not stated with start() then the base-id will be found from rootLine[$this->entryLevel]
297 // Called as the next level in a menu. It is assumed that $this->MP_array is set from parent menu.
298 if ($id) {
299 $this->id = (int)$id;
300 } else {
301 // This is a BRAND NEW menu, first level. So we take ID from rootline and also find MP_array (mount points)
302 $this->id = (int)$this->tmpl->rootLine[$this->entryLevel]['uid'];
303 // Traverse rootline to build MP_array of pages BEFORE the entryLevel
304 // (MP var for ->id is picked up in the next part of the code...)
305 foreach ($this->tmpl->rootLine as $entryLevel => $levelRec) {
306 // For overlaid mount points, set the variable right now:
307 if ($levelRec['_MP_PARAM'] && $levelRec['_MOUNT_OL']) {
308 $this->MP_array[] = $levelRec['_MP_PARAM'];
309 }
310 // Break when entry level is reached:
311 if ($entryLevel >= $this->entryLevel) {
312 break;
313 }
314 // For normal mount points, set the variable for next level.
315 if ($levelRec['_MP_PARAM'] && !$levelRec['_MOUNT_OL']) {
316 $this->MP_array[] = $levelRec['_MP_PARAM'];
317 }
318 }
319 }
320 // Return FALSE if no page ID was set (thus no menu of subpages can be made).
321 if ($this->id <= 0) {
322 return false;
323 }
324 // Check if page is a mount point, and if so set id and MP_array
325 // (basically this is ONLY for non-overlay mode, but in overlay mode an ID with a mount point should never reach this point anyways, so no harm done...)
326 $mount_info = $this->sys_page->getMountPointInfo($this->id);
327 if (is_array($mount_info)) {
328 $this->MP_array[] = $mount_info['MPvar'];
329 $this->id = $mount_info['mount_pid'];
330 }
331 // Gather list of page uids in root line (for "isActive" evaluation). Also adds the MP params in the path so Mount Points are respected.
332 // (List is specific for this rootline, so it may be supplied from parent menus for speed...)
333 if (!is_array($this->rL_uidRegister)) {
334 $rl_MParray = [];
335 foreach ($this->tmpl->rootLine as $v_rl) {
336 // For overlaid mount points, set the variable right now:
337 if ($v_rl['_MP_PARAM'] && $v_rl['_MOUNT_OL']) {
338 $rl_MParray[] = $v_rl['_MP_PARAM'];
339 }
340 // Add to register:
341 $this->rL_uidRegister[] = 'ITEM:' . $v_rl['uid'] .
342 (!empty($rl_MParray)
343 ? ':' . implode(',', $rl_MParray)
344 : ''
345 );
346 // For normal mount points, set the variable for next level.
347 if ($v_rl['_MP_PARAM'] && !$v_rl['_MOUNT_OL']) {
348 $rl_MParray[] = $v_rl['_MP_PARAM'];
349 }
350 }
351 }
352 // Set $directoryLevel so the following evalution of the nextActive will not return
353 // an invalid value if .special=directory was set
354 $directoryLevel = 0;
355 if ($this->conf['special'] === 'directory') {
356 $value = isset($this->conf['special.']['value.']) ? $this->parent_cObj->stdWrap(
357 $this->conf['special.']['value'],
358 $this->conf['special.']['value.']
359 ) : $this->conf['special.']['value'];
360 if ($value === '') {
361 $value = $tsfe->page['uid'];
362 }
363 $directoryLevel = (int)$tsfe->tmpl->getRootlineLevel($value);
364 }
365 // Setting "nextActive": This is the page uid + MPvar of the NEXT page in rootline. Used to expand the menu if we are in the right branch of the tree
366 // Notice: The automatic expansion of a menu is designed to work only when no "special" modes (except "directory") are used.
367 $startLevel = $directoryLevel ?: $this->entryLevel;
368 $currentLevel = $startLevel + $this->menuNumber;
369 if (is_array($this->tmpl->rootLine[$currentLevel])) {
370 $nextMParray = $this->MP_array;
371 if (empty($nextMParray) && !$this->tmpl->rootLine[$currentLevel]['_MOUNT_OL'] && $currentLevel > 0) {
372 // Make sure to slide-down any mount point information (_MP_PARAM) to children records in the rootline
373 // otherwise automatic expansion will not work
374 $parentRecord = $this->tmpl->rootLine[$currentLevel - 1];
375 if (isset($parentRecord['_MP_PARAM'])) {
376 $nextMParray[] = $parentRecord['_MP_PARAM'];
377 }
378 }
379 // In overlay mode, add next level MPvars as well:
380 if ($this->tmpl->rootLine[$currentLevel]['_MOUNT_OL']) {
381 $nextMParray[] = $this->tmpl->rootLine[$currentLevel]['_MP_PARAM'];
382 }
383 $this->nextActive = $this->tmpl->rootLine[$currentLevel]['uid'] .
384 (!empty($nextMParray)
385 ? ':' . implode(',', $nextMParray)
386 : ''
387 );
388 } else {
389 $this->nextActive = '';
390 }
391 // imgNamePrefix
392 if ($this->mconf['imgNamePrefix']) {
393 $this->imgNamePrefix = $this->mconf['imgNamePrefix'];
394 }
395 $this->imgNameNotRandom = $this->mconf['imgNameNotRandom'];
396 $retVal = true;
397 } else {
398 $this->getTimeTracker()->setTSlogMessage('ERROR in menu', 3);
399 $retVal = false;
400 }
401 return $retVal;
402 }
403
404 /**
405 * Creates the menu in the internal variables, ready for output.
406 * Basically this will read the page records needed and fill in the internal $this->menuArr
407 * Based on a hash of this array and some other variables the $this->result variable will be
408 * loaded either from cache OR by calling the generate() method of the class to create the menu for real.
409 *
410 * @return void
411 */
412 public function makeMenu()
413 {
414 if (!$this->id) {
415 return;
416 }
417
418 $this->useCacheHash = false;
419
420 // Initializing showAccessRestrictedPages
421 $SAVED_where_groupAccess = '';
422 if ($this->mconf['showAccessRestrictedPages']) {
423 // SAVING where_groupAccess
424 $SAVED_where_groupAccess = $this->sys_page->where_groupAccess;
425 // Temporarily removing fe_group checking!
426 $this->sys_page->where_groupAccess = '';
427 }
428
429 $menuItems = $this->prepareMenuItems();
430
431 $c = 0;
432 $c_b = 0;
433 $minItems = (int)($this->mconf['minItems'] ?: $this->conf['minItems']);
434 $maxItems = (int)($this->mconf['maxItems'] ?: $this->conf['maxItems']);
435 $begin = $this->parent_cObj->calc($this->mconf['begin'] ? $this->mconf['begin'] : $this->conf['begin']);
436 $minItemsConf = isset($this->mconf['minItems.']) ? $this->mconf['minItems.'] : (isset($this->conf['minItems.']) ? $this->conf['minItems.'] : null);
437 $minItems = is_array($minItemsConf) ? $this->parent_cObj->stdWrap($minItems, $minItemsConf) : $minItems;
438 $maxItemsConf = isset($this->mconf['maxItems.']) ? $this->mconf['maxItems.'] : (isset($this->conf['maxItems.']) ? $this->conf['maxItems.'] : null);
439 $maxItems = is_array($maxItemsConf) ? $this->parent_cObj->stdWrap($maxItems, $maxItemsConf) : $maxItems;
440 $beginConf = isset($this->mconf['begin.']) ? $this->mconf['begin.'] : (isset($this->conf['begin.']) ? $this->conf['begin.'] : null);
441 $begin = is_array($beginConf) ? $this->parent_cObj->stdWrap($begin, $beginConf) : $begin;
442 $banUidArray = $this->getBannedUids();
443 // Fill in the menuArr with elements that should go into the menu:
444 $this->menuArr = [];
445 foreach ($menuItems as $data) {
446 $spacer = GeneralUtility::inList($this->spacerIDList, $data['doktype']) || $data['ITEM_STATE'] === 'SPC';
447 // if item is a spacer, $spacer is set
448 if ($this->filterMenuPages($data, $banUidArray, $spacer)) {
449 $c_b++;
450 // If the beginning item has been reached.
451 if ($begin <= $c_b) {
452 $this->menuArr[$c] = $data;
453 $this->menuArr[$c]['isSpacer'] = $spacer;
454 $c++;
455 if ($maxItems && $c >= $maxItems) {
456 break;
457 }
458 }
459 }
460 }
461 // Fill in fake items, if min-items is set.
462 if ($minItems) {
463 while ($c < $minItems) {
464 $this->menuArr[$c] = [
465 'title' => '...',
466 'uid' => $this->getTypoScriptFrontendController()->id
467 ];
468 $c++;
469 }
470 }
471 // Passing the menuArr through a user defined function:
472 if ($this->mconf['itemArrayProcFunc']) {
473 $this->menuArr = $this->userProcess('itemArrayProcFunc', $this->menuArr);
474 }
475 // Setting number of menu items
476 $this->getTypoScriptFrontendController()->register['count_menuItems'] = count($this->menuArr);
477 $this->hash = md5(
478 serialize($this->menuArr) .
479 serialize($this->mconf) .
480 serialize($this->tmpl->rootLine) .
481 serialize($this->MP_array)
482 );
483 // Get the cache timeout:
484 if ($this->conf['cache_period']) {
485 $cacheTimeout = $this->conf['cache_period'];
486 } else {
487 $cacheTimeout = $this->getTypoScriptFrontendController()->get_cache_timeout();
488 }
489 $cache = $this->getCache();
490 $cachedData = $cache->get($this->hash);
491 if (!is_array($cachedData)) {
492 $this->generate();
493 $cache->set($this->hash, $this->result, ['ident_MENUDATA'], (int)$cacheTimeout);
494 } else {
495 $this->result = $cachedData;
496 }
497 // End showAccessRestrictedPages
498 if ($this->mconf['showAccessRestrictedPages']) {
499 // RESTORING where_groupAccess
500 $this->sys_page->where_groupAccess = $SAVED_where_groupAccess;
501 }
502 }
503
504 /**
505 * Generates the the menu data.
506 *
507 * Subclasses should overwrite this method.
508 *
509 * @return void
510 */
511 public function generate()
512 {
513 }
514
515 /**
516 * @return string The HTML for the menu
517 */
518 public function writeMenu()
519 {
520 return '';
521 }
522
523 /**
524 * Gets an array of page rows and removes all, which are not accessible
525 *
526 * @param array $pages
527 * @return array
528 */
529 protected function removeInaccessiblePages(array $pages)
530 {
531 $banned = $this->getBannedUids();
532 $filteredPages = [];
533 foreach ($pages as $aPage) {
534 if ($this->filterMenuPages($aPage, $banned, $aPage['doktype'] === PageRepository::DOKTYPE_SPACER)) {
535 $filteredPages[$aPage['uid']] = $aPage;
536 }
537 }
538 return $filteredPages;
539 }
540
541 /**
542 * Main function for retrieving menu items based on the menu type (special or sectionIndex or "normal")
543 *
544 * @return array
545 */
546 protected function prepareMenuItems()
547 {
548 $menuItems = [];
549 $alternativeSortingField = trim($this->mconf['alternativeSortingField']) ?: 'sorting';
550
551 // Additional where clause, usually starts with AND (as usual with all additionalWhere functionality in TS)
552 $additionalWhere = isset($this->mconf['additionalWhere']) ? $this->mconf['additionalWhere'] : '';
553 if (isset($this->mconf['additionalWhere.'])) {
554 $additionalWhere = $this->parent_cObj->stdWrap($additionalWhere, $this->mconf['additionalWhere.']);
555 }
556
557 // ... only for the FIRST level of a HMENU
558 if ($this->menuNumber == 1 && $this->conf['special']) {
559 $value = isset($this->conf['special.']['value.'])
560 ? $this->parent_cObj->stdWrap($this->conf['special.']['value'], $this->conf['special.']['value.'])
561 : $this->conf['special.']['value'];
562 switch ($this->conf['special']) {
563 case 'userfunction':
564 $menuItems = $this->prepareMenuItemsForUserSpecificMenu($value, $alternativeSortingField);
565 break;
566 case 'language':
567 $menuItems = $this->prepareMenuItemsForLanguageMenu($value);
568 break;
569 case 'directory':
570 $menuItems = $this->prepareMenuItemsForDirectoryMenu($value, $alternativeSortingField);
571 break;
572 case 'list':
573 $menuItems = $this->prepareMenuItemsForListMenu($value);
574 break;
575 case 'updated':
576 $menuItems = $this->prepareMenuItemsForUpdatedMenu(
577 $value,
578 $this->mconf['alternativeSortingField'] ?: false
579 );
580 break;
581 case 'keywords':
582 $menuItems = $this->prepareMenuItemsForKeywordsMenu(
583 $value,
584 $this->mconf['alternativeSortingField'] ?: false
585 );
586 break;
587 case 'categories':
588 /** @var CategoryMenuUtility $categoryMenuUtility */
589 $categoryMenuUtility = GeneralUtility::makeInstance(CategoryMenuUtility::class);
590 $menuItems = $categoryMenuUtility->collectPages($value, $this->conf['special.'], $this);
591 break;
592 case 'rootline':
593 $menuItems = $this->prepareMenuItemsForRootlineMenu();
594 break;
595 case 'browse':
596 $menuItems = $this->prepareMenuitemsForBrowseMenu($value, $alternativeSortingField, $additionalWhere);
597 break;
598 }
599 if ($this->mconf['sectionIndex']) {
600 $sectionIndexes = [];
601 foreach ($menuItems as $page) {
602 $sectionIndexes = $sectionIndexes + $this->sectionIndex($alternativeSortingField, $page['uid']);
603 }
604 $menuItems = $sectionIndexes;
605 }
606 } elseif (is_array($this->alternativeMenuTempArray)) {
607 // Setting $menuItems array if not level 1.
608 $menuItems = $this->alternativeMenuTempArray;
609 } elseif ($this->mconf['sectionIndex']) {
610 $menuItems = $this->sectionIndex($alternativeSortingField);
611 } else {
612 // Default: Gets a hierarchical menu based on subpages of $this->id
613 $menuItems = $this->sys_page->getMenu($this->id, '*', $alternativeSortingField, $additionalWhere);
614 }
615 return $menuItems;
616 }
617
618 /**
619 * Fetches all menuitems if special = userfunction is set
620 *
621 * @param string $specialValue The value from special.value
622 * @param string $sortingField The sorting field
623 * @return array
624 */
625 protected function prepareMenuItemsForUserSpecificMenu($specialValue, $sortingField)
626 {
627 $menuItems = $this->parent_cObj->callUserFunction(
628 $this->conf['special.']['userFunc'],
629 array_merge($this->conf['special.'], ['value' => $specialValue, '_altSortField' => $sortingField]),
630 ''
631 );
632 if (!is_array($menuItems)) {
633 $menuItems = [];
634 }
635 return $menuItems;
636 }
637
638 /**
639 * Fetches all menuitems if special = language is set
640 *
641 * @param string $specialValue The value from special.value
642 * @return array
643 */
644 protected function prepareMenuItemsForLanguageMenu($specialValue)
645 {
646 $menuItems = [];
647 // Getting current page record NOT overlaid by any translation:
648 $tsfe = $this->getTypoScriptFrontendController();
649 $currentPageWithNoOverlay = $this->sys_page->getRawRecord('pages', $tsfe->page['uid']);
650 // Traverse languages set up:
651 $languageItems = GeneralUtility::intExplode(',', $specialValue);
652 foreach ($languageItems as $sUid) {
653 // Find overlay record:
654 if ($sUid) {
655 $lRecs = $this->sys_page->getPageOverlay($tsfe->page['uid'], $sUid);
656 } else {
657 $lRecs = [];
658 }
659 // Checking if the "disabled" state should be set.
660 if (GeneralUtility::hideIfNotTranslated($tsfe->page['l18n_cfg']) && $sUid &&
661 empty($lRecs) || GeneralUtility::hideIfDefaultLanguage($tsfe->page['l18n_cfg']) &&
662 (!$sUid || empty($lRecs)) ||
663 !$this->conf['special.']['normalWhenNoLanguage'] && $sUid && empty($lRecs)
664 ) {
665 $iState = $tsfe->sys_language_uid == $sUid ? 'USERDEF2' : 'USERDEF1';
666 } else {
667 $iState = $tsfe->sys_language_uid == $sUid ? 'ACT' : 'NO';
668 }
669 if ($this->conf['addQueryString']) {
670 $getVars = $this->parent_cObj->getQueryArguments(
671 $this->conf['addQueryString.'],
672 ['L' => $sUid],
673 true
674 );
675 $this->analyzeCacheHashRequirements($getVars);
676 } else {
677 $getVars = '&L=' . $sUid;
678 }
679 // Adding menu item:
680 $menuItems[] = array_merge(
681 array_merge($currentPageWithNoOverlay, $lRecs),
682 [
683 'ITEM_STATE' => $iState,
684 '_ADD_GETVARS' => $getVars,
685 '_SAFE' => true
686 ]
687 );
688 }
689 return $menuItems;
690 }
691
692 /**
693 * Fetches all menuitems if special = directory is set
694 *
695 * @param string $specialValue The value from special.value
696 * @param string $sortingField The sorting field
697 * @return array
698 */
699 protected function prepareMenuItemsForDirectoryMenu($specialValue, $sortingField)
700 {
701 $tsfe = $this->getTypoScriptFrontendController();
702 $databaseConnection = $this->getDatabaseConnection();
703 $menuItems = [];
704 if ($specialValue == '') {
705 $specialValue = $tsfe->page['uid'];
706 }
707 $items = GeneralUtility::intExplode(',', $specialValue);
708 foreach ($items as $id) {
709 $MP = $this->tmpl->getFromMPmap($id);
710 // Checking if a page is a mount page and if so, change the ID and set the MP var properly.
711 $mount_info = $this->sys_page->getMountPointInfo($id);
712 if (is_array($mount_info)) {
713 if ($mount_info['overlay']) {
714 // Overlays should already have their full MPvars calculated:
715 $MP = $this->tmpl->getFromMPmap($mount_info['mount_pid']);
716 $MP = $MP ? $MP : $mount_info['MPvar'];
717 } else {
718 $MP = ($MP ? $MP . ',' : '') . $mount_info['MPvar'];
719 }
720 $id = $mount_info['mount_pid'];
721 }
722 // Get sub-pages:
723 $res = $this->parent_cObj->exec_getQuery('pages', ['pidInList' => $id, 'orderBy' => $sortingField]);
724 while ($row = $databaseConnection->sql_fetch_assoc($res)) {
725 $tsfe->sys_page->versionOL('pages', $row, true);
726 if (!empty($row)) {
727 // Keep mount point?
728 $mount_info = $this->sys_page->getMountPointInfo($row['uid'], $row);
729 // There is a valid mount point.
730 if (is_array($mount_info) && $mount_info['overlay']) {
731 // Using "getPage" is OK since we need the check for enableFields
732 // AND for type 2 of mount pids we DO require a doktype < 200!
733 $mp_row = $this->sys_page->getPage($mount_info['mount_pid']);
734 if (!empty($mp_row)) {
735 $row = $mp_row;
736 $row['_MP_PARAM'] = $mount_info['MPvar'];
737 } else {
738 // If the mount point could not be fetched with respect
739 // to enableFields, unset the row so it does not become a part of the menu!
740 unset($row);
741 }
742 }
743 // Add external MP params, then the row:
744 if (!empty($row)) {
745 if ($MP) {
746 $row['_MP_PARAM'] = $MP . ($row['_MP_PARAM'] ? ',' . $row['_MP_PARAM'] : '');
747 }
748 $menuItems[$row['uid']] = $this->sys_page->getPageOverlay($row);
749 }
750 }
751 }
752 $databaseConnection->sql_free_result($res);
753 }
754 return $menuItems;
755 }
756
757 /**
758 * Fetches all menuitems if special = list is set
759 *
760 * @param string $specialValue The value from special.value
761 * @return array
762 */
763 protected function prepareMenuItemsForListMenu($specialValue)
764 {
765 $menuItems = [];
766 if ($specialValue == '') {
767 $specialValue = $this->id;
768 }
769 $skippedEnableFields = [];
770 if (!empty($this->mconf['showAccessRestrictedPages'])) {
771 $skippedEnableFields = ['fe_group' => 1];
772 }
773 /** @var RelationHandler $loadDB*/
774 $loadDB = GeneralUtility::makeInstance(RelationHandler::class);
775 $loadDB->setFetchAllFields(true);
776 $loadDB->start($specialValue, 'pages');
777 $loadDB->additionalWhere['pages'] = $this->parent_cObj->enableFields('pages', false, $skippedEnableFields);
778 $loadDB->getFromDB();
779 foreach ($loadDB->itemArray as $val) {
780 $MP = $this->tmpl->getFromMPmap($val['id']);
781 // Keep mount point?
782 $mount_info = $this->sys_page->getMountPointInfo($val['id']);
783 // There is a valid mount point.
784 if (is_array($mount_info) && $mount_info['overlay']) {
785 // Using "getPage" is OK since we need the check for enableFields
786 // AND for type 2 of mount pids we DO require a doktype < 200!
787 $mp_row = $this->sys_page->getPage($mount_info['mount_pid']);
788 if (!empty($mp_row)) {
789 $row = $mp_row;
790 $row['_MP_PARAM'] = $mount_info['MPvar'];
791 // Overlays should already have their full MPvars calculated
792 if ($mount_info['overlay']) {
793 $MP = $this->tmpl->getFromMPmap($mount_info['mount_pid']);
794 if ($MP) {
795 unset($row['_MP_PARAM']);
796 }
797 }
798 } else {
799 // If the mount point could not be fetched with respect to
800 // enableFields, unset the row so it does not become a part of the menu!
801 unset($row);
802 }
803 } else {
804 $row = $loadDB->results['pages'][$val['id']];
805 }
806 // Add versioning overlay for current page (to respect workspaces)
807 if (isset($row) && is_array($row)) {
808 $this->sys_page->versionOL('pages', $row, true);
809 }
810 // Add external MP params, then the row:
811 if (isset($row) && is_array($row)) {
812 if ($MP) {
813 $row['_MP_PARAM'] = $MP . ($row['_MP_PARAM'] ? ',' . $row['_MP_PARAM'] : '');
814 }
815 $menuItems[] = $this->sys_page->getPageOverlay($row);
816 }
817 }
818 return $menuItems;
819 }
820
821 /**
822 * Fetches all menuitems if special = updated is set
823 *
824 * @param string $specialValue The value from special.value
825 * @param string $sortingField The sorting field
826 * @return array
827 */
828 protected function prepareMenuItemsForUpdatedMenu($specialValue, $sortingField)
829 {
830 $tsfe = $this->getTypoScriptFrontendController();
831 $menuItems = [];
832 if ($specialValue == '') {
833 $specialValue = $tsfe->page['uid'];
834 }
835 $items = GeneralUtility::intExplode(',', $specialValue);
836 if (MathUtility::canBeInterpretedAsInteger($this->conf['special.']['depth'])) {
837 $depth = MathUtility::forceIntegerInRange($this->conf['special.']['depth'], 1, 20);
838 } else {
839 $depth = 20;
840 }
841 // Max number of items
842 $limit = MathUtility::forceIntegerInRange($this->conf['special.']['limit'], 0, 100);
843 $maxAge = (int)$this->parent_cObj->calc($this->conf['special.']['maxAge']);
844 if (!$limit) {
845 $limit = 10;
846 }
847 // *'auto', 'manual', 'tstamp'
848 $mode = $this->conf['special.']['mode'];
849 // Get id's
850 $id_list_arr = [];
851 foreach ($items as $id) {
852 $bA = MathUtility::forceIntegerInRange($this->conf['special.']['beginAtLevel'], 0, 100);
853 $id_list_arr[] = $this->parent_cObj->getTreeList(-1 * $id, $depth - 1 + $bA, $bA - 1);
854 }
855 $id_list = implode(',', $id_list_arr);
856 // Get sortField (mode)
857 switch ($mode) {
858 case 'starttime':
859 $sortField = 'starttime';
860 break;
861 case 'lastUpdated':
862 case 'manual':
863 $sortField = 'lastUpdated';
864 break;
865 case 'tstamp':
866 $sortField = 'tstamp';
867 break;
868 case 'crdate':
869 $sortField = 'crdate';
870 break;
871 default:
872 $sortField = 'SYS_LASTCHANGED';
873 }
874 $extraWhere = ($this->conf['includeNotInMenu'] ? '' : ' AND pages.nav_hide=0') . $this->getDoktypeExcludeWhere();
875 if ($this->conf['special.']['excludeNoSearchPages']) {
876 $extraWhere .= ' AND pages.no_search=0';
877 }
878 if ($maxAge > 0) {
879 $extraWhere .= ' AND ' . $sortField . '>' . ($GLOBALS['SIM_ACCESS_TIME'] - $maxAge);
880 }
881 $res = $this->parent_cObj->exec_getQuery('pages', [
882 'pidInList' => '0',
883 'uidInList' => $id_list,
884 'where' => $sortField . '>=0' . $extraWhere,
885 'orderBy' => $sortingField ?: $sortField . ' DESC',
886 'max' => $limit
887 ]);
888 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
889 $tsfe->sys_page->versionOL('pages', $row, true);
890 if (is_array($row)) {
891 $menuItems[$row['uid']] = $this->sys_page->getPageOverlay($row);
892 }
893 }
894 $this->getDatabaseConnection()->sql_free_result($res);
895 return $menuItems;
896 }
897
898 /**
899 * Fetches all menuitems if special = keywords is set
900 *
901 * @param string $specialValue The value from special.value
902 * @param string $sortingField The sorting field
903 * @return array
904 */
905 protected function prepareMenuItemsForKeywordsMenu($specialValue, $sortingField)
906 {
907 $tsfe = $this->getTypoScriptFrontendController();
908 $menuItems = [];
909 list($specialValue) = GeneralUtility::intExplode(',', $specialValue);
910 if (!$specialValue) {
911 $specialValue = $tsfe->page['uid'];
912 }
913 if ($this->conf['special.']['setKeywords'] || $this->conf['special.']['setKeywords.']) {
914 $kw = isset($this->conf['special.']['setKeywords.']) ? $this->parent_cObj->stdWrap($this->conf['special.']['setKeywords'], $this->conf['special.']['setKeywords.']) : $this->conf['special.']['setKeywords'];
915 } else {
916 // The page record of the 'value'.
917 $value_rec = $this->sys_page->getPage($specialValue);
918 $kfieldSrc = $this->conf['special.']['keywordsField.']['sourceField'] ? $this->conf['special.']['keywordsField.']['sourceField'] : 'keywords';
919 // keywords.
920 $kw = trim($this->parent_cObj->keywords($value_rec[$kfieldSrc]));
921 }
922 // *'auto', 'manual', 'tstamp'
923 $mode = $this->conf['special.']['mode'];
924 switch ($mode) {
925 case 'starttime':
926 $sortField = 'starttime';
927 break;
928 case 'lastUpdated':
929 case 'manual':
930 $sortField = 'lastUpdated';
931 break;
932 case 'tstamp':
933 $sortField = 'tstamp';
934 break;
935 case 'crdate':
936 $sortField = 'crdate';
937 break;
938 default:
939 $sortField = 'SYS_LASTCHANGED';
940 }
941 // Depth, limit, extra where
942 if (MathUtility::canBeInterpretedAsInteger($this->conf['special.']['depth'])) {
943 $depth = MathUtility::forceIntegerInRange($this->conf['special.']['depth'], 0, 20);
944 } else {
945 $depth = 20;
946 }
947 // Max number of items
948 $limit = MathUtility::forceIntegerInRange($this->conf['special.']['limit'], 0, 100);
949 $extraWhere = ' AND pages.uid<>' . $specialValue . ($this->conf['includeNotInMenu'] ? '' : ' AND pages.nav_hide=0') . $this->getDoktypeExcludeWhere();
950 if ($this->conf['special.']['excludeNoSearchPages']) {
951 $extraWhere .= ' AND pages.no_search=0';
952 }
953 // Start point
954 $eLevel = $this->parent_cObj->getKey(isset($this->conf['special.']['entryLevel.'])
955 ? $this->parent_cObj->stdWrap($this->conf['special.']['entryLevel'], $this->conf['special.']['entryLevel.'])
956 : $this->conf['special.']['entryLevel'], $this->tmpl->rootLine
957 );
958 $startUid = (int)$this->tmpl->rootLine[$eLevel]['uid'];
959 // Which field is for keywords
960 $kfield = 'keywords';
961 if ($this->conf['special.']['keywordsField']) {
962 list($kfield) = explode(' ', trim($this->conf['special.']['keywordsField']));
963 }
964 // If there are keywords and the startuid is present
965 if ($kw && $startUid) {
966 $bA = MathUtility::forceIntegerInRange($this->conf['special.']['beginAtLevel'], 0, 100);
967 $id_list = $this->parent_cObj->getTreeList(-1 * $startUid, $depth - 1 + $bA, $bA - 1);
968 $kwArr = explode(',', $kw);
969 $keyWordsWhereArr = [];
970 foreach ($kwArr as $word) {
971 $word = trim($word);
972 if ($word) {
973 $keyWordsWhereArr[] = $kfield . ' LIKE \'%' . $this->getDatabaseConnection()->quoteStr($word, 'pages') . '%\'';
974 }
975 }
976 $where = empty($keyWordsWhereArr) ? '' : '(' . implode(' OR ', $keyWordsWhereArr) . ')';
977 $res = $this->parent_cObj->exec_getQuery('pages', [
978 'pidInList' => '0',
979 'uidInList' => $id_list,
980 'where' => $where . $extraWhere,
981 'orderBy' => $sortingField ?: $sortField . ' desc',
982 'max' => $limit
983 ]);
984 while (($row = $this->getDatabaseConnection()->sql_fetch_assoc($res))) {
985 $tsfe->sys_page->versionOL('pages', $row, true);
986 if (is_array($row)) {
987 $menuItems[$row['uid']] = $this->sys_page->getPageOverlay($row);
988 }
989 }
990 $this->getDatabaseConnection()->sql_free_result($res);
991 }
992 return $menuItems;
993 }
994
995 /**
996 * Fetches all menuitems if special = rootline is set
997 *
998 * @return array
999 */
1000 protected function prepareMenuItemsForRootlineMenu()
1001 {
1002 $menuItems = [];
1003 $range = isset($this->conf['special.']['range.'])
1004 ? $this->parent_cObj->stdWrap($this->conf['special.']['range'], $this->conf['special.']['range.'])
1005 : $this->conf['special.']['range'];
1006 $begin_end = explode('|', $range);
1007 $begin_end[0] = (int)$begin_end[0];
1008 if (!MathUtility::canBeInterpretedAsInteger($begin_end[1])) {
1009 $begin_end[1] = -1;
1010 }
1011 $beginKey = $this->parent_cObj->getKey($begin_end[0], $this->tmpl->rootLine);
1012 $endKey = $this->parent_cObj->getKey($begin_end[1], $this->tmpl->rootLine);
1013 if ($endKey < $beginKey) {
1014 $endKey = $beginKey;
1015 }
1016 $rl_MParray = [];
1017 foreach ($this->tmpl->rootLine as $k_rl => $v_rl) {
1018 // For overlaid mount points, set the variable right now:
1019 if ($v_rl['_MP_PARAM'] && $v_rl['_MOUNT_OL']) {
1020 $rl_MParray[] = $v_rl['_MP_PARAM'];
1021 }
1022 // Traverse rootline:
1023 if ($k_rl >= $beginKey && $k_rl <= $endKey) {
1024 $temp_key = $k_rl;
1025 $menuItems[$temp_key] = $this->sys_page->getPage($v_rl['uid']);
1026 if (!empty($menuItems[$temp_key])) {
1027 // If there are no specific target for the page, put the level specific target on.
1028 if (!$menuItems[$temp_key]['target']) {
1029 $menuItems[$temp_key]['target'] = $this->conf['special.']['targets.'][$k_rl];
1030 $menuItems[$temp_key]['_MP_PARAM'] = implode(',', $rl_MParray);
1031 }
1032 } else {
1033 unset($menuItems[$temp_key]);
1034 }
1035 }
1036 // For normal mount points, set the variable for next level.
1037 if ($v_rl['_MP_PARAM'] && !$v_rl['_MOUNT_OL']) {
1038 $rl_MParray[] = $v_rl['_MP_PARAM'];
1039 }
1040 }
1041 // Reverse order of elements (e.g. "1,2,3,4" gets "4,3,2,1"):
1042 if (isset($this->conf['special.']['reverseOrder']) && $this->conf['special.']['reverseOrder']) {
1043 $menuItems = array_reverse($menuItems);
1044 }
1045 return $menuItems;
1046 }
1047
1048 /**
1049 * Fetches all menuitems if special = browse is set
1050 *
1051 * @param string $specialValue The value from special.value
1052 * @param string $sortingField The sorting field
1053 * @param string $additionalWhere Additional WHERE clause
1054 * @return array
1055 */
1056 protected function prepareMenuItemsForBrowseMenu($specialValue, $sortingField, $additionalWhere)
1057 {
1058 $menuItems = [];
1059 list($specialValue) = GeneralUtility::intExplode(',', $specialValue);
1060 if (!$specialValue) {
1061 $specialValue = $this->getTypoScriptFrontendController()->page['uid'];
1062 }
1063 // Will not work out of rootline
1064 if ($specialValue != $this->tmpl->rootLine[0]['uid']) {
1065 $recArr = [];
1066 // The page record of the 'value'.
1067 $value_rec = $this->sys_page->getPage($specialValue);
1068 // 'up' page cannot be outside rootline
1069 if ($value_rec['pid']) {
1070 // The page record of 'up'.
1071 $recArr['up'] = $this->sys_page->getPage($value_rec['pid']);
1072 }
1073 // If the 'up' item was NOT level 0 in rootline...
1074 if ($recArr['up']['pid'] && $value_rec['pid'] != $this->tmpl->rootLine[0]['uid']) {
1075 // The page record of "index".
1076 $recArr['index'] = $this->sys_page->getPage($recArr['up']['pid']);
1077 }
1078 // check if certain pages should be excluded
1079 $additionalWhere .= ($this->conf['includeNotInMenu'] ? '' : ' AND pages.nav_hide=0') . $this->getDoktypeExcludeWhere();
1080 if ($this->conf['special.']['excludeNoSearchPages']) {
1081 $additionalWhere .= ' AND pages.no_search=0';
1082 }
1083 // prev / next is found
1084 $prevnext_menu = $this->removeInaccessiblePages($this->sys_page->getMenu($value_rec['pid'], '*', $sortingField, $additionalWhere));
1085 $lastKey = 0;
1086 $nextActive = 0;
1087 foreach ($prevnext_menu as $k_b => $v_b) {
1088 if ($nextActive) {
1089 $recArr['next'] = $v_b;
1090 $nextActive = 0;
1091 }
1092 if ($v_b['uid'] == $specialValue) {
1093 if ($lastKey) {
1094 $recArr['prev'] = $prevnext_menu[$lastKey];
1095 }
1096 $nextActive = 1;
1097 }
1098 $lastKey = $k_b;
1099 }
1100
1101 $recArr['first'] = reset($prevnext_menu);
1102 $recArr['last'] = end($prevnext_menu);
1103 // prevsection / nextsection is found
1104 // You can only do this, if there is a valid page two levels up!
1105 if (!empty($recArr['index']['uid'])) {
1106 $prevnextsection_menu = $this->removeInaccessiblePages($this->sys_page->getMenu($recArr['index']['uid'], '*', $sortingField, $additionalWhere));
1107 $lastKey = 0;
1108 $nextActive = 0;
1109 foreach ($prevnextsection_menu as $k_b => $v_b) {
1110 if ($nextActive) {
1111 $sectionRec_temp = $this->removeInaccessiblePages($this->sys_page->getMenu($v_b['uid'], '*', $sortingField, $additionalWhere));
1112 if (!empty($sectionRec_temp)) {
1113 $recArr['nextsection'] = reset($sectionRec_temp);
1114 $recArr['nextsection_last'] = end($sectionRec_temp);
1115 $nextActive = 0;
1116 }
1117 }
1118 if ($v_b['uid'] == $value_rec['pid']) {
1119 if ($lastKey) {
1120 $sectionRec_temp = $this->removeInaccessiblePages($this->sys_page->getMenu($prevnextsection_menu[$lastKey]['uid'], '*', $sortingField, $additionalWhere));
1121 if (!empty($sectionRec_temp)) {
1122 $recArr['prevsection'] = reset($sectionRec_temp);
1123 $recArr['prevsection_last'] = end($sectionRec_temp);
1124 }
1125 }
1126 $nextActive = 1;
1127 }
1128 $lastKey = $k_b;
1129 }
1130 }
1131 if ($this->conf['special.']['items.']['prevnextToSection']) {
1132 if (!is_array($recArr['prev']) && is_array($recArr['prevsection_last'])) {
1133 $recArr['prev'] = $recArr['prevsection_last'];
1134 }
1135 if (!is_array($recArr['next']) && is_array($recArr['nextsection'])) {
1136 $recArr['next'] = $recArr['nextsection'];
1137 }
1138 }
1139 $items = explode('|', $this->conf['special.']['items']);
1140 $c = 0;
1141 foreach ($items as $k_b => $v_b) {
1142 $v_b = strtolower(trim($v_b));
1143 if ((int)$this->conf['special.'][$v_b . '.']['uid']) {
1144 $recArr[$v_b] = $this->sys_page->getPage((int)$this->conf['special.'][$v_b . '.']['uid']);
1145 }
1146 if (is_array($recArr[$v_b])) {
1147 $menuItems[$c] = $recArr[$v_b];
1148 if ($this->conf['special.'][$v_b . '.']['target']) {
1149 $menuItems[$c]['target'] = $this->conf['special.'][$v_b . '.']['target'];
1150 }
1151 $tmpSpecialFields = $this->conf['special.'][$v_b . '.']['fields.'];
1152 if (is_array($tmpSpecialFields)) {
1153 foreach ($tmpSpecialFields as $fk => $val) {
1154 $menuItems[$c][$fk] = $val;
1155 }
1156 }
1157 $c++;
1158 }
1159 }
1160 }
1161 return $menuItems;
1162 }
1163
1164 /**
1165 * Analyzes the parameters to find if the link needs a cHash parameter.
1166 *
1167 * @param string $queryString
1168 * @return void
1169 */
1170 protected function analyzeCacheHashRequirements($queryString)
1171 {
1172 $parameters = GeneralUtility::explodeUrl2Array($queryString);
1173 if (!empty($parameters)) {
1174 if (!isset($parameters['id'])) {
1175 $queryString .= '&id=' . $this->getTypoScriptFrontendController()->id;
1176 }
1177 /** @var CacheHashCalculator $cacheHashCalculator */
1178 $cacheHashCalculator = GeneralUtility::makeInstance(CacheHashCalculator::class);
1179 $cHashParameters = $cacheHashCalculator->getRelevantParameters($queryString);
1180 if (count($cHashParameters) > 1) {
1181 $this->useCacheHash = (
1182 $GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter'] ||
1183 !isset($parameters['no_cache']) ||
1184 !$parameters['no_cache']
1185 );
1186 }
1187 }
1188 }
1189
1190 /**
1191 * Checks if a page is OK to include in the final menu item array. Pages can be excluded if the doktype is wrong,
1192 * if they are hidden in navigation, have a uid in the list of banned uids etc.
1193 *
1194 * @param array $data Array of menu items
1195 * @param array $banUidArray Array of page uids which are to be excluded
1196 * @param bool $spacer If set, then the page is a spacer.
1197 * @return bool Returns TRUE if the page can be safely included.
1198 *
1199 * @throws \UnexpectedValueException
1200 */
1201 public function filterMenuPages(&$data, $banUidArray, $spacer)
1202 {
1203 $includePage = true;
1204 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/tslib/class.tslib_menu.php']['filterMenuPages'])) {
1205 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/tslib/class.tslib_menu.php']['filterMenuPages'] as $classRef) {
1206 $hookObject = GeneralUtility::getUserObj($classRef);
1207 if (!$hookObject instanceof AbstractMenuFilterPagesHookInterface) {
1208 throw new \UnexpectedValueException($classRef . ' must implement interface ' . AbstractMenuFilterPagesHookInterface::class, 1269877402);
1209 }
1210 $includePage = $includePage && $hookObject->processFilter($data, $banUidArray, $spacer, $this);
1211 }
1212 }
1213 if (!$includePage) {
1214 return false;
1215 }
1216 if ($data['_SAFE']) {
1217 return true;
1218 }
1219
1220 if (
1221 ($this->mconf['SPC'] || !$spacer) // If the spacer-function is not enabled, spacers will not enter the $menuArr
1222 && (!$data['nav_hide'] || $this->conf['includeNotInMenu']) // Not hidden in navigation
1223 && !GeneralUtility::inList($this->doktypeExcludeList, $data['doktype']) // Page may not be 'not_in_menu' or 'Backend User Section'
1224 && !ArrayUtility::inArray($banUidArray, $data['uid']) // not in banned uid's
1225 ) {
1226 // Checks if the default language version can be shown:
1227 // Block page is set, if l18n_cfg allows plus: 1) Either default language or 2) another language but NO overlay record set for page!
1228 $tsfe = $this->getTypoScriptFrontendController();
1229 $blockPage = GeneralUtility::hideIfDefaultLanguage($data['l18n_cfg']) && (!$tsfe->sys_language_uid || $tsfe->sys_language_uid && !$data['_PAGES_OVERLAY']);
1230 if (!$blockPage) {
1231 // Checking if a page should be shown in the menu depending on whether a translation exists:
1232 $tok = true;
1233 // There is an alternative language active AND the current page requires a translation:
1234 if ($tsfe->sys_language_uid && GeneralUtility::hideIfNotTranslated($data['l18n_cfg'])) {
1235 if (!$data['_PAGES_OVERLAY']) {
1236 $tok = false;
1237 }
1238 }
1239 // Continue if token is TRUE:
1240 if ($tok) {
1241 // Checking if "&L" should be modified so links to non-accessible pages will not happen.
1242 if ($this->conf['protectLvar']) {
1243 $languageUid = (int)$tsfe->config['config']['sys_language_uid'];
1244 if ($languageUid && ($this->conf['protectLvar'] == 'all' || GeneralUtility::hideIfNotTranslated($data['l18n_cfg']))) {
1245 $olRec = $tsfe->sys_page->getPageOverlay($data['uid'], $languageUid);
1246 if (empty($olRec)) {
1247 // If no pages_language_overlay record then page can NOT be accessed in
1248 // the language pointed to by "&L" and therefore we protect the link by setting "&L=0"
1249 $data['_ADD_GETVARS'] .= '&L=0';
1250 }
1251 }
1252 }
1253 return true;
1254 }
1255 }
1256 }
1257 return false;
1258 }
1259
1260 /**
1261 * Generating the per-menu-item configuration arrays based on the settings for item states (NO, RO, ACT, CUR etc)
1262 * set in ->mconf (config for the current menu object)
1263 * Basically it will produce an individual array for each menu item based on the item states.
1264 * BUT in addition the "optionSplit" syntax for the values is ALSO evaluated here so that all property-values
1265 * are "option-splitted" and the output will thus be resolved.
1266 * Is called from the "generate" functions in the extension classes. The function is processor intensive due to
1267 * the option split feature in particular. But since the generate function is not always called
1268 * (since the ->result array may be cached, see makeMenu) it doesn't hurt so badly.
1269 *
1270 * @param int $splitCount Number of menu items in the menu
1271 * @return array An array with two keys: array($NOconf,$ROconf) - where $NOconf contains the resolved configuration for each item when NOT rolled-over and $ROconf contains the ditto for the mouseover state (if any)
1272 *
1273 * @internal
1274 */
1275 public function procesItemStates($splitCount)
1276 {
1277 // Prepare normal settings
1278 if (!is_array($this->mconf['NO.']) && $this->mconf['NO']) {
1279 // Setting a blank array if NO=1 and there are no properties.
1280 $this->mconf['NO.'] = [];
1281 }
1282 $NOconf = $this->tmpl->splitConfArray($this->mconf['NO.'], $splitCount);
1283 // Prepare rollOver settings, overriding normal settings
1284 $ROconf = [];
1285 if ($this->mconf['RO']) {
1286 $ROconf = $this->tmpl->splitConfArray($this->mconf['RO.'], $splitCount);
1287 }
1288 // Prepare IFSUB settings, overriding normal settings
1289 // IFSUB is TRUE if there exist submenu items to the current item
1290 if (!empty($this->mconf['IFSUB'])) {
1291 $IFSUBconf = null;
1292 $IFSUBROconf = null;
1293 foreach ($NOconf as $key => $val) {
1294 if ($this->isItemState('IFSUB', $key)) {
1295 // if this is the first IFSUB element, we must generate IFSUB.
1296 if ($IFSUBconf === null) {
1297 $IFSUBconf = $this->tmpl->splitConfArray($this->mconf['IFSUB.'], $splitCount);
1298 if (!empty($this->mconf['IFSUBRO'])) {
1299 $IFSUBROconf = $this->tmpl->splitConfArray($this->mconf['IFSUBRO.'], $splitCount);
1300 }
1301 }
1302 // Substitute normal with ifsub
1303 if (isset($IFSUBconf[$key])) {
1304 $NOconf[$key] = $IFSUBconf[$key];
1305 }
1306 // If rollOver on normal, we must apply a state for rollOver on the active
1307 if ($ROconf) {
1308 // If RollOver on active then apply this
1309 $ROconf[$key] = !empty($IFSUBROconf[$key]) ? $IFSUBROconf[$key] : $IFSUBconf[$key];
1310 }
1311 }
1312 }
1313 }
1314 // Prepare active settings, overriding normal settings
1315 if (!empty($this->mconf['ACT'])) {
1316 $ACTconf = null;
1317 $ACTROconf = null;
1318 // Find active
1319 foreach ($NOconf as $key => $val) {
1320 if ($this->isItemState('ACT', $key)) {
1321 // If this is the first 'active', we must generate ACT.
1322 if ($ACTconf === null) {
1323 $ACTconf = $this->tmpl->splitConfArray($this->mconf['ACT.'], $splitCount);
1324 // Prepare active rollOver settings, overriding normal active settings
1325 if (!empty($this->mconf['ACTRO'])) {
1326 $ACTROconf = $this->tmpl->splitConfArray($this->mconf['ACTRO.'], $splitCount);
1327 }
1328 }
1329 // Substitute normal with active
1330 if (isset($ACTconf[$key])) {
1331 $NOconf[$key] = $ACTconf[$key];
1332 }
1333 // If rollOver on normal, we must apply a state for rollOver on the active
1334 if ($ROconf) {
1335 // If RollOver on active then apply this
1336 $ROconf[$key] = !empty($ACTROconf[$key]) ? $ACTROconf[$key] : $ACTconf[$key];
1337 }
1338 }
1339 }
1340 }
1341 // Prepare ACT (active)/IFSUB settings, overriding normal settings
1342 // ACTIFSUB is TRUE if there exist submenu items to the current item and the current item is active
1343 if (!empty($this->mconf['ACTIFSUB'])) {
1344 $ACTIFSUBconf = null;
1345 $ACTIFSUBROconf = null;
1346 // Find active
1347 foreach ($NOconf as $key => $val) {
1348 if ($this->isItemState('ACTIFSUB', $key)) {
1349 // If this is the first 'active', we must generate ACTIFSUB.
1350 if ($ACTIFSUBconf === null) {
1351 $ACTIFSUBconf = $this->tmpl->splitConfArray($this->mconf['ACTIFSUB.'], $splitCount);
1352 // Prepare active rollOver settings, overriding normal active settings
1353 if (!empty($this->mconf['ACTIFSUBRO'])) {
1354 $ACTIFSUBROconf = $this->tmpl->splitConfArray($this->mconf['ACTIFSUBRO.'], $splitCount);
1355 }
1356 }
1357 // Substitute normal with active
1358 if (isset($ACTIFSUBconf[$key])) {
1359 $NOconf[$key] = $ACTIFSUBconf[$key];
1360 }
1361 // If rollOver on normal, we must apply a state for rollOver on the active
1362 if ($ROconf) {
1363 // If RollOver on active then apply this
1364 $ROconf[$key] = !empty($ACTIFSUBROconf[$key]) ? $ACTIFSUBROconf[$key] : $ACTIFSUBconf[$key];
1365 }
1366 }
1367 }
1368 }
1369 // Prepare CUR (current) settings, overriding normal settings
1370 // CUR is TRUE if the current page equals the item here!
1371 if (!empty($this->mconf['CUR'])) {
1372 $CURconf = null;
1373 $CURROconf = null;
1374 foreach ($NOconf as $key => $val) {
1375 if ($this->isItemState('CUR', $key)) {
1376 // if this is the first 'current', we must generate CUR. Basically this control is just inherited
1377 // from the other implementations as current would only exist one time and that's it
1378 // (unless you use special-features of HMENU)
1379 if ($CURconf === null) {
1380 $CURconf = $this->tmpl->splitConfArray($this->mconf['CUR.'], $splitCount);
1381 if (!empty($this->mconf['CURRO'])) {
1382 $CURROconf = $this->tmpl->splitConfArray($this->mconf['CURRO.'], $splitCount);
1383 }
1384 }
1385 // Substitute normal with current
1386 if (isset($CURconf[$key])) {
1387 $NOconf[$key] = $CURconf[$key];
1388 }
1389 // If rollOver on normal, we must apply a state for rollOver on the active
1390 if ($ROconf) {
1391 // If RollOver on active then apply this
1392 $ROconf[$key] = !empty($CURROconf[$key]) ? $CURROconf[$key] : $CURconf[$key];
1393 }
1394 }
1395 }
1396 }
1397 // Prepare CUR (current)/IFSUB settings, overriding normal settings
1398 // CURIFSUB is TRUE if there exist submenu items to the current item and the current page equals the item here!
1399 if (!empty($this->mconf['CURIFSUB'])) {
1400 $CURIFSUBconf = null;
1401 $CURIFSUBROconf = null;
1402 foreach ($NOconf as $key => $val) {
1403 if ($this->isItemState('CURIFSUB', $key)) {
1404 // If this is the first 'current', we must generate CURIFSUB.
1405 if ($CURIFSUBconf === null) {
1406 $CURIFSUBconf = $this->tmpl->splitConfArray($this->mconf['CURIFSUB.'], $splitCount);
1407 // Prepare current rollOver settings, overriding normal current settings
1408 if (!empty($this->mconf['CURIFSUBRO'])) {
1409 $CURIFSUBROconf = $this->tmpl->splitConfArray($this->mconf['CURIFSUBRO.'], $splitCount);
1410 }
1411 }
1412 // Substitute normal with active
1413 if ($CURIFSUBconf[$key]) {
1414 $NOconf[$key] = $CURIFSUBconf[$key];
1415 }
1416 // If rollOver on normal, we must apply a state for rollOver on the current
1417 if ($ROconf) {
1418 // If RollOver on current then apply this
1419 $ROconf[$key] = !empty($CURIFSUBROconf[$key]) ? $CURIFSUBROconf[$key] : $CURIFSUBconf[$key];
1420 }
1421 }
1422 }
1423 }
1424 // Prepare active settings, overriding normal settings
1425 if (!empty($this->mconf['USR'])) {
1426 $USRconf = null;
1427 $USRROconf = null;
1428 // Find active
1429 foreach ($NOconf as $key => $val) {
1430 if ($this->isItemState('USR', $key)) {
1431 // if this is the first active, we must generate USR.
1432 if ($USRconf === null) {
1433 $USRconf = $this->tmpl->splitConfArray($this->mconf['USR.'], $splitCount);
1434 // Prepare active rollOver settings, overriding normal active settings
1435 if (!empty($this->mconf['USRRO'])) {
1436 $USRROconf = $this->tmpl->splitConfArray($this->mconf['USRRO.'], $splitCount);
1437 }
1438 }
1439 // Substitute normal with active
1440 if ($USRconf[$key]) {
1441 $NOconf[$key] = $USRconf[$key];
1442 }
1443 // If rollOver on normal, we must apply a state for rollOver on the active
1444 if ($ROconf) {
1445 // If RollOver on active then apply this
1446 $ROconf[$key] = !empty($USRROconf[$key]) ? $USRROconf[$key] : $USRconf[$key];
1447 }
1448 }
1449 }
1450 }
1451 // Prepare spacer settings, overriding normal settings
1452 if (!empty($this->mconf['SPC'])) {
1453 $SPCconf = null;
1454 // Find spacers
1455 foreach ($NOconf as $key => $val) {
1456 if ($this->isItemState('SPC', $key)) {
1457 // If this is the first spacer, we must generate SPC.
1458 if ($SPCconf === null) {
1459 $SPCconf = $this->tmpl->splitConfArray($this->mconf['SPC.'], $splitCount);
1460 }
1461 // Substitute normal with spacer
1462 if (isset($SPCconf[$key])) {
1463 $NOconf[$key] = $SPCconf[$key];
1464 }
1465 }
1466 }
1467 }
1468 // Prepare Userdefined settings
1469 if (!empty($this->mconf['USERDEF1'])) {
1470 $USERDEF1conf = null;
1471 $USERDEF1ROconf = null;
1472 // Find active
1473 foreach ($NOconf as $key => $val) {
1474 if ($this->isItemState('USERDEF1', $key)) {
1475 // If this is the first active, we must generate USERDEF1.
1476 if ($USERDEF1conf === null) {
1477 $USERDEF1conf = $this->tmpl->splitConfArray($this->mconf['USERDEF1.'], $splitCount);
1478 // Prepare active rollOver settings, overriding normal active settings
1479 if (!empty($this->mconf['USERDEF1RO'])) {
1480 $USERDEF1ROconf = $this->tmpl->splitConfArray($this->mconf['USERDEF1RO.'], $splitCount);
1481 }
1482 }
1483 // Substitute normal with active
1484 if (isset($USERDEF1conf[$key])) {
1485 $NOconf[$key] = $USERDEF1conf[$key];
1486 }
1487 // If rollOver on normal, we must apply a state for rollOver on the active
1488 if ($ROconf) {
1489 // If RollOver on active then apply this
1490 $ROconf[$key] = !empty($USERDEF1ROconf[$key]) ? $USERDEF1ROconf[$key] : $USERDEF1conf[$key];
1491 }
1492 }
1493 }
1494 }
1495 // Prepare Userdefined settings
1496 if (!empty($this->mconf['USERDEF2'])) {
1497 $USERDEF2conf = null;
1498 $USERDEF2ROconf = null;
1499 // Find active
1500 foreach ($NOconf as $key => $val) {
1501 if ($this->isItemState('USERDEF2', $key)) {
1502 // If this is the first active, we must generate USERDEF2.
1503 if ($USERDEF2conf === null) {
1504 $USERDEF2conf = $this->tmpl->splitConfArray($this->mconf['USERDEF2.'], $splitCount);
1505 // Prepare active rollOver settings, overriding normal active settings
1506 if (!empty($this->mconf['USERDEF2RO'])) {
1507 $USERDEF2ROconf = $this->tmpl->splitConfArray($this->mconf['USERDEF2RO.'], $splitCount);
1508 }
1509 }
1510 // Substitute normal with active
1511 if (isset($USERDEF2conf[$key])) {
1512 $NOconf[$key] = $USERDEF2conf[$key];
1513 }
1514 // If rollOver on normal, we must apply a state for rollOver on the active
1515 if ($ROconf) {
1516 // If RollOver on active then apply this
1517 $ROconf[$key] = !empty($USERDEF2ROconf[$key]) ? $USERDEF2ROconf[$key] : $USERDEF2conf[$key];
1518 }
1519 }
1520 }
1521 }
1522 return [$NOconf, $ROconf];
1523 }
1524
1525 /**
1526 * Creates the URL, target and onclick values for the menu item link. Returns them in an array as key/value pairs for <A>-tag attributes
1527 * This function doesn't care about the url, because if we let the url be redirected, it will be logged in the stat!!!
1528 *
1529 * @param int $key Pointer to a key in the $this->menuArr array where the value for that key represents the menu item we are linking to (page record)
1530 * @param string $altTarget Alternative target
1531 * @param string $typeOverride Alternative type
1532 * @return array Returns an array with A-tag attributes as key/value pairs (HREF, TARGET and onClick)
1533 * @internal
1534 */
1535 public function link($key, $altTarget = '', $typeOverride = '')
1536 {
1537 // Mount points:
1538 $MP_var = $this->getMPvar($key);
1539 $MP_params = $MP_var ? '&MP=' . rawurlencode($MP_var) : '';
1540 // Setting override ID
1541 if ($this->mconf['overrideId'] || $this->menuArr[$key]['overrideId']) {
1542 $overrideArray = [];
1543 // If a user script returned the value overrideId in the menu array we use that as page id
1544 $overrideArray['uid'] = $this->mconf['overrideId'] ?: $this->menuArr[$key]['overrideId'];
1545 $overrideArray['alias'] = '';
1546 // Clear MP parameters since ID was changed.
1547 $MP_params = '';
1548 } else {
1549 $overrideArray = '';
1550 }
1551 // Setting main target:
1552 if ($altTarget) {
1553 $mainTarget = $altTarget;
1554 } elseif ($this->mconf['target.']) {
1555 $mainTarget = $this->parent_cObj->stdWrap($this->mconf['target'], $this->mconf['target.']);
1556 } else {
1557 $mainTarget = $this->mconf['target'];
1558 }
1559 // Creating link:
1560 $addParams = $this->mconf['addParams'] . $MP_params;
1561 if ($this->mconf['collapse'] && $this->isActive($this->menuArr[$key]['uid'], $this->getMPvar($key))) {
1562 $thePage = $this->sys_page->getPage($this->menuArr[$key]['pid']);
1563 $addParams .= $this->menuArr[$key]['_ADD_GETVARS'];
1564 $LD = $this->menuTypoLink($thePage, $mainTarget, '', '', $overrideArray, $addParams, $typeOverride);
1565 } else {
1566 $addParams .= $this->I['val']['additionalParams'] . $this->menuArr[$key]['_ADD_GETVARS'];
1567 $LD = $this->menuTypoLink($this->menuArr[$key], $mainTarget, '', '', $overrideArray, $addParams, $typeOverride);
1568 }
1569 // Override URL if using "External URL"
1570 if ($this->menuArr[$key]['doktype'] == PageRepository::DOKTYPE_LINK) {
1571 if ($this->menuArr[$key]['urltype'] == 3 && GeneralUtility::validEmail($this->menuArr[$key]['url'])) {
1572 // Create mailto-link using \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typolink (concerning spamProtectEmailAddresses):
1573 $LD['totalURL'] = $this->parent_cObj->typoLink_URL(['parameter' => $this->menuArr[$key]['url']]);
1574 $LD['target'] = '';
1575 } else {
1576 $LD['totalURL'] = $this->parent_cObj->typoLink_URL(['parameter' => $this->getSysPage()->getExtURL($this->menuArr[$key])]);
1577 }
1578 }
1579
1580 $tsfe = $this->getTypoScriptFrontendController();
1581
1582 // Override url if current page is a shortcut
1583 $shortcut = null;
1584 if ($this->menuArr[$key]['doktype'] == PageRepository::DOKTYPE_SHORTCUT && $this->menuArr[$key]['shortcut_mode'] != PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE) {
1585 $menuItem = $this->determineOriginalShortcutPage($this->menuArr[$key]);
1586 try {
1587 $shortcut = $tsfe->getPageShortcut(
1588 $menuItem['shortcut'],
1589 $menuItem['shortcut_mode'],
1590 $menuItem['uid'],
1591 20,
1592 [],
1593 true
1594 );
1595 } catch (\Exception $ex) {
1596 }
1597 if (!is_array($shortcut)) {
1598 return [];
1599 }
1600 // Only setting url, not target
1601 $LD['totalURL'] = $this->parent_cObj->typoLink_URL([
1602 'parameter' => $shortcut['uid'],
1603 'additionalParams' => $addParams . $this->I['val']['additionalParams'] . $menuItem['_ADD_GETVARS'],
1604 'linkAccessRestrictedPages' => $this->mconf['showAccessRestrictedPages'] && $this->mconf['showAccessRestrictedPages'] !== 'NONE'
1605 ]);
1606 }
1607 if ($shortcut) {
1608 $pageData = $shortcut;
1609 $pageData['_SHORTCUT_PAGE_UID'] = $this->menuArr[$key]['uid'];
1610 } else {
1611 $pageData = $this->menuArr[$key];
1612 }
1613 // Manipulation in case of access restricted pages:
1614 $this->changeLinksForAccessRestrictedPages($LD, $pageData, $mainTarget, $typeOverride);
1615 // Overriding URL / Target if set to do so:
1616 if ($this->menuArr[$key]['_OVERRIDE_HREF']) {
1617 $LD['totalURL'] = $this->menuArr[$key]['_OVERRIDE_HREF'];
1618 if ($this->menuArr[$key]['_OVERRIDE_TARGET']) {
1619 $LD['target'] = $this->menuArr[$key]['_OVERRIDE_TARGET'];
1620 }
1621 }
1622 // OnClick open in windows.
1623 $onClick = '';
1624 if ($this->mconf['JSWindow']) {
1625 $conf = $this->mconf['JSWindow.'];
1626 $url = $LD['totalURL'];
1627 $LD['totalURL'] = '#';
1628 $onClick = 'openPic('
1629 . GeneralUtility::quoteJSvalue($tsfe->baseUrlWrap($url)) . ','
1630 . '\'' . ($conf['newWindow'] ? md5($url) : 'theNewPage') . '\','
1631 . GeneralUtility::quoteJSvalue($conf['params']) . '); return false;';
1632 $tsfe->setJS('openPic');
1633 }
1634 // look for type and popup
1635 // following settings are valid in field target:
1636 // 230 will add type=230 to the link
1637 // 230 500x600 will add type=230 to the link and open in popup window with 500x600 pixels
1638 // 230 _blank will add type=230 to the link and open with target "_blank"
1639 // 230x450:resizable=0,location=1 will open in popup window with 500x600 pixels with settings "resizable=0,location=1"
1640 $matches = [];
1641 $targetIsType = $LD['target'] && MathUtility::canBeInterpretedAsInteger($LD['target']) ? (int)$LD['target'] : false;
1642 if (preg_match('/([0-9]+[\\s])?(([0-9]+)x([0-9]+))?(:.+)?/s', $LD['target'], $matches) || $targetIsType) {
1643 // has type?
1644 if ((int)$matches[1] || $targetIsType) {
1645 $LD['totalURL'] = $this->parent_cObj->URLqMark($LD['totalURL'], '&type=' . ($targetIsType ?: (int)$matches[1]));
1646 $LD['target'] = $targetIsType ? '' : trim(substr($LD['target'], strlen($matches[1]) + 1));
1647 }
1648 // Open in popup window?
1649 if ($matches[3] && $matches[4]) {
1650 $JSparamWH = 'width=' . $matches[3] . ',height=' . $matches[4] . ($matches[5] ? ',' . substr($matches[5], 1) : '');
1651 $onClick = 'vHWin=window.open('
1652 . GeneralUtility::quoteJSvalue($tsfe->baseUrlWrap($LD['totalURL']))
1653 . ',\'FEopenLink\',' . GeneralUtility::quoteJSvalue($JSparamWH) . ');vHWin.focus();return false;';
1654 $LD['target'] = '';
1655 }
1656 }
1657 // out:
1658 $list = [];
1659 // Added this check: What it does is to enter the baseUrl (if set, which it should for "realurl" based sites)
1660 // as URL if the calculated value is empty. The problem is that no link is generated with a blank URL
1661 // and blank URLs might appear when the realurl encoding is used and a link to the frontpage is generated.
1662 $list['HREF'] = (string)$LD['totalURL'] !== '' ? $LD['totalURL'] : $tsfe->baseUrl;
1663 $list['TARGET'] = $LD['target'];
1664 $list['onClick'] = $onClick;
1665 return $list;
1666 }
1667
1668 /**
1669 * Determines original shortcut destination in page overlays.
1670 *
1671 * Since the pages records used for menu rendering are overlaid by default,
1672 * the original 'shortcut' value is lost, if a translation did not define one.
1673 * The behaviour in TSFE can be compared to the 'mergeIfNotBlank' feature, but
1674 * it's hardcoded there and not related to the mentioned setting at all.
1675 *
1676 * @param array $page
1677 * @return array
1678 */
1679 protected function determineOriginalShortcutPage(array $page)
1680 {
1681 // Check if modification is required
1682 if (
1683 $this->getTypoScriptFrontendController()->sys_language_uid > 0
1684 && empty($page['shortcut'])
1685 && !empty($page['uid'])
1686 && !empty($page['_PAGES_OVERLAY'])
1687 && !empty($page['_PAGES_OVERLAY_UID'])
1688 ) {
1689 // Using raw record since the record was overlaid and is correct already:
1690 $originalPage = $this->sys_page->getRawRecord('pages', $page['uid']);
1691
1692 if ($originalPage['shortcut_mode'] === $page['shortcut_mode'] && !empty($originalPage['shortcut'])) {
1693 $page['shortcut'] = $originalPage['shortcut'];
1694 }
1695 }
1696
1697 return $page;
1698 }
1699
1700 /**
1701 * Will change $LD (passed by reference) if the page is access restricted
1702 *
1703 * @param array $LD The array from the linkData() function
1704 * @param array $page Page array
1705 * @param string $mainTarget Main target value
1706 * @param string $typeOverride Type number override if any
1707 * @return void ($LD passed by reference might be changed.)
1708 */
1709 public function changeLinksForAccessRestrictedPages(&$LD, $page, $mainTarget, $typeOverride)
1710 {
1711 // If access restricted pages should be shown in menus, change the link of such pages to link to a redirection page:
1712 if ($this->mconf['showAccessRestrictedPages'] && $this->mconf['showAccessRestrictedPages'] !== 'NONE' && !$this->getTypoScriptFrontendController()->checkPageGroupAccess($page)) {
1713 $thePage = $this->sys_page->getPage($this->mconf['showAccessRestrictedPages']);
1714 $addParams = str_replace(
1715 [
1716 '###RETURN_URL###',
1717 '###PAGE_ID###'
1718 ],
1719 [
1720 rawurlencode($LD['totalURL']),
1721 isset($page['_SHORTCUT_PAGE_UID']) ? $page['_SHORTCUT_PAGE_UID'] : $page['uid']
1722 ],
1723 $this->mconf['showAccessRestrictedPages.']['addParams']
1724 );
1725 $LD = $this->menuTypoLink($thePage, $mainTarget, '', '', '', $addParams, $typeOverride);
1726 }
1727 }
1728
1729 /**
1730 * Creates a submenu level to the current level - if configured for.
1731 *
1732 * @param int $uid Page id of the current page for which a submenu MAY be produced (if conditions are met)
1733 * @param string $objSuffix Object prefix, see ->start()
1734 * @return string HTML content of the submenu
1735 * @internal
1736 */
1737 public function subMenu($uid, $objSuffix = '')
1738 {
1739 // Setting alternative menu item array if _SUB_MENU has been defined in the current ->menuArr
1740 $altArray = '';
1741 if (is_array($this->menuArr[$this->I['key']]['_SUB_MENU']) && !empty($this->menuArr[$this->I['key']]['_SUB_MENU'])) {
1742 $altArray = $this->menuArr[$this->I['key']]['_SUB_MENU'];
1743 }
1744 // Make submenu if the page is the next active
1745 $menuType = $this->conf[($this->menuNumber + 1) . $objSuffix];
1746 // stdWrap for expAll
1747 if (isset($this->mconf['expAll.'])) {
1748 $this->mconf['expAll'] = $this->parent_cObj->stdWrap($this->mconf['expAll'], $this->mconf['expAll.']);
1749 }
1750 if (($this->mconf['expAll'] || $this->isNext($uid, $this->getMPvar($this->I['key'])) || is_array($altArray)) && !$this->mconf['sectionIndex']) {
1751 try {
1752 $menuObjectFactory = GeneralUtility::makeInstance(MenuContentObjectFactory::class);
1753 /** @var $submenu AbstractMenuContentObject */
1754 $submenu = $menuObjectFactory->getMenuObjectByType($menuType);
1755 $submenu->entryLevel = $this->entryLevel + 1;
1756 $submenu->rL_uidRegister = $this->rL_uidRegister;
1757 $submenu->MP_array = $this->MP_array;
1758 if ($this->menuArr[$this->I['key']]['_MP_PARAM']) {
1759 $submenu->MP_array[] = $this->menuArr[$this->I['key']]['_MP_PARAM'];
1760 }
1761 // Especially scripts that build the submenu needs the parent data
1762 $submenu->parent_cObj = $this->parent_cObj;
1763 // Setting alternativeMenuTempArray (will be effective only if an array)
1764 if (is_array($altArray)) {
1765 $submenu->alternativeMenuTempArray = $altArray;
1766 }
1767 if ($submenu->start($this->tmpl, $this->sys_page, $uid, $this->conf, $this->menuNumber + 1, $objSuffix)) {
1768 $submenu->makeMenu();
1769 // Memorize the current menu item count
1770 $tsfe = $this->getTypoScriptFrontendController();
1771 $tempCountMenuObj = $tsfe->register['count_MENUOBJ'];
1772 // Reset the menu item count for the submenu
1773 $tsfe->register['count_MENUOBJ'] = 0;
1774 $content = $submenu->writeMenu();
1775 // Restore the item count now that the submenu has been handled
1776 $tsfe->register['count_MENUOBJ'] = $tempCountMenuObj;
1777 $tsfe->register['count_menuItems'] = count($this->menuArr);
1778 return $content;
1779 }
1780 } catch (Exception\NoSuchMenuTypeException $e) {
1781 }
1782 }
1783 return '';
1784 }
1785
1786 /**
1787 * Returns TRUE if the page with UID $uid is the NEXT page in root line (which means a submenu should be drawn)
1788 *
1789 * @param int $uid Page uid to evaluate.
1790 * @param string $MPvar MPvar for the current position of item.
1791 * @return bool TRUE if page with $uid is active
1792 * @internal
1793 * @see subMenu()
1794 */
1795 public function isNext($uid, $MPvar = '')
1796 {
1797 // Check for always active PIDs:
1798 if (!empty($this->alwaysActivePIDlist) && in_array((int)$uid, $this->alwaysActivePIDlist, true)) {
1799 return true;
1800 }
1801 $testUid = $uid . ($MPvar ? ':' . $MPvar : '');
1802 if ($uid && $testUid == $this->nextActive) {
1803 return true;
1804 }
1805 return false;
1806 }
1807
1808 /**
1809 * Returns TRUE if the page with UID $uid is active (in the current rootline)
1810 *
1811 * @param int $uid Page uid to evaluate.
1812 * @param string $MPvar MPvar for the current position of item.
1813 * @return bool TRUE if page with $uid is active
1814 * @internal
1815 */
1816 public function isActive($uid, $MPvar = '')
1817 {
1818 // Check for always active PIDs:
1819 if (!empty($this->alwaysActivePIDlist) && in_array((int)$uid, $this->alwaysActivePIDlist, true)) {
1820 return true;
1821 }
1822 $testUid = $uid . ($MPvar ? ':' . $MPvar : '');
1823 if ($uid && in_array('ITEM:' . $testUid, $this->rL_uidRegister, true)) {
1824 return true;
1825 }
1826 return false;
1827 }
1828
1829 /**
1830 * Returns TRUE if the page with UID $uid is the CURRENT page (equals $this->getTypoScriptFrontendController()->id)
1831 *
1832 * @param int $uid Page uid to evaluate.
1833 * @param string $MPvar MPvar for the current position of item.
1834 * @return bool TRUE if page $uid = $this->getTypoScriptFrontendController()->id
1835 * @internal
1836 */
1837 public function isCurrent($uid, $MPvar = '')
1838 {
1839 $testUid = $uid . ($MPvar ? ':' . $MPvar : '');
1840 return $uid && end($this->rL_uidRegister) === 'ITEM:' . $testUid;
1841 }
1842
1843 /**
1844 * Returns TRUE if there is a submenu with items for the page id, $uid
1845 * Used by the item states "IFSUB", "ACTIFSUB" and "CURIFSUB" to check if there is a submenu
1846 *
1847 * @param int $uid Page uid for which to search for a submenu
1848 * @return bool Returns TRUE if there was a submenu with items found
1849 * @internal
1850 */
1851 public function isSubMenu($uid)
1852 {
1853 // Looking for a mount-pid for this UID since if that
1854 // exists we should look for a subpages THERE and not in the input $uid;
1855 $mount_info = $this->sys_page->getMountPointInfo($uid);
1856 if (is_array($mount_info)) {
1857 $uid = $mount_info['mount_pid'];
1858 }
1859 $recs = $this->sys_page->getMenu($uid, 'uid,pid,doktype,mount_pid,mount_pid_ol,nav_hide,shortcut,shortcut_mode,l18n_cfg');
1860 $hasSubPages = false;
1861 $bannedUids = $this->getBannedUids();
1862 foreach ($recs as $theRec) {
1863 // no valid subpage if the document type is excluded from the menu
1864 if (GeneralUtility::inList($this->doktypeExcludeList, $theRec['doktype'])) {
1865 continue;
1866 }
1867 // No valid subpage if the page is hidden inside menus and
1868 // it wasn't forced to show such entries
1869 if ($theRec['nav_hide'] && !$this->conf['includeNotInMenu']) {
1870 continue;
1871 }
1872 // No valid subpage if the default language should be shown and the page settings
1873 // are excluding the visibility of the default language
1874 if (!$this->getTypoScriptFrontendController()->sys_language_uid && GeneralUtility::hideIfDefaultLanguage($theRec['l18n_cfg'])) {
1875 continue;
1876 }
1877 // No valid subpage if the alternative language should be shown and the page settings
1878 // are requiring a valid overlay but it doesn't exists
1879 $hideIfNotTranslated = GeneralUtility::hideIfNotTranslated($theRec['l18n_cfg']);
1880 if ($this->getTypoScriptFrontendController()->sys_language_uid && $hideIfNotTranslated && !$theRec['_PAGES_OVERLAY']) {
1881 continue;
1882 }
1883 // No valid subpage if the subpage is banned by excludeUidList
1884 if (in_array($theRec['uid'], $bannedUids)) {
1885 continue;
1886 }
1887 $hasSubPages = true;
1888 break;
1889 }
1890 return $hasSubPages;
1891 }
1892
1893 /**
1894 * Used by procesItemStates() to evaluate if a menu item (identified by $key) is in a certain state.
1895 *
1896 * @param string $kind The item state to evaluate (SPC, IFSUB, ACT etc... but no xxxRO states of course)
1897 * @param int $key Key pointing to menu item from ->menuArr
1898 * @return bool Returns TRUE if state matches
1899 * @internal
1900 * @see procesItemStates()
1901 */
1902 public function isItemState($kind, $key)
1903 {
1904 $natVal = false;
1905 // If any value is set for ITEM_STATE the normal evaluation is discarded
1906 if ($this->menuArr[$key]['ITEM_STATE']) {
1907 if ((string)$this->menuArr[$key]['ITEM_STATE'] === (string)$kind) {
1908 $natVal = true;
1909 }
1910 } else {
1911 switch ($kind) {
1912 case 'SPC':
1913 $natVal = (bool)$this->menuArr[$key]['isSpacer'];
1914 break;
1915 case 'IFSUB':
1916 $natVal = $this->isSubMenu($this->menuArr[$key]['uid']);
1917 break;
1918 case 'ACT':
1919 $natVal = $this->isActive($this->menuArr[$key]['uid'], $this->getMPvar($key));
1920 break;
1921 case 'ACTIFSUB':
1922 $natVal = $this->isActive($this->menuArr[$key]['uid'], $this->getMPvar($key)) && $this->isSubMenu($this->menuArr[$key]['uid']);
1923 break;
1924 case 'CUR':
1925 $natVal = $this->isCurrent($this->menuArr[$key]['uid'], $this->getMPvar($key));
1926 break;
1927 case 'CURIFSUB':
1928 $natVal = $this->isCurrent($this->menuArr[$key]['uid'], $this->getMPvar($key)) && $this->isSubMenu($this->menuArr[$key]['uid']);
1929 break;
1930 case 'USR':
1931 $natVal = (bool)$this->menuArr[$key]['fe_group'];
1932 break;
1933 }
1934 }
1935 return $natVal;
1936 }
1937
1938 /**
1939 * Creates an access-key for a TMENU/GMENU menu item based on the menu item titles first letter
1940 *
1941 * @param string $title Menu item title.
1942 * @return array Returns an array with keys "code" ("accesskey" attribute for the img-tag) and "alt" (text-addition to the "alt" attribute) if an access key was defined. Otherwise array was empty
1943 * @internal
1944 */
1945 public function accessKey($title)
1946 {
1947 $tsfe = $this->getTypoScriptFrontendController();
1948 // The global array ACCESSKEY is used to globally control if letters are already used!!
1949 $result = [];
1950 $title = trim(strip_tags($title));
1951 $titleLen = strlen($title);
1952 for ($a = 0; $a < $titleLen; $a++) {
1953 $key = strtoupper(substr($title, $a, 1));
1954 if (preg_match('/[A-Z]/', $key) && !isset($tsfe->accessKey[$key])) {
1955 $tsfe->accessKey[$key] = 1;
1956 $result['code'] = ' accesskey="' . $key . '"';
1957 $result['alt'] = ' (ALT+' . $key . ')';
1958 $result['key'] = $key;
1959 break;
1960 }
1961 }
1962 return $result;
1963 }
1964
1965 /**
1966 * Calls a user function for processing of internal data.
1967 * Used for the properties "IProcFunc" and "itemArrayProcFunc"
1968 *
1969 * @param string $mConfKey Key pointing for the property in the current ->mconf array holding possibly parameters to pass along to the function/method. Currently the keys used are "IProcFunc" and "itemArrayProcFunc".
1970 * @param mixed $passVar A variable to pass to the user function and which should be returned again from the user function. The idea is that the user function modifies this variable according to what you want to achieve and then returns it. For "itemArrayProcFunc" this variable is $this->menuArr, for "IProcFunc" it is $this->I
1971 * @return mixed The processed $passVar
1972 * @internal
1973 */
1974 public function userProcess($mConfKey, $passVar)
1975 {
1976 if ($this->mconf[$mConfKey]) {
1977 $funcConf = $this->mconf[$mConfKey . '.'];
1978 $funcConf['parentObj'] = $this;
1979 $passVar = $this->parent_cObj->callUserFunction($this->mconf[$mConfKey], $funcConf, $passVar);
1980 }
1981 return $passVar;
1982 }
1983
1984 /**
1985 * Creates the <A> tag parts for the current item (in $this->I, [A1] and [A2]) based on other information in this array (like $this->I['linkHREF'])
1986 *
1987 * @return void
1988 * @internal
1989 */
1990 public function setATagParts()
1991 {
1992 $params = trim($this->I['val']['ATagParams']) . $this->I['accessKey']['code'];
1993 $params = $params !== '' ? ' ' . $params : '';
1994 $this->I['A1'] = '<a ' . GeneralUtility::implodeAttributes($this->I['linkHREF'], 1) . $params . '>';
1995 $this->I['A2'] = '</a>';
1996 }
1997
1998 /**
1999 * Returns the title for the navigation
2000 *
2001 * @param string $title The current page title
2002 * @param string $nav_title The current value of the navigation title
2003 * @return string Returns the navigation title if it is NOT blank, otherwise the page title.
2004 * @internal
2005 */
2006 public function getPageTitle($title, $nav_title)
2007 {
2008 return trim($nav_title) !== '' ? $nav_title : $title;
2009 }
2010
2011 /**
2012 * Return MPvar string for entry $key in ->menuArr
2013 *
2014 * @param int $key Pointer to element in ->menuArr
2015 * @return string MP vars for element.
2016 * @see link()
2017 */
2018 public function getMPvar($key)
2019 {
2020 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
2021 $localMP_array = $this->MP_array;
2022 // NOTICE: "_MP_PARAM" is allowed to be a commalist of PID pairs!
2023 if ($this->menuArr[$key]['_MP_PARAM']) {
2024 $localMP_array[] = $this->menuArr[$key]['_MP_PARAM'];
2025 }
2026 return !empty($localMP_array) ? implode(',', $localMP_array) : '';
2027 }
2028 return '';
2029 }
2030
2031 /**
2032 * Returns where clause part to exclude 'not in menu' pages
2033 *
2034 * @return string where clause part.
2035 * @internal
2036 */
2037 public function getDoktypeExcludeWhere()
2038 {
2039 return $this->doktypeExcludeList ? ' AND pages.doktype NOT IN (' . $this->doktypeExcludeList . ')' : '';
2040 }
2041
2042 /**
2043 * Returns an array of banned UIDs (from excludeUidList)
2044 *
2045 * @return array Array of banned UIDs
2046 * @internal
2047 */
2048 public function getBannedUids()
2049 {
2050 $excludeUidList = isset($this->conf['excludeUidList.'])
2051 ? $this->parent_cObj->stdWrap($this->conf['excludeUidList'], $this->conf['excludeUidList.'])
2052 : $this->conf['excludeUidList'];
2053
2054 if (!trim($excludeUidList)) {
2055 return [];
2056 }
2057
2058 $banUidList = str_replace('current', $this->getTypoScriptFrontendController()->page['uid'], $excludeUidList);
2059 return GeneralUtility::intExplode(',', $banUidList);
2060 }
2061
2062 /**
2063 * Calls typolink to create menu item links.
2064 *
2065 * @param array $page Page record (uid points where to link to)
2066 * @param string $oTarget Target frame/window
2067 * @param bool $no_cache TRUE if caching should be disabled
2068 * @param string $script Alternative script name (unused)
2069 * @param array|string $overrideArray Array to override values in $page, empty string to skip override
2070 * @param string $addParams Parameters to add to URL
2071 * @param int|string $typeOverride "type" value, empty string means "not set"
2072 * @return array See linkData
2073 */
2074 public function menuTypoLink($page, $oTarget, $no_cache, $script, $overrideArray = '', $addParams = '', $typeOverride = '')
2075 {
2076 $conf = [
2077 'parameter' => is_array($overrideArray) && $overrideArray['uid'] ? $overrideArray['uid'] : $page['uid']
2078 ];
2079 if (MathUtility::canBeInterpretedAsInteger($typeOverride)) {
2080 $conf['parameter'] .= ',' . (int)$typeOverride;
2081 }
2082 if ($addParams) {
2083 $conf['additionalParams'] = $addParams;
2084 }
2085 if ($no_cache) {
2086 $conf['no_cache'] = true;
2087 } elseif ($this->useCacheHash) {
2088 $conf['useCacheHash'] = true;
2089 }
2090 if ($oTarget) {
2091 $conf['target'] = $oTarget;
2092 }
2093 if ($page['sectionIndex_uid']) {
2094 $conf['section'] = $page['sectionIndex_uid'];
2095 }
2096 $conf['linkAccessRestrictedPages'] = $this->mconf['showAccessRestrictedPages'] && $this->mconf['showAccessRestrictedPages'] !== 'NONE';
2097 $this->parent_cObj->typoLink('|', $conf);
2098 $LD = $this->parent_cObj->lastTypoLinkLD;
2099 $LD['totalURL'] = $this->parent_cObj->lastTypoLinkUrl;
2100 return $LD;
2101 }
2102
2103 /**
2104 * Generates a list of content objects with sectionIndex enabled
2105 * available on a specific page
2106 *
2107 * Used for menus with sectionIndex enabled
2108 *
2109 * @param string $altSortField Alternative sorting field
2110 * @param int $pid The page id to search for sections
2111 * @throws \UnexpectedValueException if the query to fetch the content elements unexpectedly fails
2112 * @return array
2113 */
2114 protected function sectionIndex($altSortField, $pid = null)
2115 {
2116 $pid = (int)($pid ?: $this->id);
2117 $basePageRow = $this->sys_page->getPage($pid);
2118 if (!is_array($basePageRow)) {
2119 return [];
2120 }
2121 $tsfe = $this->getTypoScriptFrontendController();
2122 $configuration = $this->mconf['sectionIndex.'];
2123 $useColPos = 0;
2124 if (trim($configuration['useColPos']) !== '' || is_array($configuration['useColPos.'])) {
2125 $useColPos = $tsfe->cObj->stdWrap($configuration['useColPos'], $configuration['useColPos.']);
2126 $useColPos = (int)$useColPos;
2127 }
2128 $selectSetup = [
2129 'pidInList' => $pid,
2130 'orderBy' => $altSortField,
2131 'languageField' => 'sys_language_uid',
2132 'where' => $useColPos >= 0 ? 'colPos=' . $useColPos : ''
2133 ];
2134 if ($basePageRow['content_from_pid']) {
2135 // If the page is configured to show content from a referenced page the sectionIndex contains only contents of
2136 // the referenced page
2137 $selectSetup['pidInList'] = $basePageRow['content_from_pid'];
2138 }
2139 $resource = $this->parent_cObj->exec_getQuery('tt_content', $selectSetup);
2140 if (!$resource) {
2141 $message = 'SectionIndex: Query to fetch the content elements failed!';
2142 throw new \UnexpectedValueException($message, 1337334849);
2143 }
2144 $result = [];
2145 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($resource)) {
2146 $this->sys_page->versionOL('tt_content', $row);
2147 if ($tsfe->sys_language_contentOL && $basePageRow['_PAGES_OVERLAY_LANGUAGE']) {
2148 $row = $this->sys_page->getRecordOverlay('tt_content', $row, $basePageRow['_PAGES_OVERLAY_LANGUAGE'], $tsfe->sys_language_contentOL);
2149 }
2150 if ($this->mconf['sectionIndex.']['type'] !== 'all') {
2151 $doIncludeInSectionIndex = $row['sectionIndex'] >= 1;
2152 $doHeaderCheck = $this->mconf['sectionIndex.']['type'] === 'header';
2153 $isValidHeader = ((int)$row['header_layout'] !== 100 || !empty($this->mconf['sectionIndex.']['includeHiddenHeaders'])) && trim($row['header']) !== '';
2154 if (!$doIncludeInSectionIndex || $doHeaderCheck && !$isValidHeader) {
2155 continue;
2156 }
2157 }
2158 if (is_array($row)) {
2159 $uid = $row['uid'];
2160 $result[$uid] = $basePageRow;
2161 $result[$uid]['title'] = $row['header'];
2162 $result[$uid]['nav_title'] = $row['header'];
2163 // Prevent false exclusion in filterMenuPages, thus: Always show tt_content records
2164 $result[$uid]['nav_hide'] = 0;
2165 $result[$uid]['subtitle'] = $row['subheader'];
2166 $result[$uid]['starttime'] = $row['starttime'];
2167 $result[$uid]['endtime'] = $row['endtime'];
2168 $result[$uid]['fe_group'] = $row['fe_group'];
2169 $result[$uid]['media'] = $row['media'];
2170 $result[$uid]['header_layout'] = $row['header_layout'];
2171 $result[$uid]['bodytext'] = $row['bodytext'];
2172 $result[$uid]['image'] = $row['image'];
2173 $result[$uid]['sectionIndex_uid'] = $uid;
2174 }
2175 }
2176 $this->getDatabaseConnection()->sql_free_result($resource);
2177 return $result;
2178 }
2179
2180 /**
2181 * Returns the sys_page object
2182 *
2183 * @return \TYPO3\CMS\Frontend\Page\PageRepository
2184 */
2185 public function getSysPage()
2186 {
2187 return $this->sys_page;
2188 }
2189
2190 /**
2191 * Returns the parent content object
2192 *
2193 * @return \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
2194 */
2195 public function getParentContentObject()
2196 {
2197 return $this->parent_cObj;
2198 }
2199
2200 /**
2201 * @return DatabaseConnection
2202 */
2203 protected function getDatabaseConnection()
2204 {
2205 return $GLOBALS['TYPO3_DB'];
2206 }
2207
2208 /**
2209 * @return TypoScriptFrontendController
2210 */
2211 protected function getTypoScriptFrontendController()
2212 {
2213 return $GLOBALS['TSFE'];
2214 }
2215
2216 /**
2217 * @return TimeTracker
2218 */
2219 protected function getTimeTracker()
2220 {
2221 return $GLOBALS['TT'];
2222 }
2223
2224 /**
2225 * @return \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
2226 */
2227 protected function getCache()
2228 {
2229 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash');
2230 }
2231 }