Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  namespace core\navigation\views;
  18  
  19  use navigation_node;
  20  use url_select;
  21  use settings_navigation;
  22  
  23  /**
  24   * Class secondary_navigation_view.
  25   *
  26   * The secondary navigation view is a stripped down tweaked version of the
  27   * settings_navigation/navigation
  28   *
  29   * @package     core
  30   * @category    navigation
  31   * @copyright   2021 onwards Peter Dias
  32   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33   */
  34  class secondary extends view {
  35      /** @var string $headertitle The header for this particular menu*/
  36      public $headertitle;
  37  
  38      /** @var int The maximum limit of navigation nodes displayed in the secondary navigation */
  39      const MAX_DISPLAYED_NAV_NODES = 5;
  40  
  41      /** @var navigation_node The course overflow node. */
  42      protected $courseoverflownode = null;
  43  
  44      /** @var string The key of the node to set as selected in the course overflow menu, if explicitly set by a page. */
  45      protected $overflowselected = null;
  46  
  47      /**
  48       * Defines the default structure for the secondary nav in a course context.
  49       *
  50       * In a course context, we are curating nodes from the settingsnav and navigation objects.
  51       * The following mapping construct specifies which object we are fetching it from, the type of the node, the key
  52       * and in what order we want the node - defined as per the mockups.
  53       *
  54       * @return array
  55       */
  56      protected function get_default_course_mapping(): array {
  57          $nodes = [];
  58          $nodes['settings'] = [
  59              self::TYPE_CONTAINER => [
  60                  'coursereports' => 3,
  61                  'questionbank' => 4,
  62              ],
  63              self::TYPE_SETTING => [
  64                  'editsettings' => 0,
  65                  'review' => 1.1,
  66                  'manageinstances' => 1.2,
  67                  'groups' => 1.3,
  68                  'override' => 1.4,
  69                  'roles' => 1.5,
  70                  'permissions' => 1.6,
  71                  'otherusers' => 1.7,
  72                  'gradebooksetup' => 2.1,
  73                  'outcomes' => 2.2,
  74                  'coursecompletion' => 6,
  75                  'coursebadges' => 7.1,
  76                  'newbadge' => 7.2,
  77                  'filtermanagement' => 9,
  78                  'unenrolself' => 10,
  79                  'coursetags' => 11,
  80                  'download' => 12,
  81                  'contextlocking' => 13,
  82              ],
  83          ];
  84          $nodes['navigation'] = [
  85              self::TYPE_CONTAINER => [
  86                  'participants' => 1,
  87              ],
  88              self::TYPE_SETTING => [
  89                  'grades' => 2,
  90                  'badgesview' => 7,
  91                  'competencies' => 8,
  92              ],
  93              self::TYPE_CUSTOM => [
  94                  'contentbank' => 5,
  95                  'participants' => 1, // In site home, 'participants' is classified differently.
  96              ],
  97          ];
  98  
  99          return $nodes;
 100      }
 101  
 102      /**
 103       * Defines the default structure for the secondary nav in a module context.
 104       *
 105       * In a module context, we are curating nodes from the settingsnav object.
 106       * The following mapping construct specifies the type of the node, the key
 107       * and in what order we want the node - defined as per the mockups.
 108       *
 109       * @return array
 110       */
 111      protected function get_default_module_mapping(): array {
 112          return [
 113              self::TYPE_SETTING => [
 114                  'modedit' => 1,
 115                  "mod_{$this->page->activityname}_useroverrides" => 3, // Overrides are module specific.
 116                  "mod_{$this->page->activityname}_groupoverrides" => 4,
 117                  'roleassign' => 7.2,
 118                  'filtermanage' => 6,
 119                  'roleoverride' => 7,
 120                  'rolecheck' => 7.1,
 121                  'logreport' => 8,
 122                  'backup' => 9,
 123                  'restore' => 10,
 124                  'competencybreakdown' => 11,
 125              ],
 126              self::TYPE_CUSTOM => [
 127                  'advgrading' => 2,
 128                  'contentbank' => 12,
 129              ],
 130          ];
 131      }
 132  
 133      /**
 134       * Defines the default structure for the secondary nav in a category context.
 135       *
 136       * In a category context, we are curating nodes from the settingsnav object.
 137       * The following mapping construct specifies the type of the node, the key
 138       * and in what order we want the node - defined as per the mockups.
 139       *
 140       * @return array
 141       */
 142      protected function get_default_category_mapping(): array {
 143          return [
 144              self::TYPE_SETTING => [
 145                  'edit' => 1,
 146                  'permissions' => 2,
 147                  'roles' => 2.1,
 148                  'rolecheck' => 2.2,
 149              ]
 150          ];
 151      }
 152  
 153      /**
 154       * Define the keys of the course secondary nav nodes that should be forced into the "more" menu by default.
 155       *
 156       * @return array
 157       */
 158      protected function get_default_category_more_menu_nodes(): array {
 159          return ['addsubcat', 'roles', 'permissions', 'contentbank', 'cohort', 'filters', 'restorecourse'];
 160      }
 161      /**
 162       * Define the keys of the course secondary nav nodes that should be forced into the "more" menu by default.
 163       *
 164       * @return array
 165       */
 166      protected function get_default_course_more_menu_nodes(): array {
 167          return [];
 168      }
 169  
 170      /**
 171       * Define the keys of the module secondary nav nodes that should be forced into the "more" menu by default.
 172       *
 173       * @return array
 174       */
 175      protected function get_default_module_more_menu_nodes(): array {
 176          return ['roleoverride', 'rolecheck', 'logreport', 'roleassign', 'filtermanage', 'backup', 'restore',
 177              'competencybreakdown', "mod_{$this->page->activityname}_useroverrides",
 178              "mod_{$this->page->activityname}_groupoverrides"];
 179      }
 180  
 181      /**
 182       * Define the keys of the admin secondary nav nodes that should be forced into the "more" menu by default.
 183       *
 184       * @return array
 185       */
 186      protected function get_default_admin_more_menu_nodes(): array {
 187          return [];
 188      }
 189  
 190      /**
 191       * Initialise the view based navigation based on the current context.
 192       *
 193       * As part of the initial restructure, the secondary nav is only considered for the following pages:
 194       * 1 - Site admin settings
 195       * 2 - Course page - Does not include front_page which has the same context.
 196       * 3 - Module page
 197       */
 198      public function initialise(): void {
 199          global $SITE;
 200  
 201          if (during_initial_install() || $this->initialised) {
 202              return;
 203          }
 204          $this->id = 'secondary_navigation';
 205          $context = $this->context;
 206          $this->headertitle = get_string('menu');
 207          $defaultmoremenunodes = [];
 208          $maxdisplayednodes = self::MAX_DISPLAYED_NAV_NODES;
 209  
 210          switch ($context->contextlevel) {
 211              case CONTEXT_COURSE:
 212                  $this->headertitle = get_string('courseheader');
 213                  if ($this->page->course->format === 'singleactivity') {
 214                      $this->load_single_activity_course_navigation();
 215                  } else {
 216                      $this->load_course_navigation();
 217                      $defaultmoremenunodes = $this->get_default_course_more_menu_nodes();
 218                  }
 219                  break;
 220              case CONTEXT_MODULE:
 221                  $this->headertitle = get_string('activityheader');
 222                  if ($this->page->course->format === 'singleactivity') {
 223                      $this->load_single_activity_course_navigation();
 224                  } else {
 225                      $this->load_module_navigation($this->page->settingsnav);
 226                      $defaultmoremenunodes = $this->get_default_module_more_menu_nodes();
 227                  }
 228                  break;
 229              case CONTEXT_COURSECAT:
 230                  $this->headertitle = get_string('categoryheader');
 231                  $this->load_category_navigation();
 232                  $defaultmoremenunodes = $this->get_default_category_more_menu_nodes();
 233                  break;
 234              case CONTEXT_SYSTEM:
 235                  $this->headertitle = get_string('homeheader');
 236                  $this->load_admin_navigation();
 237                  // If the site administration navigation was generated after load_admin_navigation().
 238                  if ($this->has_children()) {
 239                      // Do not explicitly limit the number of navigation nodes displayed in the site administration
 240                      // navigation menu.
 241                      $maxdisplayednodes = null;
 242                  }
 243                  $defaultmoremenunodes = $this->get_default_admin_more_menu_nodes();
 244                  break;
 245          }
 246  
 247          $this->remove_unwanted_nodes($this);
 248  
 249          // Don't need to show anything if only the view node is available. Remove it.
 250          if ($this->children->count() == 1) {
 251              $this->children->remove('modulepage');
 252          }
 253          // Force certain navigation nodes to be displayed in the "more" menu.
 254          $this->force_nodes_into_more_menu($defaultmoremenunodes, $maxdisplayednodes);
 255          // Search and set the active node.
 256          $this->scan_for_active_node($this);
 257          $this->initialised = true;
 258      }
 259  
 260      /**
 261       * Returns a node with the action being from the first found child node that has an action (Recursive).
 262       *
 263       * @param navigation_node $node The part of the node tree we are checking.
 264       * @param navigation_node $basenode  The very first node to be used for the return.
 265       * @return navigation_node|null
 266       */
 267      protected function get_node_with_first_action(navigation_node $node, navigation_node $basenode): ?navigation_node {
 268          $newnode = null;
 269          if (!$node->has_children()) {
 270              return null;
 271          }
 272  
 273          // Find the first child with an action and update the main node.
 274          foreach ($node->children as $child) {
 275              if ($child->has_action()) {
 276                  $newnode = $basenode;
 277                  $newnode->action = $child->action;
 278                  return $newnode;
 279              }
 280          }
 281          if (is_null($newnode)) {
 282              // Check for children and go again.
 283              foreach ($node->children as $child) {
 284                  if ($child->has_children()) {
 285                      $newnode = $this->get_node_with_first_action($child, $basenode);
 286  
 287                      if (!is_null($newnode)) {
 288                          return $newnode;
 289                      }
 290                  }
 291              }
 292          }
 293          return null;
 294      }
 295  
 296      /**
 297       * Some nodes are containers only with no action. If this container has an action then nothing is done. If it does not have
 298       * an action then a search is done through the children looking for the first node that has an action. This action is then given
 299       * to the parent node that is initially provided as a parameter.
 300       *
 301       * @param navigation_node $node The navigation node that we want to ensure has an action tied to it.
 302       * @return navigation_node The node intact with an action to use.
 303       */
 304      protected function get_first_action_for_node(navigation_node $node): ?navigation_node {
 305          // If the node does not have children and has no action then no further processing is needed.
 306          $newnode = null;
 307          if ($node->has_children() && !$node->has_action()) {
 308              // We want to find the first child with an action.
 309              // We want to check all children on this level before going further down.
 310              // Note that new node gets changed here.
 311              $newnode = $this->get_node_with_first_action($node, $node);
 312          } else if ($node->has_action()) {
 313              $newnode = $node;
 314          }
 315          return $newnode;
 316      }
 317  
 318      /**
 319       * Recursive call to add all custom navigation nodes to secondary
 320       *
 321       * @param navigation_node $node The node which should be added to secondary
 322       * @param navigation_node $basenode The original parent node
 323       * @param navigation_node|null $root The parent node nodes are to be added/removed to.
 324       * @param bool $forceadd Whether or not to bypass the external action check and force add all nodes
 325       */
 326      protected function add_external_nodes_to_secondary(navigation_node $node, navigation_node $basenode,
 327             ?navigation_node $root = null, bool $forceadd = false) {
 328          $root = $root ?? $this;
 329          // Add the first node.
 330          if ($node->has_action() && !$this->get($node->key)) {
 331              $root->add_node(clone $node);
 332          }
 333  
 334          // If the node has an external action add all children to the secondary navigation.
 335          if (!$node->has_internal_action() || $forceadd) {
 336              if ($node->has_children()) {
 337                  foreach ($node->children as $child) {
 338                      if ($child->has_children()) {
 339                          $this->add_external_nodes_to_secondary($child, $basenode, $root, true);
 340                      } else if ($child->has_action() && !$this->get($child->key)) {
 341                          // Check whether the basenode matches a child's url.
 342                          // This would have happened in get_first_action_for_node.
 343                          // In these cases, we prefer the specific child content.
 344                          if ($basenode->has_action() && $basenode->action()->compare($child->action())) {
 345                              $root->children->remove($basenode->key, $basenode->type);
 346                          }
 347                          $root->add_node(clone $child);
 348                      }
 349                  }
 350              }
 351          }
 352      }
 353  
 354      /**
 355       * Returns a list of all expected nodes in the course administration.
 356       *
 357       * @return array An array of keys for navigation nodes in the course administration.
 358       */
 359      protected function get_expected_course_admin_nodes(): array {
 360          $expectednodes = [];
 361          foreach ($this->get_default_course_mapping()['settings'] as $value) {
 362              foreach ($value as $nodekey => $notused) {
 363                  $expectednodes[] = $nodekey;
 364              }
 365          }
 366          foreach ($this->get_default_course_mapping()['navigation'] as $value) {
 367              foreach ($value as $nodekey => $notused) {
 368                  $expectednodes[] = $nodekey;
 369              }
 370          }
 371          $othernodes = ['users', 'gradeadmin', 'coursereports', 'coursebadges'];
 372          $leftovercourseadminnodes = ['backup', 'restore', 'import', 'copy', 'reset'];
 373          $expectednodes = array_merge($expectednodes, $othernodes);
 374          $expectednodes = array_merge($expectednodes, $leftovercourseadminnodes);
 375          return $expectednodes;
 376      }
 377  
 378      /**
 379       * Load the course secondary navigation. Since we are sourcing all the info from existing objects that already do
 380       * the relevant checks, we don't do it again here.
 381       *
 382       * @param navigation_node|null $rootnode The node where the course navigation nodes should be added into as children.
 383       *                                       If not explicitly defined, the nodes will be added to the secondary root
 384       *                                       node by default.
 385       */
 386      protected function load_course_navigation(?navigation_node $rootnode = null): void {
 387          global $SITE;
 388  
 389          $rootnode = $rootnode ?? $this;
 390          $course = $this->page->course;
 391          // Initialise the main navigation and settings nav.
 392          // It is important that this is done before we try anything.
 393          $settingsnav = $this->page->settingsnav;
 394          $navigation = $this->page->navigation;
 395  
 396          if ($course->id == $SITE->id) {
 397              $firstnodeidentifier = get_string('home'); // The first node in the site course nav is called 'Home'.
 398              $frontpage = $settingsnav->get('frontpage'); // The site course nodes are children of a dedicated 'frontpage' node.
 399              $settingsnav = $frontpage ?: $settingsnav;
 400              $courseadminnode = $frontpage ?: null; // Custom nodes for the site course are also children of the 'frontpage' node.
 401          } else {
 402              $firstnodeidentifier = get_string('course'); // Regular courses have a first node called 'Course'.
 403              $courseadminnode = $settingsnav->get('courseadmin'); // Custom nodes for regular courses live under 'courseadmin'.
 404          }
 405  
 406          // Add the known nodes from settings and navigation.
 407          $nodes = $this->get_default_course_mapping();
 408          $nodesordered = $this->get_leaf_nodes($settingsnav, $nodes['settings'] ?? []);
 409          $nodesordered += $this->get_leaf_nodes($navigation, $nodes['navigation'] ?? []);
 410          $this->add_ordered_nodes($nodesordered, $rootnode);
 411  
 412          // Try to get any custom nodes defined by plugins, which may include containers.
 413          if ($courseadminnode) {
 414              $expectedcourseadmin = $this->get_expected_course_admin_nodes();
 415              foreach ($courseadminnode->children as $other) {
 416                  if (array_search($other->key, $expectedcourseadmin, true) === false) {
 417                      $othernode = $this->get_first_action_for_node($other);
 418                      $recursivenode = $othernode && !$rootnode->get($othernode->key) ? $othernode : $other;
 419                      // Get the first node and check whether it's been added already.
 420                      // Also check if the first node is an external link. If it is, add all children.
 421                      $this->add_external_nodes_to_secondary($recursivenode, $recursivenode, $rootnode);
 422                  }
 423              }
 424          }
 425  
 426          // Move some nodes into a 'course reuse' node.
 427          $overflownode = $this->get_course_overflow_nodes($rootnode);
 428          if (!is_null($overflownode)) {
 429              $actionnode = $this->get_first_action_for_node($overflownode);
 430              if ($actionnode) {
 431                  // All additional nodes will be available under the 'Course reuse' page.
 432                  $text = get_string('coursereuse');
 433                  $rootnode->add($text, $actionnode->action, navigation_node::TYPE_COURSE, null, 'coursereuse',
 434                      new \pix_icon('t/edit', $text));
 435              }
 436          }
 437  
 438          // Add the respective first node, provided there are other nodes included.
 439          if (!empty($nodekeys = $rootnode->children->get_key_list())) {
 440              $rootnode->add_node(
 441                  navigation_node::create($firstnodeidentifier, new \moodle_url('/course/view.php', ['id' => $course->id]),
 442                      self::TYPE_COURSE, null, 'coursehome'), reset($nodekeys)
 443              );
 444          }
 445      }
 446  
 447      /**
 448       * Gets the overflow navigation nodes for the course administration category.
 449       *
 450       * @param navigation_node|null $rootnode The node from where the course overflow nodes should be obtained.
 451       *                                       If not explicitly defined, the nodes will be obtained from the secondary root
 452       *                                       node by default.
 453       * @return navigation_node  The course overflow nodes.
 454       */
 455      protected function get_course_overflow_nodes(?navigation_node $rootnode = null): ?navigation_node {
 456          global $SITE;
 457  
 458          $rootnode = $rootnode ?? $this;
 459          // This gets called twice on some pages, and so trying to create this navigation node twice results in no children being
 460          // present the second time this is called.
 461          if (isset($this->courseoverflownode)) {
 462              return $this->courseoverflownode;
 463          }
 464  
 465          // Start with getting the base node for the front page or the course.
 466          $node = null;
 467          if ($this->page->course->id == $SITE->id) {
 468              $node = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
 469          } else {
 470              $node = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
 471          }
 472          $coursesettings = $node ? $node->get_children_key_list() : [];
 473          $thissettings = $rootnode->get_children_key_list();
 474          $diff = array_diff($coursesettings, $thissettings);
 475  
 476          // Remove our specific created elements (user - participants, badges - coursebadges, grades - gradebooksetup,
 477          // grades - outcomes).
 478          $shortdiff = array_filter($diff, function($value) {
 479              return !($value == 'users' || $value == 'coursebadges' || $value == 'gradebooksetup' ||
 480                  $value == 'outcomes');
 481          });
 482  
 483          // Permissions may be in play here that ultimately will show no overflow.
 484          if (empty($shortdiff)) {
 485              return null;
 486          }
 487  
 488          $firstitem = array_shift($shortdiff);
 489          $navnode = $node->get($firstitem);
 490          foreach ($shortdiff as $key) {
 491              $courseadminnodes = $node->get($key);
 492              if ($courseadminnodes) {
 493                  if ($courseadminnodes->parent->key == $node->key) {
 494                      $navnode->add_node($courseadminnodes);
 495                  }
 496              }
 497          }
 498          $this->courseoverflownode = $navnode;
 499          return $navnode;
 500  
 501      }
 502  
 503      /**
 504       * Recursively looks for a match to the current page url.
 505       *
 506       * @param navigation_node $node The node to look through.
 507       * @return navigation_node|null The node that matches this page's url.
 508       */
 509      protected function nodes_match_current_url(navigation_node $node): ?navigation_node {
 510          $pagenode = $this->page->url;
 511          if ($node->has_action()) {
 512              // Check this node first.
 513              if ($node->action->compare($pagenode)) {
 514                  return $node;
 515              }
 516          }
 517          if ($node->has_children()) {
 518              foreach ($node->children as $child) {
 519                  $result = $this->nodes_match_current_url($child);
 520                  if ($result) {
 521                      return $result;
 522                  }
 523              }
 524          }
 525          return null;
 526      }
 527  
 528      /**
 529       * Recursively search a node and its children for a node matching the key string $key.
 530       *
 531       * @param navigation_node $node the navigation node to check.
 532       * @param string $key the key of the node to match.
 533       * @return navigation_node|null node if found, otherwise null.
 534       */
 535      protected function node_matches_key_string(navigation_node $node, string $key): ?navigation_node {
 536          if ($node->has_action()) {
 537              // Check this node first.
 538              if ($node->key == $key) {
 539                  return $node;
 540              }
 541          }
 542          if ($node->has_children()) {
 543              foreach ($node->children as $child) {
 544                  $result = $this->node_matches_key_string($child, $key);
 545                  if ($result) {
 546                      return $result;
 547                  }
 548              }
 549          }
 550          return null;
 551      }
 552  
 553      /**
 554       * Force a specific node in the 'coursereuse' course overflow to be selected, based on the provided node key.
 555       *
 556       * Normally, the selected node is determined by matching the page URL to the node URL. E.g. The page 'backup/restorefile.php'
 557       * will match the "Restore" node which has a registered URL of 'backup/restorefile.php' because the URLs match.
 558       *
 559       * This method allows a page to choose a specific node to match, which is useful in cases where the page knows its URL won't
 560       * match the node it needs to reside under. I.e. this permits several pages to 'share' the same overflow node. When the page
 561       * knows the PAGE->url won't match the node URL, the page can simply say "I want to match the 'XXX' node".
 562       *
 563       * E.g.
 564       * - The $PAGE->url is 'backup/restore.php' (this page is used during restores but isn't the main landing page for a restore)
 565       * - The 'Restore' node in the overflow has a key of 'restore' and will only match 'backup/restorefile.php' by default (the
 566       * main restore landing page).
 567       * - The backup/restore.php page calls:
 568       * $PAGE->secondarynav->set_overflow_selected_node(new moodle_url('restore');
 569       * and when the page is loaded, the 'Restore' node be presented as the selected node.
 570       *
 571       * @param string $nodekey The string key of the overflow node to match.
 572       */
 573      public function set_overflow_selected_node(string $nodekey): void {
 574          $this->overflowselected = $nodekey;
 575      }
 576  
 577      /**
 578       * Returns a url_select object with overflow navigation nodes.
 579       * This looks to see if the current page is within the course administration, or some other page that requires an overflow
 580       * select object.
 581       *
 582       * @return url_select|null The overflow menu data.
 583       */
 584      public function get_overflow_menu_data(): ?url_select {
 585  
 586          if (!$this->page->get_navigation_overflow_state()) {
 587              return null;
 588          }
 589  
 590          $issingleactivitycourse = $this->page->course->format === 'singleactivity';
 591          $rootnode = $issingleactivitycourse ? $this->find('course', self::TYPE_COURSE) : $this;
 592          $activenode = $this->find_active_node();
 593          $incourseadmin = false;
 594  
 595          if (!$activenode || ($issingleactivitycourse && $activenode->key === 'course')) {
 596              // Could be in the course admin section.
 597              $courseadmin = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
 598              if (!$courseadmin) {
 599                  return null;
 600              }
 601  
 602              $activenode = $courseadmin->find_active_node();
 603              if (!$activenode) {
 604                  return null;
 605              }
 606              $incourseadmin = true;
 607          }
 608  
 609          if ($activenode->key === 'coursereuse' || $incourseadmin) {
 610              $courseoverflownode = $this->get_course_overflow_nodes($rootnode);
 611              if (is_null($courseoverflownode)) {
 612                  return null;
 613              }
 614              if ($incourseadmin) {
 615                  // Validate whether the active node is part of the expected course overflow nodes.
 616                  if (($activenode->key !== $courseoverflownode->key) &&
 617                      !$courseoverflownode->find($activenode->key, $activenode->type)) {
 618                      return null;
 619                  }
 620              }
 621              $menuarray = static::create_menu_element([$courseoverflownode]);
 622              if ($activenode->key != 'coursereuse') {
 623                  $inmenu = false;
 624                  foreach ($menuarray as $key => $value) {
 625                      if ($this->page->url->out(false) == $key) {
 626                          $inmenu = true;
 627                      }
 628                  }
 629                  if (!$inmenu) {
 630                      return null;
 631                  }
 632              }
 633              // If the page has explicitly set the overflow node it would like selected, find and use that node.
 634              if ($this->overflowselected) {
 635                  $selectedoverflownode = $this->node_matches_key_string($courseoverflownode, $this->overflowselected);
 636                  $selectedoverflownodeurl = $selectedoverflownode ? $selectedoverflownode->action->out(false) : null;
 637              }
 638  
 639              $menuselect = new url_select($menuarray, $selectedoverflownodeurl ?? $this->page->url, null);
 640              $menuselect->set_label(get_string('browsecourseadminindex', 'course'), ['class' => 'sr-only']);
 641              return $menuselect;
 642          } else {
 643              return $this->get_other_overflow_menu_data($activenode);
 644          }
 645      }
 646  
 647      /**
 648       * Gets overflow menu data for third party plugin settings.
 649       *
 650       * @param navigation_node $activenode The node to gather the children for to put into the overflow menu.
 651       * @return url_select|null The overflow menu in a url_select object.
 652       */
 653      protected function get_other_overflow_menu_data(navigation_node $activenode): ?url_select {
 654          if (!$activenode->has_action()) {
 655              return null;
 656          }
 657  
 658          if (!$activenode->has_children()) {
 659              return null;
 660          }
 661  
 662          // If the setting is extending the course navigation then the page being redirected to should be in the course context.
 663          // It was decided on the issue that put this code here that plugins that extend the course navigation should have the pages
 664          // that are redirected to, be in the course context or module context depending on which callback was used.
 665          // Third part plugins were checked to see if any existing plugins had settings in a system context and none were found.
 666          // The request of third party developers is to keep their settings within the specified context.
 667          if ($this->page->context->contextlevel != CONTEXT_COURSE
 668                  && $this->page->context->contextlevel != CONTEXT_MODULE
 669                  && $this->page->context->contextlevel != CONTEXT_COURSECAT) {
 670              return null;
 671          }
 672  
 673          // These areas have their own code to retrieve added plugin navigation nodes.
 674          if ($activenode->key == 'coursehome' || $activenode->key == 'questionbank' || $activenode->key == 'coursereports') {
 675              return null;
 676          }
 677  
 678          $menunode = $this->page->settingsnav->find($activenode->key, null);
 679  
 680          if (!$menunode instanceof navigation_node) {
 681              return null;
 682          }
 683          // Loop through all children and try and find a match to the current url.
 684          $matchednode = $this->nodes_match_current_url($menunode);
 685          if (is_null($matchednode)) {
 686              return null;
 687          }
 688          if (!isset($menunode) || !$menunode->has_children()) {
 689              return null;
 690          }
 691          $selectdata = static::create_menu_element([$menunode], false);
 692          $urlselect = new url_select($selectdata, $matchednode->action->out(false), null);
 693          $urlselect->set_label(get_string('browsesettingindex', 'course'), ['class' => 'sr-only']);
 694          return $urlselect;
 695      }
 696  
 697      /**
 698       * Get the module's secondary navigation. This is based on settings_nav and would include plugin nodes added via
 699       * '_extend_settings_navigation'.
 700       * It populates the tree based on the nav mockup
 701       *
 702       * If nodes change, we will have to explicitly call the callback again.
 703       *
 704       * @param settings_navigation $settingsnav The settings navigation object related to the module page
 705       * @param navigation_node|null $rootnode The node where the module navigation nodes should be added into as children.
 706       *                                       If not explicitly defined, the nodes will be added to the secondary root
 707       *                                       node by default.
 708       */
 709      protected function load_module_navigation(settings_navigation $settingsnav, ?navigation_node $rootnode = null): void {
 710          $rootnode = $rootnode ?? $this;
 711          $mainnode = $settingsnav->find('modulesettings', self::TYPE_SETTING);
 712          $nodes = $this->get_default_module_mapping();
 713  
 714          if ($mainnode) {
 715              $url = new \moodle_url('/mod/' . $settingsnav->get_page()->activityname . '/view.php',
 716                  ['id' => $settingsnav->get_page()->cm->id]);
 717              $setactive = $url->compare($settingsnav->get_page()->url, URL_MATCH_BASE);
 718              $node = $rootnode->add(get_string('modulename', $settingsnav->get_page()->activityname), $url,
 719                  null, null, 'modulepage');
 720              if ($setactive) {
 721                  $node->make_active();
 722              }
 723              // Add the initial nodes.
 724              $nodesordered = $this->get_leaf_nodes($mainnode, $nodes);
 725              $this->add_ordered_nodes($nodesordered, $rootnode);
 726  
 727              // We have finished inserting the initial structure.
 728              // Populate the menu with the rest of the nodes available.
 729              $this->load_remaining_nodes($mainnode, $nodes, $rootnode);
 730          }
 731      }
 732  
 733      /**
 734       * Load the course category navigation.
 735       */
 736      protected function load_category_navigation(): void {
 737          $settingsnav = $this->page->settingsnav;
 738          $mainnode = $settingsnav->find('categorysettings', self::TYPE_CONTAINER);
 739          $nodes = $this->get_default_category_mapping();
 740  
 741          if ($mainnode) {
 742              $url = new \moodle_url('/course/index.php', ['categoryid' => $this->context->instanceid]);
 743              $this->add(get_string('category'), $url, self::TYPE_CONTAINER, null, 'categorymain');
 744  
 745              // Add the initial nodes.
 746              $nodesordered = $this->get_leaf_nodes($mainnode, $nodes);
 747              $this->add_ordered_nodes($nodesordered);
 748  
 749              // We have finished inserting the initial structure.
 750              // Populate the menu with the rest of the nodes available.
 751              $this->load_remaining_nodes($mainnode, $nodes);
 752          }
 753      }
 754  
 755      /**
 756       * Load the site admin navigation
 757       */
 758      protected function load_admin_navigation(): void {
 759          global $PAGE, $SITE;
 760  
 761          $settingsnav = $this->page->settingsnav;
 762          $node = $settingsnav->find('root', self::TYPE_SITE_ADMIN);
 763          // We need to know if we are on the main site admin search page. Here the navigation between tabs are done via
 764          // anchors and page reload doesn't happen. On every nested admin settings page, the secondary nav needs to
 765          // exist as links with anchors appended in order to redirect back to the admin search page and the corresponding
 766          // tab. Note this value refers to being present on the page itself, before a search has been performed.
 767          $isadminsearchpage = $PAGE->url->compare(new \moodle_url('/admin/search.php', ['query' => '']), URL_MATCH_PARAMS);
 768          if ($node) {
 769              $siteadminnode = $this->add(get_string('general'), "#link$node->key", null, null, 'siteadminnode');
 770              if ($isadminsearchpage) {
 771                  $siteadminnode->action = false;
 772                  $siteadminnode->tab = "#link$node->key";
 773              } else {
 774                  $siteadminnode->action = new \moodle_url("/admin/search.php", [], "link$node->key");
 775              }
 776              foreach ($node->children as $child) {
 777                  if ($child->display && !$child->is_short_branch()) {
 778                      // Mimic the current boost behaviour and pass down anchors for the tabs.
 779                      if ($isadminsearchpage) {
 780                          $child->action = false;
 781                          $child->tab = "#link$child->key";
 782                      } else {
 783                          $child->action = new \moodle_url("/admin/search.php", [], "link$child->key");
 784                      }
 785                      $this->add_node(clone $child);
 786                  } else {
 787                      $siteadminnode->add_node(clone $child);
 788                  }
 789              }
 790          }
 791      }
 792  
 793      /**
 794       * Adds the indexed nodes to the current view or a given node. The key should indicate it's position in the tree.
 795       * Any sub nodes needs to be numbered appropriately, e.g. 3.1 would make the identified node be listed  under #3 node.
 796       *
 797       * @param array $nodes An array of navigation nodes to be added.
 798       * @param navigation_node|null $rootnode The node where the nodes should be added into as children. If not explicitly
 799       *                                       defined, the nodes will be added to the secondary root node by default.
 800       */
 801      protected function add_ordered_nodes(array $nodes, ?navigation_node $rootnode = null): void {
 802          $rootnode = $rootnode ?? $this;
 803          ksort($nodes);
 804          foreach ($nodes as $key => $node) {
 805              // If the key is a string then we are assuming this is a nested element.
 806              if (is_string($key)) {
 807                  $parentnode = $nodes[floor($key)] ?? null;
 808                  if ($parentnode) {
 809                      $parentnode->add_node(clone $node);
 810                  }
 811              } else {
 812                  $rootnode->add_node(clone $node);
 813              }
 814          }
 815      }
 816  
 817      /**
 818       * Find the remaining nodes that need to be loaded into secondary based on the current context or a given node.
 819       *
 820       * @param navigation_node $completenode The original node that we are sourcing information from
 821       * @param array           $nodesmap The map used to populate secondary nav in the given context
 822       * @param navigation_node|null $rootnode The node where the remaining nodes should be added into as children. If not
 823       *                                       explicitly defined, the nodes will be added to the secondary root node by
 824       *                                       default.
 825       */
 826      protected function load_remaining_nodes(navigation_node $completenode, array $nodesmap,
 827              ?navigation_node $rootnode = null): void {
 828          $flattenednodes = [];
 829          $rootnode = $rootnode ?? $this;
 830          foreach ($nodesmap as $nodecontainer) {
 831              $flattenednodes = array_merge(array_keys($nodecontainer), $flattenednodes);
 832          }
 833  
 834          $populatedkeys = $this->get_children_key_list();
 835          $existingkeys = $completenode->get_children_key_list();
 836          $leftover = array_diff($existingkeys, $populatedkeys);
 837          foreach ($leftover as $key) {
 838              if (!in_array($key, $flattenednodes, true) && $leftovernode = $completenode->get($key)) {
 839                  // Check for nodes with children and potentially no action to direct to.
 840                  if ($leftovernode->has_children()) {
 841                      $leftovernode = $this->get_first_action_for_node($leftovernode);
 842                  }
 843  
 844                  // We have found the first node with an action.
 845                  if ($leftovernode) {
 846                      $this->add_external_nodes_to_secondary($leftovernode, $leftovernode, $rootnode);
 847                  }
 848              }
 849          }
 850      }
 851  
 852      /**
 853       * Force certain secondary navigation nodes to be displayed in the "more" menu.
 854       *
 855       * @param array $defaultmoremenunodes Array with navigation node keys of the pre-defined nodes that
 856       *                                    should be added into the "more" menu by default
 857       * @param int|null $maxdisplayednodes The maximum limit of navigation nodes displayed in the secondary navigation
 858       */
 859      protected function force_nodes_into_more_menu(array $defaultmoremenunodes = [], ?int $maxdisplayednodes = null) {
 860          // Counter of the navigation nodes that are initially displayed in the secondary nav
 861          // (excludes the nodes from the "more" menu).
 862          $displayednodescount = 0;
 863          foreach ($this->children as $child) {
 864              // Skip if the navigation node has been already forced into the "more" menu.
 865              if ($child->forceintomoremenu) {
 866                  continue;
 867              }
 868              // If the navigation node is in the pre-defined list of nodes that should be added by default in the
 869              // "more" menu or the maximum limit of displayed navigation nodes has been reached (if defined).
 870              if (in_array($child->key, $defaultmoremenunodes) ||
 871                      (!is_null($maxdisplayednodes) && $displayednodescount >= $maxdisplayednodes)) {
 872                  // Force the node and its children into the "more" menu.
 873                  $child->set_force_into_more_menu(true);
 874                  continue;
 875              }
 876              $displayednodescount++;
 877          }
 878      }
 879  
 880      /**
 881       * Recursively remove navigation nodes that should not be displayed in the secondary navigation.
 882       *
 883       * @param navigation_node $node The starting navigation node.
 884       */
 885      protected function remove_unwanted_nodes(navigation_node $node) {
 886          foreach ($node->children as $child) {
 887              if (!$child->showinsecondarynavigation) {
 888                  $child->remove();
 889                  continue;
 890              }
 891              if (!empty($child->children)) {
 892                  $this->remove_unwanted_nodes($child);
 893              }
 894          }
 895      }
 896  
 897      /**
 898       * Takes the given navigation nodes and searches for children and formats it all into an array in a format to be used by a
 899       * url_select element.
 900       *
 901       * @param navigation_node[] $navigationnodes Navigation nodes to format into a menu.
 902       * @param bool $forceheadings Whether the returned array should be forced to use headings.
 903       * @return array|null A url select element for navigating through the navigation nodes.
 904       */
 905      public static function create_menu_element(array $navigationnodes, bool $forceheadings = false): ?array {
 906          if (empty($navigationnodes)) {
 907              return null;
 908          }
 909  
 910          // If one item, do we put this into a url_select?
 911          if (count($navigationnodes) < 2) {
 912              // Check if there are children.
 913              $navnode = array_shift($navigationnodes);
 914              $menudata = [];
 915              if (!$navnode->has_children()) {
 916                  // Just one item.
 917                  if (!$navnode->has_action()) {
 918                      return null;
 919                  }
 920                  $menudata[$navnode->action->out(false)] = static::format_node_text($navnode);
 921              } else {
 922                  if (static::does_menu_need_headings($navnode) || $forceheadings) {
 923                      // Let's do headings.
 924                      $menudata = static::get_headings_nav_array($navnode);
 925                  } else {
 926                      // Simple flat nav.
 927                      $menudata = static::get_flat_nav_array($navnode);
 928                  }
 929              }
 930              return $menudata;
 931          } else {
 932              // We have more than one navigation node to handle. Put each node in it's own heading.
 933              $menudata = [];
 934              $titledata = [];
 935              foreach ($navigationnodes as $navigationnode) {
 936                  if ($navigationnode->has_children()) {
 937                      $menuarray = [];
 938                      // Add a heading and flatten out everything else.
 939                      if ($navigationnode->has_action()) {
 940                          $menuarray[static::format_node_text($navigationnode)][$navigationnode->action->out(false)] =
 941                              static::format_node_text($navigationnode);
 942                          $menuarray[static::format_node_text($navigationnode)] += static::get_whole_tree_flat($navigationnode);
 943                      } else {
 944                          $menuarray[static::format_node_text($navigationnode)] = static::get_whole_tree_flat($navigationnode);
 945                      }
 946  
 947                      $titledata += $menuarray;
 948                  } else {
 949                      // Add with no heading.
 950                      if (!$navigationnode->has_action()) {
 951                          return null;
 952                      }
 953                      $menudata[$navigationnode->action->out(false)] = static::format_node_text($navigationnode);
 954                  }
 955              }
 956              $menudata += [$titledata];
 957              return $menudata;
 958          }
 959      }
 960  
 961      /**
 962       * Recursively goes through the provided navigation node and returns a flat version.
 963       *
 964       * @param navigation_node $navigationnode The navigationnode.
 965       * @return array The whole tree flat.
 966       */
 967      protected static function get_whole_tree_flat(navigation_node $navigationnode): array {
 968          $nodes = [];
 969          foreach ($navigationnode->children as $child) {
 970              if ($child->has_action()) {
 971                  $nodes[$child->action->out()] = $child->text;
 972              }
 973              if ($child->has_children()) {
 974                  $childnodes = static::get_whole_tree_flat($child);
 975                  $nodes = array_merge($nodes, $childnodes);
 976              }
 977          }
 978          return $nodes;
 979      }
 980  
 981      /**
 982       * Checks to see if the provided navigation node has children and determines if we want headings for a url select element.
 983       *
 984       * @param navigation_node  $navigationnode  The navigation node we are checking.
 985       * @return bool Whether we want headings or not.
 986       */
 987      protected static function does_menu_need_headings(navigation_node $navigationnode): bool {
 988          if (!$navigationnode->has_children()) {
 989              return false;
 990          }
 991          foreach ($navigationnode->children as $child) {
 992              if ($child->has_children()) {
 993                  return true;
 994              }
 995          }
 996          return false;
 997      }
 998  
 999      /**
1000       * Takes the navigation node and returns it in a flat fashion. This is not recursive.
1001       *
1002       * @param navigation_node $navigationnode The navigation node that we want to format into an array in a flat structure.
1003       * @return array The flat navigation array.
1004       */
1005      protected static function get_flat_nav_array(navigation_node $navigationnode): array {
1006          $menuarray = [];
1007          if ($navigationnode->has_action()) {
1008              $menuarray[$navigationnode->action->out(false)] = static::format_node_text($navigationnode);
1009          }
1010  
1011          foreach ($navigationnode->children as $child) {
1012              if ($child->has_action()) {
1013                  $menuarray[$child->action->out(false)] = static::format_node_text($child);
1014              }
1015          }
1016          return $menuarray;
1017      }
1018  
1019      /**
1020       * For any navigation node that we have determined needs headings we return a more tree like array structure.
1021       *
1022       * @param navigation_node $navigationnode The navigation node to use for the formatted array structure.
1023       * @return array The headings navigation array structure.
1024       */
1025      protected static function get_headings_nav_array(navigation_node $navigationnode): array {
1026          $menublock = [];
1027          // We know that this single node has headings, so grab this for the first heading.
1028          $firstheading = [];
1029          if ($navigationnode->has_action()) {
1030              $firstheading[static::format_node_text($navigationnode)][$navigationnode->action->out(false)] =
1031                  static::format_node_text($navigationnode);
1032              $firstheading[static::format_node_text($navigationnode)] += static::get_more_child_nodes($navigationnode, $menublock);
1033          } else {
1034              $firstheading[static::format_node_text($navigationnode)] = static::get_more_child_nodes($navigationnode, $menublock);
1035          }
1036           return [$firstheading + $menublock];
1037      }
1038  
1039      /**
1040       * Recursively goes and gets all children nodes.
1041       *
1042       * @param navigation_node $node The node to get the children of.
1043       * @param array $menublock Used to put all child nodes in its own container.
1044       * @return array The additional child nodes.
1045       */
1046      protected static function get_more_child_nodes(navigation_node $node, array &$menublock): array {
1047          $nodes = [];
1048          foreach ($node->children as $child) {
1049              if (!$child->has_children()) {
1050                  if (!$child->has_action()) {
1051                      continue;
1052                  }
1053                  $nodes[$child->action->out(false)] = static::format_node_text($child);
1054              } else {
1055                  $newarray = [];
1056                  if ($child->has_action()) {
1057                      $newarray[static::format_node_text($child)][$child->action->out(false)] = static::format_node_text($child);
1058                      $newarray[static::format_node_text($child)] += static::get_more_child_nodes($child, $menublock);
1059                  } else {
1060                      $newarray[static::format_node_text($child)] = static::get_more_child_nodes($child, $menublock);
1061                  }
1062                  $menublock += $newarray;
1063              }
1064          }
1065          return $nodes;
1066      }
1067  
1068      /**
1069       * Returns the navigation node text in a string.
1070       *
1071       * @param navigation_node $navigationnode The navigationnode to return the text string of.
1072       * @return string The navigation node text string.
1073       */
1074      protected static function format_node_text(navigation_node $navigationnode): string {
1075          return (is_a($navigationnode->text, 'lang_string')) ? $navigationnode->text->out() : $navigationnode->text;
1076      }
1077  
1078      /**
1079       * Load the single activity course secondary navigation.
1080       */
1081      protected function load_single_activity_course_navigation(): void {
1082          $page = $this->page;
1083          $course = $page->course;
1084  
1085          // Create 'Course' navigation node.
1086          $coursesecondarynode = navigation_node::create(get_string('course'), null, self::TYPE_COURSE, null, 'course');
1087          $this->load_course_navigation($coursesecondarynode);
1088          // Remove the unnecessary 'Course' child node generated in load_course_navigation().
1089          $coursehomenode = $coursesecondarynode->find('coursehome', self::TYPE_COURSE);
1090          if (!empty($coursehomenode)) {
1091              $coursehomenode->remove();
1092          }
1093  
1094          // Add the 'Course' node to the secondary navigation only if this node has children nodes.
1095          if (count($coursesecondarynode->children) > 0) {
1096              $this->add_node($coursesecondarynode);
1097              // Once all the items have been added to the 'Course' secondary navigation node, set the 'showchildreninsubmenu'
1098              // property to true. This is required to force the template to output these items within a dropdown menu.
1099              $coursesecondarynode->showchildreninsubmenu = true;
1100          }
1101  
1102          // Create 'Activity' navigation node.
1103          $activitysecondarynode = navigation_node::create(get_string('activity'), null, self::TYPE_ACTIVITY, null, 'activity');
1104  
1105          // We should display the module related navigation in the course context as well. Therefore, we need to
1106          // re-initialize the page object and manually set the course module to the one that it is currently visible in
1107          // the course in order to obtain the required module settings navigation.
1108          if ($page->context instanceof \context_course) {
1109              $this->page->set_secondary_active_tab($coursesecondarynode->key);
1110              // Get the currently used module in the single activity course.
1111              $module = current(array_filter(get_course_mods($course->id), function ($module) {
1112                  return $module->visible == 1;
1113              }));
1114              // If the default module for the single course format has not been set yet, skip displaying the module
1115              // related navigation in the secondary navigation.
1116              if (!$module) {
1117                  return;
1118              }
1119              $page = new \moodle_page();
1120              $page->set_cm($module, $course);
1121              $page->set_url(new \moodle_url('/mod/' . $page->activityname . '/view.php', ['id' => $page->cm->id]));
1122          }
1123  
1124          $this->load_module_navigation($page->settingsnav, $activitysecondarynode);
1125  
1126          // Add the 'Activity' node to the secondary navigation only if this node has more that one child node.
1127          if (count($activitysecondarynode->children) > 1) {
1128              // Set the 'showchildreninsubmenu' property to true to later output the the module navigation items within
1129              // a dropdown menu.
1130              $activitysecondarynode->showchildreninsubmenu = true;
1131              $this->add_node($activitysecondarynode);
1132              if ($this->context instanceof \context_module) {
1133                  $this->page->set_secondary_active_tab($activitysecondarynode->key);
1134              }
1135          } else { // Otherwise, add the 'View activity' node to the secondary navigation.
1136              $viewactivityurl = new \moodle_url('/mod/' . $page->activityname . '/view.php', ['id' => $page->cm->id]);
1137              $this->add(get_string('modulename', $page->activityname), $viewactivityurl, null, null, 'modulepage');
1138              if ($this->context instanceof \context_module) {
1139                  $this->page->set_secondary_active_tab('modulepage');
1140              }
1141          }
1142      }
1143  }