Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

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