Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core\navigation\output;

use renderable;
use renderer_base;
use templatable;
use custom_menu;

/**
 * Primary navigation renderable
 *
 * This file combines primary nav, custom menu, lang menu and
 * usermenu into a standardized format for the frontend
 *
 * @package     core
 * @category    navigation
 * @copyright   2021 onwards Peter Dias
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class primary implements renderable, templatable {
    /** @var \moodle_page $page the moodle page that the navigation belongs to */
    private $page = null;

    /**
     * primary constructor.
     * @param \moodle_page $page
     */
    public function __construct($page) {
        $this->page = $page;
    }

    /**
     * Combine the various menus into a standardized output.
     *
     * @param renderer_base|null $output
     * @return array
     */
    public function export_for_template(?renderer_base $output = null): array {
        if (!$output) {
            $output = $this->page->get_renderer('core');
        }

< $menudata = (object) array_merge($this->get_primary_nav(), $this->get_custom_menu($output));
> $menudata = (object) $this->merge_primary_and_custom($this->get_primary_nav(), $this->get_custom_menu($output));
$moremenu = new \core\navigation\output\more_menu($menudata, 'navbar-nav', false);
< $mobileprimarynav = array_merge($this->get_primary_nav(), $this->get_custom_menu($output));
> $mobileprimarynav = $this->merge_primary_and_custom($this->get_primary_nav(), $this->get_custom_menu($output), true);
$languagemenu = new \core\output\language_menu($this->page); return [ 'mobileprimarynav' => $mobileprimarynav, 'moremenu' => $moremenu->export_for_template($output), 'lang' => !isloggedin() || isguestuser() ? $languagemenu->export_for_template($output) : [], 'user' => $this->get_user_menu($output), ]; } /** * Get the primary nav object and standardize the output *
> * @param \navigation_node|null $parent used for nested nodes, by default the primarynav node
* @return array */
< protected function get_primary_nav(): array {
> protected function get_primary_nav($parent = null): array { > if ($parent === null) { > $parent = $this->page->primarynav; > }
$nodes = [];
< foreach ($this->page->primarynav->children as $node) {
> foreach ($parent->children as $node) { > $children = $this->get_primary_nav($node); > $activechildren = array_filter($children, function($child) { > return !empty($child['isactive']); > }); > if ($node->preceedwithhr && count($nodes) && empty($nodes[count($nodes) - 1]['divider'])) { > $nodes[] = ['divider' => true]; > }
$nodes[] = [ 'title' => $node->get_title(), 'url' => $node->action(), 'text' => $node->text, 'icon' => $node->icon,
< 'isactive' => $node->isactive,
> 'isactive' => $node->isactive || !empty($activechildren),
'key' => $node->key,
> 'children' => $children, ]; > 'haschildren' => !empty($children) ? 1 : 0,
} return $nodes; } /** * Custom menu items reside on the same level as the original nodes. * Fetch and convert the nodes to a standardised array. * * @param renderer_base $output * @return array */ protected function get_custom_menu(renderer_base $output): array { global $CFG; // Early return if a custom menu does not exists. if (empty($CFG->custommenuitems)) { return []; } $custommenuitems = $CFG->custommenuitems; $currentlang = current_language(); $custommenunodes = custom_menu::convert_text_to_menu_nodes($custommenuitems, $currentlang); $nodes = []; foreach ($custommenunodes as $node) { $nodes[] = $node->export_for_template($output); } return $nodes;
> } } > > /** /** > * When defining custom menu items, the active flag is not obvserved correctly. Therefore, the merge of the primary * Get/Generate the user menu. > * and custom navigation must be handled a bit smarter. Change the "isactive" flag of the nodes (this may set by * > * default in the primary nav nodes but is entirely missing in the custom nav nodes). * This is leveraging the data from user_get_user_navigation_info and the logic in $OUTPUT->user_menu() > * Set the $expandedmenu argument to true when the menu for the mobile template is build. * > * * @param renderer_base $output > * @param array $primary * @return array > * @param array $custom */ > * @param bool $expandedmenu public function get_user_menu(renderer_base $output): array { > * @return array global $CFG, $USER, $PAGE; > */ require_once($CFG->dirroot . '/user/lib.php'); > protected function merge_primary_and_custom(array $primary, array $custom, bool $expandedmenu = false): array { > if (empty($custom)) { $usermenudata = []; > return $primary; // No custom nav, nothing to merge. $submenusdata = []; > } $info = user_get_user_navigation_info($USER, $PAGE); > // Remember the amount of primary nodes and whether we changed the active flag in the custom menu nodes. if (isset($info->unauthenticateduser)) { > $primarylen = count($primary); $info->unauthenticateduser['content'] = get_string($info->unauthenticateduser['content']); > $changed = false; $info->unauthenticateduser['url'] = get_login_url(); > foreach (array_keys($custom) as $i) { return (array) $info; > if (!$changed) { } > if ($this->flag_active_nodes($custom[$i], $expandedmenu)) { // Gather all the avatar data to be displayed in the user menu. > $changed = true; $usermenudata['avatardata'][] = [ > } 'content' => $info->metadata['useravatar'], > } 'classes' => 'current' > $primary[] = $custom[$i]; ]; > } $usermenudata['userfullname'] = $info->metadata['realuserfullname'] ?? $info->metadata['userfullname']; > // In case some custom node is active, mark all primary nav elements as inactive. > if ($changed) { // Logged in as someone else. > for ($i = 0; $i < $primarylen; $i++) { if ($info->metadata['asotheruser']) { > $primary[$i]['isactive'] = false; $usermenudata['avatardata'][] = [ > } 'content' => $info->metadata['realuseravatar'], > } 'classes' => 'realuser' > return $primary; ]; > } $usermenudata['metadata'][] = [ > 'content' => get_string('loggedinas', 'moodle', $info->metadata['userfullname']), > /** 'classes' => 'viewingas' > * Recursive checks if any of the children is active. If that's the case this node (the parent) is active as ]; > * well. If the node has no children, check if the node itself is active. Use pass by reference for the node } > * object because we actively change/set the "isactive" flag inside the method and this needs to be kept at the > * callers side. // Gather all the meta data to be displayed in the user menu. > * Set $expandedmenu to true, if the mobile menu is done, in this case the active flag gets the node that is $metadata = [ > * actually active, while the parent hierarchy of the active node gets the flag isopen. 'asotherrole' => [ > * 'value' => 'rolename', > * @param object $node 'class' => 'role role-##GENERATEDCLASS##', > * @param bool $expandedmenu ], > * @return bool 'userloginfail' => [ > */ 'value' => 'userloginfail', > protected function flag_active_nodes(object $node, bool $expandedmenu = false): bool { 'class' => 'loginfailures', > global $FULLME; ], > $active = false; 'asmnetuser' => [ > foreach (array_keys($node->children ?? []) as $c) { 'value' => 'mnetidprovidername', > if ($this->flag_active_nodes($node->children[$c], $expandedmenu)) { 'class' => 'mnet mnet-##GENERATEDCLASS##', > $active = true; ], > } ]; > } foreach ($metadata as $key => $value) { > // One of the children is active, so this node (the parent) is active as well. if (!empty($info->metadata[$key])) { > if ($active) { $content = $info->metadata[$value['value']] ?? ''; > if ($expandedmenu) { $generatedclass = strtolower(preg_replace('#[ ]+#', '-', trim($content))); > $node->isopen = true; $customclass = str_replace('##GENERATEDCLASS##', $generatedclass, ($value['class'] ?? '')); > } else { $usermenudata['metadata'][] = [ > $node->isactive = true; 'content' => $content, > } 'classes' => $customclass > return true; ]; > } } > } > // By default, the menu item node to check is not active. > $node->isactive = false; $modifiedarray = array_map(function($value) { > $value->divider = $value->itemtype == 'divider'; > // Check if the node url matches the called url. The node url may omit the trailing index.php, therefore check $value->link = $value->itemtype == 'link'; > // this as well. if (isset($value->pix) && !empty($value->pix)) { > if (empty($node->url)) { $value->pixicon = $value->pix; > // Current menu node has no url set, so it can't be active. unset($value->pix); > return false; } > } return $value; > $nodeurl = parse_url($node->url); }, $info->navitems); > $current = parse_url($FULLME ?? ''); > // Include the language menu as a submenu within the user menu. > $pathmatches = false; $languagemenu = new \core\output\language_menu($this->page); > $langmenu = $languagemenu->export_for_template($output); > // Exact match of the path of node and current url. if (!empty($langmenu)) { > $nodepath = $nodeurl['path'] ?? '/'; $languageitems = $langmenu['items']; > $currentpath = $current['path'] ?? '/'; // If there are available languages, generate the data for the the language selector submenu. > if ($nodepath === $currentpath) { if (!empty($languageitems)) { > $pathmatches = true; $langsubmenuid = uniqid(); > } // Generate the data for the link to language selector submenu. > // The current url may be trailed by a index.php, otherwise it's the same as the node path. $language = (object) [ > if (!$pathmatches && $nodepath . 'index.php' === $currentpath) { 'itemtype' => 'submenu-link', > $pathmatches = true; 'submenuid' => $langsubmenuid, > } 'title' => get_string('language'), > // No path did match, so the node can't be active. 'divider' => false, > if (!$pathmatches) { 'submenulink' => true, > return false; ]; > } > // We are here because the path matches, so now look at the query string. // Place the link before the 'Log out' menu item which is either the last item in the menu or > $nodequery = $nodeurl['query'] ?? ''; // second to last when 'Switch roles' is available. > $currentquery = $current['query'] ?? ''; $menuposition = count($modifiedarray) - 1; > // If the node has no query string defined, then the patch match is sufficient. if (has_capability('moodle/role:switchroles', $PAGE->context)) { > if (empty($nodeurl['query'])) { $menuposition = count($modifiedarray) - 2; > $node->isactive = true; } > return true; array_splice($modifiedarray, $menuposition, 0, [$language]); > } > // If the node contains a query string then also the current url must match this query. // Generate the data for the language selector submenu. > if ($nodequery === $currentquery) { $submenusdata[] = (object)[ > $node->isactive = true; 'id' => $langsubmenuid, > } 'title' => get_string('languageselector'), > return $node->isactive;
'items' => $languageitems, ]; } } // Add divider before the last item. $modifiedarray[count($modifiedarray) - 2]->divider = true; $usermenudata['items'] = $modifiedarray; $usermenudata['submenus'] = array_values($submenusdata); return $usermenudata; } }