Search moodle.org's
Developer Documentation

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
  • Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 37 and 311] [Versions 38 and 311] [Versions 39 and 311]

       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  /**
      18   * This file contains classes used to manage the navigation structures within Moodle.
      19   *
      20   * @since      Moodle 2.0
      21   * @package    core
      22   * @copyright  2009 Sam Hemelryk
      23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      24   */
      25  
      26  defined('MOODLE_INTERNAL') || die();
      27  
      28  /**
      29   * The name that will be used to separate the navigation cache within SESSION
      30   */
      31  define('NAVIGATION_CACHE_NAME', 'navigation');
      32  define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
      33  
      34  /**
      35   * This class is used to represent a node in a navigation tree
      36   *
      37   * This class is used to represent a node in a navigation tree within Moodle,
      38   * the tree could be one of global navigation, settings navigation, or the navbar.
      39   * Each node can be one of two types either a Leaf (default) or a branch.
      40   * When a node is first created it is created as a leaf, when/if children are added
      41   * the node then becomes a branch.
      42   *
      43   * @package   core
      44   * @category  navigation
      45   * @copyright 2009 Sam Hemelryk
      46   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      47   */
      48  class navigation_node implements renderable {
      49      /** @var int Used to identify this node a leaf (default) 0 */
      50      const NODETYPE_LEAF =   0;
      51      /** @var int Used to identify this node a branch, happens with children  1 */
      52      const NODETYPE_BRANCH = 1;
      53      /** @var null Unknown node type null */
      54      const TYPE_UNKNOWN =    null;
      55      /** @var int System node type 0 */
      56      const TYPE_ROOTNODE =   0;
      57      /** @var int System node type 1 */
      58      const TYPE_SYSTEM =     1;
      59      /** @var int Category node type 10 */
      60      const TYPE_CATEGORY =   10;
      61      /** var int Category displayed in MyHome navigation node */
      62      const TYPE_MY_CATEGORY = 11;
      63      /** @var int Course node type 20 */
      64      const TYPE_COURSE =     20;
      65      /** @var int Course Structure node type 30 */
      66      const TYPE_SECTION =    30;
      67      /** @var int Activity node type, e.g. Forum, Quiz 40 */
      68      const TYPE_ACTIVITY =   40;
      69      /** @var int Resource node type, e.g. Link to a file, or label 50 */
      70      const TYPE_RESOURCE =   50;
      71      /** @var int A custom node type, default when adding without specifing type 60 */
      72      const TYPE_CUSTOM =     60;
      73      /** @var int Setting node type, used only within settings nav 70 */
      74      const TYPE_SETTING =    70;
      75      /** @var int site admin branch node type, used only within settings nav 71 */
      76      const TYPE_SITE_ADMIN = 71;
      77      /** @var int Setting node type, used only within settings nav 80 */
      78      const TYPE_USER =       80;
      79      /** @var int Setting node type, used for containers of no importance 90 */
      80      const TYPE_CONTAINER =  90;
      81      /** var int Course the current user is not enrolled in */
      82      const COURSE_OTHER = 0;
      83      /** var int Course the current user is enrolled in but not viewing */
      84      const COURSE_MY = 1;
      85      /** var int Course the current user is currently viewing */
      86      const COURSE_CURRENT = 2;
      87      /** var string The course index page navigation node */
      88      const COURSE_INDEX_PAGE = 'courseindexpage';
      89  
      90      /** @var int Parameter to aid the coder in tracking [optional] */
      91      public $id = null;
      92      /** @var string|int The identifier for the node, used to retrieve the node */
      93      public $key = null;
      94      /** @var string The text to use for the node */
      95      public $text = null;
      96      /** @var string Short text to use if requested [optional] */
      97      public $shorttext = null;
      98      /** @var string The title attribute for an action if one is defined */
      99      public $title = null;
     100      /** @var string A string that can be used to build a help button */
     101      public $helpbutton = null;
     102      /** @var moodle_url|action_link|null An action for the node (link) */
     103      public $action = null;
     104      /** @var pix_icon The path to an icon to use for this node */
     105      public $icon = null;
     106      /** @var int See TYPE_* constants defined for this class */
     107      public $type = self::TYPE_UNKNOWN;
     108      /** @var int See NODETYPE_* constants defined for this class */
     109      public $nodetype = self::NODETYPE_LEAF;
     110      /** @var bool If set to true the node will be collapsed by default */
     111      public $collapse = false;
     112      /** @var bool If set to true the node will be expanded by default */
     113      public $forceopen = false;
     114      /** @var array An array of CSS classes for the node */
     115      public $classes = array();
     116      /** @var navigation_node_collection An array of child nodes */
     117      public $children = array();
     118      /** @var bool If set to true the node will be recognised as active */
     119      public $isactive = false;
     120      /** @var bool If set to true the node will be dimmed */
     121      public $hidden = false;
     122      /** @var bool If set to false the node will not be displayed */
     123      public $display = true;
     124      /** @var bool If set to true then an HR will be printed before the node */
     125      public $preceedwithhr = false;
     126      /** @var bool If set to true the the navigation bar should ignore this node */
     127      public $mainnavonly = false;
     128      /** @var bool If set to true a title will be added to the action no matter what */
     129      public $forcetitle = false;
     130      /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
     131      public $parent = null;
     132      /** @var bool Override to not display the icon even if one is provided **/
     133      public $hideicon = false;
     134      /** @var bool Set to true if we KNOW that this node can be expanded.  */
     135      public $isexpandable = false;
     136      /** @var array */
     137      protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
     138                                    50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
     139                                    90 => 'container');
     140      /** @var moodle_url */
     141      protected static $fullmeurl = null;
     142      /** @var bool toogles auto matching of active node */
     143      public static $autofindactive = true;
     144      /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
     145      protected static $loadadmintree = false;
     146      /** @var mixed If set to an int, that section will be included even if it has no activities */
     147      public $includesectionnum = false;
     148      /** @var bool does the node need to be loaded via ajax */
     149      public $requiresajaxloading = false;
     150      /** @var bool If set to true this node will be added to the "flat" navigation */
     151      public $showinflatnavigation = false;
     152  
     153      /**
     154       * Constructs a new navigation_node
     155       *
     156       * @param array|string $properties Either an array of properties or a string to use
     157       *                     as the text for the node
     158       */
     159      public function __construct($properties) {
     160          if (is_array($properties)) {
     161              // Check the array for each property that we allow to set at construction.
     162              // text         - The main content for the node
     163              // shorttext    - A short text if required for the node
     164              // icon         - The icon to display for the node
     165              // type         - The type of the node
     166              // key          - The key to use to identify the node
     167              // parent       - A reference to the nodes parent
     168              // action       - The action to attribute to this node, usually a URL to link to
     169              if (array_key_exists('text', $properties)) {
     170                  $this->text = $properties['text'];
     171              }
     172              if (array_key_exists('shorttext', $properties)) {
     173                  $this->shorttext = $properties['shorttext'];
     174              }
     175              if (!array_key_exists('icon', $properties)) {
     176                  $properties['icon'] = new pix_icon('i/navigationitem', '');
     177              }
     178              $this->icon = $properties['icon'];
     179              if ($this->icon instanceof pix_icon) {
     180                  if (empty($this->icon->attributes['class'])) {
     181                      $this->icon->attributes['class'] = 'navicon';
     182                  } else {
     183                      $this->icon->attributes['class'] .= ' navicon';
     184                  }
     185              }
     186              if (array_key_exists('type', $properties)) {
     187                  $this->type = $properties['type'];
     188              } else {
     189                  $this->type = self::TYPE_CUSTOM;
     190              }
     191              if (array_key_exists('key', $properties)) {
     192                  $this->key = $properties['key'];
     193              }
     194              // This needs to happen last because of the check_if_active call that occurs
     195              if (array_key_exists('action', $properties)) {
     196                  $this->action = $properties['action'];
     197                  if (is_string($this->action)) {
     198                      $this->action = new moodle_url($this->action);
     199                  }
     200                  if (self::$autofindactive) {
     201                      $this->check_if_active();
     202                  }
     203              }
     204              if (array_key_exists('parent', $properties)) {
     205                  $this->set_parent($properties['parent']);
     206              }
     207          } else if (is_string($properties)) {
     208              $this->text = $properties;
     209          }
     210          if ($this->text === null) {
     211              throw new coding_exception('You must set the text for the node when you create it.');
     212          }
     213          // Instantiate a new navigation node collection for this nodes children
     214          $this->children = new navigation_node_collection();
     215      }
     216  
     217      /**
     218       * Checks if this node is the active node.
     219       *
     220       * This is determined by comparing the action for the node against the
     221       * defined URL for the page. A match will see this node marked as active.
     222       *
     223       * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
     224       * @return bool
     225       */
     226      public function check_if_active($strength=URL_MATCH_EXACT) {
     227          global $FULLME, $PAGE;
     228          // Set fullmeurl if it hasn't already been set
     229          if (self::$fullmeurl == null) {
     230              if ($PAGE->has_set_url()) {
     231                  self::override_active_url(new moodle_url($PAGE->url));
     232              } else {
     233                  self::override_active_url(new moodle_url($FULLME));
     234              }
     235          }
     236  
     237          // Compare the action of this node against the fullmeurl
     238          if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
     239              $this->make_active();
     240              return true;
     241          }
     242          return false;
     243      }
     244  
     245      /**
     246       * True if this nav node has siblings in the tree.
     247       *
     248       * @return bool
     249       */
     250      public function has_siblings() {
     251          if (empty($this->parent) || empty($this->parent->children)) {
     252              return false;
     253          }
     254          if ($this->parent->children instanceof navigation_node_collection) {
     255              $count = $this->parent->children->count();
     256          } else {
     257              $count = count($this->parent->children);
     258          }
     259          return ($count > 1);
     260      }
     261  
     262      /**
     263       * Get a list of sibling navigation nodes at the same level as this one.
     264       *
     265       * @return bool|array of navigation_node
     266       */
     267      public function get_siblings() {
     268          // Returns a list of the siblings of the current node for display in a flat navigation element. Either
     269          // the in-page links or the breadcrumb links.
     270          $siblings = false;
     271  
     272          if ($this->has_siblings()) {
     273              $siblings = [];
     274              foreach ($this->parent->children as $child) {
     275                  if ($child->display) {
     276                      $siblings[] = $child;
     277                  }
     278              }
     279          }
     280          return $siblings;
     281      }
     282  
     283      /**
     284       * This sets the URL that the URL of new nodes get compared to when locating
     285       * the active node.
     286       *
     287       * The active node is the node that matches the URL set here. By default this
     288       * is either $PAGE->url or if that hasn't been set $FULLME.
     289       *
     290       * @param moodle_url $url The url to use for the fullmeurl.
     291       * @param bool $loadadmintree use true if the URL point to administration tree
     292       */
     293      public static function override_active_url(moodle_url $url, $loadadmintree = false) {
     294          // Clone the URL, in case the calling script changes their URL later.
     295          self::$fullmeurl = new moodle_url($url);
     296          // True means we do not want AJAX loaded admin tree, required for all admin pages.
     297          if ($loadadmintree) {
     298              // Do not change back to false if already set.
     299              self::$loadadmintree = true;
     300          }
     301      }
     302  
     303      /**
     304       * Use when page is linked from the admin tree,
     305       * if not used navigation could not find the page using current URL
     306       * because the tree is not fully loaded.
     307       */
     308      public static function require_admin_tree() {
     309          self::$loadadmintree = true;
     310      }
     311  
     312      /**
     313       * Creates a navigation node, ready to add it as a child using add_node
     314       * function. (The created node needs to be added before you can use it.)
     315       * @param string $text
     316       * @param moodle_url|action_link $action
     317       * @param int $type
     318       * @param string $shorttext
     319       * @param string|int $key
     320       * @param pix_icon $icon
     321       * @return navigation_node
     322       */
     323      public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
     324              $shorttext=null, $key=null, pix_icon $icon=null) {
     325          // Properties array used when creating the new navigation node
     326          $itemarray = array(
     327              'text' => $text,
     328              'type' => $type
     329          );
     330          // Set the action if one was provided
     331          if ($action!==null) {
     332              $itemarray['action'] = $action;
     333          }
     334          // Set the shorttext if one was provided
     335          if ($shorttext!==null) {
     336              $itemarray['shorttext'] = $shorttext;
     337          }
     338          // Set the icon if one was provided
     339          if ($icon!==null) {
     340              $itemarray['icon'] = $icon;
     341          }
     342          // Set the key
     343          $itemarray['key'] = $key;
     344          // Construct and return
     345          return new navigation_node($itemarray);
     346      }
     347  
     348      /**
     349       * Adds a navigation node as a child of this node.
     350       *
     351       * @param string $text
     352       * @param moodle_url|action_link $action
     353       * @param int $type
     354       * @param string $shorttext
     355       * @param string|int $key
     356       * @param pix_icon $icon
     357       * @return navigation_node
     358       */
     359      public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
     360          // Create child node
     361          $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
     362  
     363          // Add the child to end and return
     364          return $this->add_node($childnode);
     365      }
     366  
     367      /**
     368       * Adds a navigation node as a child of this one, given a $node object
     369       * created using the create function.
     370       * @param navigation_node $childnode Node to add
     371       * @param string $beforekey
     372       * @return navigation_node The added node
     373       */
     374      public function add_node(navigation_node $childnode, $beforekey=null) {
     375          // First convert the nodetype for this node to a branch as it will now have children
     376          if ($this->nodetype !== self::NODETYPE_BRANCH) {
     377              $this->nodetype = self::NODETYPE_BRANCH;
     378          }
     379          // Set the parent to this node
     380          $childnode->set_parent($this);
     381  
     382          // Default the key to the number of children if not provided
     383          if ($childnode->key === null) {
     384              $childnode->key = $this->children->count();
     385          }
     386  
     387          // Add the child using the navigation_node_collections add method
     388          $node = $this->children->add($childnode, $beforekey);
     389  
     390          // If added node is a category node or the user is logged in and it's a course
     391          // then mark added node as a branch (makes it expandable by AJAX)
     392          $type = $childnode->type;
     393          if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
     394                  ($type === self::TYPE_SITE_ADMIN)) {
     395              $node->nodetype = self::NODETYPE_BRANCH;
     396          }
     397          // If this node is hidden mark it's children as hidden also
     398          if ($this->hidden) {
     399              $node->hidden = true;
     400          }
     401          // Return added node (reference returned by $this->children->add()
     402          return $node;
     403      }
     404  
     405      /**
     406       * Return a list of all the keys of all the child nodes.
     407       * @return array the keys.
     408       */
     409      public function get_children_key_list() {
     410          return $this->children->get_key_list();
     411      }
     412  
     413      /**
     414       * Searches for a node of the given type with the given key.
     415       *
     416       * This searches this node plus all of its children, and their children....
     417       * If you know the node you are looking for is a child of this node then please
     418       * use the get method instead.
     419       *
     420       * @param int|string $key The key of the node we are looking for
     421       * @param int $type One of navigation_node::TYPE_*
     422       * @return navigation_node|false
     423       */
     424      public function find($key, $type) {
     425          return $this->children->find($key, $type);
     426      }
     427  
     428      /**
     429       * Walk the tree building up a list of all the flat navigation nodes.
     430       *
     431       * @param flat_navigation $nodes List of the found flat navigation nodes.
     432       * @param boolean $showdivider Show a divider before the first node.
     433       * @param string $label A label for the collection of navigation links.
     434       */
     435      public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
     436          if ($this->showinflatnavigation) {
     437              $indent = 0;
     438              if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
     439                  $indent = 1;
     440              }
     441              $flat = new flat_navigation_node($this, $indent);
     442              $flat->set_showdivider($showdivider, $label);
     443              $nodes->add($flat);
     444          }
     445          foreach ($this->children as $child) {
     446              $child->build_flat_navigation_list($nodes, false);
     447          }
     448      }
     449  
     450      /**
     451       * Get the child of this node that has the given key + (optional) type.
     452       *
     453       * If you are looking for a node and want to search all children + their children
     454       * then please use the find method instead.
     455       *
     456       * @param int|string $key The key of the node we are looking for
     457       * @param int $type One of navigation_node::TYPE_*
     458       * @return navigation_node|false
     459       */
     460      public function get($key, $type=null) {
     461          return $this->children->get($key, $type);
     462      }
     463  
     464      /**
     465       * Removes this node.
     466       *
     467       * @return bool
     468       */
     469      public function remove() {
     470          return $this->parent->children->remove($this->key, $this->type);
     471      }
     472  
     473      /**
     474       * Checks if this node has or could have any children
     475       *
     476       * @return bool Returns true if it has children or could have (by AJAX expansion)
     477       */
     478      public function has_children() {
     479          return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
     480      }
     481  
     482      /**
     483       * Marks this node as active and forces it open.
     484       *
     485       * Important: If you are here because you need to mark a node active to get
     486       * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
     487       * You can use it to specify a different URL to match the active navigation node on
     488       * rather than having to locate and manually mark a node active.
     489       */
     490      public function make_active() {
     491          $this->isactive = true;
     492          $this->add_class('active_tree_node');
     493          $this->force_open();
     494          if ($this->parent !== null) {
     495              $this->parent->make_inactive();
     496          }
     497      }
     498  
     499      /**
     500       * Marks a node as inactive and recusised back to the base of the tree
     501       * doing the same to all parents.
     502       */
     503      public function make_inactive() {
     504          $this->isactive = false;
     505          $this->remove_class('active_tree_node');
     506          if ($this->parent !== null) {
     507              $this->parent->make_inactive();
     508          }
     509      }
     510  
     511      /**
     512       * Forces this node to be open and at the same time forces open all
     513       * parents until the root node.
     514       *
     515       * Recursive.
     516       */
     517      public function force_open() {
     518          $this->forceopen = true;
     519          if ($this->parent !== null) {
     520              $this->parent->force_open();
     521          }
     522      }
     523  
     524      /**
     525       * Adds a CSS class to this node.
     526       *
     527       * @param string $class
     528       * @return bool
     529       */
     530      public function add_class($class) {
     531          if (!in_array($class, $this->classes)) {
     532              $this->classes[] = $class;
     533          }
     534          return true;
     535      }
     536  
     537      /**
     538       * Removes a CSS class from this node.
     539       *
     540       * @param string $class
     541       * @return bool True if the class was successfully removed.
     542       */
     543      public function remove_class($class) {
     544          if (in_array($class, $this->classes)) {
     545              $key = array_search($class,$this->classes);
     546              if ($key!==false) {
     547                  // Remove the class' array element.
     548                  unset($this->classes[$key]);
     549                  // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
     550                  $this->classes = array_values($this->classes);
     551  
     552                  return true;
     553              }
     554          }
     555          return false;
     556      }
     557  
     558      /**
     559       * Sets the title for this node and forces Moodle to utilise it.
     560       * @param string $title
     561       */
     562      public function title($title) {
     563          $this->title = $title;
     564          $this->forcetitle = true;
     565      }
     566  
     567      /**
     568       * Resets the page specific information on this node if it is being unserialised.
     569       */
     570      public function __wakeup(){
     571          $this->forceopen = false;
     572          $this->isactive = false;
     573          $this->remove_class('active_tree_node');
     574      }
     575  
     576      /**
     577       * Checks if this node or any of its children contain the active node.
     578       *
     579       * Recursive.
     580       *
     581       * @return bool
     582       */
     583      public function contains_active_node() {
     584          if ($this->isactive) {
     585              return true;
     586          } else {
     587              foreach ($this->children as $child) {
     588                  if ($child->isactive || $child->contains_active_node()) {
     589                      return true;
     590                  }
     591              }
     592          }
     593          return false;
     594      }
     595  
     596      /**
     597       * To better balance the admin tree, we want to group all the short top branches together.
     598       *
     599       * This means < 8 nodes and no subtrees.
     600       *
     601       * @return bool
     602       */
     603      public function is_short_branch() {
     604          $limit = 8;
     605          if ($this->children->count() >= $limit) {
     606              return false;
     607          }
     608          foreach ($this->children as $child) {
     609              if ($child->has_children()) {
     610                  return false;
     611              }
     612          }
     613          return true;
     614      }
     615  
     616      /**
     617       * Finds the active node.
     618       *
     619       * Searches this nodes children plus all of the children for the active node
     620       * and returns it if found.
     621       *
     622       * Recursive.
     623       *
     624       * @return navigation_node|false
     625       */
     626      public function find_active_node() {
     627          if ($this->isactive) {
     628              return $this;
     629          } else {
     630              foreach ($this->children as &$child) {
     631                  $outcome = $child->find_active_node();
     632                  if ($outcome !== false) {
     633                      return $outcome;
     634                  }
     635              }
     636          }
     637          return false;
     638      }
     639  
     640      /**
     641       * Searches all children for the best matching active node
     642       * @return navigation_node|false
     643       */
     644      public function search_for_active_node() {
     645          if ($this->check_if_active(URL_MATCH_BASE)) {
     646              return $this;
     647          } else {
     648              foreach ($this->children as &$child) {
     649                  $outcome = $child->search_for_active_node();
     650                  if ($outcome !== false) {
     651                      return $outcome;
     652                  }
     653              }
     654          }
     655          return false;
     656      }
     657  
     658      /**
     659       * Gets the content for this node.
     660       *
     661       * @param bool $shorttext If true shorttext is used rather than the normal text
     662       * @return string
     663       */
     664      public function get_content($shorttext=false) {
     665          $navcontext = \context_helper::get_navigation_filter_context(null);
     666          $options = !empty($navcontext) ? ['context' => $navcontext] : null;
     667  
     668          if ($shorttext && $this->shorttext!==null) {
     669              return format_string($this->shorttext, null, $options);
     670          } else {
     671              return format_string($this->text, null, $options);
     672          }
     673      }
     674  
     675      /**
     676       * Gets the title to use for this node.
     677       *
     678       * @return string
     679       */
     680      public function get_title() {
     681          if ($this->forcetitle || $this->action != null){
     682              return $this->title;
     683          } else {
     684              return '';
     685          }
     686      }
     687  
     688      /**
     689       * Used to easily determine if this link in the breadcrumbs has a valid action/url.
     690       *
     691       * @return boolean
     692       */
     693      public function has_action() {
     694          return !empty($this->action);
     695      }
     696  
     697      /**
     698       * Used to easily determine if this link in the breadcrumbs is hidden.
     699       *
     700       * @return boolean
     701       */
     702      public function is_hidden() {
     703          return $this->hidden;
     704      }
     705  
     706      /**
     707       * Gets the CSS class to add to this node to describe its type
     708       *
     709       * @return string
     710       */
     711      public function get_css_type() {
     712          if (array_key_exists($this->type, $this->namedtypes)) {
     713              return 'type_'.$this->namedtypes[$this->type];
     714          }
     715          return 'type_unknown';
     716      }
     717  
     718      /**
     719       * Finds all nodes that are expandable by AJAX
     720       *
     721       * @param array $expandable An array by reference to populate with expandable nodes.
     722       */
     723      public function find_expandable(array &$expandable) {
     724          foreach ($this->children as &$child) {
     725              if ($child->display && $child->has_children() && $child->children->count() == 0) {
     726                  $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
     727                  $this->add_class('canexpand');
     728                  $child->requiresajaxloading = true;
     729                  $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
     730              }
     731              $child->find_expandable($expandable);
     732          }
     733      }
     734  
     735      /**
     736       * Finds all nodes of a given type (recursive)
     737       *
     738       * @param int $type One of navigation_node::TYPE_*
     739       * @return array
     740       */
     741      public function find_all_of_type($type) {
     742          $nodes = $this->children->type($type);
     743          foreach ($this->children as &$node) {
     744              $childnodes = $node->find_all_of_type($type);
     745              $nodes = array_merge($nodes, $childnodes);
     746          }
     747          return $nodes;
     748      }
     749  
     750      /**
     751       * Removes this node if it is empty
     752       */
     753      public function trim_if_empty() {
     754          if ($this->children->count() == 0) {
     755              $this->remove();
     756          }
     757      }
     758  
     759      /**
     760       * Creates a tab representation of this nodes children that can be used
     761       * with print_tabs to produce the tabs on a page.
     762       *
     763       * call_user_func_array('print_tabs', $node->get_tabs_array());
     764       *
     765       * @param array $inactive
     766       * @param bool $return
     767       * @return array Array (tabs, selected, inactive, activated, return)
     768       */
     769      public function get_tabs_array(array $inactive=array(), $return=false) {
     770          $tabs = array();
     771          $rows = array();
     772          $selected = null;
     773          $activated = array();
     774          foreach ($this->children as $node) {
     775              $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
     776              if ($node->contains_active_node()) {
     777                  if ($node->children->count() > 0) {
     778                      $activated[] = $node->key;
     779                      foreach ($node->children as $child) {
     780                          if ($child->contains_active_node()) {
     781                              $selected = $child->key;
     782                          }
     783                          $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
     784                      }
     785                  } else {
     786                      $selected = $node->key;
     787                  }
     788              }
     789          }
     790          return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
     791      }
     792  
     793      /**
     794       * Sets the parent for this node and if this node is active ensures that the tree is properly
     795       * adjusted as well.
     796       *
     797       * @param navigation_node $parent
     798       */
     799      public function set_parent(navigation_node $parent) {
     800          // Set the parent (thats the easy part)
     801          $this->parent = $parent;
     802          // Check if this node is active (this is checked during construction)
     803          if ($this->isactive) {
     804              // Force all of the parent nodes open so you can see this node
     805              $this->parent->force_open();
     806              // Make all parents inactive so that its clear where we are.
     807              $this->parent->make_inactive();
     808          }
     809      }
     810  
     811      /**
     812       * Hides the node and any children it has.
     813       *
     814       * @since Moodle 2.5
     815       * @param array $typestohide Optional. An array of node types that should be hidden.
     816       *      If null all nodes will be hidden.
     817       *      If an array is given then nodes will only be hidden if their type mtatches an element in the array.
     818       *          e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
     819       */
     820      public function hide(array $typestohide = null) {
     821          if ($typestohide === null || in_array($this->type, $typestohide)) {
     822              $this->display = false;
     823              if ($this->has_children()) {
     824                  foreach ($this->children as $child) {
     825                      $child->hide($typestohide);
     826                  }
     827              }
     828          }
     829      }
     830  
     831      /**
     832       * Get the action url for this navigation node.
     833       * Called from templates.
     834       *
     835       * @since Moodle 3.2
     836       */
     837      public function action() {
     838          if ($this->action instanceof moodle_url) {
     839              return $this->action;
     840          } else if ($this->action instanceof action_link) {
     841              return $this->action->url;
     842          }
     843          return $this->action;
     844      }
     845  
     846      /**
     847       * Add the menu item to handle locking and unlocking of a conext.
     848       *
     849       * @param \navigation_node $node Node to add
     850       * @param \context $context The context to be locked
     851       */
     852      protected function add_context_locking_node(\navigation_node $node, \context $context) {
     853          global $CFG;
     854          // Manage context locking.
     855          if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
     856              $parentcontext = $context->get_parent_context();
     857              if (empty($parentcontext) || !$parentcontext->locked) {
     858                  if ($context->locked) {
     859                      $lockicon = 'i/unlock';
     860                      $lockstring = get_string('managecontextunlock', 'admin');
     861                  } else {
     862                      $lockicon = 'i/lock';
     863                      $lockstring = get_string('managecontextlock', 'admin');
     864                  }
     865                  $node->add(
     866                      $lockstring,
     867                      new moodle_url(
     868                          '/admin/lock.php',
     869                          [
     870                              'id' => $context->id,
     871                          ]
     872                      ),
     873                      self::TYPE_SETTING,
     874                      null,
     875                      'contextlocking',
     876                       new pix_icon($lockicon, '')
     877                  );
     878              }
     879          }
     880  
     881      }
     882  }
     883  
     884  /**
     885   * Navigation node collection
     886   *
     887   * This class is responsible for managing a collection of navigation nodes.
     888   * It is required because a node's unique identifier is a combination of both its
     889   * key and its type.
     890   *
     891   * Originally an array was used with a string key that was a combination of the two
     892   * however it was decided that a better solution would be to use a class that
     893   * implements the standard IteratorAggregate interface.
     894   *
     895   * @package   core
     896   * @category  navigation
     897   * @copyright 2010 Sam Hemelryk
     898   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     899   */
     900  class navigation_node_collection implements IteratorAggregate, Countable {
     901      /**
     902       * A multidimensional array to where the first key is the type and the second
     903       * key is the nodes key.
     904       * @var array
     905       */
     906      protected $collection = array();
     907      /**
     908       * An array that contains references to nodes in the same order they were added.
     909       * This is maintained as a progressive array.
     910       * @var array
     911       */
     912      protected $orderedcollection = array();
     913      /**
     914       * A reference to the last node that was added to the collection
     915       * @var navigation_node
     916       */
     917      protected $last = null;
     918      /**
     919       * The total number of items added to this array.
     920       * @var int
     921       */
     922      protected $count = 0;
     923  
     924      /**
     925       * Label for collection of nodes.
     926       * @var string
     927       */
     928      protected $collectionlabel = '';
     929  
     930      /**
     931       * Adds a navigation node to the collection
     932       *
     933       * @param navigation_node $node Node to add
     934       * @param string $beforekey If specified, adds before a node with this key,
     935       *   otherwise adds at end
     936       * @return navigation_node Added node
     937       */
     938      public function add(navigation_node $node, $beforekey=null) {
     939          global $CFG;
     940          $key = $node->key;
     941          $type = $node->type;
     942  
     943          // First check we have a 2nd dimension for this type
     944          if (!array_key_exists($type, $this->orderedcollection)) {
     945              $this->orderedcollection[$type] = array();
     946          }
     947          // Check for a collision and report if debugging is turned on
     948          if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
     949              debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
     950          }
     951  
     952          // Find the key to add before
     953          $newindex = $this->count;
     954          $last = true;
     955          if ($beforekey !== null) {
     956              foreach ($this->collection as $index => $othernode) {
     957                  if ($othernode->key === $beforekey) {
     958                      $newindex = $index;
     959                      $last = false;
     960                      break;
     961                  }
     962              }
     963              if ($newindex === $this->count) {
     964                  debugging('Navigation node add_before: Reference node not found ' . $beforekey .
     965                          ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
     966              }
     967          }
     968  
     969          // Add the node to the appropriate place in the by-type structure (which
     970          // is not ordered, despite the variable name)
     971          $this->orderedcollection[$type][$key] = $node;
     972          if (!$last) {
     973              // Update existing references in the ordered collection (which is the
     974              // one that isn't called 'ordered') to shuffle them along if required
     975              for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
     976                  $this->collection[$oldindex] = $this->collection[$oldindex - 1];
     977              }
     978          }
     979          // Add a reference to the node to the progressive collection.
     980          $this->collection[$newindex] = $this->orderedcollection[$type][$key];
     981          // Update the last property to a reference to this new node.
     982          $this->last = $this->orderedcollection[$type][$key];
     983  
     984          // Reorder the array by index if needed
     985          if (!$last) {
     986              ksort($this->collection);
     987          }
     988          $this->count++;
     989          // Return the reference to the now added node
     990          return $node;
     991      }
     992  
     993      /**
     994       * Return a list of all the keys of all the nodes.
     995       * @return array the keys.
     996       */
     997      public function get_key_list() {
     998          $keys = array();
     999          foreach ($this->collection as $node) {
    1000              $keys[] = $node->key;
    1001          }
    1002          return $keys;
    1003      }
    1004  
    1005      /**
    1006       * Set a label for this collection.
    1007       *
    1008       * @param string $label
    1009       */
    1010      public function set_collectionlabel($label) {
    1011          $this->collectionlabel = $label;
    1012      }
    1013  
    1014      /**
    1015       * Return a label for this collection.
    1016       *
    1017       * @return string
    1018       */
    1019      public function get_collectionlabel() {
    1020          return $this->collectionlabel;
    1021      }
    1022  
    1023      /**
    1024       * Fetches a node from this collection.
    1025       *
    1026       * @param string|int $key The key of the node we want to find.
    1027       * @param int $type One of navigation_node::TYPE_*.
    1028       * @return navigation_node|null
    1029       */
    1030      public function get($key, $type=null) {
    1031          if ($type !== null) {
    1032              // If the type is known then we can simply check and fetch
    1033              if (!empty($this->orderedcollection[$type][$key])) {
    1034                  return $this->orderedcollection[$type][$key];
    1035              }
    1036          } else {
    1037              // Because we don't know the type we look in the progressive array
    1038              foreach ($this->collection as $node) {
    1039                  if ($node->key === $key) {
    1040                      return $node;
    1041                  }
    1042              }
    1043          }
    1044          return false;
    1045      }
    1046  
    1047      /**
    1048       * Searches for a node with matching key and type.
    1049       *
    1050       * This function searches both the nodes in this collection and all of
    1051       * the nodes in each collection belonging to the nodes in this collection.
    1052       *
    1053       * Recursive.
    1054       *
    1055       * @param string|int $key  The key of the node we want to find.
    1056       * @param int $type  One of navigation_node::TYPE_*.
    1057       * @return navigation_node|null
    1058       */
    1059      public function find($key, $type=null) {
    1060          if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
    1061              return $this->orderedcollection[$type][$key];
    1062          } else {
    1063              $nodes = $this->getIterator();
    1064              // Search immediate children first
    1065              foreach ($nodes as &$node) {
    1066                  if ($node->key === $key && ($type === null || $type === $node->type)) {
    1067                      return $node;
    1068                  }
    1069              }
    1070              // Now search each childs children
    1071              foreach ($nodes as &$node) {
    1072                  $result = $node->children->find($key, $type);
    1073                  if ($result !== false) {
    1074                      return $result;
    1075                  }
    1076              }
    1077          }
    1078          return false;
    1079      }
    1080  
    1081      /**
    1082       * Fetches the last node that was added to this collection
    1083       *
    1084       * @return navigation_node
    1085       */
    1086      public function last() {
    1087          return $this->last;
    1088      }
    1089  
    1090      /**
    1091       * Fetches all nodes of a given type from this collection
    1092       *
    1093       * @param string|int $type  node type being searched for.
    1094       * @return array ordered collection
    1095       */
    1096      public function type($type) {
    1097          if (!array_key_exists($type, $this->orderedcollection)) {
    1098              $this->orderedcollection[$type] = array();
    1099          }
    1100          return $this->orderedcollection[$type];
    1101      }
    1102      /**
    1103       * Removes the node with the given key and type from the collection
    1104       *
    1105       * @param string|int $key The key of the node we want to find.
    1106       * @param int $type
    1107       * @return bool
    1108       */
    1109      public function remove($key, $type=null) {
    1110          $child = $this->get($key, $type);
    1111          if ($child !== false) {
    1112              foreach ($this->collection as $colkey => $node) {
    1113                  if ($node->key === $key && (is_null($type) || $node->type == $type)) {
    1114                      unset($this->collection[$colkey]);
    1115                      $this->collection = array_values($this->collection);
    1116                      break;
    1117                  }
    1118              }
    1119              unset($this->orderedcollection[$child->type][$child->key]);
    1120              $this->count--;
    1121              return true;
    1122          }
    1123          return false;
    1124      }
    1125  
    1126      /**
    1127       * Gets the number of nodes in this collection
    1128       *
    1129       * This option uses an internal count rather than counting the actual options to avoid
    1130       * a performance hit through the count function.
    1131       *
    1132       * @return int
    1133       */
    1134      public function count() {
    1135          return $this->count;
    1136      }
    1137      /**
    1138       * Gets an array iterator for the collection.
    1139       *
    1140       * This is required by the IteratorAggregator interface and is used by routines
    1141       * such as the foreach loop.
    1142       *
    1143       * @return ArrayIterator
    1144       */
    1145      public function getIterator() {
    1146          return new ArrayIterator($this->collection);
    1147      }
    1148  }
    1149  
    1150  /**
    1151   * The global navigation class used for... the global navigation
    1152   *
    1153   * This class is used by PAGE to store the global navigation for the site
    1154   * and is then used by the settings nav and navbar to save on processing and DB calls
    1155   *
    1156   * See
    1157   * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
    1158   * {@link lib/ajax/getnavbranch.php} Called by ajax
    1159   *
    1160   * @package   core
    1161   * @category  navigation
    1162   * @copyright 2009 Sam Hemelryk
    1163   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1164   */
    1165  class global_navigation extends navigation_node {
    1166      /** @var moodle_page The Moodle page this navigation object belongs to. */
    1167      protected $page;
    1168      /** @var bool switch to let us know if the navigation object is initialised*/
    1169      protected $initialised = false;
    1170      /** @var array An array of course information */
    1171      protected $mycourses = array();
    1172      /** @var navigation_node[] An array for containing  root navigation nodes */
    1173      protected $rootnodes = array();
    1174      /** @var bool A switch for whether to show empty sections in the navigation */
    1175      protected $showemptysections = true;
    1176      /** @var bool A switch for whether courses should be shown within categories on the navigation. */
    1177      protected $showcategories = null;
    1178      /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
    1179      protected $showmycategories = null;
    1180      /** @var array An array of stdClasses for users that the navigation is extended for */
    1181      protected $extendforuser = array();
    1182      /** @var navigation_cache */
    1183      protected $cache;
    1184      /** @var array An array of course ids that are present in the navigation */
    1185      protected $addedcourses = array();
    1186      /** @var bool */
    1187      protected $allcategoriesloaded = false;
    1188      /** @var array An array of category ids that are included in the navigation */
    1189      protected $addedcategories = array();
    1190      /** @var int expansion limit */
    1191      protected $expansionlimit = 0;
    1192      /** @var int userid to allow parent to see child's profile page navigation */
    1193      protected $useridtouseforparentchecks = 0;
    1194      /** @var cache_session A cache that stores information on expanded courses */
    1195      protected $cacheexpandcourse = null;
    1196  
    1197      /** Used when loading categories to load all top level categories [parent = 0] **/
    1198      const LOAD_ROOT_CATEGORIES = 0;
    1199      /** Used when loading categories to load all categories **/
    1200      const LOAD_ALL_CATEGORIES = -1;
    1201  
    1202      /**
    1203       * Constructs a new global navigation
    1204       *
    1205       * @param moodle_page $page The page this navigation object belongs to
    1206       */
    1207      public function __construct(moodle_page $page) {
    1208          global $CFG, $SITE, $USER;
    1209  
    1210          if (during_initial_install()) {
    1211              return;
    1212          }
    1213  
    1214          if (get_home_page() == HOMEPAGE_SITE) {
    1215              // We are using the site home for the root element
    1216              $properties = array(
    1217                  'key' => 'home',
    1218                  'type' => navigation_node::TYPE_SYSTEM,
    1219                  'text' => get_string('home'),
    1220                  'action' => new moodle_url('/'),
    1221                  'icon' => new pix_icon('i/home', '')
    1222              );
    1223          } else {
    1224              // We are using the users my moodle for the root element
    1225              $properties = array(
    1226                  'key' => 'myhome',
    1227                  'type' => navigation_node::TYPE_SYSTEM,
    1228                  'text' => get_string('myhome'),
    1229                  'action' => new moodle_url('/my/'),
    1230                  'icon' => new pix_icon('i/dashboard', '')
    1231              );
    1232          }
    1233  
    1234          // Use the parents constructor.... good good reuse
    1235          parent::__construct($properties);
    1236          $this->showinflatnavigation = true;
    1237  
    1238          // Initalise and set defaults
    1239          $this->page = $page;
    1240          $this->forceopen = true;
    1241          $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
    1242      }
    1243  
    1244      /**
    1245       * Mutator to set userid to allow parent to see child's profile
    1246       * page navigation. See MDL-25805 for initial issue. Linked to it
    1247       * is an issue explaining why this is a REALLY UGLY HACK thats not
    1248       * for you to use!
    1249       *
    1250       * @param int $userid userid of profile page that parent wants to navigate around.
    1251       */
    1252      public function set_userid_for_parent_checks($userid) {
    1253          $this->useridtouseforparentchecks = $userid;
    1254      }
    1255  
    1256  
    1257      /**
    1258       * Initialises the navigation object.
    1259       *
    1260       * This causes the navigation object to look at the current state of the page
    1261       * that it is associated with and then load the appropriate content.
    1262       *
    1263       * This should only occur the first time that the navigation structure is utilised
    1264       * which will normally be either when the navbar is called to be displayed or
    1265       * when a block makes use of it.
    1266       *
    1267       * @return bool
    1268       */
    1269      public function initialise() {
    1270          global $CFG, $SITE, $USER;
    1271          // Check if it has already been initialised
    1272          if ($this->initialised || during_initial_install()) {
    1273              return true;
    1274          }
    1275          $this->initialised = true;
    1276  
    1277          // Set up the five base root nodes. These are nodes where we will put our
    1278          // content and are as follows:
    1279          // site: Navigation for the front page.
    1280          // myprofile: User profile information goes here.
    1281          // currentcourse: The course being currently viewed.
    1282          // mycourses: The users courses get added here.
    1283          // courses: Additional courses are added here.
    1284          // users: Other users information loaded here.
    1285          $this->rootnodes = array();
    1286          if (get_home_page() == HOMEPAGE_SITE) {
    1287              // The home element should be my moodle because the root element is the site
    1288              if (isloggedin() && !isguestuser()) {  // Makes no sense if you aren't logged in
    1289                  $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
    1290                      self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
    1291                  $this->rootnodes['home']->showinflatnavigation = true;
    1292              }
    1293          } else {
    1294              // The home element should be the site because the root node is my moodle
    1295              $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
    1296                  self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
    1297              $this->rootnodes['home']->showinflatnavigation = true;
    1298              if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
    1299                  // We need to stop automatic redirection
    1300                  $this->rootnodes['home']->action->param('redirect', '0');
    1301              }
    1302          }
    1303          $this->rootnodes['site'] = $this->add_course($SITE);
    1304          $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
    1305          $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
    1306          $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
    1307          $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
    1308          if (!core_course_category::user_top()) {
    1309              $this->rootnodes['courses']->hide();
    1310          }
    1311          $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
    1312  
    1313          // We always load the frontpage course to ensure it is available without
    1314          // JavaScript enabled.
    1315          $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
    1316          $this->load_course_sections($SITE, $this->rootnodes['site']);
    1317  
    1318          $course = $this->page->course;
    1319          $this->load_courses_enrolled();
    1320  
    1321          // $issite gets set to true if the current pages course is the sites frontpage course
    1322          $issite = ($this->page->course->id == $SITE->id);
    1323  
    1324          // Determine if the user is enrolled in any course.
    1325          $enrolledinanycourse = enrol_user_sees_own_courses();
    1326  
    1327          $this->rootnodes['currentcourse']->mainnavonly = true;
    1328          if ($enrolledinanycourse) {
    1329              $this->rootnodes['mycourses']->isexpandable = true;
    1330              $this->rootnodes['mycourses']->showinflatnavigation = true;
    1331              if ($CFG->navshowallcourses) {
    1332                  // When we show all courses we need to show both the my courses and the regular courses branch.
    1333                  $this->rootnodes['courses']->isexpandable = true;
    1334              }
    1335          } else {
    1336              $this->rootnodes['courses']->isexpandable = true;
    1337          }
    1338          $this->rootnodes['mycourses']->forceopen = true;
    1339  
    1340          $canviewcourseprofile = true;
    1341  
    1342          // Next load context specific content into the navigation
    1343          switch ($this->page->context->contextlevel) {
    1344              case CONTEXT_SYSTEM :
    1345                  // Nothing left to do here I feel.
    1346                  break;
    1347              case CONTEXT_COURSECAT :
    1348                  // This is essential, we must load categories.
    1349                  $this->load_all_categories($this->page->context->instanceid, true);
    1350                  break;
    1351              case CONTEXT_BLOCK :
    1352              case CONTEXT_COURSE :
    1353                  if ($issite) {
    1354                      // Nothing left to do here.
    1355                      break;
    1356                  }
    1357  
    1358                  // Load the course associated with the current page into the navigation.
    1359                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
    1360                  // If the course wasn't added then don't try going any further.
    1361                  if (!$coursenode) {
    1362                      $canviewcourseprofile = false;
    1363                      break;
    1364                  }
    1365  
    1366                  // If the user is not enrolled then we only want to show the
    1367                  // course node and not populate it.
    1368  
    1369                  // Not enrolled, can't view, and hasn't switched roles
    1370                  if (!can_access_course($course, null, '', true)) {
    1371                      if ($coursenode->isexpandable === true) {
    1372                          // Obviously the situation has changed, update the cache and adjust the node.
    1373                          // This occurs if the user access to a course has been revoked (one way or another) after
    1374                          // initially logging in for this session.
    1375                          $this->get_expand_course_cache()->set($course->id, 1);
    1376                          $coursenode->isexpandable = true;
    1377                          $coursenode->nodetype = self::NODETYPE_BRANCH;
    1378                      }
    1379                      // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
    1380                      // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
    1381                      if (!$this->current_user_is_parent_role()) {
    1382                          $coursenode->make_active();
    1383                          $canviewcourseprofile = false;
    1384                          break;
    1385                      }
    1386                  } else if ($coursenode->isexpandable === false) {
    1387                      // Obviously the situation has changed, update the cache and adjust the node.
    1388                      // This occurs if the user has been granted access to a course (one way or another) after initially
    1389                      // logging in for this session.
    1390                      $this->get_expand_course_cache()->set($course->id, 1);
    1391                      $coursenode->isexpandable = true;
    1392                      $coursenode->nodetype = self::NODETYPE_BRANCH;
    1393                  }
    1394  
    1395                  // Add the essentials such as reports etc...
    1396                  $this->add_course_essentials($coursenode, $course);
    1397                  // Extend course navigation with it's sections/activities
    1398                  $this->load_course_sections($course, $coursenode);
    1399                  if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
    1400                      $coursenode->make_active();
    1401                  }
    1402  
    1403                  break;
    1404              case CONTEXT_MODULE :
    1405                  if ($issite) {
    1406                      // If this is the site course then most information will have
    1407                      // already been loaded.
    1408                      // However we need to check if there is more content that can
    1409                      // yet be loaded for the specific module instance.
    1410                      $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
    1411                      if ($activitynode) {
    1412                          $this->load_activity($this->page->cm, $this->page->course, $activitynode);
    1413                      }
    1414                      break;
    1415                  }
    1416  
    1417                  $course = $this->page->course;
    1418                  $cm = $this->page->cm;
    1419  
    1420                  // Load the course associated with the page into the navigation
    1421                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
    1422  
    1423                  // If the course wasn't added then don't try going any further.
    1424                  if (!$coursenode) {
    1425                      $canviewcourseprofile = false;
    1426                      break;
    1427                  }
    1428  
    1429                  // If the user is not enrolled then we only want to show the
    1430                  // course node and not populate it.
    1431                  if (!can_access_course($course, null, '', true)) {
    1432                      $coursenode->make_active();
    1433                      $canviewcourseprofile = false;
    1434                      break;
    1435                  }
    1436  
    1437                  $this->add_course_essentials($coursenode, $course);
    1438  
    1439                  // Load the course sections into the page
    1440                  $this->load_course_sections($course, $coursenode, null, $cm);
    1441                  $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
    1442                  if (!empty($activity)) {
    1443                      // Finally load the cm specific navigaton information
    1444                      $this->load_activity($cm, $course, $activity);
    1445                      // Check if we have an active ndoe
    1446                      if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
    1447                          // And make the activity node active.
    1448                          $activity->make_active();
    1449                      }
    1450                  }
    1451                  break;
    1452              case CONTEXT_USER :
    1453                  if ($issite) {
    1454                      // The users profile information etc is already loaded
    1455                      // for the front page.
    1456                      break;
    1457                  }
    1458                  $course = $this->page->course;
    1459                  // Load the course associated with the user into the navigation
    1460                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
    1461  
    1462                  // If the course wasn't added then don't try going any further.
    1463                  if (!$coursenode) {
    1464                      $canviewcourseprofile = false;
    1465                      break;
    1466                  }
    1467  
    1468                  // If the user is not enrolled then we only want to show the
    1469                  // course node and not populate it.
    1470                  if (!can_access_course($course, null, '', true)) {
    1471                      $coursenode->make_active();
    1472                      $canviewcourseprofile = false;
    1473                      break;
    1474                  }
    1475                  $this->add_course_essentials($coursenode, $course);
    1476                  $this->load_course_sections($course, $coursenode);
    1477                  break;
    1478          }
    1479  
    1480          // Load for the current user
    1481          $this->load_for_user();
    1482          if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
    1483              $this->load_for_user(null, true);
    1484          }
    1485          // Load each extending user into the navigation.
    1486          foreach ($this->extendforuser as $user) {
    1487              if ($user->id != $USER->id) {
    1488                  $this->load_for_user($user);
    1489              }
    1490          }
    1491  
    1492          // Give the local plugins a chance to include some navigation if they want.
    1493          $this->load_local_plugin_navigation();
    1494  
    1495          // Remove any empty root nodes
    1496          foreach ($this->rootnodes as $node) {
    1497              // Dont remove the home node
    1498              /** @var navigation_node $node */
    1499              if (!in_array($node->key, ['home', 'myhome']) && !$node->has_children() && !$node->isactive) {
    1500                  $node->remove();
    1501              }
    1502          }
    1503  
    1504          if (!$this->contains_active_node()) {
    1505              $this->search_for_active_node();
    1506          }
    1507  
    1508          // If the user is not logged in modify the navigation structure as detailed
    1509          // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
    1510          if (!isloggedin()) {
    1511              $activities = clone($this->rootnodes['site']->children);
    1512              $this->rootnodes['site']->remove();
    1513              $children = clone($this->children);
    1514              $this->children = new navigation_node_collection();
    1515              foreach ($activities as $child) {
    1516                  $this->children->add($child);
    1517              }
    1518              foreach ($children as $child) {
    1519                  $this->children->add($child);
    1520              }
    1521          }
    1522          return true;
    1523      }
    1524  
    1525      /**
    1526       * This function gives local plugins an opportunity to modify navigation.
    1527       */
    1528      protected function load_local_plugin_navigation() {
    1529          foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
    1530              $function($this);
    1531          }
    1532      }
    1533  
    1534      /**
    1535       * Returns true if the current user is a parent of the user being currently viewed.
    1536       *
    1537       * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
    1538       * other user being viewed this function returns false.
    1539       * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
    1540       *
    1541       * @since Moodle 2.4
    1542       * @return bool
    1543       */
    1544      protected function current_user_is_parent_role() {
    1545          global $USER, $DB;
    1546          if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
    1547              $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
    1548              if (!has_capability('moodle/user:viewdetails', $usercontext)) {
    1549                  return false;
    1550              }
    1551              if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
    1552                  return true;
    1553              }
    1554          }
    1555          return false;
    1556      }
    1557  
    1558      /**
    1559       * Returns true if courses should be shown within categories on the navigation.
    1560       *
    1561       * @param bool $ismycourse Set to true if you are calculating this for a course.
    1562       * @return bool
    1563       */
    1564      protected function show_categories($ismycourse = false) {
    1565          global $CFG, $DB;
    1566          if ($ismycourse) {
    1567              return $this->show_my_categories();
    1568          }
    1569          if ($this->showcategories === null) {
    1570              $show = false;
    1571              if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
    1572                  $show = true;
    1573              } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
    1574                  $show = true;
    1575              }
    1576              $this->showcategories = $show;
    1577          }
    1578          return $this->showcategories;
    1579      }
    1580  
    1581      /**
    1582       * Returns true if we should show categories in the My Courses branch.
    1583       * @return bool
    1584       */
    1585      protected function show_my_categories() {
    1586          global $CFG;
    1587          if ($this->showmycategories === null) {
    1588              $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
    1589          }
    1590          return $this->showmycategories;
    1591      }
    1592  
    1593      /**
    1594       * Loads the courses in Moodle into the navigation.
    1595       *
    1596       * @global moodle_database $DB
    1597       * @param string|array $categoryids An array containing categories to load courses
    1598       *                     for, OR null to load courses for all categories.
    1599       * @return array An array of navigation_nodes one for each course
    1600       */
    1601      protected function load_all_courses($categoryids = null) {
    1602          global $CFG, $DB, $SITE;
    1603  
    1604          // Work out the limit of courses.
    1605          $limit = 20;
    1606          if (!empty($CFG->navcourselimit)) {
    1607              $limit = $CFG->navcourselimit;
    1608          }
    1609  
    1610          $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
    1611  
    1612          // If we are going to show all courses AND we are showing categories then
    1613          // to save us repeated DB calls load all of the categories now
    1614          if ($this->show_categories()) {
    1615              $this->load_all_categories($toload);
    1616          }
    1617  
    1618          // Will be the return of our efforts
    1619          $coursenodes = array();
    1620  
    1621          // Check if we need to show categories.
    1622          if ($this->show_categories()) {
    1623              // Hmmm we need to show categories... this is going to be painful.
    1624              // We now need to fetch up to $limit courses for each category to
    1625              // be displayed.
    1626              if ($categoryids !== null) {
    1627                  if (!is_array($categoryids)) {
    1628                      $categoryids = array($categoryids);
    1629                  }
    1630                  list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
    1631                  $categorywhere = 'WHERE cc.id '.$categorywhere;
    1632              } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
    1633                  $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
    1634                  $categoryparams = array();
    1635              } else {
    1636                  $categorywhere = '';
    1637                  $categoryparams = array();
    1638              }
    1639  
    1640              // First up we are going to get the categories that we are going to
    1641              // need so that we can determine how best to load the courses from them.
    1642              $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
    1643                          FROM {course_categories} cc
    1644                      LEFT JOIN {course} c ON c.category = cc.id
    1645                              {$categorywhere}
    1646                      GROUP BY cc.id";
    1647              $categories = $DB->get_recordset_sql($sql, $categoryparams);
    1648              $fullfetch = array();
    1649              $partfetch = array();
    1650              foreach ($categories as $category) {
    1651                  if (!$this->can_add_more_courses_to_category($category->id)) {
    1652                      continue;
    1653                  }
    1654                  if ($category->coursecount > $limit * 5) {
    1655                      $partfetch[] = $category->id;
    1656                  } else if ($category->coursecount > 0) {
    1657                      $fullfetch[] = $category->id;
    1658                  }
    1659              }
    1660              $categories->close();
    1661  
    1662              if (count($fullfetch)) {
    1663                  // First up fetch all of the courses in categories where we know that we are going to
    1664                  // need the majority of courses.
    1665                  list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
    1666                  $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
    1667                  $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
    1668                  $categoryparams['contextlevel'] = CONTEXT_COURSE;
    1669                  $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
    1670                              FROM {course} c
    1671                                  $ccjoin
    1672                              WHERE c.category {$categoryids}
    1673                          ORDER BY c.sortorder ASC";
    1674                  $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
    1675                  foreach ($coursesrs as $course) {
    1676                      if ($course->id == $SITE->id) {
    1677                          // This should not be necessary, frontpage is not in any category.
    1678                          continue;
    1679                      }
    1680                      if (array_key_exists($course->id, $this->addedcourses)) {
    1681                          // It is probably better to not include the already loaded courses
    1682                          // directly in SQL because inequalities may confuse query optimisers
    1683                          // and may interfere with query caching.
    1684                          continue;
    1685                      }
    1686                      if (!$this->can_add_more_courses_to_category($course->category)) {
    1687                          continue;
    1688                      }
    1689                      context_helper::preload_from_record($course);
    1690                      if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
    1691                          continue;
    1692                      }
    1693                      $coursenodes[$course->id] = $this->add_course($course);
    1694                  }
    1695                  $coursesrs->close();
    1696              }
    1697  
    1698              if (count($partfetch)) {
    1699                  // Next we will work our way through the categories where we will likely only need a small
    1700                  // proportion of the courses.
    1701                  foreach ($partfetch as $categoryid) {
    1702                      $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
    1703                      $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
    1704                      $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
    1705                                  FROM {course} c
    1706                                      $ccjoin
    1707                                  WHERE c.category = :categoryid
    1708                              ORDER BY c.sortorder ASC";
    1709                      $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
    1710                      $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
    1711                      foreach ($coursesrs as $course) {
    1712                          if ($course->id == $SITE->id) {
    1713                              // This should not be necessary, frontpage is not in any category.
    1714                              continue;
    1715                          }
    1716                          if (array_key_exists($course->id, $this->addedcourses)) {
    1717                              // It is probably better to not include the already loaded courses
    1718                              // directly in SQL because inequalities may confuse query optimisers
    1719                              // and may interfere with query caching.
    1720                              // This also helps to respect expected $limit on repeated executions.
    1721                              continue;
    1722                          }
    1723                          if (!$this->can_add_more_courses_to_category($course->category)) {
    1724                              break;
    1725                          }
    1726                          context_helper::preload_from_record($course);
    1727                          if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
    1728                              continue;
    1729                          }
    1730                          $coursenodes[$course->id] = $this->add_course($course);
    1731                      }
    1732                      $coursesrs->close();
    1733                  }
    1734              }
    1735          } else {
    1736              // Prepare the SQL to load the courses and their contexts
    1737              list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
    1738              $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
    1739              $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
    1740              $courseparams['contextlevel'] = CONTEXT_COURSE;
    1741              $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
    1742                          FROM {course} c
    1743                              $ccjoin
    1744                          WHERE c.id {$courseids}
    1745                      ORDER BY c.sortorder ASC";
    1746              $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
    1747              foreach ($coursesrs as $course) {
    1748                  if ($course->id == $SITE->id) {
    1749                      // frotpage is not wanted here
    1750                      continue;
    1751                  }
    1752                  if ($this->page->course && ($this->page->course->id == $course->id)) {
    1753                      // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
    1754                      continue;
    1755                  }
    1756                  context_helper::preload_from_record($course);
    1757                  if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
    1758                      continue;
    1759                  }
    1760                  $coursenodes[$course->id] = $this->add_course($course);
    1761                  if (count($coursenodes) >= $limit) {
    1762                      break;
    1763                  }
    1764              }
    1765              $coursesrs->close();
    1766          }
    1767  
    1768          return $coursenodes;
    1769      }
    1770  
    1771      /**
    1772       * Returns true if more courses can be added to the provided category.
    1773       *
    1774       * @param int|navigation_node|stdClass $category
    1775       * @return bool
    1776       */
    1777      protected function can_add_more_courses_to_category($category) {
    1778          global $CFG;
    1779          $limit = 20;
    1780          if (!empty($CFG->navcourselimit)) {
    1781              $limit = (int)$CFG->navcourselimit;
    1782          }
    1783          if (is_numeric($category)) {
    1784              if (!array_key_exists($category, $this->addedcategories)) {
    1785                  return true;
    1786              }
    1787              $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
    1788          } else if ($category instanceof navigation_node) {
    1789              if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
    1790                  return false;
    1791              }
    1792              $coursecount = count($category->children->type(self::TYPE_COURSE));
    1793          } else if (is_object($category) && property_exists($category,'id')) {
    1794              $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
    1795          }
    1796          return ($coursecount <= $limit);
    1797      }
    1798  
    1799      /**
    1800       * Loads all categories (top level or if an id is specified for that category)
    1801       *
    1802       * @param int $categoryid The category id to load or null/0 to load all base level categories
    1803       * @param bool $showbasecategories If set to true all base level categories will be loaded as well
    1804       *        as the requested category and any parent categories.
    1805       * @return navigation_node|void returns a navigation node if a category has been loaded.
    1806       */
    1807      protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
    1808          global $CFG, $DB;
    1809  
    1810          // Check if this category has already been loaded
    1811          if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
    1812              return true;
    1813          }
    1814  
    1815          $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
    1816          $sqlselect = "SELECT cc.*, $catcontextsql
    1817                        FROM {course_categories} cc
    1818                        JOIN {context} ctx ON cc.id = ctx.instanceid";
    1819          $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
    1820          $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
    1821          $params = array();
    1822  
    1823          $categoriestoload = array();
    1824          if ($categoryid == self::LOAD_ALL_CATEGORIES) {
    1825              // We are going to load all categories regardless... prepare to fire
    1826              // on the database server!
    1827          } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
    1828              // We are going to load all of the first level categories (categories without parents)
    1829              $sqlwhere .= " AND cc.parent = 0";
    1830          } else if (array_key_exists($categoryid, $this->addedcategories)) {
    1831              // The category itself has been loaded already so we just need to ensure its subcategories
    1832              // have been loaded
    1833              $addedcategories = $this->addedcategories;
    1834              unset($addedcategories[$categoryid]);
    1835              if (count($addedcategories) > 0) {
    1836                  list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
    1837                  if ($showbasecategories) {
    1838                      // We need to include categories with parent = 0 as well
    1839                      $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
    1840                  } else {
    1841                      // All we need is categories that match the parent
    1842                      $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
    1843                  }
    1844              }
    1845              $params['categoryid'] = $categoryid;
    1846          } else {
    1847              // This category hasn't been loaded yet so we need to fetch it, work out its category path
    1848              // and load this category plus all its parents and subcategories
    1849              $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
    1850              $categoriestoload = explode('/', trim($category->path, '/'));
    1851              list($select, $params) = $DB->get_in_or_equal($categoriestoload);
    1852              // We are going to use select twice so double the params
    1853              $params = array_merge($params, $params);
    1854              $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
    1855              $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
    1856          }
    1857  
    1858          $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
    1859          $categories = array();
    1860          foreach ($categoriesrs as $category) {
    1861              // Preload the context.. we'll need it when adding the category in order
    1862              // to format the category name.
    1863              context_helper::preload_from_record($category);
    1864              if (array_key_exists($category->id, $this->addedcategories)) {
    1865                  // Do nothing, its already been added.
    1866              } else if ($category->parent == '0') {
    1867                  // This is a root category lets add it immediately
    1868                  $this->add_category($category, $this->rootnodes['courses']);
    1869              } else if (array_key_exists($category->parent, $this->addedcategories)) {
    1870                  // This categories parent has already been added we can add this immediately
    1871                  $this->add_category($category, $this->addedcategories[$category->parent]);
    1872              } else {
    1873                  $categories[] = $category;
    1874              }
    1875          }
    1876          $categoriesrs->close();
    1877  
    1878          // Now we have an array of categories we need to add them to the navigation.
    1879          while (!empty($categories)) {
    1880              $category = reset($categories);
    1881              if (array_key_exists($category->id, $this->addedcategories)) {
    1882                  // Do nothing
    1883              } else if ($category->parent == '0') {
    1884                  $this->add_category($category, $this->rootnodes['courses']);
    1885              } else if (array_key_exists($category->parent, $this->addedcategories)) {
    1886                  $this->add_category($category, $this->addedcategories[$category->parent]);
    1887              } else {
    1888                  // This category isn't in the navigation and niether is it's parent (yet).
    1889                  // We need to go through the category path and add all of its components in order.
    1890                  $path = explode('/', trim($category->path, '/'));
    1891                  foreach ($path as $catid) {
    1892                      if (!array_key_exists($catid, $this->addedcategories)) {
    1893                          // This category isn't in the navigation yet so add it.
    1894                          $subcategory = $categories[$catid];
    1895                          if ($subcategory->parent == '0') {
    1896                              // Yay we have a root category - this likely means we will now be able
    1897                              // to add categories without problems.
    1898                              $this->add_category($subcategory, $this->rootnodes['courses']);
    1899                          } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
    1900                              // The parent is in the category (as we'd expect) so add it now.
    1901                              $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
    1902                              // Remove the category from the categories array.
    1903                              unset($categories[$catid]);
    1904                          } else {
    1905                              // We should never ever arrive here - if we have then there is a bigger
    1906                              // problem at hand.
    1907                              throw new coding_exception('Category path order is incorrect and/or there are missing categories');
    1908                          }
    1909                      }
    1910                  }
    1911              }
    1912              // Remove the category from the categories array now that we know it has been added.
    1913              unset($categories[$category->id]);
    1914          }
    1915          if ($categoryid === self::LOAD_ALL_CATEGORIES) {
    1916              $this->allcategoriesloaded = true;
    1917          }
    1918          // Check if there are any categories to load.
    1919          if (count($categoriestoload) > 0) {
    1920              $readytoloadcourses = array();
    1921              foreach ($categoriestoload as $category) {
    1922                  if ($this->can_add_more_courses_to_category($category)) {
    1923                      $readytoloadcourses[] = $category;
    1924                  }
    1925              }
    1926              if (count($readytoloadcourses)) {
    1927                  $this->load_all_courses($readytoloadcourses);
    1928              }
    1929          }
    1930  
    1931          // Look for all categories which have been loaded
    1932          if (!empty($this->addedcategories)) {
    1933              $categoryids = array();
    1934              foreach ($this->addedcategories as $category) {
    1935                  if ($this->can_add_more_courses_to_category($category)) {
    1936                      $categoryids[] = $category->key;
    1937                  }
    1938              }
    1939              if ($categoryids) {
    1940                  list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
    1941                  $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
    1942                  $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
    1943                            FROM {course_categories} cc
    1944                            JOIN {course} c ON c.category = cc.id
    1945                           WHERE cc.id {$categoriessql}
    1946                        GROUP BY cc.id
    1947                          HAVING COUNT(c.id) > :limit";
    1948                  $excessivecategories = $DB->get_records_sql($sql, $params);
    1949                  foreach ($categories as &$category) {
    1950                      if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
    1951                          $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
    1952                          $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
    1953                      }
    1954                  }
    1955              }
    1956          }
    1957      }
    1958  
    1959      /**
    1960       * Adds a structured category to the navigation in the correct order/place
    1961       *
    1962       * @param stdClass $category category to be added in navigation.
    1963       * @param navigation_node $parent parent navigation node
    1964       * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
    1965       * @return void.
    1966       */
    1967      protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
    1968          global $CFG;
    1969          if (array_key_exists($category->id, $this->addedcategories)) {
    1970              return;
    1971          }
    1972          $canview = core_course_category::can_view_category($category);
    1973          $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
    1974          $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id));
    1975          $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) :
    1976              get_string('categoryhidden');
    1977          $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
    1978          if (!$canview) {
    1979              // User does not have required capabilities to view category.
    1980              $categorynode->display = false;
    1981          } else if (!$category->visible) {
    1982              // Category is hidden but user has capability to view hidden categories.
    1983              $categorynode->hidden = true;
    1984          }
    1985          $this->addedcategories[$category->id] = $categorynode;
    1986      }
    1987  
    1988      /**
    1989       * Loads the given course into the navigation
    1990       *
    1991       * @param stdClass $course
    1992       * @return navigation_node
    1993       */
    1994      protected function load_course(stdClass $course) {
    1995          global $SITE;
    1996          if ($course->id == $SITE->id) {
    1997              // This is always loaded during initialisation
    1998              return $this->rootnodes['site'];
    1999          } else if (array_key_exists($course->id, $this->addedcourses)) {
    2000              // The course has already been loaded so return a reference
    2001              return $this->addedcourses[$course->id];
    2002          } else {
    2003              // Add the course
    2004              return $this->add_course($course);
    2005          }
    2006      }
    2007  
    2008      /**
    2009       * Loads all of the courses section into the navigation.
    2010       *
    2011       * This function calls method from current course format, see
    2012       * {@link format_base::extend_course_navigation()}
    2013       * If course module ($cm) is specified but course format failed to create the node,
    2014       * the activity node is created anyway.
    2015       *
    2016       * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
    2017       *
    2018       * @param stdClass $course Database record for the course
    2019       * @param navigation_node $coursenode The course node within the navigation
    2020       * @param null|int $sectionnum If specified load the contents of section with this relative number
    2021       * @param null|cm_info $cm If specified make sure that activity node is created (either
    2022       *    in containg section or by calling load_stealth_activity() )
    2023       */
    2024      protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
    2025          global $CFG, $SITE;
    2026          require_once($CFG->dirroot.'/course/lib.php');
    2027          if (isset($cm->sectionnum)) {
    2028              $sectionnum = $cm->sectionnum;
    2029          }
    2030          if ($sectionnum !== null) {
    2031              $this->includesectionnum = $sectionnum;
    2032          }
    2033          course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
    2034          if (isset($cm->id)) {
    2035              $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
    2036              if (empty($activity)) {
    2037                  $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
    2038              }
    2039          }
    2040     }
    2041  
    2042      /**
    2043       * Generates an array of sections and an array of activities for the given course.
    2044       *
    2045       * This method uses the cache to improve performance and avoid the get_fast_modinfo call
    2046       *
    2047       * @param stdClass $course
    2048       * @return array Array($sections, $activities)
    2049       */
    2050      protected function generate_sections_and_activities(stdClass $course) {
    2051          global $CFG;
    2052          require_once($CFG->dirroot.'/course/lib.php');
    2053  
    2054          $modinfo = get_fast_modinfo($course);
    2055          $sections = $modinfo->get_section_info_all();
    2056  
    2057          // For course formats using 'numsections' trim the sections list
    2058          $courseformatoptions = course_get_format($course)->get_format_options();
    2059          if (isset($courseformatoptions['numsections'])) {
    2060              $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
    2061          }
    2062  
    2063          $activities = array();
    2064  
    2065          foreach ($sections as $key => $section) {
    2066              // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
    2067              $sections[$key] = clone($section);
    2068              unset($sections[$key]->summary);
    2069              $sections[$key]->hasactivites = false;
    2070              if (!array_key_exists($section->section, $modinfo->sections)) {
    2071                  continue;
    2072              }
    2073              foreach ($modinfo->sections[$section->section] as $cmid) {
    2074                  $cm = $modinfo->cms[$cmid];
    2075                  $activity = new stdClass;
    2076                  $activity->id = $cm->id;
    2077                  $activity->course = $course->id;
    2078                  $activity->section = $section->section;
    2079                  $activity->name = $cm->name;
    2080                  $activity->icon = $cm->icon;
    2081                  $activity->iconcomponent = $cm->iconcomponent;
    2082                  $activity->hidden = (!$cm->visible);
    2083                  $activity->modname = $cm->modname;
    2084                  $activity->nodetype = navigation_node::NODETYPE_LEAF;
    2085                  $activity->onclick = $cm->onclick;
    2086                  $url = $cm->url;
    2087                  if (!$url) {
    2088                      $activity->url = null;
    2089                      $activity->display = false;
    2090                  } else {
    2091                      $activity->url = $url->out();
    2092                      $activity->display = $cm->is_visible_on_course_page() ? true : false;
    2093                      if (self::module_extends_navigation($cm->modname)) {
    2094                          $activity->nodetype = navigation_node::NODETYPE_BRANCH;
    2095                      }
    2096                  }
    2097                  $activities[$cmid] = $activity;
    2098                  if ($activity->display) {
    2099                      $sections[$key]->hasactivites = true;
    2100                  }
    2101              }
    2102          }
    2103  
    2104          return array($sections, $activities);
    2105      }
    2106  
    2107      /**
    2108       * Generically loads the course sections into the course's navigation.
    2109       *
    2110       * @param stdClass $course
    2111       * @param navigation_node $coursenode
    2112       * @return array An array of course section nodes
    2113       */
    2114      public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
    2115          global $CFG, $DB, $USER, $SITE;
    2116          require_once($CFG->dirroot.'/course/lib.php');
    2117  
    2118          list($sections, $activities) = $this->generate_sections_and_activities($course);
    2119  
    2120          $navigationsections = array();
    2121          foreach ($sections as $sectionid => $section) {
    2122              $section = clone($section);
    2123              if ($course->id == $SITE->id) {
    2124                  $this->load_section_activities($coursenode, $section->section, $activities);
    2125              } else {
    2126                  if (!$section->uservisible || (!$this->showemptysections &&
    2127                          !$section->hasactivites && $this->includesectionnum !== $section->section)) {
    2128                      continue;
    2129                  }
    2130  
    2131                  $sectionname = get_section_name($course, $section);
    2132                  $url = course_get_url($course, $section->section, array('navigation' => true));
    2133  
    2134                  $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
    2135                      null, $section->id, new pix_icon('i/section', ''));
    2136                  $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
    2137                  $sectionnode->hidden = (!$section->visible || !$section->available);
    2138                  if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
    2139                      $this->load_section_activities($sectionnode, $section->section, $activities);
    2140                  }
    2141                  $section->sectionnode = $sectionnode;
    2142                  $navigationsections[$sectionid] = $section;
    2143              }
    2144          }
    2145          return $navigationsections;
    2146      }
    2147  
    2148      /**
    2149       * Loads all of the activities for a section into the navigation structure.
    2150       *
    2151       * @param navigation_node $sectionnode
    2152       * @param int $sectionnumber
    2153       * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
    2154       * @param stdClass $course The course object the section and activities relate to.
    2155       * @return array Array of activity nodes
    2156       */
    2157      protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
    2158          global $CFG, $SITE;
    2159          // A static counter for JS function naming
    2160          static $legacyonclickcounter = 0;
    2161  
    2162          $activitynodes = array();
    2163          if (empty($activities)) {
    2164              return $activitynodes;
    2165          }
    2166  
    2167          if (!is_object($course)) {
    2168              $activity = reset($activities);
    2169              $courseid = $activity->course;
    2170          } else {
    2171              $courseid = $course->id;
    2172          }
    2173          $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
    2174  
    2175          foreach ($activities as $activity) {
    2176              if ($activity->section != $sectionnumber) {
    2177                  continue;
    2178              }
    2179              if ($activity->icon) {
    2180                  $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
    2181              } else {
    2182                  $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
    2183              }
    2184  
    2185              // Prepare the default name and url for the node
    2186              $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activity->id));
    2187              $activityname = format_string($activity->name, true, ['context' => $displaycontext]);
    2188              $action = new moodle_url($activity->url);
    2189  
    2190              // Check if the onclick property is set (puke!)
    2191              if (!empty($activity->onclick)) {
    2192                  // Increment the counter so that we have a unique number.
    2193                  $legacyonclickcounter++;
    2194                  // Generate the function name we will use
    2195                  $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
    2196                  $propogrationhandler = '';
    2197                  // Check if we need to cancel propogation. Remember inline onclick
    2198                  // events would return false if they wanted to prevent propogation and the
    2199                  // default action.
    2200                  if (strpos($activity->onclick, 'return false')) {
    2201                      $propogrationhandler = 'e.halt();';
    2202                  }
    2203                  // Decode the onclick - it has already been encoded for display (puke)
    2204                  $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
    2205                  // Build the JS function the click event will call
    2206                  $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
    2207                  $this->page->requires->js_amd_inline($jscode);
    2208                  // Override the default url with the new action link
    2209                  $action = new action_link($action, $activityname, new component_action('click', $functionname));
    2210              }
    2211  
    2212              $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
    2213              $activitynode->title(get_string('modulename', $activity->modname));
    2214              $activitynode->hidden = $activity->hidden;
    2215              $activitynode->display = $showactivities && $activity->display;
    2216              $activitynode->nodetype = $activity->nodetype;
    2217              $activitynodes[$activity->id] = $activitynode;
    2218          }
    2219  
    2220          return $activitynodes;
    2221      }
    2222      /**
    2223       * Loads a stealth module from unavailable section
    2224       * @param navigation_node $coursenode
    2225       * @param stdClass $modinfo
    2226       * @return navigation_node or null if not accessible
    2227       */
    2228      protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
    2229          if (empty($modinfo->cms[$this->page->cm->id])) {
    2230              return null;
    2231          }
    2232          $cm = $modinfo->cms[$this->page->cm->id];
    2233          if ($cm->icon) {
    2234              $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
    2235          } else {
    2236              $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
    2237          }
    2238          $url = $cm->url;
    2239          $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
    2240          $activitynode->title(get_string('modulename', $cm->modname));
    2241          $activitynode->hidden = (!$cm->visible);
    2242          if (!$cm->is_visible_on_course_page()) {
    2243              // Do not show any error here, let the page handle exception that activity is not visible for the current user.
    2244              // Also there may be no exception at all in case when teacher is logged in as student.
    2245              $activitynode->display = false;
    2246          } else if (!$url) {
    2247              // Don't show activities that don't have links!
    2248              $activitynode->display = false;
    2249          } else if (self::module_extends_navigation($cm->modname)) {
    2250              $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
    2251          }
    2252          return $activitynode;
    2253      }
    2254      /**
    2255       * Loads the navigation structure for the given activity into the activities node.
    2256       *
    2257       * This method utilises a callback within the modules lib.php file to load the
    2258       * content specific to activity given.
    2259       *
    2260       * The callback is a method: {modulename}_extend_navigation()
    2261       * Examples:
    2262       *  * {@link forum_extend_navigation()}
    2263       *  * {@link workshop_extend_navigation()}
    2264       *
    2265       * @param cm_info|stdClass $cm
    2266       * @param stdClass $course
    2267       * @param navigation_node $activity
    2268       * @return bool
    2269       */
    2270      protected function load_activity($cm, stdClass $course, navigation_node $activity) {
    2271          global $CFG, $DB;
    2272  
    2273          // make sure we have a $cm from get_fast_modinfo as this contains activity access details
    2274          if (!($cm instanceof cm_info)) {
    2275              $modinfo = get_fast_modinfo($course);
    2276              $cm = $modinfo->get_cm($cm->id);
    2277          }
    2278          $activity->nodetype = navigation_node::NODETYPE_LEAF;
    2279          $activity->make_active();
    2280          $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
    2281          $function = $cm->modname.'_extend_navigation';
    2282  
    2283          if (file_exists($file)) {
    2284              require_once($file);
    2285              if (function_exists($function)) {
    2286                  $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
    2287                  $function($activity, $course, $activtyrecord, $cm);
    2288              }
    2289          }
    2290  
    2291          // Allow the active advanced grading method plugin to append module navigation
    2292          $featuresfunc = $cm->modname.'_supports';
    2293          if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
    2294              require_once($CFG->dirroot.'/grade/grading/lib.php');
    2295              $gradingman = get_grading_manager($cm->context,  'mod_'.$cm->modname);
    2296              $gradingman->extend_navigation($this, $activity);
    2297          }
    2298  
    2299          return $activity->has_children();
    2300      }
    2301      /**
    2302       * Loads user specific information into the navigation in the appropriate place.
    2303       *
    2304       * If no user is provided the current user is assumed.
    2305       *
    2306       * @param stdClass $user
    2307       * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
    2308       * @return bool
    2309       */
    2310      protected function load_for_user($user=null, $forceforcontext=false) {
    2311          global $DB, $CFG, $USER, $SITE;
    2312  
    2313          require_once($CFG->dirroot . '/course/lib.php');
    2314  
    2315          if ($user === null) {
    2316              // We can't require login here but if the user isn't logged in we don't
    2317              // want to show anything
    2318              if (!isloggedin() || isguestuser()) {
    2319                  return false;
    2320              }
    2321              $user = $USER;
    2322          } else if (!is_object($user)) {
    2323              // If the user is not an object then get them from the database
    2324              $select = context_helper::get_preload_record_columns_sql('ctx');
    2325              $sql = "SELECT u.*, $select
    2326                        FROM {user} u
    2327                        JOIN {context} ctx ON u.id = ctx.instanceid
    2328                       WHERE u.id = :userid AND
    2329                             ctx.contextlevel = :contextlevel";
    2330              $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
    2331              context_helper::preload_from_record($user);
    2332          }
    2333  
    2334          $iscurrentuser = ($user->id == $USER->id);
    2335  
    2336          $usercontext = context_user::instance($user->id);
    2337  
    2338          // Get the course set against the page, by default this will be the site
    2339          $course = $this->page->course;
    2340          $baseargs = array('id'=>$user->id);
    2341          if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
    2342              $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
    2343              $baseargs['course'] = $course->id;
    2344              $coursecontext = context_course::instance($course->id);
    2345              $issitecourse = false;
    2346          } else {
    2347              // Load all categories and get the context for the system
    2348              $coursecontext = context_system::instance();
    2349              $issitecourse = true;
    2350          }
    2351  
    2352          // Create a node to add user information under.
    2353          $usersnode = null;
    2354          if (!$issitecourse) {
    2355              // Not the current user so add it to the participants node for the current course.
    2356              $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
    2357              $userviewurl = new moodle_url('/user/view.php', $baseargs);
    2358          } else if ($USER->id != $user->id) {
    2359              // This is the site so add a users node to the root branch.
    2360              $usersnode = $this->rootnodes['users'];
    2361              if (course_can_view_participants($coursecontext)) {
    2362                  $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
    2363              }
    2364              $userviewurl = new moodle_url('/user/profile.php', $baseargs);
    2365          }
    2366          if (!$usersnode) {
    2367              // We should NEVER get here, if the course hasn't been populated
    2368              // with a participants node then the navigaiton either wasn't generated
    2369              // for it (you are missing a require_login or set_context call) or
    2370              // you don't have access.... in the interests of no leaking informatin
    2371              // we simply quit...
    2372              return false;
    2373          }
    2374          // Add a branch for the current user.
    2375          // Only reveal user details if $user is the current user, or a user to which the current user has access.
    2376          $viewprofile = true;
    2377          if (!$iscurrentuser) {
    2378              require_once($CFG->dirroot . '/user/lib.php');
    2379              if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
    2380                  $viewprofile = false;
    2381              } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
    2382                  $viewprofile = false;
    2383              }
    2384              if (!$viewprofile) {
    2385                  $viewprofile = user_can_view_profile($user, null, $usercontext);
    2386              }
    2387          }
    2388  
    2389          // Now, conditionally add the user node.
    2390          if ($viewprofile) {
    2391              $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
    2392              $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
    2393          } else {
    2394              $usernode = $usersnode->add(get_string('user'));
    2395          }
    2396  
    2397          if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
    2398              $usernode->make_active();
    2399          }
    2400  
    2401          // Add user information to the participants or user node.
    2402          if ($issitecourse) {
    2403  
    2404              // If the user is the current user or has permission to view the details of the requested
    2405              // user than add a view profile link.
    2406              if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
    2407                      has_capability('moodle/user:viewdetails', $usercontext)) {
    2408                  if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
    2409                      $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
    2410                  } else {
    2411                      $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
    2412                  }
    2413              }
    2414  
    2415              if (!empty($CFG->navadduserpostslinks)) {
    2416                  // Add nodes for forum posts and discussions if the user can view either or both
    2417                  // There are no capability checks here as the content of the page is based
    2418                  // purely on the forums the current user has access too.
    2419                  $forumtab = $usernode->add(get_string('forumposts', 'forum'));
    2420                  $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
    2421                  $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
    2422                          array_merge($baseargs, array('mode' => 'discussions'))));
    2423              }
    2424  
    2425              // Add blog nodes.
    2426              if (!empty($CFG->enableblogs)) {
    2427                  if (!$this->cache->cached('userblogoptions'.$user->id)) {
    2428                      require_once($CFG->dirroot.'/blog/lib.php');
    2429                      // Get all options for the user.
    2430                      $options = blog_get_options_for_user($user);
    2431                      $this->cache->set('userblogoptions'.$user->id, $options);
    2432                  } else {
    2433                      $options = $this->cache->{'userblogoptions'.$user->id};
    2434                  }
    2435  
    2436                  if (count($options) > 0) {
    2437                      $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
    2438                      foreach ($options as $type => $option) {
    2439                          if ($type == "rss") {
    2440                              $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
    2441                                      new pix_icon('i/rss', ''));
    2442                          } else {
    2443                              $blogs->add($option['string'], $option['link']);
    2444                          }
    2445                      }
    2446                  }
    2447              }
    2448  
    2449              // Add the messages link.
    2450              // It is context based so can appear in the user's profile and in course participants information.
    2451              if (!empty($CFG->messaging)) {
    2452                  $messageargs = array('user1' => $USER->id);
    2453                  if ($USER->id != $user->id) {
    2454                      $messageargs['user2'] = $user->id;
    2455                  }
    2456                  $url = new moodle_url('/message/index.php', $messageargs);
    2457                  $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
    2458              }
    2459  
    2460              // Add the "My private files" link.
    2461              // This link doesn't have a unique display for course context so only display it under the user's profile.
    2462              if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
    2463                  $url = new moodle_url('/user/files.php');
    2464                  $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
    2465              }
    2466  
    2467              // Add a node to view the users notes if permitted.
    2468              if (!empty($CFG->enablenotes) &&
    2469                      has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
    2470                  $url = new moodle_url('/notes/index.php', array('user' => $user->id));
    2471                  if ($coursecontext->instanceid != SITEID) {
    2472                      $url->param('course', $coursecontext->instanceid);
    2473                  }
    2474                  $usernode->add(get_string('notes', 'notes'), $url);
    2475              }
    2476  
    2477              // Show the grades node.
    2478              if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
    2479                  require_once($CFG->dirroot . '/user/lib.php');
    2480                  // Set the grades node to link to the "Grades" page.
    2481                  if ($course->id == SITEID) {
    2482                      $url = user_mygrades_url($user->id, $course->id);
    2483                  } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
    2484                      $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
    2485                  }
    2486                  if ($USER->id != $user->id) {
    2487                      $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
    2488                  } else {
    2489                      $usernode->add(get_string('grades', 'grades'), $url);
    2490                  }
    2491              }
    2492  
    2493              // If the user is the current user add the repositories for the current user.
    2494              $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
    2495              if (!$iscurrentuser &&
    2496                      $course->id == $SITE->id &&
    2497                      has_capability('moodle/user:viewdetails', $usercontext) &&
    2498                      (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
    2499  
    2500                  // Add view grade report is permitted.
    2501                  $reports = core_component::get_plugin_list('gradereport');
    2502                  arsort($reports); // User is last, we want to test it first.
    2503  
    2504                  $userscourses = enrol_get_users_courses($user->id, false, '*');
    2505                  $userscoursesnode = $usernode->add(get_string('courses'));
    2506  
    2507                  $count = 0;
    2508                  foreach ($userscourses as $usercourse) {
    2509                      if ($count === (int)$CFG->navcourselimit) {
    2510                          $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
    2511                          $userscoursesnode->add(get_string('showallcourses'), $url);
    2512                          break;
    2513                      }
    2514                      $count++;
    2515                      $usercoursecontext = context_course::instance($usercourse->id);
    2516                      $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
    2517                      $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
    2518                              array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
    2519  
    2520                      $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
    2521                      if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
    2522                          foreach ($reports as $plugin => $plugindir) {
    2523                              if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
    2524                                  // Stop when the first visible plugin is found.
    2525                                  $gradeavailable = true;
    2526                                  break;
    2527                              }
    2528                          }
    2529                      }
    2530  
    2531                      if ($gradeavailable) {
    2532                          $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
    2533                          $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
    2534                                  new pix_icon('i/grades', ''));
    2535                      }
    2536  
    2537                      // Add a node to view the users notes if permitted.
    2538                      if (!empty($CFG->enablenotes) &&
    2539                              has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
    2540                          $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
    2541                          $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
    2542                      }
    2543  
    2544                      if (can_access_course($usercourse, $user->id, '', true)) {
    2545                          $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
    2546                                  array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
    2547                      }
    2548  
    2549                      $reporttab = $usercoursenode->add(get_string('activityreports'));
    2550  
    2551                      $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
    2552                      foreach ($reportfunctions as $reportfunction) {
    2553                          $reportfunction($reporttab, $user, $usercourse);
    2554                      }
    2555  
    2556                      $reporttab->trim_if_empty();
    2557                  }
    2558              }
    2559  
    2560              // Let plugins hook into user navigation.
    2561              $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
    2562              foreach ($pluginsfunction as $plugintype => $plugins) {
    2563                  if ($plugintype != 'report') {
    2564                      foreach ($plugins as $pluginfunction) {
    2565                          $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
    2566                      }
    2567                  }
    2568              }
    2569          }
    2570          return true;
    2571      }
    2572  
    2573      /**
    2574       * This method simply checks to see if a given module can extend the navigation.
    2575       *
    2576       * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
    2577       *
    2578       * @param string $modname
    2579       * @return bool
    2580       */
    2581      public static function module_extends_navigation($modname) {
    2582          global $CFG;
    2583          static $extendingmodules = array();
    2584          if (!array_key_exists($modname, $extendingmodules)) {
    2585              $extendingmodules[$modname] = false;
    2586              $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
    2587              if (file_exists($file)) {
    2588                  $function = $modname.'_extend_navigation';
    2589                  require_once($file);
    2590                  $extendingmodules[$modname] = (function_exists($function));
    2591              }
    2592          }
    2593          return $extendingmodules[$modname];
    2594      }
    2595      /**
    2596       * Extends the navigation for the given user.
    2597       *
    2598       * @param stdClass $user A user from the database
    2599       */
    2600      public function extend_for_user($user) {
    2601          $this->extendforuser[] = $user;
    2602      }
    2603  
    2604      /**
    2605       * Returns all of the users the navigation is being extended for
    2606       *
    2607       * @return array An array of extending users.
    2608       */
    2609      public function get_extending_users() {
    2610          return $this->extendforuser;
    2611      }
    2612      /**
    2613       * Adds the given course to the navigation structure.
    2614       *
    2615       * @param stdClass $course
    2616       * @param bool $forcegeneric
    2617       * @param bool $ismycourse
    2618       * @return navigation_node
    2619       */
    2620      public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
    2621          global $CFG, $SITE;
    2622  
    2623          // We found the course... we can return it now :)
    2624          if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
    2625              return $this->addedcourses[$course->id];
    2626          }
    2627  
    2628          $coursecontext = context_course::instance($course->id);
    2629  
    2630          if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
    2631              if (is_role_switched($course->id)) {
    2632                  // user has to be able to access course in order to switch, let's skip the visibility test here
    2633              } else if (!core_course_category::can_view_course_info($course)) {
    2634                  return false;
    2635              }
    2636          }
    2637  
    2638          $issite = ($course->id == $SITE->id);
    2639          $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
    2640          $shortname = format_string($course->shortname, true, ['context' => $displaycontext]);
    2641          $fullname = format_string($course->fullname, true, ['context' => $displaycontext]);
    2642          // This is the name that will be shown for the course.
    2643          $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
    2644  
    2645          if ($coursetype == self::COURSE_CURRENT) {
    2646              if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
    2647                  return $coursenode;
    2648              } else {
    2649                  $coursetype = self::COURSE_OTHER;
    2650              }
    2651          }
    2652  
    2653          // Can the user expand the course to see its content.
    2654          $canexpandcourse = true;
    2655          if ($issite) {
    2656              $parent = $this;
    2657              $url = null;
    2658              if (empty($CFG->usesitenameforsitepages)) {
    2659                  $coursename = get_string('sitepages');
    2660              }
    2661          } else if ($coursetype == self::COURSE_CURRENT) {
    2662              $parent = $this->rootnodes['currentcourse'];
    2663              $url = new moodle_url('/course/view.php', array('id'=>$course->id));
    2664              $canexpandcourse = $this->can_expand_course($course);
    2665          } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
    2666              if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
    2667                  // Nothing to do here the above statement set $parent to the category within mycourses.
    2668              } else {
    2669                  $parent = $this->rootnodes['mycourses'];
    2670              }
    2671              $url = new moodle_url('/course/view.php', array('id'=>$course->id));
    2672          } else {
    2673              $parent = $this->rootnodes['courses'];
    2674              $url = new moodle_url('/course/view.php', array('id'=>$course->id));
    2675              // They can only expand the course if they can access it.
    2676              $canexpandcourse = $this->can_expand_course($course);
    2677              if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
    2678                  if (!$this->is_category_fully_loaded($course->category)) {
    2679                      // We need to load the category structure for this course
    2680                      $this->load_all_categories($course->category, false);
    2681                  }
    2682                  if (array_key_exists($course->category, $this->addedcategories)) {
    2683                      $parent = $this->addedcategories[$course->category];
    2684                      // This could lead to the course being created so we should check whether it is the case again
    2685                      if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
    2686                          return $this->addedcourses[$course->id];
    2687                      }
    2688                  }
    2689              }
    2690          }
    2691  
    2692          $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
    2693          $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
    2694  
    2695          $coursenode->hidden = (!$course->visible);
    2696          $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false]));
    2697          if ($canexpandcourse) {
    2698              // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
    2699              $coursenode->nodetype = self::NODETYPE_BRANCH;
    2700              $coursenode->isexpandable = true;
    2701          } else {
    2702              $coursenode->nodetype = self::NODETYPE_LEAF;
    2703              $coursenode->isexpandable = false;
    2704          }
    2705          if (!$forcegeneric) {
    2706              $this->addedcourses[$course->id] = $coursenode;
    2707          }
    2708  
    2709          return $coursenode;
    2710      }
    2711  
    2712      /**
    2713       * Returns a cache instance to use for the expand course cache.
    2714       * @return cache_session
    2715       */
    2716      protected function get_expand_course_cache() {
    2717          if ($this->cacheexpandcourse === null) {
    2718              $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
    2719          }
    2720          return $this->cacheexpandcourse;
    2721      }
    2722  
    2723      /**
    2724       * Checks if a user can expand a course in the navigation.
    2725       *
    2726       * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
    2727       * Because this functionality is basic + non-essential and because we lack good event triggering this cache
    2728       * permits stale data.
    2729       * In the situation the user is granted access to a course after we've initialised this session cache the cache
    2730       * will be stale.
    2731       * It is brought up to date in only one of two ways.
    2732       *   1. The user logs out and in again.
    2733       *   2. The user browses to the course they've just being given access to.
    2734       *
    2735       * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
    2736       *
    2737       * @param stdClass $course
    2738       * @return bool
    2739       */
    2740      protected function can_expand_course($course) {
    2741          $cache = $this->get_expand_course_cache();
    2742          $canexpand = $cache->get($course->id);
    2743          if ($canexpand === false) {
    2744              $canexpand = isloggedin() && can_access_course($course, null, '', true);
    2745              $canexpand = (int)$canexpand;
    2746              $cache->set($course->id, $canexpand);
    2747          }
    2748          return ($canexpand === 1);
    2749      }
    2750  
    2751      /**
    2752       * Returns true if the category has already been loaded as have any child categories
    2753       *
    2754       * @param int $categoryid
    2755       * @return bool
    2756       */
    2757      protected function is_category_fully_loaded($categoryid) {
    2758          return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
    2759      }
    2760  
    2761      /**
    2762       * Adds essential course nodes to the navigation for the given course.
    2763       *
    2764       * This method adds nodes such as reports, blogs and participants
    2765       *
    2766       * @param navigation_node $coursenode
    2767       * @param stdClass $course
    2768       * @return bool returns true on successful addition of a node.
    2769       */
    2770      public function add_course_essentials($coursenode, stdClass $course) {
    2771          global $CFG, $SITE;
    2772          require_once($CFG->dirroot . '/course/lib.php');
    2773  
    2774          if ($course->id == $SITE->id) {
    2775              return $this->add_front_page_course_essentials($coursenode, $course);
    2776          }
    2777  
    2778          if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
    2779              return true;
    2780          }
    2781  
    2782          $navoptions = course_get_user_navigation_options($this->page->context, $course);
    2783  
    2784          //Participants
    2785          if ($navoptions->participants) {
    2786              $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
    2787                  self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
    2788  
    2789              if ($navoptions->blogs) {
    2790                  $blogsurls = new moodle_url('/blog/index.php');
    2791                  if ($currentgroup = groups_get_course_group($course, true)) {
    2792                      $blogsurls->param('groupid', $currentgroup);
    2793                  } else {
    2794                      $blogsurls->param('courseid', $course->id);
    2795                  }
    2796                  $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
    2797              }
    2798  
    2799              if ($navoptions->notes) {
    2800                  $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
    2801              }
    2802          } else if (count($this->extendforuser) > 0) {
    2803              $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
    2804          }
    2805  
    2806          // Badges.
    2807          if ($navoptions->badges) {
    2808              $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
    2809  
    2810              $coursenode->add(get_string('coursebadges', 'badges'), $url,
    2811                      navigation_node::TYPE_SETTING, null, 'badgesview',
    2812                      new pix_icon('i/badge', get_string('coursebadges', 'badges')));
    2813          }
    2814  
    2815          // Check access to the course and competencies page.
    2816          if ($navoptions->competencies) {
    2817              // Just a link to course competency.
    2818              $title = get_string('competencies', 'core_competency');
    2819              $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
    2820              $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
    2821                      new pix_icon('i/competencies', ''));
    2822          }
    2823          if ($navoptions->grades) {
    2824              $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
    2825              $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
    2826                  'grades', new pix_icon('i/grades', ''));
    2827              // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
    2828              if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
    2829                  $gradenode->make_active();
    2830              }
    2831          }
    2832  
    2833          return true;
    2834      }
    2835      /**
    2836       * This generates the structure of the course that won't be generated when
    2837       * the modules and sections are added.
    2838       *
    2839       * Things such as the reports branch, the participants branch, blogs... get
    2840       * added to the course node by this method.
    2841       *
    2842       * @param navigation_node $coursenode
    2843       * @param stdClass $course
    2844       * @return bool True for successfull generation
    2845       */
    2846      public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
    2847          global $CFG, $USER, $COURSE, $SITE;
    2848          require_once($CFG->dirroot . '/course/lib.php');
    2849  
    2850          if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
    2851              return true;
    2852          }
    2853  
    2854          $systemcontext = context_system::instance();
    2855          $navoptions = course_get_user_navigation_options($systemcontext, $course);
    2856  
    2857          // Hidden node that we use to determine if the front page navigation is loaded.
    2858          // This required as there are not other guaranteed nodes that may be loaded.
    2859          $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
    2860  
    2861          // Participants.
    2862          if ($navoptions->participants) {
    2863              $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
    2864          }
    2865  
    2866          // Blogs.
    2867          if ($navoptions->blogs) {
    2868              $blogsurls = new moodle_url('/blog/index.php');
    2869              $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
    2870          }
    2871  
    2872          $filterselect = 0;
    2873  
    2874          // Badges.
    2875          if ($navoptions->badges) {
    2876              $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
    2877              $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
    2878          }
    2879  
    2880          // Notes.
    2881          if ($navoptions->notes) {
    2882              $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
    2883                  array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
    2884          }
    2885  
    2886          // Tags
    2887          if ($navoptions->tags) {
    2888              $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
    2889                      self::TYPE_SETTING, null, 'tags');
    2890          }
    2891  
    2892          // Search.
    2893          if ($navoptions->search) {
    2894              $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
    2895                      self::TYPE_SETTING, null, 'search');
    2896          }
    2897  
    2898          if ($navoptions->calendar) {
    2899              $courseid = $COURSE->id;
    2900              $params = array('view' => 'month');
    2901              if ($courseid != $SITE->id) {
    2902                  $params['course'] = $courseid;
    2903              }
    2904  
    2905              // Calendar
    2906              $calendarurl = new moodle_url('/calendar/view.php', $params);
    2907              $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
    2908                  self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
    2909              $node->showinflatnavigation = true;
    2910          }
    2911  
    2912          if (isloggedin()) {
    2913              $usercontext = context_user::instance($USER->id);
    2914              if (has_capability('moodle/user:manageownfiles', $usercontext)) {
    2915                  $url = new moodle_url('/user/files.php');
    2916                  $node = $coursenode->add(get_string('privatefiles'), $url,
    2917                      self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
    2918                  $node->display = false;
    2919                  $node->showinflatnavigation = true;
    2920                  $node->mainnavonly = true;
    2921              }
    2922          }
    2923  
    2924          if (isloggedin()) {
    2925              $context = $this->page->context;
    2926              switch ($context->contextlevel) {
    2927                  case CONTEXT_COURSECAT:
    2928                      // OK, expected context level.
    2929                      break;
    2930                  case CONTEXT_COURSE:
    2931                      // OK, expected context level if not on frontpage.
    2932                      if ($COURSE->id != $SITE->id) {
    2933                          break;
    2934                      }
    2935                  default:
    2936                      // If this context is part of a course (excluding frontpage), use the course context.
    2937                      // Otherwise, use the system context.
    2938                      $coursecontext = $context->get_course_context(false);
    2939                      if ($coursecontext && $coursecontext->instanceid !== $SITE->id) {
    2940                          $context = $coursecontext;
    2941                      } else {
    2942                          $context = $systemcontext;
    2943                      }
    2944              }
    2945  
    2946              $params = ['contextid' => $context->id];
    2947              if (has_capability('moodle/contentbank:access', $context)) {
    2948                  $url = new moodle_url('/contentbank/index.php', $params);
    2949                  $node = $coursenode->add(get_string('contentbank'), $url,
    2950                      self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', ''));
    2951                  $node->showinflatnavigation = true;
    2952              }
    2953          }
    2954  
    2955          return true;
    2956      }
    2957  
    2958      /**
    2959       * Clears the navigation cache
    2960       */
    2961      public function clear_cache() {
    2962          $this->cache->clear();
    2963      }
    2964  
    2965      /**
    2966       * Sets an expansion limit for the navigation
    2967       *
    2968       * The expansion limit is used to prevent the display of content that has a type
    2969       * greater than the provided $type.
    2970       *
    2971       * Can be used to ensure things such as activities or activity content don't get
    2972       * shown on the navigation.
    2973       * They are still generated in order to ensure the navbar still makes sense.
    2974       *
    2975       * @param int $type One of navigation_node::TYPE_*
    2976       * @return bool true when complete.
    2977       */
    2978      public function set_expansion_limit($type) {
    2979          global $SITE;
    2980          $nodes = $this->find_all_of_type($type);
    2981  
    2982          // We only want to hide specific types of nodes.
    2983          // Only nodes that represent "structure" in the navigation tree should be hidden.
    2984          // If we hide all nodes then we risk hiding vital information.
    2985          $typestohide = array(
    2986              self::TYPE_CATEGORY,
    2987              self::TYPE_COURSE,
    2988              self::TYPE_SECTION,
    2989              self::TYPE_ACTIVITY
    2990          );
    2991  
    2992          foreach ($nodes as $node) {
    2993              // We need to generate the full site node
    2994              if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
    2995                  continue;
    2996              }
    2997              foreach ($node->children as $child) {
    2998                  $child->hide($typestohide);
    2999              }
    3000          }
    3001          return true;
    3002      }
    3003      /**
    3004       * Attempts to get the navigation with the given key from this nodes children.
    3005       *
    3006       * This function only looks at this nodes children, it does NOT look recursivily.
    3007       * If the node can't be found then false is returned.
    3008       *
    3009       * If you need to search recursivily then use the {@link global_navigation::find()} method.
    3010       *
    3011       * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
    3012       * may be of more use to you.
    3013       *
    3014       * @param string|int $key The key of the node you wish to receive.
    3015       * @param int $type One of navigation_node::TYPE_*
    3016       * @return navigation_node|false
    3017       */
    3018      public function get($key, $type = null) {
    3019          if (!$this->initialised) {
    3020              $this->initialise();
    3021          }
    3022          return parent::get($key, $type);
    3023      }
    3024  
    3025      /**
    3026       * Searches this nodes children and their children to find a navigation node
    3027       * with the matching key and type.
    3028       *
    3029       * This method is recursive and searches children so until either a node is
    3030       * found or there are no more nodes to search.
    3031       *
    3032       * If you know that the node being searched for is a child of this node
    3033       * then use the {@link global_navigation::get()} method instead.
    3034       *
    3035       * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
    3036       * may be of more use to you.
    3037       *
    3038       * @param string|int $key The key of the node you wish to receive.
    3039       * @param int $type One of navigation_node::TYPE_*
    3040       * @return navigation_node|false
    3041       */
    3042      public function find($key, $type) {
    3043          if (!$this->initialised) {
    3044              $this->initialise();
    3045          }
    3046          if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
    3047              return $this->rootnodes[$key];
    3048          }
    3049          return parent::find($key, $type);
    3050      }
    3051  
    3052      /**
    3053       * They've expanded the 'my courses' branch.
    3054       */
    3055      protected function load_courses_enrolled() {
    3056          global $CFG;
    3057  
    3058          $limit = (int) $CFG->navcourselimit;
    3059  
    3060          $courses = enrol_get_my_courses('*');
    3061          $flatnavcourses = [];
    3062  
    3063          // Go through the courses and see which ones we want to display in the flatnav.
    3064          foreach ($courses as $course) {
    3065              $classify = course_classify_for_timeline($course);
    3066  
    3067              if ($classify == COURSE_TIMELINE_INPROGRESS) {
    3068                  $flatnavcourses[$course->id] = $course;
    3069              }
    3070          }
    3071  
    3072          // Get the number of courses that can be displayed in the nav block and in the flatnav.
    3073          $numtotalcourses = count($courses);
    3074          $numtotalflatnavcourses = count($flatnavcourses);
    3075  
    3076          // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
    3077          $courses = array_slice($courses, 0, $limit, true);
    3078          $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
    3079  
    3080          // Get the number of courses we are going to show for each.
    3081          $numshowncourses = count($courses);
    3082          $numshownflatnavcourses = count($flatnavcourses);
    3083          if ($numshowncourses && $this->show_my_categories()) {
    3084              // Generate an array containing unique values of all the courses' categories.
    3085              $categoryids = array();
    3086              foreach ($courses as $course) {
    3087                  if (in_array($course->category, $categoryids)) {
    3088                      continue;
    3089                  }
    3090                  $categoryids[] = $course->category;
    3091              }
    3092  
    3093              // Array of category IDs that include the categories of the user's courses and the related course categories.
    3094              $fullpathcategoryids = [];
    3095              // Get the course categories for the enrolled courses' category IDs.
    3096              $mycoursecategories = core_course_category::get_many($categoryids);
    3097              // Loop over each of these categories and build the category tree using each category's path.
    3098              foreach ($mycoursecategories as $mycoursecat) {
    3099                  $pathcategoryids = explode('/', $mycoursecat->path);
    3100                  // First element of the exploded path is empty since paths begin with '/'.
    3101                  array_shift($pathcategoryids);
    3102                  // Merge the exploded category IDs into the full list of category IDs that we will fetch.
    3103                  $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
    3104              }
    3105  
    3106              // Fetch all of the categories related to the user's courses.
    3107              $pathcategories = core_course_category::get_many($fullpathcategoryids);
    3108              // Loop over each of these categories and build the category tree.
    3109              foreach ($pathcategories as $coursecat) {
    3110                  // No need to process categories that have already been added.
    3111                  if (isset($this->addedcategories[$coursecat->id])) {
    3112                      continue;
    3113                  }
    3114                  // Skip categories that are not visible.
    3115                  if (!$coursecat->is_uservisible()) {
    3116                      continue;
    3117                  }
    3118  
    3119                  // Get this course category's parent node.
    3120                  $parent = null;
    3121                  if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
    3122                      $parent = $this->addedcategories[$coursecat->parent];
    3123                  }
    3124                  if (!$parent) {
    3125                      // If it has no parent, then it should be right under the My courses node.
    3126                      $parent = $this->rootnodes['mycourses'];
    3127                  }
    3128  
    3129                  // Build the category object based from the coursecat object.
    3130                  $mycategory = new stdClass();
    3131                  $mycategory->id = $coursecat->id;
    3132                  $mycategory->name = $coursecat->name;
    3133                  $mycategory->visible = $coursecat->visible;
    3134  
    3135                  // Add this category to the nav tree.
    3136                  $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
    3137              }
    3138          }
    3139  
    3140          // Go through each course now and add it to the nav block, and the flatnav if applicable.
    3141          foreach ($courses as $course) {
    3142              $node = $this->add_course($course, false, self::COURSE_MY);
    3143              if ($node) {
    3144                  $node->showinflatnavigation = false;
    3145                  // Check if we should also add this to the flat nav as well.
    3146                  if (isset($flatnavcourses[$course->id])) {
    3147                      $node->showinflatnavigation = true;
    3148                  }
    3149              }
    3150          }
    3151  
    3152          // Go through each course in the flatnav now.
    3153          foreach ($flatnavcourses as $course) {
    3154              // Check if we haven't already added it.
    3155              if (!isset($courses[$course->id])) {
    3156                  // Ok, add it to the flatnav only.
    3157                  $node = $this->add_course($course, false, self::COURSE_MY);
    3158                  $node->display = false;
    3159                  $node->showinflatnavigation = true;
    3160              }
    3161          }
    3162  
    3163          $showmorelinkinnav = $numtotalcourses > $numshowncourses;
    3164          $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
    3165          // Show a link to the course page if there are more courses the user is enrolled in.
    3166          if ($showmorelinkinnav || $showmorelinkinflatnav) {
    3167              // Adding hash to URL so the link is not highlighted in the navigation when clicked.
    3168              $url = new moodle_url('/my/');
    3169              $parent = $this->rootnodes['mycourses'];
    3170              $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
    3171  
    3172              if ($showmorelinkinnav) {
    3173                  $coursenode->display = true;
    3174              }
    3175  
    3176              if ($showmorelinkinflatnav) {
    3177                  $coursenode->showinflatnavigation = true;
    3178              }
    3179          }
    3180      }
    3181  }
    3182  
    3183  /**
    3184   * The global navigation class used especially for AJAX requests.
    3185   *
    3186   * The primary methods that are used in the global navigation class have been overriden
    3187   * to ensure that only the relevant branch is generated at the root of the tree.
    3188   * This can be done because AJAX is only used when the backwards structure for the
    3189   * requested branch exists.
    3190   * This has been done only because it shortens the amounts of information that is generated
    3191   * which of course will speed up the response time.. because no one likes laggy AJAX.
    3192   *
    3193   * @package   core
    3194   * @category  navigation
    3195   * @copyright 2009 Sam Hemelryk
    3196   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3197   */
    3198  class global_navigation_for_ajax extends global_navigation {
    3199  
    3200      /** @var int used for determining what type of navigation_node::TYPE_* is being used */
    3201      protected $branchtype;
    3202  
    3203      /** @var int the instance id */
    3204      protected $instanceid;
    3205  
    3206      /** @var array Holds an array of expandable nodes */
    3207      protected $expandable = array();
    3208  
    3209      /**
    3210       * Constructs the navigation for use in an AJAX request
    3211       *
    3212       * @param moodle_page $page moodle_page object
    3213       * @param int $branchtype
    3214       * @param int $id
    3215       */
    3216      public function __construct($page, $branchtype, $id) {
    3217          $this->page = $page;
    3218          $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
    3219          $this->children = new navigation_node_collection();
    3220          $this->branchtype = $branchtype;
    3221          $this->instanceid = $id;
    3222          $this->initialise();
    3223      }
    3224      /**
    3225       * Initialise the navigation given the type and id for the branch to expand.
    3226       *
    3227       * @return array An array of the expandable nodes
    3228       */
    3229      public function initialise() {
    3230          global $DB, $SITE;
    3231  
    3232          if ($this->initialised || during_initial_install()) {
    3233              return $this->expandable;
    3234          }
    3235          $this->initialised = true;
    3236  
    3237          $this->rootnodes = array();
    3238          $this->rootnodes['site']    = $this->add_course($SITE);
    3239          $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
    3240          $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
    3241          // The courses branch is always displayed, and is always expandable (although may be empty).
    3242          // This mimicks what is done during {@link global_navigation::initialise()}.
    3243          $this->rootnodes['courses']->isexpandable = true;
    3244  
    3245          // Branchtype will be one of navigation_node::TYPE_*
    3246          switch ($this->branchtype) {
    3247              case 0:
    3248                  if ($this->instanceid === 'mycourses') {
    3249                      $this->load_courses_enrolled();
    3250                  } else if ($this->instanceid === 'courses') {
    3251                      $this->load_courses_other();
    3252                  }
    3253                  break;
    3254              case self::TYPE_CATEGORY :
    3255                  $this->load_category($this->instanceid);
    3256                  break;
    3257              case self::TYPE_MY_CATEGORY :
    3258                  $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
    3259                  break;
    3260              case self::TYPE_COURSE :
    3261                  $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
    3262                  if (!can_access_course($course, null, '', true)) {
    3263                      // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
    3264                      // add the course node and break. This leads to an empty node.
    3265                      $this->add_course($course);
    3266                      break;
    3267                  }
    3268                  require_course_login($course, true, null, false, true);
    3269                  $this->page->set_context(context_course::instance($course->id));
    3270                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
    3271                  $this->add_course_essentials($coursenode, $course);
    3272                  $this->load_course_sections($course, $coursenode);
    3273                  break;
    3274              case self::TYPE_SECTION :
    3275                  $sql = 'SELECT c.*, cs.section AS sectionnumber
    3276                          FROM {course} c
    3277                          LEFT JOIN {course_sections} cs ON cs.course = c.id
    3278                          WHERE cs.id = ?';
    3279                  $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
    3280                  require_course_login($course, true, null, false, true);
    3281                  $this->page->set_context(context_course::instance($course->id));
    3282                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
    3283                  $this->add_course_essentials($coursenode, $course);
    3284                  $this->load_course_sections($course, $coursenode, $course->sectionnumber);
    3285                  break;
    3286              case self::TYPE_ACTIVITY :
    3287                  $sql = "SELECT c.*
    3288                            FROM {course} c
    3289                            JOIN {course_modules} cm ON cm.course = c.id
    3290                           WHERE cm.id = :cmid";
    3291                  $params = array('cmid' => $this->instanceid);
    3292                  $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
    3293                  $modinfo = get_fast_modinfo($course);
    3294                  $cm = $modinfo->get_cm($this->instanceid);
    3295                  require_course_login($course, true, $cm, false, true);
    3296                  $this->page->set_context(context_module::instance($cm->id));
    3297                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
    3298                  $this->load_course_sections($course, $coursenode, null, $cm);
    3299                  $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
    3300                  if ($activitynode) {
    3301                      $modulenode = $this->load_activity($cm, $course, $activitynode);
    3302                  }
    3303                  break;
    3304              default:
    3305                  throw new Exception('Unknown type');
    3306                  return $this->expandable;
    3307          }
    3308  
    3309          if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
    3310              $this->load_for_user(null, true);
    3311          }
    3312  
    3313          // Give the local plugins a chance to include some navigation if they want.
    3314          $this->load_local_plugin_navigation();
    3315  
    3316          $this->find_expandable($this->expandable);
    3317          return $this->expandable;
    3318      }
    3319  
    3320      /**
    3321       * They've expanded the general 'courses' branch.
    3322       */
    3323      protected function load_courses_other() {
    3324          $this->load_all_courses();
    3325      }
    3326  
    3327      /**
    3328       * Loads a single category into the AJAX navigation.
    3329       *
    3330       * This function is special in that it doesn't concern itself with the parent of
    3331       * the requested category or its siblings.
    3332       * This is because with the AJAX navigation we know exactly what is wanted and only need to
    3333       * request that.
    3334       *
    3335       * @global moodle_database $DB
    3336       * @param int $categoryid id of category to load in navigation.
    3337       * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
    3338       * @return void.
    3339       */
    3340      protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
    3341          global $CFG, $DB;
    3342  
    3343          $limit = 20;
    3344          if (!empty($CFG->navcourselimit)) {
    3345              $limit = (int)$CFG->navcourselimit;
    3346          }
    3347  
    3348          $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
    3349          $sql = "SELECT cc.*, $catcontextsql
    3350                    FROM {course_categories} cc
    3351                    JOIN {context} ctx ON cc.id = ctx.instanceid
    3352                   WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
    3353                         (cc.id = :categoryid1 OR cc.parent = :categoryid2)
    3354                ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
    3355          $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
    3356          $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
    3357          $categorylist = array();
    3358          $subcategories = array();
    3359          $basecategory = null;
    3360          foreach ($categories as $category) {
    3361              $categorylist[] = $category->id;
    3362              context_helper::preload_from_record($category);
    3363              if ($category->id == $categoryid) {
    3364                  $this->add_category($category, $this, $nodetype);
    3365                  $basecategory = $this->addedcategories[$category->id];
    3366              } else {
    3367                  $subcategories[$category->id] = $category;
    3368              }
    3369          }
    3370          $categories->close();
    3371  
    3372  
    3373          // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
    3374          // else show all courses.
    3375          if ($nodetype === self::TYPE_MY_CATEGORY) {
    3376              $courses = enrol_get_my_courses('*');
    3377              $categoryids = array();
    3378  
    3379              // Only search for categories if basecategory was found.
    3380              if (!is_null($basecategory)) {
    3381                  // Get course parent category ids.
    3382                  foreach ($courses as $course) {
    3383                      $categoryids[] = $course->category;
    3384                  }
    3385  
    3386                  // Get a unique list of category ids which a part of the path
    3387                  // to user's courses.
    3388                  $coursesubcategories = array();
    3389                  $addedsubcategories = array();
    3390  
    3391                  list($sql, $params) = $DB->get_in_or_equal($categoryids);
    3392                  $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
    3393  
    3394                  foreach ($categories as $category){
    3395                      $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
    3396                  }
    3397                  $categories->close();
    3398                  $coursesubcategories = array_unique($coursesubcategories);
    3399  
    3400                  // Only add a subcategory if it is part of the path to user's course and
    3401                  // wasn't already added.
    3402                  foreach ($subcategories as $subid => $subcategory) {
    3403                      if (in_array($subid, $coursesubcategories) &&
    3404                              !in_array($subid, $addedsubcategories)) {
    3405                              $this->add_category($subcategory, $basecategory, $nodetype);
    3406                              $addedsubcategories[] = $subid;
    3407                      }
    3408                  }
    3409              }
    3410  
    3411              foreach ($courses as $course) {
    3412                  // Add course if it's in category.
    3413                  if (in_array($course->category, $categorylist)) {
    3414                      $this->add_course($course, true, self::COURSE_MY);
    3415                  }
    3416              }
    3417          } else {
    3418              if (!is_null($basecategory)) {
    3419                  foreach ($subcategories as $key=>$category) {
    3420                      $this->add_category($category, $basecategory, $nodetype);
    3421                  }
    3422              }
    3423              $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
    3424              foreach ($courses as $course) {
    3425                  $this->add_course($course);
    3426              }
    3427              $courses->close();
    3428          }
    3429      }
    3430  
    3431      /**
    3432       * Returns an array of expandable nodes
    3433       * @return array
    3434       */
    3435      public function get_expandable() {
    3436          return $this->expandable;
    3437      }
    3438  }
    3439  
    3440  /**
    3441   * Navbar class
    3442   *
    3443   * This class is used to manage the navbar, which is initialised from the navigation
    3444   * object held by PAGE
    3445   *
    3446   * @package   core
    3447   * @category  navigation
    3448   * @copyright 2009 Sam Hemelryk
    3449   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3450   */
    3451  class navbar extends navigation_node {
    3452      /** @var bool A switch for whether the navbar is initialised or not */
    3453      protected $initialised = false;
    3454      /** @var mixed keys used to reference the nodes on the navbar */
    3455      protected $keys = array();
    3456      /** @var null|string content of the navbar */
    3457      protected $content = null;
    3458      /** @var moodle_page object the moodle page that this navbar belongs to */
    3459      protected $page;
    3460      /** @var bool A switch for whether to ignore the active navigation information */
    3461      protected $ignoreactive = false;
    3462      /** @var bool A switch to let us know if we are in the middle of an install */
    3463      protected $duringinstall = false;
    3464      /** @var bool A switch for whether the navbar has items */
    3465      protected $hasitems = false;
    3466      /** @var array An array of navigation nodes for the navbar */
    3467      protected $items;
    3468      /** @var array An array of child node objects */
    3469      public $children = array();
    3470      /** @var bool A switch for whether we want to include the root node in the navbar */
    3471      public $includesettingsbase = false;
    3472      /** @var breadcrumb_navigation_node[] $prependchildren */
    3473      protected $prependchildren = array();
    3474  
    3475      /**
    3476       * The almighty constructor
    3477       *
    3478       * @param moodle_page $page
    3479       */
    3480      public function __construct(moodle_page $page) {
    3481          global $CFG;
    3482          if (during_initial_install()) {
    3483              $this->duringinstall = true;
    3484              return false;
    3485          }
    3486          $this->page = $page;
    3487          $this->text = get_string('home');
    3488          $this->shorttext = get_string('home');
    3489          $this->action = new moodle_url($CFG->wwwroot);
    3490          $this->nodetype = self::NODETYPE_BRANCH;
    3491          $this->type = self::TYPE_SYSTEM;
    3492      }
    3493  
    3494      /**
    3495       * Quick check to see if the navbar will have items in.
    3496       *
    3497       * @return bool Returns true if the navbar will have items, false otherwise
    3498       */
    3499      public function has_items() {
    3500          if ($this->duringinstall) {
    3501              return false;
    3502          } else if ($this->hasitems !== false) {
    3503              return true;
    3504          }
    3505          if (count($this->children) > 0 || count($this->prependchildren) > 0) {
    3506              // There have been manually added items - there are definitely items.
    3507              $outcome = true;
    3508          } else if (!$this->ignoreactive) {
    3509              // We will need to initialise the navigation structure to check if there are active items.
    3510              $this->page->navigation->initialise($this->page);
    3511              $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
    3512          }
    3513          $this->hasitems = $outcome;
    3514          return $outcome;
    3515      }
    3516  
    3517      /**
    3518       * Turn on/off ignore active
    3519       *
    3520       * @param bool $setting
    3521       */
    3522      public function ignore_active($setting=true) {
    3523          $this->ignoreactive = ($setting);
    3524      }
    3525  
    3526      /**
    3527       * Gets a navigation node
    3528       *
    3529       * @param string|int $key for referencing the navbar nodes
    3530       * @param int $type breadcrumb_navigation_node::TYPE_*
    3531       * @return breadcrumb_navigation_node|bool
    3532       */
    3533      public function get($key, $type = null) {
    3534          foreach ($this->children as &$child) {
    3535              if ($child->key === $key && ($type == null || $type == $child->type)) {
    3536                  return $child;
    3537              }
    3538          }
    3539          foreach ($this->prependchildren as &$child) {
    3540              if ($child->key === $key && ($type == null || $type == $child->type)) {
    3541                  return $child;
    3542              }
    3543          }
    3544          return false;
    3545      }
    3546      /**
    3547       * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
    3548       *
    3549       * @return array
    3550       */
    3551      public function get_items() {
    3552          global $CFG;
    3553          $items = array();
    3554          // Make sure that navigation is initialised
    3555          if (!$this->has_items()) {
    3556              return $items;
    3557          }
    3558          if ($this->items !== null) {
    3559              return $this->items;
    3560          }
    3561  
    3562          if (count($this->children) > 0) {
    3563              // Add the custom children.
    3564              $items = array_reverse($this->children);
    3565          }
    3566  
    3567          // Check if navigation contains the active node
    3568          if (!$this->ignoreactive) {
    3569              // We will need to ensure the navigation has been initialised.
    3570              $this->page->navigation->initialise($this->page);
    3571              // Now find the active nodes on both the navigation and settings.
    3572              $navigationactivenode = $this->page->navigation->find_active_node();
    3573              $settingsactivenode = $this->page->settingsnav->find_active_node();
    3574  
    3575              if ($navigationactivenode && $settingsactivenode) {
    3576                  // Parse a combined navigation tree
    3577                  while ($settingsactivenode && $settingsactivenode->parent !== null) {
    3578                      if (!$settingsactivenode->mainnavonly) {
    3579                          $items[] = new breadcrumb_navigation_node($settingsactivenode);
    3580                      }
    3581                      $settingsactivenode = $settingsactivenode->parent;
    3582                  }
    3583                  if (!$this->includesettingsbase) {
    3584                      // Removes the first node from the settings (root node) from the list
    3585                      array_pop($items);
    3586                  }
    3587                  while ($navigationactivenode && $navigationactivenode->parent !== null) {
    3588                      if (!$navigationactivenode->mainnavonly) {
    3589                          $items[] = new breadcrumb_navigation_node($navigationactivenode);
    3590                      }
    3591                      if (!empty($CFG->navshowcategories) &&
    3592                              $navigationactivenode->type === self::TYPE_COURSE &&
    3593                              $navigationactivenode->parent->key === 'currentcourse') {
    3594                          foreach ($this->get_course_categories() as $item) {
    3595                              $items[] = new breadcrumb_navigation_node($item);
    3596                          }
    3597                      }
    3598                      $navigationactivenode = $navigationactivenode->parent;
    3599                  }
    3600              } else if ($navigationactivenode) {
    3601                  // Parse the navigation tree to get the active node
    3602                  while ($navigationactivenode && $navigationactivenode->parent !== null) {
    3603                      if (!$navigationactivenode->mainnavonly) {
    3604                          $items[] = new breadcrumb_navigation_node($navigationactivenode);
    3605                      }
    3606                      if (!empty($CFG->navshowcategories) &&
    3607                              $navigationactivenode->type === self::TYPE_COURSE &&
    3608                              $navigationactivenode->parent->key === 'currentcourse') {
    3609                          foreach ($this->get_course_categories() as $item) {
    3610                              $items[] = new breadcrumb_navigation_node($item);
    3611                          }
    3612                      }
    3613                      $navigationactivenode = $navigationactivenode->parent;
    3614                  }
    3615              } else if ($settingsactivenode) {
    3616                  // Parse the settings navigation to get the active node
    3617                  while ($settingsactivenode && $settingsactivenode->parent !== null) {
    3618                      if (!$settingsactivenode->mainnavonly) {
    3619                          $items[] = new breadcrumb_navigation_node($settingsactivenode);
    3620                      }
    3621                      $settingsactivenode = $settingsactivenode->parent;
    3622                  }
    3623              }
    3624          }
    3625  
    3626          $items[] = new breadcrumb_navigation_node(array(
    3627              'text' => $this->page->navigation->text,
    3628              'shorttext' => $this->page->navigation->shorttext,
    3629              'key' => $this->page->navigation->key,
    3630              'action' => $this->page->navigation->action
    3631          ));
    3632  
    3633          if (count($this->prependchildren) > 0) {
    3634              // Add the custom children
    3635              $items = array_merge($items, array_reverse($this->prependchildren));
    3636          }
    3637  
    3638          $last = reset($items);
    3639          if ($last) {
    3640              $last->set_last(true);
    3641          }
    3642          $this->items = array_reverse($items);
    3643          return $this->items;
    3644      }
    3645  
    3646      /**
    3647       * Get the list of categories leading to this course.
    3648       *
    3649       * This function is used by {@link navbar::get_items()} to add back the "courses"
    3650       * node and category chain leading to the current course.  Note that this is only ever
    3651       * called for the current course, so we don't need to bother taking in any parameters.
    3652       *
    3653       * @return array
    3654       */
    3655      private function get_course_categories() {
    3656          global $CFG;
    3657          require_once($CFG->dirroot.'/course/lib.php');
    3658  
    3659          $categories = array();
    3660          $cap = 'moodle/category:viewhiddencategories';
    3661          $showcategories = !core_course_category::is_simple_site();
    3662  
    3663          if ($showcategories) {
    3664              foreach ($this->page->categories as $category) {
    3665                  $context = context_coursecat::instance($category->id);
    3666                  if (!core_course_category::can_view_category($category)) {
    3667                      continue;
    3668                  }
    3669  
    3670                  $displaycontext = \context_helper::get_navigation_filter_context($context);
    3671                  $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]);
    3672                  $name = format_string($category->name, true, ['context' => $displaycontext]);
    3673                  $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
    3674                  if (!$category->visible) {
    3675                      $categorynode->hidden = true;
    3676                  }
    3677                  $categories[] = $categorynode;
    3678              }
    3679          }
    3680  
    3681          // Don't show the 'course' node if enrolled in this course.
    3682          $coursecontext = context_course::instance($this->page->course->id);
    3683          if (!is_enrolled($coursecontext, null, '', true)) {
    3684              $courses = $this->page->navigation->get('courses');
    3685              if (!$courses) {
    3686                  // Courses node may not be present.
    3687                  $courses = breadcrumb_navigation_node::create(
    3688                      get_string('courses'),
    3689                      new moodle_url('/course/index.php'),
    3690                      self::TYPE_CONTAINER
    3691                  );
    3692              }
    3693              $categories[] = $courses;
    3694          }
    3695  
    3696          return $categories;
    3697      }
    3698  
    3699      /**
    3700       * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
    3701       *
    3702       * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
    3703       * the way nodes get added to allow us to simply call add and have the node added to the
    3704       * end of the navbar
    3705       *
    3706       * @param string $text
    3707       * @param string|moodle_url|action_link $action An action to associate with this node.
    3708       * @param int $type One of navigation_node::TYPE_*
    3709       * @param string $shorttext
    3710       * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
    3711       * @param pix_icon $icon An optional icon to use for this node.
    3712       * @return navigation_node
    3713       */
    3714      public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
    3715          if ($this->content !== null) {
    3716              debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
    3717          }
    3718  
    3719          // Properties array used when creating the new navigation node
    3720          $itemarray = array(
    3721              'text' => $text,
    3722              'type' => $type
    3723          );
    3724          // Set the action if one was provided
    3725          if ($action!==null) {
    3726              $itemarray['action'] = $action;
    3727          }
    3728          // Set the shorttext if one was provided
    3729          if ($shorttext!==null) {
    3730              $itemarray['shorttext'] = $shorttext;
    3731          }
    3732          // Set the icon if one was provided
    3733          if ($icon!==null) {
    3734              $itemarray['icon'] = $icon;
    3735          }
    3736          // Default the key to the number of children if not provided
    3737          if ($key === null) {
    3738              $key = count($this->children);
    3739          }
    3740          // Set the key
    3741          $itemarray['key'] = $key;
    3742          // Set the parent to this node
    3743          $itemarray['parent'] = $this;
    3744          // Add the child using the navigation_node_collections add method
    3745          $this->children[] = new breadcrumb_navigation_node($itemarray);
    3746          return $this;
    3747      }
    3748  
    3749      /**
    3750       * Prepends a new navigation_node to the start of the navbar
    3751       *
    3752       * @param string $text
    3753       * @param string|moodle_url|action_link $action An action to associate with this node.
    3754       * @param int $type One of navigation_node::TYPE_*
    3755       * @param string $shorttext
    3756       * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
    3757       * @param pix_icon $icon An optional icon to use for this node.
    3758       * @return navigation_node
    3759       */
    3760      public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon