1<?php
2/**
3 * Elgg navigation library
4 * Functions for managing menus and other navigational elements
5 *
6 * Breadcrumbs
7 * Elgg uses a breadcrumb stack. The page handlers (controllers in MVC terms)
8 * push the breadcrumb links onto the stack. @see elgg_push_breadcrumb()
9 *
10 *
11 * Pagination
12 * Automatically handled by Elgg when using elgg_list_entities* functions.
13 * @see elgg_list_entities()
14 *
15 *
16 * Tabs
17 * @see navigation/tabs view
18 *
19 *
20 * Menus
21 * Elgg uses a single interface to manage its menus. Menu items are added with
22 * {@link elgg_register_menu_item()}. This is generally used for menus that
23 * appear only once per page. For dynamic menus (such as the hover
24 * menu for user's avatar), a plugin hook is emitted when the menu is being
25 * created. The hook is 'register', 'menu:<menu_name>'. For more details on this,
26 * @see elgg_view_menu().
27 *
28 * Menus supported by the Elgg core
29 * Standard menus:
30 *     site   Site navigation shown on every page.
31 *     page   Page menu usually shown in a sidebar. Uses Elgg's context.
32 *     topbar Topbar menu shown on every page. The default has two sections.
33 *     footer Like the topbar but in the footer.
34 *
35 * Dynamic menus (also called just-in-time menus):
36 *     user_hover  Avatar hover menu. The user entity is passed as a parameter.
37 *     entity      The set of links shown in the summary of an entity.
38 *     river       Links shown on river items.
39 *     owner_block Links shown for a user or group in their owner block.
40 *     filter      The tab filter for content (all, mine, friends)
41 *     title       The buttons shown next to a content title.
42 *     longtext    The links shown above the input/longtext view.
43 *     login       Menu of links at bottom of login box
44 */
45
46use Elgg\Menu\MenuItems;
47use Elgg\Menu\PreparedMenu;
48
49/**
50 * Register an item for an Elgg menu
51 *
52 * @warning Generally you should not use this in response to the plugin hook:
53 * 'register', 'menu:<menu_name>'. If you do, you may end up with many incorrect
54 * links on a dynamic menu.
55 *
56 * @warning A menu item's name must be unique per menu. If more than one menu
57 * item with the same name are registered, the last menu item takes priority.
58 *
59 * @see elgg_view_menu() for the plugin hooks available for modifying a menu as
60 * it is being rendered.
61 *
62 * @see ElggMenuItem::factory() is used to turn an array value of $menu_item into an
63 * ElggMenuItem object.
64 *
65 * @param string $menu_name The name of the menu: site, page, userhover,
66 *                          userprofile, groupprofile, or any custom menu
67 * @param mixed  $menu_item A \ElggMenuItem object or an array of options in format:
68 *                          name        => STR  Menu item identifier (required)
69 *                          text        => STR  Menu item display text as HTML (required)
70 *                          href        => STR  Menu item URL (required)
71 *                                              false = do not create a link.
72 *                                              null = current URL.
73 *                                              "" = current URL.
74 *                                              "/" = site home page.
75 *                                              @warning If href is false, the <a> tag will
76 *                                              not appear, so the link_class will not apply. If you
77 *                                              put <a> tags in manually through the 'text' option
78 *                                              the default CSS selector .elgg-menu-$menu > li > a
79 *                                              may affect formatting. Wrap in a <span> if it does.)
80 *                          contexts    => ARR  Page context strings
81 *                          section     => STR  Menu section identifier
82 *                          title       => STR  Menu item tooltip
83 *                          selected    => BOOL Is this menu item currently selected
84 *                          parent_name => STR  Identifier of the parent menu item
85 *                          link_class  => STR  A class or classes for the <a> tag
86 *                          item_class  => STR  A class or classes for the <li> tag
87 *                          deps     => STR  One or more AMD modules to require
88 *
89 *                          Additional options that the view output/url takes can be
90 *							passed in the array. Custom options can be added by using
91 *							the 'data' key with the	value being an associative array.
92 *
93 * @return bool False if the item could not be added
94 * @since 1.8.0
95 */
96function elgg_register_menu_item($menu_name, $menu_item) {
97	if (is_array($menu_item)) {
98		$options = $menu_item;
99		$menu_item = ElggMenuItem::factory($options);
100		if (!$menu_item instanceof ElggMenuItem) {
101			$menu_item_name = elgg_extract('name', $options, 'MISSING NAME');
102			elgg_log("Unable to add menu item '{$menu_item_name}' to '$menu_name' menu", 'WARNING');
103			return false;
104		}
105	}
106
107	if (!$menu_item instanceof ElggMenuItem) {
108		elgg_log('Second argument of elgg_register_menu_item() must be an instance of '
109			. 'ElggMenuItem or an array of menu item factory options', 'ERROR');
110		return false;
111	}
112
113	$menus = _elgg_config()->menus;
114	if (empty($menus)) {
115		$menus = [];
116	}
117
118	$menus[$menu_name][] = $menu_item;
119	_elgg_config()->menus = $menus;
120
121	return true;
122}
123
124/**
125 * Remove an item from a menu
126 *
127 * @param string $menu_name The name of the menu
128 * @param string $item_name The unique identifier for this menu item
129 *
130 * @return \ElggMenuItem|null
131 * @since 1.8.0
132 */
133function elgg_unregister_menu_item($menu_name, $item_name) {
134	$menus = _elgg_config()->menus;
135	if (empty($menus)) {
136		return null;
137	}
138
139	if (!isset($menus[$menu_name])) {
140		return null;
141	}
142
143	foreach ($menus[$menu_name] as $index => $menu_object) {
144		/* @var \ElggMenuItem $menu_object */
145		if ($menu_object instanceof ElggMenuItem && $menu_object->getName() == $item_name) {
146			$item = $menus[$menu_name][$index];
147			unset($menus[$menu_name][$index]);
148			elgg_set_config('menus', $menus);
149			return $item;
150		}
151	}
152
153	return null;
154}
155
156/**
157 * Convenience function for registering a button to the title menu
158 *
159 * The URL must be $handler/$name/$guid where $guid is the guid of the page owner.
160 * The label of the button is "$handler:$name" so that must be defined in a
161 * language file.
162 *
163 * This is used primarily to support adding an add content button
164 *
165 * @param string $handler        The handler to use or null to autodetect from context
166 * @param string $name           Name of the button (defaults to 'add')
167 * @param string $entity_type    Optional entity type to be added (used to verify canWriteToContainer permission)
168 * @param string $entity_subtype Optional entity subtype to be added (used to verify canWriteToContainer permission)
169 * @return void
170 * @since 1.8.0
171 */
172function elgg_register_title_button($handler = null, $name = 'add', $entity_type = 'all', $entity_subtype = 'all') {
173
174	$owner = elgg_get_page_owner_entity();
175	if (!$owner) {
176		// noone owns the page so this is probably an all site list page
177		$owner = elgg_get_logged_in_user_entity();
178	}
179
180	if (($name === 'add') && ($owner instanceof ElggUser)) {
181		// make sure the add link goes to the current logged in user, not the page owner
182		$logged_in_user = elgg_get_logged_in_user_entity();
183		if (!empty($logged_in_user) && ($logged_in_user->guid !== $owner->guid)) {
184			// change the 'owner' for the link to the current logged in user
185			$owner = $logged_in_user;
186		}
187	}
188
189	// do we have an owner and is the current user allowed to create content here
190	if (!$owner || !$owner->canWriteToContainer(0, $entity_type, $entity_subtype)) {
191		return;
192	}
193
194	$href = elgg_generate_url("$name:$entity_type:$entity_subtype", [
195		'guid' => $owner->guid,
196	]);
197
198	if (!$href) {
199		if (!$handler) {
200			$handler = elgg_get_context();
201		}
202		$href = "$handler/$name/$owner->guid";
203	}
204
205	if (elgg_language_key_exists("$name:$entity_type:$entity_subtype")) {
206		$text = elgg_echo("$name:$entity_type:$entity_subtype");
207	} elseif (elgg_language_key_exists("$handler:$name")) {
208		$text = elgg_echo("$handler:$name");
209	} else {
210		$text = elgg_echo($name);
211	}
212
213	// register the title menu item
214	elgg_register_menu_item('title', [
215		'name' => $name,
216		'icon' => $name === 'add' ? 'plus' : '',
217		'href' => $href,
218		'text' => $text,
219		'link_class' => 'elgg-button elgg-button-action',
220	]);
221}
222
223/**
224 * Adds a breadcrumb to the breadcrumbs stack.
225 *
226 * See elgg_get_breadcrumbs() and the navigation/breadcrumbs view.
227 *
228 * @param string       $text The title to display. During rendering this is HTML encoded.
229 * @param false|string $href Optional. The href for the title. During rendering links are
230 *                           normalized via elgg_normalize_url().
231 *
232 * @return void
233 * @since 1.8.0
234 * @see elgg_get_breadcrumbs()
235 */
236function elgg_push_breadcrumb($text, $href = false) {
237	$breadcrumbs = (array) _elgg_config()->breadcrumbs;
238
239	$breadcrumbs[] = [
240		'text' => $text,
241		'href' => $href,
242	];
243
244	elgg_set_config('breadcrumbs', $breadcrumbs);
245}
246
247/**
248 * Removes last breadcrumb entry.
249 *
250 * @return array popped breadcrumb array or empty array
251 * @since 1.8.0
252 */
253function elgg_pop_breadcrumb() {
254	$breadcrumbs = (array) _elgg_config()->breadcrumbs;
255
256	if (empty($breadcrumbs)) {
257		return [];
258	}
259
260	$popped = array_pop($breadcrumbs);
261	elgg_set_config('breadcrumbs', $breadcrumbs);
262
263	return $popped;
264}
265
266/**
267 * Returns all breadcrumbs as an array
268 * <code>
269 * [
270 *    [
271 *       'text' => 'Breadcrumb title',
272 *       'href' => '/path/to/page',
273 *    ]
274 * ]
275 * </code>
276 *
277 * Breadcrumbs are filtered through the plugin hook [prepare, breadcrumbs] before
278 * being returned.
279 *
280 * @param array $breadcrumbs An array of breadcrumbs
281 *                           If set, will override breadcrumbs in the stack
282 * @return array
283 * @since 1.8.0
284 * @see elgg_prepare_breadcrumbs()
285 */
286function elgg_get_breadcrumbs(array $breadcrumbs = null) {
287	if (!isset($breadcrumbs)) {
288		// if no crumbs set, still allow hook to populate it
289		$breadcrumbs = (array) _elgg_config()->breadcrumbs;
290	}
291
292	$params = [
293		'breadcrumbs' => $breadcrumbs,
294	];
295
296	$params['identifier'] = _elgg_services()->request->getFirstUrlSegment();
297	$params['segments'] = _elgg_services()->request->getUrlSegments();
298	array_shift($params['segments']);
299
300	$breadcrumbs = elgg_trigger_plugin_hook('prepare', 'breadcrumbs', $params, $breadcrumbs);
301	if (!is_array($breadcrumbs)) {
302		_elgg_services()->logger->error('"prepare, breadcrumbs" hook must return an array of breadcrumbs');
303		return [];
304	}
305
306	foreach ($breadcrumbs as $key => $breadcrumb) {
307		$text = elgg_extract('text', $breadcrumb, elgg_extract('title', $breadcrumb));
308		if (isset($breadcrumb['link'])) {
309			elgg_deprecated_notice("Breadcrumb [{$text}] requires 'href' instead of 'link' set in the configuration", '3.0');
310
311			$breadcrumbs[$key]['href'] = $breadcrumb['link'];
312			unset($breadcrumbs[$key]['link']);
313		}
314		if (isset($breadcrumb['title'])) {
315			elgg_deprecated_notice("Breadcrumb [{$text}] requires 'text' instead of 'title' set in the configuration", '3.0');
316
317			$breadcrumbs[$key]['text'] = $breadcrumb['title'];
318			unset($breadcrumbs[$key]['title']);
319		}
320
321		// adds name for usage in menu items
322		if (!isset($breadcrumb['name'])) {
323			$breadcrumbs[$key]['name'] = $key;
324		}
325	}
326
327	return $breadcrumbs;
328}
329
330/**
331 * Prepare breadcrumbs before display. This turns titles into 100-character excerpts, and also
332 * removes the last crumb if it's not a link.
333 *
334 * @param \Elgg\Hook $hook "prepare", "breadcrumbs"
335 *
336 * @return array
337 * @since 1.11
338 */
339function elgg_prepare_breadcrumbs(\Elgg\Hook $hook) {
340	$breadcrumbs = $hook->getValue();
341
342	// remove last crumb if not a link
343	$last_crumb = end($breadcrumbs);
344	if (empty($last_crumb['href'])) {
345		array_pop($breadcrumbs);
346	}
347
348	// apply excerpt to text
349	foreach (array_keys($breadcrumbs) as $i) {
350		$breadcrumbs[$i]['text'] = elgg_get_excerpt($breadcrumbs[$i]['text'], 100);
351	}
352	return $breadcrumbs;
353}
354
355/**
356 * Resolves and pushes entity breadcrumbs based on named routes
357 *
358 * @param ElggEntity $entity    Entity
359 * @param bool       $link_self Use entity link in the last crumb
360 *
361 * @return void
362 */
363function elgg_push_entity_breadcrumbs(ElggEntity $entity, $link_self = true) {
364
365	$container = $entity->getContainerEntity() ? : null;
366	elgg_push_collection_breadcrumbs($entity->type, $entity->subtype, $container);
367
368	$entity_url = $link_self ? $entity->getURL() : false;
369	elgg_push_breadcrumb($entity->getDisplayName(), $entity_url);
370}
371
372/**
373 * Resolves and pushes collection breadcrumbs for a container
374 *
375 * @param string          $entity_type    Entity type in the collection
376 * @param string          $entity_subtype Entity subtype in the collection
377 * @param ElggEntity|null $container      Container/page owner entity
378 * @param bool            $friends        Collection belongs to container's friends?
379 *
380 * @return void
381 */
382function elgg_push_collection_breadcrumbs($entity_type, $entity_subtype, ElggEntity $container = null, $friends = false) {
383
384	if ($container) {
385		if (!$container instanceof \ElggSite) {
386			elgg_push_breadcrumb($container->getDisplayName(), $container->getURL());
387		}
388
389		if ($friends) {
390			$collection_route = "collection:$entity_type:$entity_subtype:friends";
391		} else if ($container instanceof ElggUser) {
392			$collection_route = "collection:$entity_type:$entity_subtype:owner";
393		} else if ($container instanceof ElggGroup) {
394			$collection_route = "collection:$entity_type:$entity_subtype:group";
395		} else if ($container instanceof ElggSite) {
396			$collection_route = "collection:$entity_type:$entity_subtype:all";
397		} else {
398			$collection_route = "collection:$entity_type:$entity_subtype:container";
399		}
400
401		$parameters = _elgg_services()->routes->resolveRouteParameters($collection_route, $container);
402		if ($parameters !== false) {
403			$label = elgg_echo("collection:$entity_type:$entity_subtype");
404			if ($friends) {
405				if (elgg_language_key_exists("collection:$entity_type:$entity_subtype:friends")) {
406					$label = elgg_echo("collection:$entity_type:$entity_subtype:friends");
407				} else {
408					$label = elgg_echo('collection:friends', [$label]);
409				}
410			}
411			$collection_url = elgg_generate_url($collection_route, $parameters);
412			elgg_push_breadcrumb($label, $collection_url);
413		}
414	} else {
415		$label = elgg_echo("collection:$entity_type:$entity_subtype");
416		$collection_url = elgg_generate_url("collection:$entity_type:$entity_subtype:all");
417		elgg_push_breadcrumb($label, $collection_url);
418	}
419}
420
421/**
422 * Returns default filter tabs (All, Mine, Friends) for the user
423 *
424 * @param string   $context  Context to be used to prefix tab URLs
425 * @param string   $selected Name of the selected tab
426 * @param ElggUser $user     User who owns the layout (defaults to logged in user)
427 * @param array    $vars     Additional vars
428 * @return ElggMenuItem[]
429 * @since 2.3
430 */
431function elgg_get_filter_tabs($context = null, $selected = null, ElggUser $user = null, array $vars = []) {
432
433	if (!isset($selected)) {
434		$selected = 'all';
435	}
436
437	if (!$user) {
438		$user = elgg_get_logged_in_user_entity();
439	}
440
441	$items = [];
442	$items[] = ElggMenuItem::factory([
443		'name' => 'all',
444		'text' => elgg_echo('all'),
445		'href' => (isset($vars['all_link'])) ? $vars['all_link'] : "$context/all",
446		'selected' => ($selected == 'all'),
447		'priority' => 200,
448	]);
449
450	if ($user) {
451		$items[] = ElggMenuItem::factory([
452			'name' => 'mine',
453			'text' => elgg_echo('mine'),
454			'href' => (isset($vars['mine_link'])) ? $vars['mine_link'] : "$context/owner/{$user->username}",
455			'selected' => ($selected == 'mine'),
456			'priority' => 300,
457		]);
458	}
459
460	$params = [
461		'selected' => $selected,
462		'user' => $user,
463		'vars' => $vars,
464	];
465	$items = _elgg_services()->hooks->trigger('filter_tabs', $context, $params, $items);
466
467	return $items;
468}
469
470/**
471 * Init site menu
472 *
473 * Registers custom menu items
474 *
475 * @param \Elgg\Hook $hook 'register', 'menu:site'
476 *
477 * @return MenuItems
478 *
479 * @internal
480 */
481function _elgg_site_menu_init(\Elgg\Hook $hook) {
482	$custom_menu_items = elgg_get_config('site_custom_menu_items');
483	if (empty($custom_menu_items)) {
484		return;
485	}
486
487	$return = $hook->getValue();
488
489	// add custom menu items
490	$n = 1;
491	foreach ($custom_menu_items as $title => $url) {
492		$item = new ElggMenuItem("custom$n", $title, $url);
493		$return[] = $item;
494		$n++;
495	}
496
497	return $return;
498}
499
500/**
501 * Set up the site menu
502 *
503 * Handles default, featured, and custom menu items
504 *
505 * @param \Elgg\Hook $hook 'prepare', 'menu:site'
506 *
507 * @return PreparedMenu
508 *
509 * @internal
510 */
511function _elgg_site_menu_setup(\Elgg\Hook $hook) {
512
513	$menu = $hook->getValue();
514	$featured_menu_names = array_values((array) elgg_get_config('site_featured_menu_names'));
515
516	$registered = $menu->getItems('default');
517	if (empty($registered)) {
518		return;
519	}
520
521	$has_selected = false;
522	$priority = 500;
523
524	foreach ($registered as $item) {
525		if (in_array($item->getName(), $featured_menu_names)) {
526			$featured_index = array_search($item->getName(), $featured_menu_names);
527			$item->setPriority($featured_index);
528		} else {
529			$item->setPriority($priority);
530			$priority++;
531		}
532		if ($item->getSelected()) {
533			$has_selected = true;
534		}
535	}
536
537	if (!$has_selected) {
538		$is_selected = function (ElggMenuItem $item) {
539			$current_url = current_page_url();
540			if (elgg_strpos($item->getHref(), elgg_get_site_url()) === 0) {
541				if ($item->getName() == elgg_get_context()) {
542					return true;
543				}
544				if ($item->getHref() == $current_url) {
545					return true;
546				}
547			}
548
549			return false;
550		};
551
552		foreach ($registered as $item) {
553			if ($is_selected($item)) {
554				$item->setSelected(true);
555				break;
556			}
557		}
558	}
559
560	usort($registered, [\ElggMenuBuilder::class, 'compareByPriority']);
561
562	$max_display_items = $hook->getParam('max_display_items', 5);
563
564	$num_menu_items = count($registered);
565
566	$more = [];
567	if ($max_display_items && $num_menu_items > ($max_display_items + 1)) {
568		$more = array_splice($registered, $max_display_items);
569	}
570
571	if (!empty($more)) {
572		$dropdown = ElggMenuItem::factory([
573			'name' => 'more',
574			'href' => false,
575			'text' => elgg_echo('more'),
576			'icon_alt' => 'angle-down',
577			'priority' => 999,
578		]);
579
580		foreach ($more as &$item) {
581			$item->setParentName('more');
582		}
583
584		$dropdown->setChildren($more);
585
586		$registered[] = $dropdown;
587	}
588
589	$menu->getSection('default')->fill($registered);
590
591}
592
593/**
594 * Prepare vertically stacked menu
595 *
596 * Sets the display child menu option to "toggle" if not set
597 * Recursively marks parents of the selected item as selected (expanded)
598 *
599 * @elgg_plugin_hook prepare menu:page
600 * @elgg_plugin_hook prepare menu:owner_block
601 *
602 * @param \Elgg\Hook $hook Hook
603 *
604 * @return PreparedMenu
605 *
606 * @internal
607 */
608function _elgg_setup_vertical_menu(\Elgg\Hook $hook) {
609	$menu = $hook->getValue();
610	/* @var $menu PreparedMenu */
611
612	$prepare = function(ElggMenuItem $menu_item) use (&$prepare) {
613		$child_menu_vars = $menu_item->getChildMenuOptions();
614		if (empty($child_menu_vars['display'])) {
615			$child_menu_vars['display'] = 'toggle';
616		}
617		$menu_item->setChildMenuOptions($child_menu_vars);
618
619		foreach ($menu_item->getChildren() as $child_menu_item) {
620			$prepare($child_menu_item);
621		}
622	};
623
624	foreach ($menu as $section => $menu_items) {
625		foreach ($menu_items as $menu_item) {
626			if ($menu_item instanceof ElggMenuItem) {
627				$prepare($menu_item);
628			}
629		}
630	}
631
632	$selected_item = $hook->getParam('selected_item');
633	if ($selected_item instanceof \ElggMenuItem) {
634		$parent = $selected_item->getParent();
635		while ($parent instanceof \ElggMenuItem) {
636			$parent->setSelected();
637			$parent->addItemClass('elgg-has-selected-child');
638			$parent = $parent->getParent();
639		}
640	}
641
642	return $menu;
643}
644
645/**
646 * Entity menu is list of links and info on any entity
647 *
648 * @param \Elgg\Hook $hook 'register', 'menu:entity'
649 *
650 * @return MenuItems
651 *
652 * @internal
653 */
654function _elgg_entity_menu_setup(\Elgg\Hook $hook) {
655	$entity = $hook->getEntityParam();
656	if (!($entity instanceof \ElggEntity) || $entity instanceof \ElggUser) {
657		// users mostly use the hover menu for their actions
658		return;
659	}
660
661	$handler = $hook->getParam('handler', false);
662	if ($handler) {
663		elgg_deprecated_notice("Using 'handler' in entity menu parameters is deprecated. Use named routes instead.", '3.0');
664
665		$edit_url = "$handler/edit/{$entity->guid}";
666
667		if (elgg_action_exists("$handler/delete")) {
668			$action = "$handler/delete";
669		} else {
670			$action = "entity/delete";
671		}
672		$delete_url = elgg_generate_action_url($action, [
673			'guid' => $entity->guid,
674		]);
675	} else {
676		$edit_url = elgg_generate_entity_url($entity, 'edit');
677		$delete_url = elgg_generate_action_url('entity/delete', [
678			'guid' => $entity->guid,
679		]);
680	}
681
682	$return = $hook->getValue();
683
684	if ($entity->canEdit() && $edit_url) {
685		$return[] = \ElggMenuItem::factory([
686			'name' => 'edit',
687			'icon' => 'edit',
688			'text' => elgg_echo('edit'),
689			'title' => elgg_echo('edit:this'),
690			'href' => $edit_url,
691			'priority' => 900,
692		]);
693	}
694
695	if ($entity->canDelete() && $delete_url) {
696		$return[] = \ElggMenuItem::factory([
697			'name' => 'delete',
698			'icon' => 'delete',
699			'text' => elgg_echo('delete'),
700			'title' => elgg_echo('delete:this'),
701			'href' => $delete_url,
702			'confirm' => elgg_echo('deleteconfirm'),
703			'priority' => 950,
704		]);
705	}
706
707	return $return;
708}
709
710/**
711 * Moves default menu items into a dropdown
712 *
713 * @tip    Pass 'dropdown' => false to entity menu options to render the menu inline without a dropdown
714 *
715 * @elgg_plugin_hook prepare menu:entity
716 * @elgg_plugin_hook prepare menu:river
717 *
718 * @param \Elgg\Hook $hook Hook
719 *
720 * @return void
721 *
722 * @internal
723 */
724function _elgg_menu_transform_to_dropdown(\Elgg\Hook $hook) {
725	$menu = $hook->getValue();
726	/* @var $menu PreparedMenu */
727
728	$is_dropdown = $hook->getParam('dropdown', true);
729	if ($is_dropdown === false) {
730		return;
731	}
732
733	$items = $menu->getItems('default');
734	if (empty($items)) {
735		return;
736	}
737
738	$menu->getSection('default')->fill([
739		\ElggMenuItem::factory([
740			'name' => 'entity-menu-toggle',
741			'icon' => 'ellipsis-v',
742			'href' => false,
743			'text' => '',
744			'child_menu' => [
745				'display' => 'dropdown',
746				'data-position' => json_encode([
747					'at' => 'right bottom',
748					'my' => 'right top',
749					'collision' => 'fit fit',
750				]),
751				'class' => "elgg-{$hook->getParam('name')}-dropdown-menu",
752			],
753			'children' => $items,
754		]),
755	]);
756}
757
758/**
759 * Entity navigation menu is previous/next link for an entity
760 *
761 * @elgg_plugin_hook register menu:entity_navigation
762 *
763 * @param \Elgg\Hook $hook Hook
764 *
765 * @return MenuItems
766 *
767 * @internal
768 */
769function _elgg_entity_navigation_menu_setup(\Elgg\Hook $hook) {
770	$entity = $hook->getEntityParam();
771	if (!$entity) {
772		return;
773	}
774
775	$return = $hook->getValue();
776	/* @var $return MenuItems */
777
778	$options = [
779		'type' => $entity->getType(),
780		'subtype' => $entity->getSubtype(),
781		'container_guid' => $entity->container_guid,
782		'limit' => 1,
783	];
784
785	$previous_options = $options;
786	$previous_options['wheres'] = [
787		function (\Elgg\Database\QueryBuilder $qb, $main_alias) use ($entity) {
788			return $qb->merge([
789				$qb->compare("{$main_alias}.time_created", '<', $entity->time_created, ELGG_VALUE_INTEGER),
790				$qb->merge([
791					$qb->compare("{$main_alias}.time_created", '=', $entity->time_created, ELGG_VALUE_INTEGER),
792					$qb->compare("{$main_alias}.guid", '<', $entity->guid, ELGG_VALUE_GUID),
793				], 'AND'),
794			], 'OR');
795		},
796	];
797	$previous_options['order_by'] = [
798		new \Elgg\Database\Clauses\OrderByClause('time_created', 'DESC'),
799		new \Elgg\Database\Clauses\OrderByClause('guid', 'DESC'),
800	];
801
802	$previous = elgg_get_entities($previous_options);
803	if ($previous) {
804		$previous = $previous[0];
805		$return[] = \ElggMenuItem::factory([
806			'name' => 'previous',
807			'text' => elgg_echo('previous'),
808			'entity' => $previous,
809			'href' => $previous->getUrl(),
810			'title' => $previous->getDisplayName(),
811			'icon' => 'angle-double-left',
812			'link_class' => 'elgg-button elgg-button-outline',
813			'priority' => 100,
814		]);
815	}
816
817	$next_options = $options;
818	$next_options['wheres'] = [
819		function (\Elgg\Database\QueryBuilder $qb, $main_alias) use ($entity) {
820			return $qb->merge([
821				$qb->compare("{$main_alias}.time_created", '>', $entity->time_created, ELGG_VALUE_INTEGER),
822				$qb->merge([
823					$qb->compare("{$main_alias}.time_created", '=', $entity->time_created, ELGG_VALUE_INTEGER),
824					$qb->compare("{$main_alias}.guid", '>', $entity->guid, ELGG_VALUE_GUID),
825				], 'AND'),
826			], 'OR');
827		},
828	];
829	$next_options['order_by'] = [
830		new \Elgg\Database\Clauses\OrderByClause('time_created', 'ASC'),
831		new \Elgg\Database\Clauses\OrderByClause('guid', 'ASC'),
832	];
833
834	$next = elgg_get_entities($next_options);
835	if ($next) {
836		$next = $next[0];
837		$return[] = \ElggMenuItem::factory([
838			'name' => 'next',
839			'text' => elgg_echo('next'),
840			'entity' => $next,
841			'href' => $next->getUrl(),
842			'title' => $next->getDisplayName(),
843			'icon_alt' => 'angle-double-right',
844			'link_class' => 'elgg-button elgg-button-outline',
845			'priority' => 800,
846		]);
847	}
848
849	return $return;
850}
851
852/**
853 * Widget menu is a set of widget controls
854 *
855 * @param \Elgg\Hook $hook 'register', 'menu:widget'
856 *
857 * @return MenuItems
858 *
859 * @internal
860 */
861function _elgg_widget_menu_setup(\Elgg\Hook $hook) {
862
863	$widget = $hook->getEntityParam();
864	if (!($widget instanceof \ElggWidget)) {
865		return;
866	}
867
868	$return = $hook->getValue();
869
870	if ($widget->canDelete()) {
871		$return[] = \ElggMenuItem::factory([
872			'name' => 'delete',
873			'text' => elgg_view_icon('delete-alt'),
874			'title' => elgg_echo('widget:delete', [$widget->getDisplayName()]),
875			'href' => "action/widgets/delete?widget_guid=$widget->guid",
876			'is_action' => true,
877			'link_class' => 'elgg-widget-delete-button',
878			'id' => "elgg-widget-delete-button-$widget->guid",
879			'data-elgg-widget-type' => $widget->handler,
880			'priority' => 900,
881		]);
882	}
883
884	$show_edit = $hook->getParam('show_edit', $widget->canEdit());
885	if ($show_edit) {
886		$return[] = \ElggMenuItem::factory([
887			'name' => 'settings',
888			'text' => elgg_view_icon('settings-alt'),
889			'title' => elgg_echo('widget:edit'),
890			'href' => "#widget-edit-$widget->guid",
891			'link_class' => "elgg-widget-edit-button",
892			'rel' => 'toggle',
893			'priority' => 800,
894		]);
895	}
896
897	return $return;
898}
899
900/**
901 * Add the register and forgot password links to login menu
902 *
903 * @param \Elgg\Hook $hook 'register', 'menu:login'
904 *
905 * @return MenuItems
906 *
907 * @internal
908 */
909function _elgg_login_menu_setup(\Elgg\Hook $hook) {
910	$return = $hook->getValue();
911
912	if (_elgg_config()->allow_registration) {
913		$return[] = \ElggMenuItem::factory([
914			'name' => 'register',
915			'href' => elgg_get_registration_url(),
916			'text' => elgg_echo('register'),
917			'link_class' => 'registration_link',
918		]);
919	}
920
921	$return[] = \ElggMenuItem::factory([
922		'name' => 'forgotpassword',
923		'href' => elgg_generate_url('account:password:reset'),
924		'text' => elgg_echo('user:password:lost'),
925		'link_class' => 'forgot_link',
926	]);
927
928	return $return;
929}
930
931/**
932 * Add the RSS link to the menu
933 *
934 * @param \Elgg\Hook $hook 'register', 'menu:footer'
935 *
936 * @return MenuItems
937 *
938 * @internal
939 */
940function _elgg_rss_menu_setup(\Elgg\Hook $hook) {
941
942	if (!elgg_is_logged_in()) {
943		return;
944	}
945
946	if (!_elgg_has_rss_link()) {
947		return;
948	}
949
950	$return = $hook->getValue();
951
952	$return[] = ElggMenuItem::factory([
953		'name' => 'rss',
954		'text' => elgg_echo('feed:rss'),
955		'icon' => 'rss',
956		'href' => elgg_http_add_url_query_elements(current_page_url(), [
957			'view' => 'rss',
958		]),
959		'title' => elgg_echo('feed:rss:title'),
960	]);
961
962	return $return;
963}
964
965/**
966 * Navigation initialization
967 *
968 * @return void
969 *
970 * @internal
971 */
972function _elgg_nav_init() {
973	elgg_register_plugin_hook_handler('prepare', 'breadcrumbs', 'elgg_prepare_breadcrumbs');
974
975	elgg_register_plugin_hook_handler('prepare', 'menu:site', '_elgg_site_menu_setup', 999);
976	elgg_register_plugin_hook_handler('register', 'menu:site', '_elgg_site_menu_init');
977
978	elgg_register_plugin_hook_handler('prepare', 'menu:page', '_elgg_setup_vertical_menu', 999);
979	elgg_register_plugin_hook_handler('prepare', 'menu:owner_block', '_elgg_setup_vertical_menu', 999);
980
981	elgg_register_plugin_hook_handler('prepare', 'menu:annotation', '_elgg_menu_transform_to_dropdown');
982	elgg_register_plugin_hook_handler('prepare', 'menu:entity', '_elgg_menu_transform_to_dropdown');
983	elgg_register_plugin_hook_handler('prepare', 'menu:relationship', '_elgg_menu_transform_to_dropdown');
984	elgg_register_plugin_hook_handler('prepare', 'menu:river', '_elgg_menu_transform_to_dropdown');
985	elgg_register_plugin_hook_handler('register', 'menu:entity', '_elgg_entity_menu_setup');
986	elgg_register_plugin_hook_handler('register', 'menu:widget', '_elgg_widget_menu_setup');
987	elgg_register_plugin_hook_handler('register', 'menu:login', '_elgg_login_menu_setup');
988	elgg_register_plugin_hook_handler('register', 'menu:footer', '_elgg_rss_menu_setup');
989	elgg_register_plugin_hook_handler('register', 'menu:entity_navigation', '_elgg_entity_navigation_menu_setup');
990
991	elgg_register_plugin_hook_handler('public_pages', 'walled_garden', '_elgg_nav_public_pages');
992
993	if (!_elgg_config()->remove_branding) {
994		elgg_register_menu_item('footer', \ElggMenuItem::factory([
995			'name' => 'powered',
996			'text' => elgg_echo("elgg:powered"),
997			'href' => 'http://elgg.org',
998			'title' => 'Elgg ' . elgg_get_version(true),
999			'section' => 'meta',
1000			'priority' => 600,
1001		]));
1002	}
1003
1004	elgg_register_ajax_view('navigation/menu/user_hover/contents');
1005
1006	// Using a view extension to ensure that themes that have replaced the item view
1007	// still load the required AMD modules
1008	elgg_extend_view('navigation/menu/elements/item', 'navigation/menu/elements/item_deps');
1009}
1010
1011/**
1012 * Extend public pages
1013 *
1014 * @param \Elgg\Hook $hook "public_pages", "walled_garden"
1015 *
1016 * @return string[]
1017 * @internal
1018 * @since 1.11.0
1019 */
1020function _elgg_nav_public_pages(\Elgg\Hook $hook) {
1021	$return_value = $hook->getValue();
1022
1023	$return_value[] = 'navigation/menu/user_hover/contents';
1024
1025	return $return_value;
1026}
1027
1028/**
1029 * @see \Elgg\Application::loadCore Do not do work here. Just register for events.
1030 */
1031return function(\Elgg\EventsService $events) {
1032	$events->registerHandler('init', 'system', '_elgg_nav_init');
1033};
1034