[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/lib/ -> navigationlib.php (source)

   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)) {
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                  }
1192  
1193                  if ($coursenode->isexpandable === false) {
1194                      // Obviously the situation has changed, update the cache and adjust the node.
1195                      // This occurs if the user has been granted access to a course (one way or another) after initially
1196                      // logging in for this session.
1197                      $this->get_expand_course_cache()->set($course->id, 1);
1198                      $coursenode->isexpandable = true;
1199                      $coursenode->nodetype = self::NODETYPE_BRANCH;
1200                  }
1201  
1202                  // Add the essentials such as reports etc...
1203                  $this->add_course_essentials($coursenode, $course);
1204                  // Extend course navigation with it's sections/activities
1205                  $this->load_course_sections($course, $coursenode);
1206                  if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1207                      $coursenode->make_active();
1208                  }
1209  
1210                  break;
1211              case CONTEXT_MODULE :
1212                  if ($issite) {
1213                      // If this is the site course then most information will have
1214                      // already been loaded.
1215                      // However we need to check if there is more content that can
1216                      // yet be loaded for the specific module instance.
1217                      $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1218                      if ($activitynode) {
1219                          $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1220                      }
1221                      break;
1222                  }
1223  
1224                  $course = $this->page->course;
1225                  $cm = $this->page->cm;
1226  
1227                  // Load the course associated with the page into the navigation
1228                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1229  
1230                  // If the course wasn't added then don't try going any further.
1231                  if (!$coursenode) {
1232                      $canviewcourseprofile = false;
1233                      break;
1234                  }
1235  
1236                  // If the user is not enrolled then we only want to show the
1237                  // course node and not populate it.
1238                  if (!can_access_course($course)) {
1239                      $coursenode->make_active();
1240                      $canviewcourseprofile = false;
1241                      break;
1242                  }
1243  
1244                  $this->add_course_essentials($coursenode, $course);
1245  
1246                  // Load the course sections into the page
1247                  $this->load_course_sections($course, $coursenode, null, $cm);
1248                  $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1249                  if (!empty($activity)) {
1250                      // Finally load the cm specific navigaton information
1251                      $this->load_activity($cm, $course, $activity);
1252                      // Check if we have an active ndoe
1253                      if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1254                          // And make the activity node active.
1255                          $activity->make_active();
1256                      }
1257                  }
1258                  break;
1259              case CONTEXT_USER :
1260                  if ($issite) {
1261                      // The users profile information etc is already loaded
1262                      // for the front page.
1263                      break;
1264                  }
1265                  $course = $this->page->course;
1266                  // Load the course associated with the user into the navigation
1267                  $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1268  
1269                  // If the course wasn't added then don't try going any further.
1270                  if (!$coursenode) {
1271                      $canviewcourseprofile = false;
1272                      break;
1273                  }
1274  
1275                  // If the user is not enrolled then we only want to show the
1276                  // course node and not populate it.
1277                  if (!can_access_course($course)) {
1278                      $coursenode->make_active();
1279                      $canviewcourseprofile = false;
1280                      break;
1281                  }
1282                  $this->add_course_essentials($coursenode, $course);
1283                  $this->load_course_sections($course, $coursenode);
1284                  break;
1285          }
1286  
1287          // Load for the current user
1288          $this->load_for_user();
1289          if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1290              $this->load_for_user(null, true);
1291          }
1292          // Load each extending user into the navigation.
1293          foreach ($this->extendforuser as $user) {
1294              if ($user->id != $USER->id) {
1295                  $this->load_for_user($user);
1296              }
1297          }
1298  
1299          // Give the local plugins a chance to include some navigation if they want.
1300          foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1301              $function = "local_{$plugin}_extends_navigation";
1302              $oldfunction = "{$plugin}_extends_navigation";
1303              if (function_exists($function)) {
1304                  // This is the preferred function name as there is less chance of conflicts
1305                  $function($this);
1306              } else if (function_exists($oldfunction)) {
1307                  // We continue to support the old function name to ensure backwards compatibility
1308                  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);
1309                  $oldfunction($this);
1310              }
1311          }
1312  
1313          // Remove any empty root nodes
1314          foreach ($this->rootnodes as $node) {
1315              // Dont remove the home node
1316              /** @var navigation_node $node */
1317              if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1318                  $node->remove();
1319              }
1320          }
1321  
1322          if (!$this->contains_active_node()) {
1323              $this->search_for_active_node();
1324          }
1325  
1326          // If the user is not logged in modify the navigation structure as detailed
1327          // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1328          if (!isloggedin()) {
1329              $activities = clone($this->rootnodes['site']->children);
1330              $this->rootnodes['site']->remove();
1331              $children = clone($this->children);
1332              $this->children = new navigation_node_collection();
1333              foreach ($activities as $child) {
1334                  $this->children->add($child);
1335              }
1336              foreach ($children as $child) {
1337                  $this->children->add($child);
1338              }
1339          }
1340          return true;
1341      }
1342  
1343      /**
1344       * Returns true if the current user is a parent of the user being currently viewed.
1345       *
1346       * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1347       * other user being viewed this function returns false.
1348       * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1349       *
1350       * @since Moodle 2.4
1351       * @return bool
1352       */
1353      protected function current_user_is_parent_role() {
1354          global $USER, $DB;
1355          if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1356              $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1357              if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1358                  return false;
1359              }
1360              if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1361                  return true;
1362              }
1363          }
1364          return false;
1365      }
1366  
1367      /**
1368       * Returns true if courses should be shown within categories on the navigation.
1369       *
1370       * @param bool $ismycourse Set to true if you are calculating this for a course.
1371       * @return bool
1372       */
1373      protected function show_categories($ismycourse = false) {
1374          global $CFG, $DB;
1375          if ($ismycourse) {
1376              return $this->show_my_categories();
1377          }
1378          if ($this->showcategories === null) {
1379              $show = false;
1380              if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1381                  $show = true;
1382              } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1383                  $show = true;
1384              }
1385              $this->showcategories = $show;
1386          }
1387          return $this->showcategories;
1388      }
1389  
1390      /**
1391       * Returns true if we should show categories in the My Courses branch.
1392       * @return bool
1393       */
1394      protected function show_my_categories() {
1395          global $CFG, $DB;
1396          if ($this->showmycategories === null) {
1397              $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1398          }
1399          return $this->showmycategories;
1400      }
1401  
1402      /**
1403       * Loads the courses in Moodle into the navigation.
1404       *
1405       * @global moodle_database $DB
1406       * @param string|array $categoryids An array containing categories to load courses
1407       *                     for, OR null to load courses for all categories.
1408       * @return array An array of navigation_nodes one for each course
1409       */
1410      protected function load_all_courses($categoryids = null) {
1411          global $CFG, $DB, $SITE;
1412  
1413          // Work out the limit of courses.
1414          $limit = 20;
1415          if (!empty($CFG->navcourselimit)) {
1416              $limit = $CFG->navcourselimit;
1417          }
1418  
1419          $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1420  
1421          // If we are going to show all courses AND we are showing categories then
1422          // to save us repeated DB calls load all of the categories now
1423          if ($this->show_categories()) {
1424              $this->load_all_categories($toload);
1425          }
1426  
1427          // Will be the return of our efforts
1428          $coursenodes = array();
1429  
1430          // Check if we need to show categories.
1431          if ($this->show_categories()) {
1432              // Hmmm we need to show categories... this is going to be painful.
1433              // We now need to fetch up to $limit courses for each category to
1434              // be displayed.
1435              if ($categoryids !== null) {
1436                  if (!is_array($categoryids)) {
1437                      $categoryids = array($categoryids);
1438                  }
1439                  list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1440                  $categorywhere = 'WHERE cc.id '.$categorywhere;
1441              } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1442                  $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1443                  $categoryparams = array();
1444              } else {
1445                  $categorywhere = '';
1446                  $categoryparams = array();
1447              }
1448  
1449              // First up we are going to get the categories that we are going to
1450              // need so that we can determine how best to load the courses from them.
1451              $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1452                          FROM {course_categories} cc
1453                      LEFT JOIN {course} c ON c.category = cc.id
1454                              {$categorywhere}
1455                      GROUP BY cc.id";
1456              $categories = $DB->get_recordset_sql($sql, $categoryparams);
1457              $fullfetch = array();
1458              $partfetch = array();
1459              foreach ($categories as $category) {
1460                  if (!$this->can_add_more_courses_to_category($category->id)) {
1461                      continue;
1462                  }
1463                  if ($category->coursecount > $limit * 5) {
1464                      $partfetch[] = $category->id;
1465                  } else if ($category->coursecount > 0) {
1466                      $fullfetch[] = $category->id;
1467                  }
1468              }
1469              $categories->close();
1470  
1471              if (count($fullfetch)) {
1472                  // First up fetch all of the courses in categories where we know that we are going to
1473                  // need the majority of courses.
1474                  list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1475                  $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1476                  $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1477                  $categoryparams['contextlevel'] = CONTEXT_COURSE;
1478                  $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1479                              FROM {course} c
1480                                  $ccjoin
1481                              WHERE c.category {$categoryids}
1482                          ORDER BY c.sortorder ASC";
1483                  $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1484                  foreach ($coursesrs as $course) {
1485                      if ($course->id == $SITE->id) {
1486                          // This should not be necessary, frontpage is not in any category.
1487                          continue;
1488                      }
1489                      if (array_key_exists($course->id, $this->addedcourses)) {
1490                          // It is probably better to not include the already loaded courses
1491                          // directly in SQL because inequalities may confuse query optimisers
1492                          // and may interfere with query caching.
1493                          continue;
1494                      }
1495                      if (!$this->can_add_more_courses_to_category($course->category)) {
1496                          continue;
1497                      }
1498                      context_helper::preload_from_record($course);
1499                      if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1500                          continue;
1501                      }
1502                      $coursenodes[$course->id] = $this->add_course($course);
1503                  }
1504                  $coursesrs->close();
1505              }
1506  
1507              if (count($partfetch)) {
1508                  // Next we will work our way through the categories where we will likely only need a small
1509                  // proportion of the courses.
1510                  foreach ($partfetch as $categoryid) {
1511                      $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1512                      $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1513                      $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1514                                  FROM {course} c
1515                                      $ccjoin
1516                                  WHERE c.category = :categoryid
1517                              ORDER BY c.sortorder ASC";
1518                      $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1519                      $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1520                      foreach ($coursesrs as $course) {
1521                          if ($course->id == $SITE->id) {
1522                              // This should not be necessary, frontpage is not in any category.
1523                              continue;
1524                          }
1525                          if (array_key_exists($course->id, $this->addedcourses)) {
1526                              // It is probably better to not include the already loaded courses
1527                              // directly in SQL because inequalities may confuse query optimisers
1528                              // and may interfere with query caching.
1529                              // This also helps to respect expected $limit on repeated executions.
1530                              continue;
1531                          }
1532                          if (!$this->can_add_more_courses_to_category($course->category)) {
1533                              break;
1534                          }
1535                          context_helper::preload_from_record($course);
1536                          if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1537                              continue;
1538                          }
1539                          $coursenodes[$course->id] = $this->add_course($course);
1540                      }
1541                      $coursesrs->close();
1542                  }
1543              }
1544          } else {
1545              // Prepare the SQL to load the courses and their contexts
1546              list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1547              $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1548              $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1549              $courseparams['contextlevel'] = CONTEXT_COURSE;
1550              $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1551                          FROM {course} c
1552                              $ccjoin
1553                          WHERE c.id {$courseids}
1554                      ORDER BY c.sortorder ASC";
1555              $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1556              foreach ($coursesrs as $course) {
1557                  if ($course->id == $SITE->id) {
1558                      // frotpage is not wanted here
1559                      continue;
1560                  }
1561                  if ($this->page->course && ($this->page->course->id == $course->id)) {
1562                      // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1563                      continue;
1564                  }
1565                  context_helper::preload_from_record($course);
1566                  if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1567                      continue;
1568                  }
1569                  $coursenodes[$course->id] = $this->add_course($course);
1570                  if (count($coursenodes) >= $limit) {
1571                      break;
1572                  }
1573              }
1574              $coursesrs->close();
1575          }
1576  
1577          return $coursenodes;
1578      }
1579  
1580      /**
1581       * Returns true if more courses can be added to the provided category.
1582       *
1583       * @param int|navigation_node|stdClass $category
1584       * @return bool
1585       */
1586      protected function can_add_more_courses_to_category($category) {
1587          global $CFG;
1588          $limit = 20;
1589          if (!empty($CFG->navcourselimit)) {
1590              $limit = (int)$CFG->navcourselimit;
1591          }
1592          if (is_numeric($category)) {
1593              if (!array_key_exists($category, $this->addedcategories)) {
1594                  return true;
1595              }
1596              $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1597          } else if ($category instanceof navigation_node) {
1598              if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1599                  return false;
1600              }
1601              $coursecount = count($category->children->type(self::TYPE_COURSE));
1602          } else if (is_object($category) && property_exists($category,'id')) {
1603              $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1604          }
1605          return ($coursecount <= $limit);
1606      }
1607  
1608      /**
1609       * Loads all categories (top level or if an id is specified for that category)
1610       *
1611       * @param int $categoryid The category id to load or null/0 to load all base level categories
1612       * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1613       *        as the requested category and any parent categories.
1614       * @return navigation_node|void returns a navigation node if a category has been loaded.
1615       */
1616      protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1617          global $CFG, $DB;
1618  
1619          // Check if this category has already been loaded
1620          if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1621              return true;
1622          }
1623  
1624          $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1625          $sqlselect = "SELECT cc.*, $catcontextsql
1626                        FROM {course_categories} cc
1627                        JOIN {context} ctx ON cc.id = ctx.instanceid";
1628          $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1629          $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1630          $params = array();
1631  
1632          $categoriestoload = array();
1633          if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1634              // We are going to load all categories regardless... prepare to fire
1635              // on the database server!
1636          } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1637              // We are going to load all of the first level categories (categories without parents)
1638              $sqlwhere .= " AND cc.parent = 0";
1639          } else if (array_key_exists($categoryid, $this->addedcategories)) {
1640              // The category itself has been loaded already so we just need to ensure its subcategories
1641              // have been loaded
1642              list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1643              if ($showbasecategories) {
1644                  // We need to include categories with parent = 0 as well
1645                  $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1646              } else {
1647                  // All we need is categories that match the parent
1648                  $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1649              }
1650              $params['categoryid'] = $categoryid;
1651          } else {
1652              // This category hasn't been loaded yet so we need to fetch it, work out its category path
1653              // and load this category plus all its parents and subcategories
1654              $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1655              $categoriestoload = explode('/', trim($category->path, '/'));
1656              list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1657              // We are going to use select twice so double the params
1658              $params = array_merge($params, $params);
1659              $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1660              $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1661          }
1662  
1663          $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1664          $categories = array();
1665          foreach ($categoriesrs as $category) {
1666              // Preload the context.. we'll need it when adding the category in order
1667              // to format the category name.
1668              context_helper::preload_from_record($category);
1669              if (array_key_exists($category->id, $this->addedcategories)) {
1670                  // Do nothing, its already been added.
1671              } else if ($category->parent == '0') {
1672                  // This is a root category lets add it immediately
1673                  $this->add_category($category, $this->rootnodes['courses']);
1674              } else if (array_key_exists($category->parent, $this->addedcategories)) {
1675                  // This categories parent has already been added we can add this immediately
1676                  $this->add_category($category, $this->addedcategories[$category->parent]);
1677              } else {
1678                  $categories[] = $category;
1679              }
1680          }
1681          $categoriesrs->close();
1682  
1683          // Now we have an array of categories we need to add them to the navigation.
1684          while (!empty($categories)) {
1685              $category = reset($categories);
1686              if (array_key_exists($category->id, $this->addedcategories)) {
1687                  // Do nothing
1688              } else if ($category->parent == '0') {
1689                  $this->add_category($category, $this->rootnodes['courses']);
1690              } else if (array_key_exists($category->parent, $this->addedcategories)) {
1691                  $this->add_category($category, $this->addedcategories[$category->parent]);
1692              } else {
1693                  // This category isn't in the navigation and niether is it's parent (yet).
1694                  // We need to go through the category path and add all of its components in order.
1695                  $path = explode('/', trim($category->path, '/'));
1696                  foreach ($path as $catid) {
1697                      if (!array_key_exists($catid, $this->addedcategories)) {
1698                          // This category isn't in the navigation yet so add it.
1699                          $subcategory = $categories[$catid];
1700                          if ($subcategory->parent == '0') {
1701                              // Yay we have a root category - this likely means we will now be able
1702                              // to add categories without problems.
1703                              $this->add_category($subcategory, $this->rootnodes['courses']);
1704                          } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1705                              // The parent is in the category (as we'd expect) so add it now.
1706                              $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1707                              // Remove the category from the categories array.
1708                              unset($categories[$catid]);
1709                          } else {
1710                              // We should never ever arrive here - if we have then there is a bigger
1711                              // problem at hand.
1712                              throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1713                          }
1714                      }
1715                  }
1716              }
1717              // Remove the category from the categories array now that we know it has been added.
1718              unset($categories[$category->id]);
1719          }
1720          if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1721              $this->allcategoriesloaded = true;
1722          }
1723          // Check if there are any categories to load.
1724          if (count($categoriestoload) > 0) {
1725              $readytoloadcourses = array();
1726              foreach ($categoriestoload as $category) {
1727                  if ($this->can_add_more_courses_to_category($category)) {
1728                      $readytoloadcourses[] = $category;
1729                  }
1730              }
1731              if (count($readytoloadcourses)) {
1732                  $this->load_all_courses($readytoloadcourses);
1733              }
1734          }
1735  
1736          // Look for all categories which have been loaded
1737          if (!empty($this->addedcategories)) {
1738              $categoryids = array();
1739              foreach ($this->addedcategories as $category) {
1740                  if ($this->can_add_more_courses_to_category($category)) {
1741                      $categoryids[] = $category->key;
1742                  }
1743              }
1744              if ($categoryids) {
1745                  list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1746                  $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1747                  $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1748                            FROM {course_categories} cc
1749                            JOIN {course} c ON c.category = cc.id
1750                           WHERE cc.id {$categoriessql}
1751                        GROUP BY cc.id
1752                          HAVING COUNT(c.id) > :limit";
1753                  $excessivecategories = $DB->get_records_sql($sql, $params);
1754                  foreach ($categories as &$category) {
1755                      if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1756                          $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1757                          $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1758                      }
1759                  }
1760              }
1761          }
1762      }
1763  
1764      /**
1765       * Adds a structured category to the navigation in the correct order/place
1766       *
1767       * @param stdClass $category category to be added in navigation.
1768       * @param navigation_node $parent parent navigation node
1769       * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1770       * @return void.
1771       */
1772      protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1773          if (array_key_exists($category->id, $this->addedcategories)) {
1774              return;
1775          }
1776          $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1777          $context = context_coursecat::instance($category->id);
1778          $categoryname = format_string($category->name, true, array('context' => $context));
1779          $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1780          if (empty($category->visible)) {
1781              if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1782                  $categorynode->hidden = true;
1783              } else {
1784                  $categorynode->display = false;
1785              }
1786          }
1787          $this->addedcategories[$category->id] = $categorynode;
1788      }
1789  
1790      /**
1791       * Loads the given course into the navigation
1792       *
1793       * @param stdClass $course
1794       * @return navigation_node
1795       */
1796      protected function load_course(stdClass $course) {
1797          global $SITE;
1798          if ($course->id == $SITE->id) {
1799              // This is always loaded during initialisation
1800              return $this->rootnodes['site'];
1801          } else if (array_key_exists($course->id, $this->addedcourses)) {
1802              // The course has already been loaded so return a reference
1803              return $this->addedcourses[$course->id];
1804          } else {
1805              // Add the course
1806              return $this->add_course($course);
1807          }
1808      }
1809  
1810      /**
1811       * Loads all of the courses section into the navigation.
1812       *
1813       * This function calls method from current course format, see
1814       * {@link format_base::extend_course_navigation()}
1815       * If course module ($cm) is specified but course format failed to create the node,
1816       * the activity node is created anyway.
1817       *
1818       * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1819       *
1820       * @param stdClass $course Database record for the course
1821       * @param navigation_node $coursenode The course node within the navigation
1822       * @param null|int $sectionnum If specified load the contents of section with this relative number
1823       * @param null|cm_info $cm If specified make sure that activity node is created (either
1824       *    in containg section or by calling load_stealth_activity() )
1825       */
1826      protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1827          global $CFG, $SITE;
1828          require_once($CFG->dirroot.'/course/lib.php');
1829          if (isset($cm->sectionnum)) {
1830              $sectionnum = $cm->sectionnum;
1831          }
1832          if ($sectionnum !== null) {
1833              $this->includesectionnum = $sectionnum;
1834          }
1835          course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1836          if (isset($cm->id)) {
1837              $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1838              if (empty($activity)) {
1839                  $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1840              }
1841          }
1842     }
1843  
1844      /**
1845       * Generates an array of sections and an array of activities for the given course.
1846       *
1847       * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1848       *
1849       * @param stdClass $course
1850       * @return array Array($sections, $activities)
1851       */
1852      protected function generate_sections_and_activities(stdClass $course) {
1853          global $CFG;
1854          require_once($CFG->dirroot.'/course/lib.php');
1855  
1856          $modinfo = get_fast_modinfo($course);
1857          $sections = $modinfo->get_section_info_all();
1858  
1859          // For course formats using 'numsections' trim the sections list
1860          $courseformatoptions = course_get_format($course)->get_format_options();
1861          if (isset($courseformatoptions['numsections'])) {
1862              $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1863          }
1864  
1865          $activities = array();
1866  
1867          foreach ($sections as $key => $section) {
1868              // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1869              $sections[$key] = clone($section);
1870              unset($sections[$key]->summary);
1871              $sections[$key]->hasactivites = false;
1872              if (!array_key_exists($section->section, $modinfo->sections)) {
1873                  continue;
1874              }
1875              foreach ($modinfo->sections[$section->section] as $cmid) {
1876                  $cm = $modinfo->cms[$cmid];
1877                  $activity = new stdClass;
1878                  $activity->id = $cm->id;
1879                  $activity->course = $course->id;
1880                  $activity->section = $section->section;
1881                  $activity->name = $cm->name;
1882                  $activity->icon = $cm->icon;
1883                  $activity->iconcomponent = $cm->iconcomponent;
1884                  $activity->hidden = (!$cm->visible);
1885                  $activity->modname = $cm->modname;
1886                  $activity->nodetype = navigation_node::NODETYPE_LEAF;
1887                  $activity->onclick = $cm->onclick;
1888                  $url = $cm->url;
1889                  if (!$url) {
1890                      $activity->url = null;
1891                      $activity->display = false;
1892                  } else {
1893                      $activity->url = $url->out();
1894                      $activity->display = $cm->uservisible ? true : false;
1895                      if (self::module_extends_navigation($cm->modname)) {
1896                          $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1897                      }
1898                  }
1899                  $activities[$cmid] = $activity;
1900                  if ($activity->display) {
1901                      $sections[$key]->hasactivites = true;
1902                  }
1903              }
1904          }
1905  
1906          return array($sections, $activities);
1907      }
1908  
1909      /**
1910       * Generically loads the course sections into the course's navigation.
1911       *
1912       * @param stdClass $course
1913       * @param navigation_node $coursenode
1914       * @return array An array of course section nodes
1915       */
1916      public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1917          global $CFG, $DB, $USER, $SITE;
1918          require_once($CFG->dirroot.'/course/lib.php');
1919  
1920          list($sections, $activities) = $this->generate_sections_and_activities($course);
1921  
1922          $navigationsections = array();
1923          foreach ($sections as $sectionid => $section) {
1924              $section = clone($section);
1925              if ($course->id == $SITE->id) {
1926                  $this->load_section_activities($coursenode, $section->section, $activities);
1927              } else {
1928                  if (!$section->uservisible || (!$this->showemptysections &&
1929                          !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1930                      continue;
1931                  }
1932  
1933                  $sectionname = get_section_name($course, $section);
1934                  $url = course_get_url($course, $section->section, array('navigation' => true));
1935  
1936                  $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1937                  $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1938                  $sectionnode->hidden = (!$section->visible || !$section->available);
1939                  if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1940                      $this->load_section_activities($sectionnode, $section->section, $activities);
1941                  }
1942                  $section->sectionnode = $sectionnode;
1943                  $navigationsections[$sectionid] = $section;
1944              }
1945          }
1946          return $navigationsections;
1947      }
1948  
1949      /**
1950       * Loads all of the activities for a section into the navigation structure.
1951       *
1952       * @param navigation_node $sectionnode
1953       * @param int $sectionnumber
1954       * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1955       * @param stdClass $course The course object the section and activities relate to.
1956       * @return array Array of activity nodes
1957       */
1958      protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1959          global $CFG, $SITE;
1960          // A static counter for JS function naming
1961          static $legacyonclickcounter = 0;
1962  
1963          $activitynodes = array();
1964          if (empty($activities)) {
1965              return $activitynodes;
1966          }
1967  
1968          if (!is_object($course)) {
1969              $activity = reset($activities);
1970              $courseid = $activity->course;
1971          } else {
1972              $courseid = $course->id;
1973          }
1974          $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1975  
1976          foreach ($activities as $activity) {
1977              if ($activity->section != $sectionnumber) {
1978                  continue;
1979              }
1980              if ($activity->icon) {
1981                  $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1982              } else {
1983                  $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1984              }
1985  
1986              // Prepare the default name and url for the node
1987              $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1988              $action = new moodle_url($activity->url);
1989  
1990              // Check if the onclick property is set (puke!)
1991              if (!empty($activity->onclick)) {
1992                  // Increment the counter so that we have a unique number.
1993                  $legacyonclickcounter++;
1994                  // Generate the function name we will use
1995                  $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1996                  $propogrationhandler = '';
1997                  // Check if we need to cancel propogation. Remember inline onclick
1998                  // events would return false if they wanted to prevent propogation and the
1999                  // default action.
2000                  if (strpos($activity->onclick, 'return false')) {
2001                      $propogrationhandler = 'e.halt();';
2002                  }
2003                  // Decode the onclick - it has already been encoded for display (puke)
2004                  $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2005                  // Build the JS function the click event will call
2006                  $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2007                  $this->page->requires->js_init_code($jscode);
2008                  // Override the default url with the new action link
2009                  $action = new action_link($action, $activityname, new component_action('click', $functionname));
2010              }
2011  
2012              $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2013              $activitynode->title(get_string('modulename', $activity->modname));
2014              $activitynode->hidden = $activity->hidden;
2015              $activitynode->display = $showactivities && $activity->display;
2016              $activitynode->nodetype = $activity->nodetype;
2017              $activitynodes[$activity->id] = $activitynode;
2018          }
2019  
2020          return $activitynodes;
2021      }
2022      /**
2023       * Loads a stealth module from unavailable section
2024       * @param navigation_node $coursenode
2025       * @param stdClass $modinfo
2026       * @return navigation_node or null if not accessible
2027       */
2028      protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2029          if (empty($modinfo->cms[$this->page->cm->id])) {
2030              return null;
2031          }
2032          $cm = $modinfo->cms[$this->page->cm->id];
2033          if ($cm->icon) {
2034              $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2035          } else {
2036              $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2037          }
2038          $url = $cm->url;
2039          $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2040          $activitynode->title(get_string('modulename', $cm->modname));
2041          $activitynode->hidden = (!$cm->visible);
2042          if (!$cm->uservisible) {
2043              // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2044              // Also there may be no exception at all in case when teacher is logged in as student.
2045              $activitynode->display = false;
2046          } else if (!$url) {
2047              // Don't show activities that don't have links!
2048              $activitynode->display = false;
2049          } else if (self::module_extends_navigation($cm->modname)) {
2050              $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2051          }
2052          return $activitynode;
2053      }
2054      /**
2055       * Loads the navigation structure for the given activity into the activities node.
2056       *
2057       * This method utilises a callback within the modules lib.php file to load the
2058       * content specific to activity given.
2059       *
2060       * The callback is a method: {modulename}_extend_navigation()
2061       * Examples:
2062       *  * {@link forum_extend_navigation()}
2063       *  * {@link workshop_extend_navigation()}
2064       *
2065       * @param cm_info|stdClass $cm
2066       * @param stdClass $course
2067       * @param navigation_node $activity
2068       * @return bool
2069       */
2070      protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2071          global $CFG, $DB;
2072  
2073          // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2074          if (!($cm instanceof cm_info)) {
2075              $modinfo = get_fast_modinfo($course);
2076              $cm = $modinfo->get_cm($cm->id);
2077          }
2078          $activity->nodetype = navigation_node::NODETYPE_LEAF;
2079          $activity->make_active();
2080          $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2081          $function = $cm->modname.'_extend_navigation';
2082  
2083          if (file_exists($file)) {
2084              require_once($file);
2085              if (function_exists($function)) {
2086                  $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2087                  $function($activity, $course, $activtyrecord, $cm);
2088              }
2089          }
2090  
2091          // Allow the active advanced grading method plugin to append module navigation
2092          $featuresfunc = $cm->modname.'_supports';
2093          if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2094              require_once($CFG->dirroot.'/grade/grading/lib.php');
2095              $gradingman = get_grading_manager($cm->context,  'mod_'.$cm->modname);
2096              $gradingman->extend_navigation($this, $activity);
2097          }
2098  
2099          return $activity->has_children();
2100      }
2101      /**
2102       * Loads user specific information into the navigation in the appropriate place.
2103       *
2104       * If no user is provided the current user is assumed.
2105       *
2106       * @param stdClass $user
2107       * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2108       * @return bool
2109       */
2110      protected function load_for_user($user=null, $forceforcontext=false) {
2111          global $DB, $CFG, $USER, $SITE;
2112  
2113          if ($user === null) {
2114              // We can't require login here but if the user isn't logged in we don't
2115              // want to show anything
2116              if (!isloggedin() || isguestuser()) {
2117                  return false;
2118              }
2119              $user = $USER;
2120          } else if (!is_object($user)) {
2121              // If the user is not an object then get them from the database
2122              $select = context_helper::get_preload_record_columns_sql('ctx');
2123              $sql = "SELECT u.*, $select
2124                        FROM {user} u
2125                        JOIN {context} ctx ON u.id = ctx.instanceid
2126                       WHERE u.id = :userid AND
2127                             ctx.contextlevel = :contextlevel";
2128              $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2129              context_helper::preload_from_record($user);
2130          }
2131  
2132          $iscurrentuser = ($user->id == $USER->id);
2133  
2134          $usercontext = context_user::instance($user->id);
2135  
2136          // Get the course set against the page, by default this will be the site
2137          $course = $this->page->course;
2138          $baseargs = array('id'=>$user->id);
2139          if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2140              $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2141              $baseargs['course'] = $course->id;
2142              $coursecontext = context_course::instance($course->id);
2143              $issitecourse = false;
2144          } else {
2145              // Load all categories and get the context for the system
2146              $coursecontext = context_system::instance();
2147              $issitecourse = true;
2148          }
2149  
2150          // Create a node to add user information under.
2151          if ($iscurrentuser && !$forceforcontext) {
2152              // If it's the current user the information will go under the profile root node
2153              $usernode = $this->rootnodes['myprofile'];
2154              $course = get_site();
2155              $coursecontext = context_course::instance($course->id);
2156              $issitecourse = true;
2157          } else {
2158              if (!$issitecourse) {
2159                  // Not the current user so add it to the participants node for the current course
2160                  $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2161                  $userviewurl = new moodle_url('/user/view.php', $baseargs);
2162              } else {
2163                  // This is the site so add a users node to the root branch
2164                  $usersnode = $this->rootnodes['users'];
2165                  if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2166                      $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2167                  }
2168                  $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2169              }
2170              if (!$usersnode) {
2171                  // We should NEVER get here, if the course hasn't been populated
2172                  // with a participants node then the navigaiton either wasn't generated
2173                  // for it (you are missing a require_login or set_context call) or
2174                  // you don't have access.... in the interests of no leaking informatin
2175                  // we simply quit...
2176                  return false;
2177              }
2178              // Add a branch for the current user
2179              $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2180              $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2181  
2182              if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2183                  $usernode->make_active();
2184              }
2185          }
2186  
2187          // If the user is the current user or has permission to view the details of the requested
2188          // user than add a view profile link.
2189          if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2190              if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2191                  $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2192              } else {
2193                  $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2194              }
2195          }
2196  
2197          if (!empty($CFG->navadduserpostslinks)) {
2198              // Add nodes for forum posts and discussions if the user can view either or both
2199              // There are no capability checks here as the content of the page is based
2200              // purely on the forums the current user has access too.
2201              $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2202              $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2203              $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2204          }
2205  
2206          // Add blog nodes
2207          if (!empty($CFG->enableblogs)) {
2208              if (!$this->cache->cached('userblogoptions'.$user->id)) {
2209                  require_once($CFG->dirroot.'/blog/lib.php');
2210                  // Get all options for the user
2211                  $options = blog_get_options_for_user($user);
2212                  $this->cache->set('userblogoptions'.$user->id, $options);
2213              } else {
2214                  $options = $this->cache->{'userblogoptions'.$user->id};
2215              }
2216  
2217              if (count($options) > 0) {
2218                  $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2219                  foreach ($options as $type => $option) {
2220                      if ($type == "rss") {
2221                          $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2222                      } else {
2223                          $blogs->add($option['string'], $option['link']);
2224                      }
2225                  }
2226              }
2227          }
2228  
2229          if (!empty($CFG->messaging)) {
2230              $messageargs = array('user1' => $USER->id);
2231              if ($USER->id != $user->id) {
2232                  $messageargs['user2'] = $user->id;
2233              }
2234              if ($course->id != $SITE->id) {
2235                  $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
2236              }
2237              $url = new moodle_url('/message/index.php',$messageargs);
2238              $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2239          }
2240  
2241          if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
2242              $url = new moodle_url('/user/files.php');
2243              $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2244          }
2245  
2246          if (!empty($CFG->enablebadges) && $iscurrentuser &&
2247                  has_capability('moodle/badges:manageownbadges', context_user::instance($USER->id))) {
2248              $url = new moodle_url('/badges/mybadges.php');
2249              $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2250          }
2251  
2252          // Add a node to view the users notes if permitted
2253          if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2254              $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2255              if ($coursecontext->instanceid != SITEID) {
2256                  $url->param('course', $coursecontext->instanceid);
2257              }
2258              $usernode->add(get_string('notes', 'notes'), $url);
2259          }
2260  
2261          // If the user is the current user add the repositories for the current user
2262          $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2263          if ($iscurrentuser) {
2264              if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2265                  require_once($CFG->dirroot . '/repository/lib.php');
2266                  $editabletypes = repository::get_editable_types($usercontext);
2267                  $haseditabletypes = !empty($editabletypes);
2268                  unset($editabletypes);
2269                  $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2270              } else {
2271                  $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2272              }
2273              if ($haseditabletypes) {
2274                  $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2275              }
2276          } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2277  
2278              // Add view grade report is permitted
2279              $reports = core_component::get_plugin_list('gradereport');
2280              arsort($reports); // user is last, we want to test it first
2281  
2282              $userscourses = enrol_get_users_courses($user->id);
2283              $userscoursesnode = $usernode->add(get_string('courses'));
2284  
2285              $count = 0;
2286              foreach ($userscourses as $usercourse) {
2287                  if ($count === (int)$CFG->navcourselimit) {
2288                      $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2289                      $userscoursesnode->add(get_string('showallcourses'), $url);
2290                      break;
2291                  }
2292                  $count++;
2293                  $usercoursecontext = context_course::instance($usercourse->id);
2294                  $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2295                  $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2296  
2297                  $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2298                  if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2299                      foreach ($reports as $plugin => $plugindir) {
2300                          if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2301                              //stop when the first visible plugin is found
2302                              $gradeavailable = true;
2303                              break;
2304                          }
2305                      }
2306                  }
2307  
2308                  if ($gradeavailable) {
2309                      $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2310                      $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2311                  }
2312  
2313                  // Add a node to view the users notes if permitted
2314                  if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2315                      $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2316                      $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2317                  }
2318  
2319                  if (can_access_course($usercourse, $user->id)) {
2320                      $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', ''));
2321                  }
2322  
2323                  $reporttab = $usercoursenode->add(get_string('activityreports'));
2324  
2325                  $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2326                  foreach ($reports as $reportfunction) {
2327                      $reportfunction($reporttab, $user, $usercourse);
2328                  }
2329  
2330                  $reporttab->trim_if_empty();
2331              }
2332          }
2333          return true;
2334      }
2335  
2336      /**
2337       * This method simply checks to see if a given module can extend the navigation.
2338       *
2339       * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2340       *
2341       * @param string $modname
2342       * @return bool
2343       */
2344      public static function module_extends_navigation($modname) {
2345          global $CFG;
2346          static $extendingmodules = array();
2347          if (!array_key_exists($modname, $extendingmodules)) {
2348              $extendingmodules[$modname] = false;
2349              $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2350              if (file_exists($file)) {
2351                  $function = $modname.'_extend_navigation';
2352                  require_once($file);
2353                  $extendingmodules[$modname] = (function_exists($function));
2354              }
2355          }
2356          return $extendingmodules[$modname];
2357      }
2358      /**
2359       * Extends the navigation for the given user.
2360       *
2361       * @param stdClass $user A user from the database
2362       */
2363      public function extend_for_user($user) {
2364          $this->extendforuser[] = $user;
2365      }
2366  
2367      /**
2368       * Returns all of the users the navigation is being extended for
2369       *
2370       * @return array An array of extending users.
2371       */
2372      public function get_extending_users() {
2373          return $this->extendforuser;
2374      }
2375      /**
2376       * Adds the given course to the navigation structure.
2377       *
2378       * @param stdClass $course
2379       * @param bool $forcegeneric
2380       * @param bool $ismycourse
2381       * @return navigation_node
2382       */
2383      public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2384          global $CFG, $SITE;
2385  
2386          // We found the course... we can return it now :)
2387          if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2388              return $this->addedcourses[$course->id];
2389          }
2390  
2391          $coursecontext = context_course::instance($course->id);
2392  
2393          if ($course->id != $SITE->id && !$course->visible) {
2394              if (is_role_switched($course->id)) {
2395                  // user has to be able to access course in order to switch, let's skip the visibility test here
2396              } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2397                  return false;
2398              }
2399          }
2400  
2401          $issite = ($course->id == $SITE->id);
2402          $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2403          $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2404          // This is the name that will be shown for the course.
2405          $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2406  
2407          // Can the user expand the course to see its content.
2408          $canexpandcourse = true;
2409          if ($issite) {
2410              $parent = $this;
2411              $url = null;
2412              if (empty($CFG->usesitenameforsitepages)) {
2413                  $coursename = get_string('sitepages');
2414              }
2415          } else if ($coursetype == self::COURSE_CURRENT) {
2416              $parent = $this->rootnodes['currentcourse'];
2417              $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2418          } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2419              if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2420                  // Nothing to do here the above statement set $parent to the category within mycourses.
2421              } else {
2422                  $parent = $this->rootnodes['mycourses'];
2423              }
2424              $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2425          } else {
2426              $parent = $this->rootnodes['courses'];
2427              $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2428              // They can only expand the course if they can access it.
2429              $canexpandcourse = $this->can_expand_course($course);
2430              if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2431                  if (!$this->is_category_fully_loaded($course->category)) {
2432                      // We need to load the category structure for this course
2433                      $this->load_all_categories($course->category, false);
2434                  }
2435                  if (array_key_exists($course->category, $this->addedcategories)) {
2436                      $parent = $this->addedcategories[$course->category];
2437                      // This could lead to the course being created so we should check whether it is the case again
2438                      if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2439                          return $this->addedcourses[$course->id];
2440                      }
2441                  }
2442              }
2443          }
2444  
2445          $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2446          $coursenode->hidden = (!$course->visible);
2447          // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
2448          // later.
2449          $coursenode->title(str_replace('&amp;', '&', $fullname));
2450          if ($canexpandcourse) {
2451              // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2452              $coursenode->nodetype = self::NODETYPE_BRANCH;
2453              $coursenode->isexpandable = true;
2454          } else {
2455              $coursenode->nodetype = self::NODETYPE_LEAF;
2456              $coursenode->isexpandable = false;
2457          }
2458          if (!$forcegeneric) {
2459              $this->addedcourses[$course->id] = $coursenode;
2460          }
2461  
2462          return $coursenode;
2463      }
2464  
2465      /**
2466       * Returns a cache instance to use for the expand course cache.
2467       * @return cache_session
2468       */
2469      protected function get_expand_course_cache() {
2470          if ($this->cacheexpandcourse === null) {
2471              $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2472          }
2473          return $this->cacheexpandcourse;
2474      }
2475  
2476      /**
2477       * Checks if a user can expand a course in the navigation.
2478       *
2479       * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2480       * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2481       * permits stale data.
2482       * In the situation the user is granted access to a course after we've initialised this session cache the cache
2483       * will be stale.
2484       * It is brought up to date in only one of two ways.
2485       *   1. The user logs out and in again.
2486       *   2. The user browses to the course they've just being given access to.
2487       *
2488       * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2489       *
2490       * @param stdClass $course
2491       * @return bool
2492       */
2493      protected function can_expand_course($course) {
2494          $cache = $this->get_expand_course_cache();
2495          $canexpand = $cache->get($course->id);
2496          if ($canexpand === false) {
2497              $canexpand = isloggedin() && can_access_course($course);
2498              $canexpand = (int)$canexpand;
2499              $cache->set($course->id, $canexpand);
2500          }
2501          return ($canexpand === 1);
2502      }
2503  
2504      /**
2505       * Returns true if the category has already been loaded as have any child categories
2506       *
2507       * @param int $categoryid
2508       * @return bool
2509       */
2510      protected function is_category_fully_loaded($categoryid) {
2511          return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2512      }
2513  
2514      /**
2515       * Adds essential course nodes to the navigation for the given course.
2516       *
2517       * This method adds nodes such as reports, blogs and participants
2518       *
2519       * @param navigation_node $coursenode
2520       * @param stdClass $course
2521       * @return bool returns true on successful addition of a node.
2522       */
2523      public function add_course_essentials($coursenode, stdClass $course) {
2524          global $CFG, $SITE;
2525  
2526          if ($course->id == $SITE->id) {
2527              return $this->add_front_page_course_essentials($coursenode, $course);
2528          }
2529  
2530          if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2531              return true;
2532          }
2533  
2534          //Participants
2535          if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2536              $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2537              if (!empty($CFG->enableblogs)) {
2538                  if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2539                     and has_capability('moodle/blog:view', context_system::instance())) {
2540                      $blogsurls = new moodle_url('/blog/index.php');
2541                      if ($course->id == $SITE->id) {
2542                          $blogsurls->param('courseid', 0);
2543                      } else if ($currentgroup = groups_get_course_group($course, true)) {
2544                          $blogsurls->param('groupid', $currentgroup);
2545                      } else {
2546                          $blogsurls->param('courseid', $course->id);
2547                      }
2548                      $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2549                  }
2550              }
2551              if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2552                  $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2553              }
2554          } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2555              $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2556          }
2557  
2558          // Badges.
2559          if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2560              has_capability('moodle/badges:viewbadges', $this->page->context)) {
2561              $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2562  
2563              $coursenode->add(get_string('coursebadges', 'badges'), null,
2564                      navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2565              $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2566                      navigation_node::TYPE_SETTING, null, 'badgesview',
2567                      new pix_icon('i/badge', get_string('badgesview', 'badges')));
2568          }
2569  
2570          return true;
2571      }
2572      /**
2573       * This generates the structure of the course that won't be generated when
2574       * the modules and sections are added.
2575       *
2576       * Things such as the reports branch, the participants branch, blogs... get
2577       * added to the course node by this method.
2578       *
2579       * @param navigation_node $coursenode
2580       * @param stdClass $course
2581       * @return bool True for successfull generation
2582       */
2583      public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2584          global $CFG;
2585  
2586          if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2587              return true;
2588          }
2589  
2590          // Hidden node that we use to determine if the front page navigation is loaded.
2591          // This required as there are not other guaranteed nodes that may be loaded.
2592          $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2593  
2594          //Participants
2595          if (has_capability('moodle/course:viewparticipants',  context_system::instance())) {
2596              $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2597          }
2598  
2599          $filterselect = 0;
2600  
2601          // Blogs
2602          if (!empty($CFG->enableblogs)
2603            and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2604            and has_capability('moodle/blog:view', context_system::instance())) {
2605              $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2606              $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2607          }
2608  
2609          //Badges
2610          if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2611              $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2612              $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2613          }
2614  
2615          // Notes
2616          if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2617              $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2618          }
2619  
2620          // Tags
2621          if (!empty($CFG->usetags) && isloggedin()) {
2622              $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2623          }
2624  
2625          if (isloggedin()) {
2626              // Calendar
2627              $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2628              $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2629          }
2630  
2631          return true;
2632      }
2633  
2634      /**
2635       * Clears the navigation cache
2636       */
2637      public function clear_cache() {
2638          $this->cache->clear();
2639      }
2640  
2641      /**
2642       * Sets an expansion limit for the navigation
2643       *
2644       * The expansion limit is used to prevent the display of content that has a type
2645       * greater than the provided $type.
2646       *
2647       * Can be used to ensure things such as activities or activity content don't get
2648       * shown on the navigation.
2649       * They are still generated in order to ensure the navbar still makes sense.
2650       *
2651       * @param int $type One of navigation_node::TYPE_*
2652       * @return bool true when complete.
2653       */
2654      public function set_expansion_limit($type) {
2655          global $SITE;
2656          $nodes = $this->find_all_of_type($type);
2657  
2658          // We only want to hide specific types of nodes.
2659          // Only nodes that represent "structure" in the navigation tree should be hidden.
2660          // If we hide all nodes then we risk hiding vital information.
2661          $typestohide = array(
2662              self::TYPE_CATEGORY,
2663              self::TYPE_COURSE,
2664              self::TYPE_SECTION,
2665              self::TYPE_ACTIVITY
2666          );
2667  
2668          foreach ($nodes as $node) {
2669              // We need to generate the full site node
2670              if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2671                  continue;
2672              }
2673              foreach ($node->children as $child) {
2674                  $child->hide($typestohide);
2675              }
2676          }
2677          return true;
2678      }
2679      /**
2680       * Attempts to get the navigation with the given key from this nodes children.
2681       *
2682       * This function only looks at this nodes children, it does NOT look recursivily.
2683       * If the node can't be found then false is returned.
2684       *
2685       * If you need to search recursivily then use the {@link global_navigation::find()} method.
2686       *
2687       * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2688       * may be of more use to you.
2689       *
2690       * @param string|int $key The key of the node you wish to receive.
2691       * @param int $type One of navigation_node::TYPE_*
2692       * @return navigation_node|false
2693       */
2694      public function get($key, $type = null) {
2695          if (!$this->initialised) {
2696              $this->initialise();
2697          }
2698          return parent::get($key, $type);
2699      }
2700  
2701      /**
2702       * Searches this nodes children and their children to find a navigation node
2703       * with the matching key and type.
2704       *
2705       * This method is recursive and searches children so until either a node is
2706       * found or there are no more nodes to search.
2707       *
2708       * If you know that the node being searched for is a child of this node
2709       * then use the {@link global_navigation::get()} method instead.
2710       *
2711       * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2712       * may be of more use to you.
2713       *
2714       * @param string|int $key The key of the node you wish to receive.
2715       * @param int $type One of navigation_node::TYPE_*
2716       * @return navigation_node|false
2717       */
2718      public function find($key, $type) {
2719          if (!$this->initialised) {
2720              $this->initialise();
2721          }
2722          if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2723              return $this->rootnodes[$key];
2724          }
2725          return parent::find($key, $type);
2726      }
2727  
2728      /**
2729       * They've expanded the 'my courses' branch.
2730       */
2731      protected function load_courses_enrolled() {
2732          global $CFG, $DB;
2733          $sortorder = 'visible DESC';
2734          // Prevent undefined $CFG->navsortmycoursessort errors.
2735          if (empty($CFG->navsortmycoursessort)) {
2736              $CFG->navsortmycoursessort = 'sortorder';
2737          }
2738          // Append the chosen sortorder.
2739          $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2740          $courses = enrol_get_my_courses(null, $sortorder);
2741          if (count($courses) && $this->show_my_categories()) {
2742              // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2743              // In order to make sure we load everything required we must first find the categories that are not
2744              // base categories and work out the bottom category in thier path.
2745              $categoryids = array();
2746              foreach ($courses as $course) {
2747                  $categoryids[] = $course->category;
2748              }
2749              $categoryids = array_unique($categoryids);
2750              list($sql, $params) = $DB->get_in_or_equal($categoryids);
2751              $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2752              foreach ($categories as $category) {
2753                  $bits = explode('/', trim($category->path,'/'));
2754                  $categoryids[] = array_shift($bits);
2755              }
2756              $categoryids = array_unique($categoryids);
2757              $categories->close();
2758  
2759              // Now we load the base categories.
2760              list($sql, $params) = $DB->get_in_or_equal($categoryids);
2761              $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2762              foreach ($categories as $category) {
2763                  $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2764              }
2765              $categories->close();
2766          } else {
2767              foreach ($courses as $course) {
2768                  $this->add_course($course, false, self::COURSE_MY);
2769              }
2770          }
2771      }
2772  }
2773  
2774  /**
2775   * The global navigation class used especially for AJAX requests.
2776   *
2777   * The primary methods that are used in the global navigation class have been overriden
2778   * to ensure that only the relevant branch is generated at the root of the tree.
2779   * This can be done because AJAX is only used when the backwards structure for the
2780   * requested branch exists.
2781   * This has been done only because it shortens the amounts of information that is generated
2782   * which of course will speed up the response time.. because no one likes laggy AJAX.
2783   *
2784   * @package   core
2785   * @category  navigation
2786   * @copyright 2009 Sam Hemelryk
2787   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2788   */
2789  class global_navigation_for_ajax extends global_navigation {
2790  
2791      /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2792      protected $branchtype;
2793  
2794      /** @var int the instance id */
2795      protected $instanceid;
2796  
2797      /** @var array Holds an array of expandable nodes */
2798      protected $expandable = array();
2799  
2800      /**
2801       * Constructs the navigation for use in an AJAX request
2802       *
2803       * @param moodle_page $page moodle_page object
2804       * @param int $branchtype
2805       * @param int $id
2806       */
2807      public function __construct($page, $branchtype, $id) {
2808          $this->page = $page;
2809          $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2810          $this->children = new navigation_node_collection();
2811          $this->branchtype = $branchtype;
2812          $this->instanceid = $id;
2813          $this->initialise();
2814      }
2815      /**
2816       * Initialise the navigation given the type and id for the branch to expand.
2817       *
2818       * @return array An array of the expandable nodes
2819       */
2820      public function initialise() {
2821          global $DB, $SITE;
2822  
2823          if ($this->initialised || during_initial_install()) {
2824              return $this->expandable;
2825          }
2826          $this->initialised = true;
2827  
2828          $this->rootnodes = array();
2829          $this->rootnodes['site']    = $this->add_course($SITE);
2830          $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2831          $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2832          // The courses branch is always displayed, and is always expandable (although may be empty).
2833          // This mimicks what is done during {@link global_navigation::initialise()}.
2834          $this->rootnodes['courses']->isexpandable = true;
2835  
2836          // Branchtype will be one of navigation_node::TYPE_*
2837          switch ($this->branchtype) {
2838              case 0:
2839                  if ($this->instanceid === 'mycourses') {
2840                      $this->load_courses_enrolled();
2841                  } else if ($this->instanceid === 'courses') {
2842                      $this->load_courses_other();
2843                  }
2844                  break;
2845              case self::TYPE_CATEGORY :
2846                  $this->load_category($this->instanceid);
2847                  break;
2848              case self::TYPE_MY_CATEGORY :
2849                  $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2850                  break;
2851              case self::TYPE_COURSE :
2852                  $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2853                  if (!can_access_course($course)) {
2854                      // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
2855                      // add the course node and break. This leads to an empty node.
2856                      $this->add_course($course);
2857                      break;
2858                  }
2859                  require_course_login($course, true, null, false, true);
2860                  $this->page->set_context(context_course::instance($course->id));
2861                  $coursenode = $this->add_course($course);
2862                  $this->add_course_essentials($coursenode, $course);
2863                  $this->load_course_sections($course, $coursenode);
2864                  break;
2865              case self::TYPE_SECTION :
2866                  $sql = 'SELECT c.*, cs.section AS sectionnumber
2867                          FROM {course} c
2868                          LEFT JOIN {course_sections} cs ON cs.course = c.id
2869                          WHERE cs.id = ?';
2870                  $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
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, $course->sectionnumber);
2876                  break;
2877              case self::TYPE_ACTIVITY :
2878                  $sql = "SELECT c.*
2879                            FROM {course} c
2880                            JOIN {course_modules} cm ON cm.course = c.id
2881                           WHERE cm.id = :cmid";
2882                  $params = array('cmid' => $this->instanceid);
2883                  $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2884                  $modinfo = get_fast_modinfo($course);
2885                  $cm = $modinfo->get_cm($this->instanceid);
2886                  require_course_login($course, true, $cm, false, true);
2887                  $this->page->set_context(context_module::instance($cm->id));
2888                  $coursenode = $this->load_course($course);
2889                  $this->load_course_sections($course, $coursenode, null, $cm);
2890                  $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2891                  if ($activitynode) {
2892                      $modulenode = $this->load_activity($cm, $course, $activitynode);
2893                  }
2894                  break;
2895              default:
2896                  throw new Exception('Unknown type');
2897                  return $this->expandable;
2898          }
2899  
2900          if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2901              $this->load_for_user(null, true);
2902          }
2903  
2904          $this->find_expandable($this->expandable);
2905          return $this->expandable;
2906      }
2907  
2908      /**
2909       * They've expanded the general 'courses' branch.
2910       */
2911      protected function load_courses_other() {
2912          $this->load_all_courses();
2913      }
2914  
2915      /**
2916       * Loads a single category into the AJAX navigation.
2917       *
2918       * This function is special in that it doesn't concern itself with the parent of
2919       * the requested category or its siblings.
2920       * This is because with the AJAX navigation we know exactly what is wanted and only need to
2921       * request that.
2922       *
2923       * @global moodle_database $DB
2924       * @param int $categoryid id of category to load in navigation.
2925       * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2926       * @return void.
2927       */
2928      protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2929          global $CFG, $DB;
2930  
2931          $limit = 20;
2932          if (!empty($CFG->navcourselimit)) {
2933              $limit = (int)$CFG->navcourselimit;
2934          }
2935  
2936          $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2937          $sql = "SELECT cc.*, $catcontextsql
2938                    FROM {course_categories} cc
2939                    JOIN {context} ctx ON cc.id = ctx.instanceid
2940                   WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2941                         (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2942                ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2943          $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2944          $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2945          $categorylist = array();
2946          $subcategories = array();
2947          $basecategory = null;
2948          foreach ($categories as $category) {
2949              $categorylist[] = $category->id;
2950              context_helper::preload_from_record($category);
2951              if ($category->id == $categoryid) {
2952                  $this->add_category($category, $this, $nodetype);
2953                  $basecategory = $this->addedcategories[$category->id];
2954              } else {
2955                  $subcategories[$category->id] = $category;
2956              }
2957          }
2958          $categories->close();
2959  
2960  
2961          // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2962          // else show all courses.
2963          if ($nodetype === self::TYPE_MY_CATEGORY) {
2964              $courses = enrol_get_my_courses();
2965              $categoryids = array();
2966  
2967              // Only search for categories if basecategory was found.
2968              if (!is_null($basecategory)) {
2969                  // Get course parent category ids.
2970                  foreach ($courses as $course) {
2971                      $categoryids[] = $course->category;
2972                  }
2973  
2974                  // Get a unique list of category ids which a part of the path
2975                  // to user's courses.
2976                  $coursesubcategories = array();
2977                  $addedsubcategories = array();
2978  
2979                  list($sql, $params) = $DB->get_in_or_equal($categoryids);
2980                  $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
2981  
2982                  foreach ($categories as $category){
2983                      $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
2984                  }
2985                  $coursesubcategories = array_unique($coursesubcategories);
2986  
2987                  // Only add a subcategory if it is part of the path to user's course and
2988                  // wasn't already added.
2989                  foreach ($subcategories as $subid => $subcategory) {
2990                      if (in_array($subid, $coursesubcategories) &&
2991                              !in_array($subid, $addedsubcategories)) {
2992                              $this->add_category($subcategory, $basecategory, $nodetype);
2993                              $addedsubcategories[] = $subid;
2994                      }
2995                  }
2996              }
2997  
2998              foreach ($courses as $course) {
2999                  // Add course if it's in category.
3000                  if (in_array($course->category, $categorylist)) {
3001                      $this->add_course($course, true, self::COURSE_MY);
3002                  }
3003              }
3004          } else {
3005              if (!is_null($basecategory)) {
3006                  foreach ($subcategories as $key=>$category) {
3007                      $this->add_category($category, $basecategory, $nodetype);
3008                  }
3009              }
3010              $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3011              foreach ($courses as $course) {
3012                  $this->add_course($course);
3013              }
3014              $courses->close();
3015          }
3016      }
3017  
3018      /**
3019       * Returns an array of expandable nodes
3020       * @return array
3021       */
3022      public function get_expandable() {
3023          return $this->expandable;
3024      }
3025  }
3026  
3027  /**
3028   * Navbar class
3029   *
3030   * This class is used to manage the navbar, which is initialised from the navigation
3031   * object held by PAGE
3032   *
3033   * @package   core
3034   * @category  navigation
3035   * @copyright 2009 Sam Hemelryk
3036   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3037   */
3038  class navbar extends navigation_node {
3039      /** @var bool A switch for whether the navbar is initialised or not */
3040      protected $initialised = false;
3041      /** @var mixed keys used to reference the nodes on the navbar */
3042      protected $keys = array();
3043      /** @var null|string content of the navbar */
3044      protected $content = null;
3045      /** @var moodle_page object the moodle page that this navbar belongs to */
3046      protected $page;
3047      /** @var bool A switch for whether to ignore the active navigation information */
3048      protected $ignoreactive = false;
3049      /** @var bool A switch to let us know if we are in the middle of an install */
3050      protected $duringinstall = false;
3051      /** @var bool A switch for whether the navbar has items */
3052      protected $hasitems = false;
3053      /** @var array An array of navigation nodes for the navbar */
3054      protected $items;
3055      /** @var array An array of child node objects */
3056      public $children = array();
3057      /** @var bool A switch for whether we want to include the root node in the navbar */
3058      public $includesettingsbase = false;
3059      /** @var navigation_node[] $prependchildren */
3060      protected $prependchildren = array();
3061      /**
3062       * The almighty constructor
3063       *
3064       * @param moodle_page $page
3065       */
3066      public function __construct(moodle_page $page) {
3067          global $CFG;
3068          if (during_initial_install()) {
3069              $this->duringinstall = true;
3070              return false;
3071          }
3072          $this->page = $page;
3073          $this->text = get_string('home');
3074          $this->shorttext = get_string('home');
3075          $this->action = new moodle_url($CFG->wwwroot);
3076          $this->nodetype = self::NODETYPE_BRANCH;
3077          $this->type = self::TYPE_SYSTEM;
3078      }
3079  
3080      /**
3081       * Quick check to see if the navbar will have items in.
3082       *
3083       * @return bool Returns true if the navbar will have items, false otherwise
3084       */
3085      public function has_items() {
3086          if ($this->duringinstall) {
3087              return false;
3088          } else if ($this->hasitems !== false) {
3089              return true;
3090          }
3091          $this->page->navigation->initialise($this->page);
3092  
3093          $activenodefound = ($this->page->navigation->contains_active_node() ||
3094                              $this->page->settingsnav->contains_active_node());
3095  
3096          $outcome = (count($this->children) > 0 || count($this->prependchildren) || (!$this->ignoreactive && $activenodefound));
3097          $this->hasitems = $outcome;
3098          return $outcome;
3099      }
3100  
3101      /**
3102       * Turn on/off ignore active
3103       *
3104       * @param bool $setting
3105       */
3106      public function ignore_active($setting=true) {
3107          $this->ignoreactive = ($setting);
3108      }
3109  
3110      /**
3111       * Gets a navigation node
3112       *
3113       * @param string|int $key for referencing the navbar nodes
3114       * @param int $type navigation_node::TYPE_*
3115       * @return navigation_node|bool
3116       */
3117      public function get($key, $type = null) {
3118          foreach ($this->children as &$child) {
3119              if ($child->key === $key && ($type == null || $type == $child->type)) {
3120                  return $child;
3121              }
3122          }
3123          foreach ($this->prependchildren as &$child) {
3124              if ($child->key === $key && ($type == null || $type == $child->type)) {
3125                  return $child;
3126              }
3127          }
3128          return false;
3129      }
3130      /**
3131       * Returns an array of navigation_node's that make up the navbar.
3132       *
3133       * @return array
3134       */
3135      public function get_items() {
3136          global $CFG;
3137          $items = array();
3138          // Make sure that navigation is initialised
3139          if (!$this->has_items()) {
3140              return $items;
3141          }
3142          if ($this->items !== null) {
3143              return $this->items;
3144          }
3145  
3146          if (count($this->children) > 0) {
3147              // Add the custom children.
3148              $items = array_reverse($this->children);
3149          }
3150  
3151          $navigationactivenode = $this->page->navigation->find_active_node();
3152          $settingsactivenode = $this->page->settingsnav->find_active_node();
3153  
3154          // Check if navigation contains the active node
3155          if (!$this->ignoreactive) {
3156  
3157              if ($navigationactivenode && $settingsactivenode) {
3158                  // Parse a combined navigation tree
3159                  while ($settingsactivenode && $settingsactivenode->parent !== null) {
3160                      if (!$settingsactivenode->mainnavonly) {
3161                          $items[] = $settingsactivenode;
3162                      }
3163                      $settingsactivenode = $settingsactivenode->parent;
3164                  }
3165                  if (!$this->includesettingsbase) {
3166                      // Removes the first node from the settings (root node) from the list
3167                      array_pop($items);
3168                  }
3169                  while ($navigationactivenode && $navigationactivenode->parent !== null) {
3170                      if (!$navigationactivenode->mainnavonly) {
3171                          $items[] = $navigationactivenode;
3172                      }
3173                      if (!empty($CFG->navshowcategories) &&
3174                              $navigationactivenode->type === self::TYPE_COURSE &&
3175                              $navigationactivenode->parent->key === 'currentcourse') {
3176                          $items = array_merge($items, $this->get_course_categories());
3177                      }
3178                      $navigationactivenode = $navigationactivenode->parent;
3179                  }
3180              } else if ($navigationactivenode) {
3181                  // Parse the navigation tree to get the active node
3182                  while ($navigationactivenode && $navigationactivenode->parent !== null) {
3183                      if (!$navigationactivenode->mainnavonly) {
3184                          $items[] = $navigationactivenode;
3185                      }
3186                      if (!empty($CFG->navshowcategories) &&
3187                              $navigationactivenode->type === self::TYPE_COURSE &&
3188                              $navigationactivenode->parent->key === 'currentcourse') {
3189                          $items = array_merge($items, $this->get_course_categories());
3190                      }
3191                      $navigationactivenode = $navigationactivenode->parent;
3192                  }
3193              } else if ($settingsactivenode) {
3194                  // Parse the settings navigation to get the active node
3195                  while ($settingsactivenode && $settingsactivenode->parent !== null) {
3196                      if (!$settingsactivenode->mainnavonly) {
3197                          $items[] = $settingsactivenode;
3198                      }
3199                      $settingsactivenode = $settingsactivenode->parent;
3200                  }
3201              }
3202          }
3203  
3204          $items[] = new navigation_node(array(
3205              'text'=>$this->page->navigation->text,
3206              'shorttext'=>$this->page->navigation->shorttext,
3207              'key'=>$this->page->navigation->key,
3208              'action'=>$this->page->navigation->action
3209          ));
3210  
3211          if (count($this->prependchildren) > 0) {
3212              // Add the custom children
3213              $items = array_merge($items, array_reverse($this->prependchildren));
3214          }
3215  
3216          $this->items = array_reverse($items);
3217          return $this->items;
3218      }
3219  
3220      /**
3221       * Get the list of categories leading to this course.
3222       *
3223       * This function is used by {@link navbar::get_items()} to add back the "courses"
3224       * node and category chain leading to the current course.  Note that this is only ever
3225       * called for the current course, so we don't need to bother taking in any parameters.
3226       *
3227       * @return array
3228       */
3229      private function get_course_categories() {
3230          global $CFG;
3231  
3232          require_once($CFG->dirroot.'/course/lib.php');
3233          $categories = array();
3234          $cap = 'moodle/category:viewhiddencategories';
3235          foreach ($this->page->categories as $category) {
3236              if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3237                  continue;
3238              }
3239              $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3240              $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3241              $categorynode = navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3242              if (!$category->visible) {
3243                  $categorynode->hidden = true;
3244              }
3245              $categories[] = $categorynode;
3246          }
3247          if (is_enrolled(context_course::instance($this->page->course->id))) {
3248              $courses = $this->page->navigation->get('mycourses');
3249          } else {
3250              $courses = $this->page->navigation->get('courses');
3251          }
3252          if (!$courses) {
3253              // Courses node may not be present.
3254              $courses = navigation_node::create(
3255                  get_string('courses'),
3256                  new moodle_url('/course/index.php'),
3257                  self::TYPE_CONTAINER
3258              );
3259          }
3260          $categories[] = $courses;
3261          return $categories;
3262      }
3263  
3264      /**
3265       * Add a new navigation_node to the navbar, overrides parent::add
3266       *
3267       * This function overrides {@link navigation_node::add()} so that we can change
3268       * the way nodes get added to allow us to simply call add and have the node added to the
3269       * end of the navbar
3270       *
3271       * @param string $text
3272       * @param string|moodle_url|action_link $action An action to associate with this node.
3273       * @param int $type One of navigation_node::TYPE_*
3274       * @param string $shorttext
3275       * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3276       * @param pix_icon $icon An optional icon to use for this node.
3277       * @return navigation_node
3278       */
3279      public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3280          if ($this->content !== null) {
3281              debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3282          }
3283  
3284          // Properties array used when creating the new navigation node
3285          $itemarray = array(
3286              'text' => $text,
3287              'type' => $type
3288          );
3289          // Set the action if one was provided
3290          if ($action!==null) {
3291              $itemarray['action'] = $action;
3292          }
3293          // Set the shorttext if one was provided
3294          if ($shorttext!==null) {
3295              $itemarray['shorttext'] = $shorttext;
3296          }
3297          // Set the icon if one was provided
3298          if ($icon!==null) {
3299              $itemarray['icon'] = $icon;
3300          }
3301          // Default the key to the number of children if not provided
3302          if ($key === null) {
3303              $key = count($this->children);
3304          }
3305          // Set the key
3306          $itemarray['key'] = $key;
3307          // Set the parent to this node
3308          $itemarray['parent'] = $this;
3309          // Add the child using the navigation_node_collections add method
3310          $this->children[] = new navigation_node($itemarray);
3311          return $this;
3312      }
3313  
3314      /**
3315       * Prepends a new navigation_node to the start of the navbar
3316       *
3317       * @param string $text
3318       * @param string|moodle_url|action_link $action An action to associate with this node.
3319       * @param int $type One of navigation_node::TYPE_*
3320       * @param string $shorttext
3321       * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3322       * @param pix_icon $icon An optional icon to use for this node.
3323       * @return navigation_node
3324       */
3325      public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3326          if ($this->content !== null) {
3327              debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3328          }
3329          // Properties array used when creating the new navigation node.
3330          $itemarray = array(
3331              'text' => $text,
3332              'type' => $type
3333          );
3334          // Set the action if one was provided.
3335          if ($action!==null) {
3336              $itemarray['action'] = $action;
3337          }
3338          // Set the shorttext if one was provided.
3339          if ($shorttext!==null) {
3340              $itemarray['shorttext'] = $shorttext;
3341          }
3342          // Set the icon if one was provided.
3343          if ($icon!==null) {
3344              $itemarray['icon'] = $icon;
3345          }
3346          // Default the key to the number of children if not provided.
3347          if ($key === null) {
3348              $key = count($this->children);
3349          }
3350          // Set the key.
3351          $itemarray['key'] = $key;
3352          // Set the parent to this node.
3353          $itemarray['parent'] = $this;
3354          // Add the child node to the prepend list.
3355          $this->prependchildren[] = new navigation_node($itemarray);
3356          return $this;
3357      }
3358  }
3359  
3360  /**
3361   * Class used to manage the settings option for the current page
3362   *
3363   * This class is used to manage the settings options in a tree format (recursively)
3364   * and was created initially for use with the settings blocks.
3365   *
3366   * @package   core
3367   * @category  navigation
3368   * @copyright 2009 Sam Hemelryk
3369   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3370   */
3371  class settings_navigation extends navigation_node {
3372      /** @var stdClass the current context */
3373      protected $context;
3374      /** @var moodle_page the moodle page that the navigation belongs to */
3375      protected $page;
3376      /** @var string contains administration section navigation_nodes */
3377      protected $adminsection;
3378      /** @var bool A switch to see if the navigation node is initialised */
3379      protected $initialised = false;
3380      /** @var array An array of users that the nodes can extend for. */
3381      protected $userstoextendfor = array();
3382      /** @var navigation_cache **/
3383      protected $cache;
3384  
3385      /**
3386       * Sets up the object with basic settings and preparse it for use
3387       *
3388       * @param moodle_page $page
3389       */
3390      public function __construct(moodle_page &$page) {
3391          if (during_initial_install()) {
3392              return false;
3393          }
3394          $this->page = $page;
3395          // Initialise the main navigation. It is most important that this is done
3396          // before we try anything
3397          $this->page->navigation->initialise();
3398          // Initialise the navigation cache
3399          $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3400          $this->children = new navigation_node_collection();
3401      }
3402      /**
3403       * Initialise the settings navigation based on the current context
3404       *
3405       * This function initialises the settings navigation tree for a given context
3406       * by calling supporting functions to generate major parts of the tree.
3407       *
3408       */
3409      public function initialise() {
3410          global $DB, $SESSION, $SITE;
3411  
3412          if (during_initial_install()) {
3413              return false;
3414          } else if ($this->initialised) {
3415              return true;
3416          }
3417          $this->id = 'settingsnav';
3418          $this->context = $this->page->context;
3419  
3420          $context = $this->context;
3421          if ($context->contextlevel == CONTEXT_BLOCK) {
3422              $this->load_block_settings();
3423              $context = $context->get_parent_context();
3424          }
3425          switch ($context->contextlevel) {
3426              case CONTEXT_SYSTEM:
3427                  if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3428                      $this->load_front_page_settings(($context->id == $this->context->id));
3429                  }
3430                  break;
3431              case CONTEXT_COURSECAT:
3432                  $this->load_category_settings();
3433                  break;
3434              case CONTEXT_COURSE:
3435                  if ($this->page->course->id != $SITE->id) {
3436                      $this->load_course_settings(($context->id == $this->context->id));
3437                  } else {
3438                      $this->load_front_page_settings(($context->id == $this->context->id));
3439                  }
3440                  break;
3441              case CONTEXT_MODULE:
3442                  $this->load_module_settings();
3443                  $this->load_course_settings();
3444                  break;
3445              case CONTEXT_USER:
3446                  if ($this->page->course->id != $SITE->id) {
3447                      $this->load_course_settings();
3448                  }
3449                  break;
3450          }
3451  
3452          $usersettings = $this->load_user_settings($this->page->course->id);
3453  
3454          $adminsettings = false;
3455          if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
3456              $isadminpage = $this->is_admin_tree_needed();
3457  
3458              if (has_capability('moodle/site:config', context_system::instance())) {
3459                  // Make sure this works even if config capability changes on the fly
3460                  // and also make it fast for admin right after login.
3461                  $SESSION->load_navigation_admin = 1;
3462                  if ($isadminpage) {
3463                      $adminsettings = $this->load_administration_settings();
3464                  }
3465  
3466              } else if (!isset($SESSION->load_navigation_admin)) {
3467                  $adminsettings = $this->load_administration_settings();
3468                  $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
3469  
3470              } else if ($SESSION->load_navigation_admin) {
3471                  if ($isadminpage) {
3472                      $adminsettings = $this->load_administration_settings();
3473                  }
3474              }
3475  
3476              // Print empty navigation node, if needed.
3477              if ($SESSION->load_navigation_admin && !$isadminpage) {
3478                  if ($adminsettings) {
3479                      // Do not print settings tree on pages that do not need it, this helps with performance.
3480                      $adminsettings->remove();
3481                      $adminsettings = false;
3482                  }
3483                  $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin'), self::TYPE_SITE_ADMIN, null, 'siteadministration');
3484                  $siteadminnode->id = 'expandable_branch_'.$siteadminnode->type.'_'.clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
3485                  $this->page->requires->data_for_js('siteadminexpansion', $siteadminnode);
3486              }
3487          }
3488  
3489          if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
3490              $adminsettings->force_open();
3491          } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
3492              $usersettings->force_open();
3493          }
3494  
3495          // Check if the user is currently logged in as another user
3496          if (\core\session\manager::is_loggedinas()) {
3497              // Get the actual user, we need this so we can display an informative return link
3498              $realuser = \core\session\manager::get_realuser();
3499              // Add the informative return to original user link
3500              $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3501              $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3502          }
3503  
3504          // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3505          $this->load_local_plugin_settings();
3506  
3507          foreach ($this->children as $key=>$node) {
3508              if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3509                  // Site administration is shown as link.
3510                  if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
3511                      continue;
3512                  }
3513                  $node->remove();
3514              }
3515          }
3516          $this->initialised = true;
3517      }
3518      /**
3519       * Override the parent function so that we can add preceeding hr's and set a
3520       * root node class against all first level element
3521       *
3522       * It does this by first calling the parent's add method {@link navigation_node::add()}
3523       * and then proceeds to use the key to set class and hr
3524       *
3525       * @param string $text text to be used for the link.
3526       * @param string|moodle_url $url url for the new node
3527       * @param int $type the type of node navigation_node::TYPE_*
3528       * @param string $shorttext
3529       * @param string|int $key a key to access the node by.
3530       * @param pix_icon $icon An icon that appears next to the node.
3531       * @return navigation_node with the new node added to it.
3532       */
3533      public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3534          $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3535          $node->add_class('root_node');
3536          return $node;
3537      }
3538  
3539      /**
3540       * This function allows the user to add something to the start of the settings
3541       * navigation, which means it will be at the top of the settings navigation block
3542       *
3543       * @param string $text text to be used for the link.
3544       * @param string|moodle_url $url url for the new node
3545       * @param int $type the type of node navigation_node::TYPE_*
3546       * @param string $shorttext
3547       * @param string|int $key a key to access the node by.
3548       * @param pix_icon $icon An icon that appears next to the node.
3549       * @return navigation_node $node with the new node added to it.
3550       */
3551      public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3552          $children = $this->children;
3553          $childrenclass = get_class($children);
3554          $this->children = new $childrenclass;
3555          $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3556          foreach ($children as $child) {
3557              $this->children->add($child);
3558          }
3559          return $node;
3560      }
3561  
3562      /**
3563       * Does this page require loading of full admin tree or is
3564       * it enough rely on AJAX?
3565       *
3566       * @return bool
3567       */
3568      protected function is_admin_tree_needed() {
3569          if (self::$loadadmintree) {
3570              // Usually external admin page or settings page.
3571              return true;
3572          }
3573  
3574          if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
3575              // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
3576              if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
3577                  return false;
3578              }
3579              return true;
3580          }
3581  
3582          return false;
3583      }
3584  
3585      /**
3586       * Load the site administration tree
3587       *
3588       * This function loads the site administration tree by using the lib/adminlib library functions
3589       *
3590       * @param navigation_node $referencebranch A reference to a branch in the settings
3591       *      navigation tree
3592       * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3593       *      tree and start at the beginning
3594       * @return mixed A key to access the admin tree by
3595       */
3596      protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3597          global $CFG;
3598  
3599          // Check if we are just starting to generate this navigation.
3600          if ($referencebranch === null) {
3601  
3602              // Require the admin lib then get an admin structure
3603              if (!function_exists('admin_get_root')) {
3604                  require_once($CFG->dirroot.'/lib/adminlib.php');
3605              }
3606              $adminroot = admin_get_root(false, false);
3607              // This is the active section identifier
3608              $this->adminsection = $this->page->url->param('section');
3609  
3610              // Disable the navigation from automatically finding the active node
3611              navigation_node::$autofindactive = false;
3612              $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SITE_ADMIN, null, 'root');
3613              foreach ($adminroot->children as $adminbranch) {
3614                  $this->load_administration_settings($referencebranch, $adminbranch);
3615              }
3616              navigation_node::$autofindactive = true;
3617  
3618              // Use the admin structure to locate the active page
3619              if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3620                  $currentnode = $this;
3621                  while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3622                      $currentnode = $currentnode->get($pathkey);
3623                  }
3624                  if ($currentnode) {
3625                      $currentnode->make_active();
3626                  }
3627              } else {
3628                  $this->scan_for_active_node($referencebranch);
3629              }
3630              return $referencebranch;
3631          } else if ($adminbranch->check_access()) {
3632              // We have a reference branch that we can access and is not hidden `hurrah`
3633              // Now we need to display it and any children it may have
3634              $url = null;
3635              $icon = null;
3636              if ($adminbranch instanceof admin_settingpage) {
3637                  $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3638              } else if ($adminbranch instanceof admin_externalpage) {
3639                  $url = $adminbranch->url;
3640              } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3641                  $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3642              }
3643  
3644              // Add the branch
3645              $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3646  
3647              if ($adminbranch->is_hidden()) {
3648                  if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3649                      $reference->add_class('hidden');
3650                  } else {
3651                      $reference->display = false;
3652                  }
3653              }
3654  
3655              // Check if we are generating the admin notifications and whether notificiations exist
3656              if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3657                  $reference->add_class('criticalnotification');
3658              }
3659              // Check if this branch has children
3660              if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3661                  foreach ($adminbranch->children as $branch) {
3662                      // Generate the child branches as well now using this branch as the reference
3663                      $this->load_administration_settings($reference, $branch);
3664                  }
3665              } else {
3666                  $reference->icon = new pix_icon('i/settings', '');
3667              }
3668          }
3669      }
3670  
3671      /**
3672       * This function recursivily scans nodes until it finds the active node or there
3673       * are no more nodes.
3674       * @param navigation_node $node
3675       */
3676      protected function scan_for_active_node(navigation_node $node) {
3677          if (!$node->check_if_active() && $node->children->count()>0) {
3678              foreach ($node->children as &$child) {
3679                  $this->scan_for_active_node($child);
3680              }
3681          }
3682      }
3683  
3684      /**
3685       * Gets a navigation node given an array of keys that represent the path to
3686       * the desired node.
3687       *
3688       * @param array $path
3689       * @return navigation_node|false
3690       */
3691      protected function get_by_path(array $path) {
3692          $node = $this->get(array_shift($path));
3693          foreach ($path as $key) {
3694              $node->get($key);
3695          }
3696          return $node;
3697      }
3698  
3699      /**
3700       * This function loads the course settings that are available for the user
3701       *
3702       * @param bool $forceopen If set to true the course node will be forced open
3703       * @return navigation_node|false
3704       */
3705      protected function load_course_settings($forceopen = false) {
3706          global $CFG;
3707  
3708          $course = $this->page->course;
3709          $coursecontext = context_course::instance($course->id);
3710  
3711          // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3712  
3713          $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3714          if ($forceopen) {
3715              $coursenode->force_open();
3716          }
3717  
3718          if ($this->page->user_allowed_editing()) {
3719              // Add the turn on/off settings
3720  
3721              if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3722                  // We are on the course page, retain the current page params e.g. section.
3723                  $baseurl = clone($this->page->url);
3724                  $baseurl->param('sesskey', sesskey());
3725              } else {
3726                  // Edit on the main course page.
3727                  $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3728              }
3729  
3730              $editurl = clone($baseurl);
3731              if ($this->page->user_is_editing()) {
3732                  $editurl->param('edit', 'off');
3733                  $editstring = get_string('turneditingoff');
3734              } else {
3735                  $editurl->param('edit', 'on');
3736                  $editstring = get_string('turneditingon');
3737              }
3738              $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
3739          }
3740  
3741          if (has_capability('moodle/course:update', $coursecontext)) {
3742              // Add the course settings link
3743              $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3744              $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
3745  
3746              // Add the course completion settings link
3747              if ($CFG->enablecompletion && $course->enablecompletion) {
3748                  $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3749                  $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3750              }
3751          }
3752  
3753          // add enrol nodes
3754          enrol_add_course_navigation($coursenode, $course);
3755  
3756          // Manage filters
3757          if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3758              $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3759              $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3760          }
3761  
3762          // View course reports.
3763          if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
3764              $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'coursereports',
3765                      new pix_icon('i/stats', ''));
3766              $coursereports = core_component::get_plugin_list('coursereport');
3767              foreach ($coursereports as $report => $dir) {
3768                  $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
3769                  if (file_exists($libfile)) {
3770                      require_once($libfile);
3771                      $reportfunction = $report.'_report_extend_navigation';
3772                      if (function_exists($report.'_report_extend_navigation')) {
3773                          $reportfunction($reportnav, $course, $coursecontext);
3774                      }
3775                  }
3776              }
3777  
3778              $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
3779              foreach ($reports as $reportfunction) {
3780                  $reportfunction($reportnav, $course, $coursecontext);
3781              }
3782          }
3783  
3784          // Add view grade report is permitted
3785          $reportavailable = false;
3786          if (has_capability('moodle/grade:viewall', $coursecontext)) {
3787              $reportavailable = true;
3788          } else if (!empty($course->showgrades)) {
3789              $reports = core_component::get_plugin_list('gradereport');
3790              if (is_array($reports) && count($reports)>0) {     // Get all installed reports
3791                  arsort($reports); // user is last, we want to test it first
3792                  foreach ($reports as $plugin => $plugindir) {
3793                      if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3794                          //stop when the first visible plugin is found
3795                          $reportavailable = true;
3796                          break;
3797                      }
3798                  }
3799              }
3800          }
3801          if ($reportavailable) {
3802              $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3803              $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3804          }
3805  
3806          //  Add outcome if permitted
3807          if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3808              $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3809              $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3810          }
3811  
3812          //Add badges navigation
3813          require_once($CFG->libdir .'/badgeslib.php');
3814          badges_add_course_navigation($coursenode, $course);
3815  
3816          // Backup this course
3817          if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3818              $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3819              $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3820          }
3821  
3822          // Restore to this course
3823          if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3824              $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3825              $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3826          }
3827  
3828          // Import data from other courses
3829          if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3830              $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3831              $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
3832          }
3833  
3834          // Publish course on a hub
3835          if (has_capability('moodle/course:publish', $coursecontext)) {
3836              $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3837              $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3838          }
3839  
3840          // Reset this course
3841          if (has_capability('moodle/course:reset', $coursecontext)) {
3842              $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3843              $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3844          }
3845  
3846          // Questions
3847          require_once($CFG->libdir . '/questionlib.php');
3848          question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3849  
3850          if (has_capability('moodle/course:update', $coursecontext)) {
3851              // Repository Instances
3852              if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3853                  require_once($CFG->dirroot . '/repository/lib.php');
3854                  $editabletypes = repository::get_editable_types($coursecontext);
3855                  $haseditabletypes = !empty($editabletypes);
3856                  unset($editabletypes);
3857                  $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3858              } else {
3859                  $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3860              }
3861              if ($haseditabletypes) {
3862                  $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3863                  $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3864              }
3865          }
3866  
3867          // Manage files
3868          if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3869              // hidden in new courses and courses where legacy files were turned off
3870              $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3871              $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
3872  
3873          }
3874  
3875          // Switch roles
3876          $roles = array();
3877          $assumedrole = $this->in_alternative_role();
3878          if ($assumedrole !== false) {
3879              $roles[0] = get_string('switchrolereturn');
3880          }
3881          if (has_capability('moodle/role:switchroles', $coursecontext)) {
3882              $availableroles = get_switchable_roles($coursecontext);
3883              if (is_array($availableroles)) {
3884                  foreach ($availableroles as $key=>$role) {
3885                      if ($assumedrole == (int)$key) {
3886                          continue;
3887                      }
3888                      $roles[$key] = $role;
3889                  }
3890              }
3891          }
3892          if (is_array($roles) && count($roles)>0) {
3893              $switchroles = $this->add(get_string('switchroleto'));
3894              if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3895                  $switchroles->force_open();
3896              }
3897              foreach ($roles as $key => $name) {
3898                  $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$this->page->url->out_as_local_url(false)));
3899                  $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
3900              }
3901          }
3902  
3903          // Let admin tools hook into course navigation.
3904          $tools = get_plugin_list_with_function('tool', 'extend_navigation_course', 'lib.php');
3905          foreach ($tools as $toolfunction) {
3906              $toolfunction($coursenode, $course, $coursecontext);
3907          }
3908  
3909          // Return we are done
3910          return $coursenode;
3911      }
3912  
3913      /**
3914       * This function calls the module function to inject module settings into the
3915       * settings navigation tree.
3916       *
3917       * This only gets called if there is a corrosponding function in the modules
3918       * lib file.
3919       *
3920       * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3921       *
3922       * @return navigation_node|false
3923       */
3924      protected function load_module_settings() {
3925          global $CFG;
3926  
3927          if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3928              $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3929              $this->page->set_cm($cm, $this->page->course);
3930          }
3931  
3932          $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3933          if (file_exists($file)) {
3934              require_once($file);
3935          }
3936  
3937          $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
3938          $modulenode->force_open();
3939  
3940          // Settings for the module
3941          if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3942              $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
3943              $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3944          }
3945          // Assign local roles
3946          if (count(get_assignable_roles($this->page->cm->context))>0) {
3947              $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3948              $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3949          }
3950          // Override roles
3951          if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3952              $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3953              $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3954          }
3955          // Check role permissions
3956          if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3957              $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3958              $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3959          }
3960          // Manage filters
3961          if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3962              $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3963              $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3964          }
3965          // Add reports
3966          $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3967          foreach ($reports as $reportfunction) {
3968              $reportfunction($modulenode, $this->page->cm);
3969          }
3970          // Add a backup link
3971          $featuresfunc = $this->page->activityname.'_supports';
3972          if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3973              $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3974              $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3975          }
3976  
3977          // Restore this activity
3978          $featuresfunc = $this->page->activityname.'_supports';
3979          if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3980              $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3981              $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3982          }
3983  
3984          // Allow the active advanced grading method plugin to append its settings
3985          $featuresfunc = $this->page->activityname.'_supports';
3986          if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3987              require_once($CFG->dirroot.'/grade/grading/lib.php');
3988              $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
3989              $gradingman->extend_settings_navigation($this, $modulenode);
3990          }
3991  
3992          $function = $this->page->activityname.'_extend_settings_navigation';
3993          if (!function_exists($function)) {
3994              return $modulenode;
3995          }
3996  
3997          $function($this, $modulenode);
3998  
3999          // Remove the module node if there are no children
4000          if (empty($modulenode->children)) {
4001              $modulenode->remove();
4002          }
4003  
4004          return $modulenode;
4005      }
4006  
4007      /**
4008       * Loads the user settings block of the settings nav
4009       *
4010       * This function is simply works out the userid and whether we need to load
4011       * just the current users profile settings, or the current user and the user the
4012       * current user is viewing.
4013       *
4014       * This function has some very ugly code to work out the user, if anyone has
4015       * any bright ideas please feel free to intervene.
4016       *
4017       * @param int $courseid The course id of the current course
4018       * @return navigation_node|false
4019       */
4020      protected function load_user_settings($courseid = SITEID) {
4021          global $USER, $CFG;
4022  
4023          if (isguestuser() || !isloggedin()) {
4024              return false;
4025          }
4026  
4027          $navusers = $this->page->navigation->get_extending_users();
4028  
4029          if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4030              $usernode = null;
4031              foreach ($this->userstoextendfor as $userid) {
4032                  if ($userid == $USER->id) {
4033                      continue;
4034                  }
4035                  $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4036                  if (is_null($usernode)) {
4037                      $usernode = $node;
4038                  }
4039              }
4040              foreach ($navusers as $user) {
4041                  if ($user->id == $USER->id) {
4042                      continue;
4043                  }
4044                  $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4045                  if (is_null($usernode)) {
4046                      $usernode = $node;
4047                  }
4048              }
4049              $this->generate_user_settings($courseid, $USER->id);
4050          } else {
4051              $usernode = $this->generate_user_settings($courseid, $USER->id);
4052          }
4053          return $usernode;
4054      }
4055  
4056      /**
4057       * Extends the settings navigation for the given user.
4058       *
4059       * Note: This method gets called automatically if you call
4060       * $PAGE->navigation->extend_for_user($userid)
4061       *
4062       * @param int $userid
4063       */
4064      public function extend_for_user($userid) {
4065          global $CFG;
4066  
4067          if (!in_array($userid, $this->userstoextendfor)) {
4068              $this->userstoextendfor[] = $userid;
4069              if ($this->initialised) {
4070                  $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4071                  $children = array();
4072                  foreach ($this->children as $child) {
4073                      $children[] = $child;
4074                  }
4075                  array_unshift($children, array_pop($children));
4076                  $this->children = new navigation_node_collection();
4077                  foreach ($children as $child) {
4078                      $this->children->add($child);
4079                  }
4080              }
4081          }
4082      }
4083  
4084      /**
4085       * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4086       * what can be shown/done
4087       *
4088       * @param int $courseid The current course' id
4089       * @param int $userid The user id to load for
4090       * @param string $gstitle The string to pass to get_string for the branch title
4091       * @return navigation_node|false
4092       */
4093      protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4094          global $DB, $CFG, $USER, $SITE;
4095  
4096          if ($courseid != $SITE->id) {
4097              if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4098                  $course = $this->page->course;
4099              } else {
4100                  $select = context_helper::get_preload_record_columns_sql('ctx');
4101                  $sql = "SELECT c.*, $select
4102                            FROM {course} c
4103                            JOIN {context} ctx ON c.id = ctx.instanceid
4104                           WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4105                  $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4106                  $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4107                  context_helper::preload_from_record($course);
4108              }
4109          } else {
4110              $course = $SITE;
4111          }
4112  
4113          $coursecontext = context_course::instance($course->id);   // Course context
4114          $systemcontext   = context_system::instance();
4115          $currentuser = ($USER->id == $userid);
4116  
4117          if ($currentuser) {
4118              $user = $USER;
4119              $usercontext = context_user::instance($user->id);       // User context
4120          } else {
4121              $select = context_helper::get_preload_record_columns_sql('ctx');
4122              $sql = "SELECT u.*, $select
4123                        FROM {user} u
4124                        JOIN {context} ctx ON u.id = ctx.instanceid
4125                       WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4126              $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4127              $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4128              if (!$user) {
4129                  return false;
4130              }
4131              context_helper::preload_from_record($user);
4132  
4133              // Check that the user can view the profile
4134              $usercontext = context_user::instance($user->id); // User context
4135              $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4136  
4137              if ($course->id == $SITE->id) {
4138                  if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {  // Reduce possibility of "browsing" userbase at site level
4139                      // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4140                      return false;
4141                  }
4142              } else {
4143                  $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4144                  $userisenrolled = is_enrolled($coursecontext, $user->id);
4145                  if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4146                      return false;
4147                  }
4148                  $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4149                  if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
4150                      // If groups are in use, make sure we can see that group (MDL-45874).
4151                      if ($courseid == $this->page->course->id) {
4152                          $mygroups = get_fast_modinfo($this->page->course)->groups;
4153                      } else {
4154                          $mygroups = groups_get_user_groups($courseid);
4155                      }
4156                      $usergroups = groups_get_user_groups($courseid, $userid);
4157                      if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4158                          return false;
4159                      }
4160                  }
4161              }
4162          }
4163  
4164          $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4165  
4166          $key = $gstitle;
4167          if ($gstitle != 'usercurrentsettings') {
4168              $key .= $userid;
4169          }
4170  
4171          // Add a user setting branch
4172          $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
4173          $usersetting->id = 'usersettings';
4174          if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
4175              // Automatically start by making it active
4176              $usersetting->make_active();
4177          }
4178  
4179          // Check if the user has been deleted
4180          if ($user->deleted) {
4181              if (!has_capability('moodle/user:update', $coursecontext)) {
4182                  // We can't edit the user so just show the user deleted message
4183                  $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4184              } else {
4185                  // We can edit the user so show the user deleted message and link it to the profile
4186                  if ($course->id == $SITE->id) {
4187                      $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4188                  } else {
4189                      $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4190                  }
4191                  $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4192              }
4193              return true;
4194          }
4195  
4196          $userauthplugin = false;
4197          if (!empty($user->auth)) {
4198              $userauthplugin = get_auth_plugin($user->auth);
4199          }
4200  
4201          // Add the profile edit link
4202          if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4203              if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
4204                  $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4205                  $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4206              } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4207                  if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4208                      $url = $userauthplugin->edit_profile_url();
4209                      if (empty($url)) {
4210                          $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4211                      }
4212                      $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4213                  }
4214              }
4215          }
4216  
4217          // Change password link
4218          if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4219              $passwordchangeurl = $userauthplugin->change_password_url();
4220              if (empty($passwordchangeurl)) {
4221                  $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4222              }
4223              $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
4224          }
4225  
4226          // View the roles settings
4227          if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
4228              $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4229  
4230              $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4231              $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4232  
4233              $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4234  
4235              if (!empty($assignableroles)) {
4236                  $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4237                  $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4238              }
4239  
4240              if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4241                  $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4242                  $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4243              }
4244  
4245              $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4246              $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4247          }
4248  
4249          // Portfolio
4250          if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4251              require_once($CFG->libdir . '/portfoliolib.php');
4252              if (portfolio_has_visible_instances()) {
4253                  $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4254  
4255                  $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4256                  $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4257  
4258                  $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4259                  $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4260              }
4261          }
4262  
4263          $enablemanagetokens = false;
4264          if (!empty($CFG->enablerssfeeds)) {
4265              $enablemanagetokens = true;
4266          } else if (!is_siteadmin($USER->id)
4267               && !empty($CFG->enablewebservices)
4268               && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4269              $enablemanagetokens = true;
4270          }
4271          // Security keys
4272          if ($currentuser && $enablemanagetokens) {
4273              $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4274              $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4275          }
4276  
4277          // Messaging
4278          if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4279              $url = new moodle_url('/message/edit.php', array('id'=>$user->id));
4280              $usersetting->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
4281          }
4282  
4283          // Blogs
4284          if ($currentuser && !empty($CFG->enableblogs)) {
4285              $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4286              $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
4287              if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
4288                  $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
4289                  $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
4290              }
4291          }
4292  
4293          // Badges.
4294          if ($currentuser && !empty($CFG->enablebadges)) {
4295              $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
4296              $badges->add(get_string('preferences'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
4297              if (!empty($CFG->badges_allowexternalbackpack)) {
4298                  $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
4299              }
4300          }
4301  
4302          // Add reports node.
4303          $reporttab = $usersetting->add(get_string('activityreports'));
4304          $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
4305          foreach ($reports as $reportfunction) {
4306              $reportfunction($reporttab, $user, $course);
4307          }
4308          $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
4309          if ($anyreport || ($course->showreports && $currentuser)) {
4310              // Add grade hardcoded grade report if necessary.
4311              $gradeaccess = false;
4312              if (has_capability('moodle/grade:viewall', $coursecontext)) {
4313                  // Can view all course grades.
4314                  $gradeaccess = true;
4315              } else if ($course->showgrades) {
4316                  if ($currentuser && has_capability('moodle/grade:view', $coursecontext)) {
4317                      // Can view own grades.
4318                      $gradeaccess = true;
4319                  } else if (has_capability('moodle/grade:viewall', $usercontext)) {
4320                      // Can view grades of this user - parent most probably.
4321                      $gradeaccess = true;
4322                  } else if ($anyreport) {
4323                      // Can view grades of this user - parent most probably.
4324                      $gradeaccess = true;
4325                  }
4326              }
4327              if ($gradeaccess) {
4328                  $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id,
4329                          'user'=>$usercontext->instanceid)));
4330              }
4331          }
4332          // Check the number of nodes in the report node... if there are none remove the node
4333          $reporttab->trim_if_empty();
4334  
4335          // Login as ...
4336          if (!$user->deleted and !$currentuser && !\core\session\manager::is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
4337              $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
4338              $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
4339          }
4340  
4341          // Let admin tools hook into user settings navigation.
4342          $tools = get_plugin_list_with_function('tool', 'extend_navigation_user_settings', 'lib.php');
4343          foreach ($tools as $toolfunction) {
4344              $toolfunction($usersetting, $user, $usercontext, $course, $coursecontext);
4345          }
4346  
4347          return $usersetting;
4348      }
4349  
4350      /**
4351       * Loads block specific settings in the navigation
4352       *
4353       * @return navigation_node
4354       */
4355      protected function load_block_settings() {
4356          global $CFG;
4357  
4358          $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
4359          $blocknode->force_open();
4360  
4361          // Assign local roles
4362          $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4363          $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4364  
4365          // Override roles
4366          if (has_capability('moodle/role:review', $this->context) or  count(get_overridable_roles($this->context))>0) {
4367              $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4368              $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4369          }
4370          // Check role permissions
4371          if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4372              $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4373              $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4374          }
4375  
4376          return $blocknode;
4377      }
4378  
4379      /**
4380       * Loads category specific settings in the navigation
4381       *
4382       * @return navigation_node
4383       */
4384      protected function load_category_settings() {
4385          global $CFG;
4386  
4387          // We can land here while being in the context of a block, in which case we
4388          // should get the parent context which should be the category one. See self::initialise().
4389          if ($this->context->contextlevel == CONTEXT_BLOCK) {
4390              $catcontext = $this->context->get_parent_context();
4391          } else {
4392              $catcontext = $this->context;
4393          }
4394  
4395          // Let's make sure that we always have the right context when getting here.
4396          if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
4397              throw new coding_exception('Unexpected context while loading category settings.');
4398          }
4399  
4400          $categorynode = $this->add($catcontext->get_context_name(), null, null, null, 'categorysettings');
4401          $categorynode->force_open();
4402  
4403          if (can_edit_in_category($catcontext->instanceid)) {
4404              $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
4405              $editstring = get_string('managecategorythis');
4406              $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4407          }
4408  
4409          if (has_capability('moodle/category:manage', $catcontext)) {
4410              $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
4411              $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4412  
4413              $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
4414              $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4415          }
4416  
4417          // Assign local roles
4418          if (has_capability('moodle/role:assign', $catcontext)) {
4419              $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
4420              $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4421          }
4422  
4423          // Override roles
4424          if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
4425              $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
4426              $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4427          }
4428          // Check role permissions
4429          if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
4430                  'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
4431              $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
4432              $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4433          }
4434  
4435          // Cohorts
4436          if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
4437              $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
4438                  array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
4439          }
4440  
4441          // Manage filters
4442          if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
4443              $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
4444              $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4445          }
4446  
4447          // Restore.
4448          if (has_capability('moodle/course:create', $catcontext)) {
4449              $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
4450              $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
4451          }
4452  
4453          return $categorynode;
4454      }
4455  
4456      /**
4457       * Determine whether the user is assuming another role
4458       *
4459       * This function checks to see if the user is assuming another role by means of
4460       * role switching. In doing this we compare each RSW key (context path) against
4461       * the current context path. This ensures that we can provide the switching
4462       * options against both the course and any page shown under the course.
4463       *
4464       * @return bool|int The role(int) if the user is in another role, false otherwise
4465       */
4466      protected function in_alternative_role() {
4467          global $USER;
4468          if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4469              if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4470                  return $USER->access['rsw'][$this->page->context->path];
4471              }
4472              foreach ($USER->access['rsw'] as $key=>$role) {
4473                  if (strpos($this->context->path,$key)===0) {
4474                      return $role;
4475                  }
4476              }
4477          }
4478          return false;
4479      }
4480  
4481      /**
4482       * This function loads all of the front page settings into the settings navigation.
4483       * This function is called when the user is on the front page, or $COURSE==$SITE
4484       * @param bool $forceopen (optional)
4485       * @return navigation_node
4486       */
4487      protected function load_front_page_settings($forceopen = false) {
4488          global $SITE, $CFG;
4489  
4490          $course = clone($SITE);
4491          $coursecontext = context_course::instance($course->id);   // Course context
4492  
4493          $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4494          if ($forceopen) {
4495              $frontpage->force_open();
4496          }
4497          $frontpage->id = 'frontpagesettings';
4498  
4499          if ($this->page->user_allowed_editing()) {
4500  
4501              // Add the turn on/off settings
4502              $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4503              if ($this->page->user_is_editing()) {
4504                  $url->param('edit', 'off');
4505                  $editstring = get_string('turneditingoff');
4506              } else {
4507                  $url->param('edit', 'on');
4508                  $editstring = get_string('turneditingon');
4509              }
4510              $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4511          }
4512  
4513          if (has_capability('moodle/course:update', $coursecontext)) {
4514              // Add the course settings link
4515              $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4516              $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4517          }
4518  
4519          // add enrol nodes
4520          enrol_add_course_navigation($frontpage, $course);
4521  
4522          // Manage filters
4523          if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4524              $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4525              $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4526          }
4527  
4528          // View course reports.
4529          if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
4530              $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
4531                      new pix_icon('i/stats', ''));
4532              $coursereports = core_component::get_plugin_list('coursereport');
4533              foreach ($coursereports as $report=>$dir) {
4534                  $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4535                  if (file_exists($libfile)) {
4536                      require_once($libfile);
4537                      $reportfunction = $report.'_report_extend_navigation';
4538                      if (function_exists($report.'_report_extend_navigation')) {
4539                          $reportfunction($frontpagenav, $course, $coursecontext);
4540                      }
4541                  }
4542              }
4543  
4544              $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4545              foreach ($reports as $reportfunction) {
4546                  $reportfunction($frontpagenav, $course, $coursecontext);
4547              }
4548          }
4549  
4550          // Backup this course
4551          if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4552              $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4553              $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4554          }
4555  
4556          // Restore to this course
4557          if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4558              $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4559              $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4560          }
4561  
4562          // Questions
4563          require_once($CFG->libdir . '/questionlib.php');
4564          question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4565  
4566          // Manage files
4567          if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4568              //hiden in new installs
4569              $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4570              $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
4571          }
4572  
4573          // Let admin tools hook into frontpage navigation.
4574          $tools = get_plugin_list_with_function('tool', 'extend_navigation_frontpage', 'lib.php');
4575          foreach ($tools as $toolfunction) {
4576              $toolfunction($frontpage, $course, $coursecontext);
4577          }
4578  
4579          return $frontpage;
4580      }
4581  
4582      /**
4583       * This function gives local plugins an opportunity to modify the settings navigation.
4584       */
4585      protected function load_local_plugin_settings() {
4586          // Get all local plugins with an extend_settings_navigation function in their lib.php file
4587          foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
4588              // Call each function providing this (the settings navigation) and the current context.
4589              $function($this, $this->context);
4590          }
4591      }
4592  
4593      /**
4594       * This function marks the cache as volatile so it is cleared during shutdown
4595       */
4596      public function clear_cache() {
4597          $this->cache->volatile();
4598      }
4599  }
4600  
4601  /**
4602   * Class used to populate site admin navigation for ajax.
4603   *
4604   * @package   core
4605   * @category  navigation
4606   * @copyright 2013 Rajesh Taneja <[email protected]>
4607   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4608   */
4609  class settings_navigation_ajax extends settings_navigation {
4610      /**
4611       * Constructs the navigation for use in an AJAX request
4612       *
4613       * @param moodle_page $page
4614       */
4615      public function __construct(moodle_page &$page) {
4616          $this->page = $page;
4617          $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4618          $this->children = new navigation_node_collection();
4619          $this->initialise();
4620      }
4621  
4622      /**
4623       * Initialise the site admin navigation.
4624       *
4625       * @return array An array of the expandable nodes
4626       */
4627      public function initialise() {
4628          if ($this->initialised || during_initial_install()) {
4629              return false;
4630          }
4631          $this->context = $this->page->context;
4632          $this->load_administration_settings();
4633  
4634          // Check if local plugins is adding node to site admin.
4635          $this->load_local_plugin_settings();
4636  
4637          $this->initialised = true;
4638      }
4639  }
4640  
4641  /**
4642   * Simple class used to output a navigation branch in XML
4643   *
4644   * @package   core
4645   * @category  navigation
4646   * @copyright 2009 Sam Hemelryk
4647   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4648   */
4649  class navigation_json {
4650      /** @var array An array of different node types */
4651      protected $nodetype = array('node','branch');
4652      /** @var array An array of node keys and types */
4653      protected $expandable = array();
4654      /**
4655       * Turns a branch and all of its children into XML
4656       *
4657       * @param navigation_node $branch
4658       * @return string XML string
4659       */
4660      public function convert($branch) {
4661          $xml = $this->convert_child($branch);
4662          return $xml;
4663      }
4664      /**
4665       * Set the expandable items in the array so that we have enough information
4666       * to attach AJAX events
4667       * @param array $expandable
4668       */
4669      public function set_expandable($expandable) {
4670          foreach ($expandable as $node) {
4671              $this->expandable[$node['key'].':'.$node['type']] = $node;
4672          }
4673      }
4674      /**
4675       * Recusively converts a child node and its children to XML for output
4676       *
4677       * @param navigation_node $child The child to convert
4678       * @param int $depth Pointlessly used to track the depth of the XML structure
4679       * @return string JSON
4680       */
4681      protected function convert_child($child, $depth=1) {
4682          if (!$child->display) {
4683              return '';
4684          }
4685          $attributes = array();
4686          $attributes['id'] = $child->id;
4687          $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
4688          $attributes['type'] = $child->type;
4689          $attributes['key'] = $child->key;
4690          $attributes['class'] = $child->get_css_type();
4691  
4692          if ($child->icon instanceof pix_icon) {
4693              $attributes['icon'] = array(
4694                  'component' => $child->icon->component,
4695                  'pix' => $child->icon->pix,
4696              );
4697              foreach ($child->icon->attributes as $key=>$value) {
4698                  if ($key == 'class') {
4699                      $attributes['icon']['classes'] = explode(' ', $value);
4700                  } else if (!array_key_exists($key, $attributes['icon'])) {
4701                      $attributes['icon'][$key] = $value;
4702                  }
4703  
4704              }
4705          } else if (!empty($child->icon)) {
4706              $attributes['icon'] = (string)$child->icon;
4707          }
4708  
4709          if ($child->forcetitle || $child->title !== $child->text) {
4710              $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
4711          }
4712          if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4713              $attributes['expandable'] = $child->key;
4714              $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4715          }
4716  
4717          if (count($child->classes)>0) {
4718              $attributes['class'] .= ' '.join(' ',$child->classes);
4719          }
4720          if (is_string($child->action)) {
4721              $attributes['link'] = $child->action;
4722          } else if ($child->action instanceof moodle_url) {
4723              $attributes['link'] = $child->action->out();
4724          } else if ($child->action instanceof action_link) {
4725              $attributes['link'] = $child->action->url->out();
4726          }
4727          $attributes['hidden'] = ($child->hidden);
4728          $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4729          $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
4730  
4731          if ($child->children->count() > 0) {
4732              $attributes['children'] = array();
4733              foreach ($child->children as $subchild) {
4734                  $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4735              }
4736          }
4737  
4738          if ($depth > 1) {
4739              return $attributes;
4740          } else {
4741              return json_encode($attributes);
4742          }
4743      }
4744  }
4745  
4746  /**
4747   * The cache class used by global navigation and settings navigation.
4748   *
4749   * It is basically an easy access point to session with a bit of smarts to make
4750   * sure that the information that is cached is valid still.
4751   *
4752   * Example use:
4753   * <code php>
4754   * if (!$cache->viewdiscussion()) {
4755   *     // Code to do stuff and produce cachable content
4756   *     $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4757   * }
4758   * $content = $cache->viewdiscussion;
4759   * </code>
4760   *
4761   * @package   core
4762   * @category  navigation
4763   * @copyright 2009 Sam Hemelryk
4764   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4765   */
4766  class navigation_cache {
4767      /** @var int represents the time created */
4768      protected $creation;
4769      /** @var array An array of session keys */
4770      protected $session;
4771      /**
4772       * The string to use to segregate this particular cache. It can either be
4773       * unique to start a fresh cache or if you want to share a cache then make
4774       * it the string used in the original cache.
4775       * @var string
4776       */
4777      protected $area;
4778      /** @var int a time that the information will time out */
4779      protected $timeout;
4780      /** @var stdClass The current context */
4781      protected $currentcontext;
4782      /** @var int cache time information */
4783      const CACHETIME = 0;
4784      /** @var int cache user id */
4785      const CACHEUSERID = 1;
4786      /** @var int cache value */
4787      const CACHEVALUE = 2;
4788      /** @var null|array An array of navigation cache areas to expire on shutdown */
4789      public static $volatilecaches;
4790  
4791      /**
4792       * Contructor for the cache. Requires two arguments
4793       *
4794       * @param string $area The string to use to segregate this particular cache
4795       *                it can either be unique to start a fresh cache or if you want
4796       *                to share a cache then make it the string used in the original
4797       *                cache
4798       * @param int $timeout The number of seconds to time the information out after
4799       */
4800      public function __construct($area, $timeout=1800) {
4801          $this->creation = time();
4802          $this->area = $area;
4803          $this->timeout = time() - $timeout;
4804          if (rand(0,100) === 0) {
4805              $this->garbage_collection();
4806          }
4807      }
4808  
4809      /**
4810       * Used to set up the cache within the SESSION.
4811       *
4812       * This is called for each access and ensure that we don't put anything into the session before
4813       * it is required.
4814       */
4815      protected function ensure_session_cache_initialised() {
4816          global $SESSION;
4817          if (empty($this->session)) {
4818              if (!isset($SESSION->navcache)) {
4819                  $SESSION->navcache = new stdClass;
4820              }
4821              if (!isset($SESSION->navcache->{$this->area})) {
4822                  $SESSION->navcache->{$this->area} = array();
4823              }
4824              $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
4825          }
4826      }
4827  
4828      /**
4829       * Magic Method to retrieve something by simply calling using = cache->key
4830       *
4831       * @param mixed $key The identifier for the information you want out again
4832       * @return void|mixed Either void or what ever was put in
4833       */
4834      public function __get($key) {
4835          if (!$this->cached($key)) {
4836              return;
4837          }
4838          $information = $this->session[$key][self::CACHEVALUE];
4839          return unserialize($information);
4840      }
4841  
4842      /**
4843       * Magic method that simply uses {@link set();} to store something in the cache
4844       *
4845       * @param string|int $key
4846       * @param mixed $information
4847       */
4848      public function __set($key, $information) {
4849          $this->set($key, $information);
4850      }
4851  
4852      /**
4853       * Sets some information against the cache (session) for later retrieval
4854       *
4855       * @param string|int $key
4856       * @param mixed $information
4857       */
4858      public function set($key, $information) {
4859          global $USER;
4860          $this->ensure_session_cache_initialised();
4861          $information = serialize($information);
4862          $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4863      }
4864      /**
4865       * Check the existence of the identifier in the cache
4866       *
4867       * @param string|int $key
4868       * @return bool
4869       */
4870      public function cached($key) {
4871          global $USER;
4872          $this->ensure_session_cache_initialised();
4873          if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) {
4874              return false;
4875          }
4876          return true;
4877      }
4878      /**
4879       * Compare something to it's equivilant in the cache
4880       *
4881       * @param string $key
4882       * @param mixed $value
4883       * @param bool $serialise Whether to serialise the value before comparison
4884       *              this should only be set to false if the value is already
4885       *              serialised
4886       * @return bool If the value is the same false if it is not set or doesn't match
4887       */
4888      public function compare($key, $value, $serialise = true) {
4889          if ($this->cached($key)) {
4890              if ($serialise) {
4891                  $value = serialize($value);
4892              }
4893              if ($this->session[$key][self::CACHEVALUE] === $value) {
4894                  return true;
4895              }
4896          }
4897          return false;
4898      }
4899      /**
4900       * Wipes the entire cache, good to force regeneration
4901       */
4902      public function clear() {
4903          global $SESSION;
4904          unset($SESSION->navcache);
4905          $this->session = null;
4906      }
4907      /**
4908       * Checks all cache entries and removes any that have expired, good ole cleanup
4909       */
4910      protected function garbage_collection() {
4911          if (empty($this->session)) {
4912              return true;
4913          }
4914          foreach ($this->session as $key=>$cachedinfo) {
4915              if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4916                  unset($this->session[$key]);
4917              }
4918          }
4919      }
4920  
4921      /**
4922       * Marks the cache as being volatile (likely to change)
4923       *
4924       * Any caches marked as volatile will be destroyed at the on shutdown by
4925       * {@link navigation_node::destroy_volatile_caches()} which is registered
4926       * as a shutdown function if any caches are marked as volatile.
4927       *
4928       * @param bool $setting True to destroy the cache false not too
4929       */
4930      public function volatile($setting = true) {
4931          if (self::$volatilecaches===null) {
4932              self::$volatilecaches = array();
4933              core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
4934          }
4935  
4936          if ($setting) {
4937              self::$volatilecaches[$this->area] = $this->area;
4938          } else if (array_key_exists($this->area, self::$volatilecaches)) {
4939              unset(self::$volatilecaches[$this->area]);
4940          }
4941      }
4942  
4943      /**
4944       * Destroys all caches marked as volatile
4945       *
4946       * This function is static and works in conjunction with the static volatilecaches
4947       * property of navigation cache.
4948       * Because this function is static it manually resets the cached areas back to an
4949       * empty array.
4950       */
4951      public static function destroy_volatile_caches() {
4952          global $SESSION;
4953          if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4954              foreach (self::$volatilecaches as $area) {
4955                  $SESSION->navcache->{$area} = array();
4956              }
4957          } else {
4958              $SESSION->navcache = new stdClass;
4959          }
4960      }
4961  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1