Merge branch 'MDL-73502' of https://github.com/stronk7/moodle
[moodle.git] / lib / navigationlib.php
blobcfeec7013a9829e9c2124efa1e7c936384e83273
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.
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/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
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
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
34 /**
35 * This class is used to represent a node in a navigation tree
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.
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
48 class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF = 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH = 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN = null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY = 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
77 /** @var int Setting node type, used only within settings nav 80 */
78 const TYPE_USER = 80;
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE = 'courseindexpage';
90 /** @var int Parameter to aid the coder in tracking [optional] */
91 public $id = null;
92 /** @var string|int The identifier for the node, used to retrieve the node */
93 public $key = null;
94 /** @var string The text to use for the node */
95 public $text = null;
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
99 public $title = null;
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
102 /** @var moodle_url|action_link|null An action for the node (link) */
103 public $action = null;
104 /** @var pix_icon The path to an icon to use for this node */
105 public $icon = null;
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self::TYPE_UNKNOWN;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self::NODETYPE_LEAF;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
114 /** @var array An array of CSS classes for the node */
115 public $classes = array();
116 /** @var navigation_node_collection An array of child nodes */
117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
120 /** @var bool If set to true the node will be dimmed */
121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
131 public $parent = null;
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
136 /** @var array */
137 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
138 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
139 90 => 'container');
140 /** @var moodle_url */
141 protected static $fullmeurl = null;
142 /** @var bool toogles auto matching of active node */
143 public static $autofindactive = true;
144 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
145 protected static $loadadmintree = false;
146 /** @var mixed If set to an int, that section will be included even if it has no activities */
147 public $includesectionnum = false;
148 /** @var bool does the node need to be loaded via ajax */
149 public $requiresajaxloading = false;
150 /** @var bool If set to true this node will be added to the "flat" navigation */
151 public $showinflatnavigation = false;
152 /** @var bool If set to true this node will be forced into a "more" menu whenever possible */
153 public $forceintomoremenu = false;
154 /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */
155 public $showinsecondarynavigation = true;
158 * Constructs a new navigation_node
160 * @param array|string $properties Either an array of properties or a string to use
161 * as the text for the node
163 public function __construct($properties) {
164 if (is_array($properties)) {
165 // Check the array for each property that we allow to set at construction.
166 // text - The main content for the node
167 // shorttext - A short text if required for the node
168 // icon - The icon to display for the node
169 // type - The type of the node
170 // key - The key to use to identify the node
171 // parent - A reference to the nodes parent
172 // action - The action to attribute to this node, usually a URL to link to
173 if (array_key_exists('text', $properties)) {
174 $this->text = $properties['text'];
176 if (array_key_exists('shorttext', $properties)) {
177 $this->shorttext = $properties['shorttext'];
179 if (!array_key_exists('icon', $properties)) {
180 $properties['icon'] = new pix_icon('i/navigationitem', '');
182 $this->icon = $properties['icon'];
183 if ($this->icon instanceof pix_icon) {
184 if (empty($this->icon->attributes['class'])) {
185 $this->icon->attributes['class'] = 'navicon';
186 } else {
187 $this->icon->attributes['class'] .= ' navicon';
190 if (array_key_exists('type', $properties)) {
191 $this->type = $properties['type'];
192 } else {
193 $this->type = self::TYPE_CUSTOM;
195 if (array_key_exists('key', $properties)) {
196 $this->key = $properties['key'];
198 // This needs to happen last because of the check_if_active call that occurs
199 if (array_key_exists('action', $properties)) {
200 $this->action = $properties['action'];
201 if (is_string($this->action)) {
202 $this->action = new moodle_url($this->action);
204 if (self::$autofindactive) {
205 $this->check_if_active();
208 if (array_key_exists('parent', $properties)) {
209 $this->set_parent($properties['parent']);
211 } else if (is_string($properties)) {
212 $this->text = $properties;
214 if ($this->text === null) {
215 throw new coding_exception('You must set the text for the node when you create it.');
217 // Instantiate a new navigation node collection for this nodes children
218 $this->children = new navigation_node_collection();
222 * Checks if this node is the active node.
224 * This is determined by comparing the action for the node against the
225 * defined URL for the page. A match will see this node marked as active.
227 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
228 * @return bool
230 public function check_if_active($strength=URL_MATCH_EXACT) {
231 global $FULLME, $PAGE;
232 // Set fullmeurl if it hasn't already been set
233 if (self::$fullmeurl == null) {
234 if ($PAGE->has_set_url()) {
235 self::override_active_url(new moodle_url($PAGE->url));
236 } else {
237 self::override_active_url(new moodle_url($FULLME));
241 // Compare the action of this node against the fullmeurl
242 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
243 $this->make_active();
244 return true;
246 return false;
250 * True if this nav node has siblings in the tree.
252 * @return bool
254 public function has_siblings() {
255 if (empty($this->parent) || empty($this->parent->children)) {
256 return false;
258 if ($this->parent->children instanceof navigation_node_collection) {
259 $count = $this->parent->children->count();
260 } else {
261 $count = count($this->parent->children);
263 return ($count > 1);
267 * Get a list of sibling navigation nodes at the same level as this one.
269 * @return bool|array of navigation_node
271 public function get_siblings() {
272 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
273 // the in-page links or the breadcrumb links.
274 $siblings = false;
276 if ($this->has_siblings()) {
277 $siblings = [];
278 foreach ($this->parent->children as $child) {
279 if ($child->display) {
280 $siblings[] = $child;
284 return $siblings;
288 * This sets the URL that the URL of new nodes get compared to when locating
289 * the active node.
291 * The active node is the node that matches the URL set here. By default this
292 * is either $PAGE->url or if that hasn't been set $FULLME.
294 * @param moodle_url $url The url to use for the fullmeurl.
295 * @param bool $loadadmintree use true if the URL point to administration tree
297 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
298 // Clone the URL, in case the calling script changes their URL later.
299 self::$fullmeurl = new moodle_url($url);
300 // True means we do not want AJAX loaded admin tree, required for all admin pages.
301 if ($loadadmintree) {
302 // Do not change back to false if already set.
303 self::$loadadmintree = true;
308 * Use when page is linked from the admin tree,
309 * if not used navigation could not find the page using current URL
310 * because the tree is not fully loaded.
312 public static function require_admin_tree() {
313 self::$loadadmintree = true;
317 * Creates a navigation node, ready to add it as a child using add_node
318 * function. (The created node needs to be added before you can use it.)
319 * @param string $text
320 * @param moodle_url|action_link $action
321 * @param int $type
322 * @param string $shorttext
323 * @param string|int $key
324 * @param pix_icon $icon
325 * @return navigation_node
327 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
328 $shorttext=null, $key=null, pix_icon $icon=null) {
329 // Properties array used when creating the new navigation node
330 $itemarray = array(
331 'text' => $text,
332 'type' => $type
334 // Set the action if one was provided
335 if ($action!==null) {
336 $itemarray['action'] = $action;
338 // Set the shorttext if one was provided
339 if ($shorttext!==null) {
340 $itemarray['shorttext'] = $shorttext;
342 // Set the icon if one was provided
343 if ($icon!==null) {
344 $itemarray['icon'] = $icon;
346 // Set the key
347 $itemarray['key'] = $key;
348 // Construct and return
349 return new navigation_node($itemarray);
353 * Adds a navigation node as a child of this node.
355 * @param string $text
356 * @param moodle_url|action_link $action
357 * @param int $type
358 * @param string $shorttext
359 * @param string|int $key
360 * @param pix_icon $icon
361 * @return navigation_node
363 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
364 // Create child node
365 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
367 // Add the child to end and return
368 return $this->add_node($childnode);
372 * Adds a navigation node as a child of this one, given a $node object
373 * created using the create function.
374 * @param navigation_node $childnode Node to add
375 * @param string $beforekey
376 * @return navigation_node The added node
378 public function add_node(navigation_node $childnode, $beforekey=null) {
379 // First convert the nodetype for this node to a branch as it will now have children
380 if ($this->nodetype !== self::NODETYPE_BRANCH) {
381 $this->nodetype = self::NODETYPE_BRANCH;
383 // Set the parent to this node
384 $childnode->set_parent($this);
386 // Default the key to the number of children if not provided
387 if ($childnode->key === null) {
388 $childnode->key = $this->children->count();
391 // Add the child using the navigation_node_collections add method
392 $node = $this->children->add($childnode, $beforekey);
394 // If added node is a category node or the user is logged in and it's a course
395 // then mark added node as a branch (makes it expandable by AJAX)
396 $type = $childnode->type;
397 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
398 ($type === self::TYPE_SITE_ADMIN)) {
399 $node->nodetype = self::NODETYPE_BRANCH;
401 // If this node is hidden mark it's children as hidden also
402 if ($this->hidden) {
403 $node->hidden = true;
405 // Return added node (reference returned by $this->children->add()
406 return $node;
410 * Return a list of all the keys of all the child nodes.
411 * @return array the keys.
413 public function get_children_key_list() {
414 return $this->children->get_key_list();
418 * Searches for a node of the given type with the given key.
420 * This searches this node plus all of its children, and their children....
421 * If you know the node you are looking for is a child of this node then please
422 * use the get method instead.
424 * @param int|string $key The key of the node we are looking for
425 * @param int $type One of navigation_node::TYPE_*
426 * @return navigation_node|false
428 public function find($key, $type) {
429 return $this->children->find($key, $type);
433 * Walk the tree building up a list of all the flat navigation nodes.
435 * @param flat_navigation $nodes List of the found flat navigation nodes.
436 * @param boolean $showdivider Show a divider before the first node.
437 * @param string $label A label for the collection of navigation links.
439 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
440 if ($this->showinflatnavigation) {
441 $indent = 0;
442 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
443 $indent = 1;
445 $flat = new flat_navigation_node($this, $indent);
446 $flat->set_showdivider($showdivider, $label);
447 $nodes->add($flat);
449 foreach ($this->children as $child) {
450 $child->build_flat_navigation_list($nodes, false);
455 * Get the child of this node that has the given key + (optional) type.
457 * If you are looking for a node and want to search all children + their children
458 * then please use the find method instead.
460 * @param int|string $key The key of the node we are looking for
461 * @param int $type One of navigation_node::TYPE_*
462 * @return navigation_node|false
464 public function get($key, $type=null) {
465 return $this->children->get($key, $type);
469 * Removes this node.
471 * @return bool
473 public function remove() {
474 return $this->parent->children->remove($this->key, $this->type);
478 * Checks if this node has or could have any children
480 * @return bool Returns true if it has children or could have (by AJAX expansion)
482 public function has_children() {
483 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
487 * Marks this node as active and forces it open.
489 * Important: If you are here because you need to mark a node active to get
490 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
491 * You can use it to specify a different URL to match the active navigation node on
492 * rather than having to locate and manually mark a node active.
494 public function make_active() {
495 $this->isactive = true;
496 $this->add_class('active_tree_node');
497 $this->force_open();
498 if ($this->parent !== null) {
499 $this->parent->make_inactive();
504 * Marks a node as inactive and recusised back to the base of the tree
505 * doing the same to all parents.
507 public function make_inactive() {
508 $this->isactive = false;
509 $this->remove_class('active_tree_node');
510 if ($this->parent !== null) {
511 $this->parent->make_inactive();
516 * Forces this node to be open and at the same time forces open all
517 * parents until the root node.
519 * Recursive.
521 public function force_open() {
522 $this->forceopen = true;
523 if ($this->parent !== null) {
524 $this->parent->force_open();
529 * Adds a CSS class to this node.
531 * @param string $class
532 * @return bool
534 public function add_class($class) {
535 if (!in_array($class, $this->classes)) {
536 $this->classes[] = $class;
538 return true;
542 * Removes a CSS class from this node.
544 * @param string $class
545 * @return bool True if the class was successfully removed.
547 public function remove_class($class) {
548 if (in_array($class, $this->classes)) {
549 $key = array_search($class,$this->classes);
550 if ($key!==false) {
551 // Remove the class' array element.
552 unset($this->classes[$key]);
553 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
554 $this->classes = array_values($this->classes);
556 return true;
559 return false;
563 * Sets the title for this node and forces Moodle to utilise it.
564 * @param string $title
566 public function title($title) {
567 $this->title = $title;
568 $this->forcetitle = true;
572 * Resets the page specific information on this node if it is being unserialised.
574 public function __wakeup(){
575 $this->forceopen = false;
576 $this->isactive = false;
577 $this->remove_class('active_tree_node');
581 * Checks if this node or any of its children contain the active node.
583 * Recursive.
585 * @return bool
587 public function contains_active_node() {
588 if ($this->isactive) {
589 return true;
590 } else {
591 foreach ($this->children as $child) {
592 if ($child->isactive || $child->contains_active_node()) {
593 return true;
597 return false;
601 * To better balance the admin tree, we want to group all the short top branches together.
603 * This means < 8 nodes and no subtrees.
605 * @return bool
607 public function is_short_branch() {
608 $limit = 8;
609 if ($this->children->count() >= $limit) {
610 return false;
612 foreach ($this->children as $child) {
613 if ($child->has_children()) {
614 return false;
617 return true;
621 * Finds the active node.
623 * Searches this nodes children plus all of the children for the active node
624 * and returns it if found.
626 * Recursive.
628 * @return navigation_node|false
630 public function find_active_node() {
631 if ($this->isactive) {
632 return $this;
633 } else {
634 foreach ($this->children as &$child) {
635 $outcome = $child->find_active_node();
636 if ($outcome !== false) {
637 return $outcome;
641 return false;
645 * Searches all children for the best matching active node
646 * @return navigation_node|false
648 public function search_for_active_node() {
649 if ($this->check_if_active(URL_MATCH_BASE)) {
650 return $this;
651 } else {
652 foreach ($this->children as &$child) {
653 $outcome = $child->search_for_active_node();
654 if ($outcome !== false) {
655 return $outcome;
659 return false;
663 * Gets the content for this node.
665 * @param bool $shorttext If true shorttext is used rather than the normal text
666 * @return string
668 public function get_content($shorttext=false) {
669 if ($shorttext && $this->shorttext!==null) {
670 return format_string($this->shorttext);
671 } else {
672 return format_string($this->text);
677 * Gets the title to use for this node.
679 * @return string
681 public function get_title() {
682 if ($this->forcetitle || $this->action != null){
683 return $this->title;
684 } else {
685 return '';
690 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
692 * @return boolean
694 public function has_action() {
695 return !empty($this->action);
699 * Used to easily determine if this link in the breadcrumbs is hidden.
701 * @return boolean
703 public function is_hidden() {
704 return $this->hidden;
708 * Gets the CSS class to add to this node to describe its type
710 * @return string
712 public function get_css_type() {
713 if (array_key_exists($this->type, $this->namedtypes)) {
714 return 'type_'.$this->namedtypes[$this->type];
716 return 'type_unknown';
720 * Finds all nodes that are expandable by AJAX
722 * @param array $expandable An array by reference to populate with expandable nodes.
724 public function find_expandable(array &$expandable) {
725 foreach ($this->children as &$child) {
726 if ($child->display && $child->has_children() && $child->children->count() == 0) {
727 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
728 $this->add_class('canexpand');
729 $child->requiresajaxloading = true;
730 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
732 $child->find_expandable($expandable);
737 * Finds all nodes of a given type (recursive)
739 * @param int $type One of navigation_node::TYPE_*
740 * @return array
742 public function find_all_of_type($type) {
743 $nodes = $this->children->type($type);
744 foreach ($this->children as &$node) {
745 $childnodes = $node->find_all_of_type($type);
746 $nodes = array_merge($nodes, $childnodes);
748 return $nodes;
752 * Removes this node if it is empty
754 public function trim_if_empty() {
755 if ($this->children->count() == 0) {
756 $this->remove();
761 * Creates a tab representation of this nodes children that can be used
762 * with print_tabs to produce the tabs on a page.
764 * call_user_func_array('print_tabs', $node->get_tabs_array());
766 * @param array $inactive
767 * @param bool $return
768 * @return array Array (tabs, selected, inactive, activated, return)
770 public function get_tabs_array(array $inactive=array(), $return=false) {
771 $tabs = array();
772 $rows = array();
773 $selected = null;
774 $activated = array();
775 foreach ($this->children as $node) {
776 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
777 if ($node->contains_active_node()) {
778 if ($node->children->count() > 0) {
779 $activated[] = $node->key;
780 foreach ($node->children as $child) {
781 if ($child->contains_active_node()) {
782 $selected = $child->key;
784 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
786 } else {
787 $selected = $node->key;
791 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
795 * Sets the parent for this node and if this node is active ensures that the tree is properly
796 * adjusted as well.
798 * @param navigation_node $parent
800 public function set_parent(navigation_node $parent) {
801 // Set the parent (thats the easy part)
802 $this->parent = $parent;
803 // Check if this node is active (this is checked during construction)
804 if ($this->isactive) {
805 // Force all of the parent nodes open so you can see this node
806 $this->parent->force_open();
807 // Make all parents inactive so that its clear where we are.
808 $this->parent->make_inactive();
813 * Hides the node and any children it has.
815 * @since Moodle 2.5
816 * @param array $typestohide Optional. An array of node types that should be hidden.
817 * If null all nodes will be hidden.
818 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
819 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
821 public function hide(array $typestohide = null) {
822 if ($typestohide === null || in_array($this->type, $typestohide)) {
823 $this->display = false;
824 if ($this->has_children()) {
825 foreach ($this->children as $child) {
826 $child->hide($typestohide);
833 * Get the action url for this navigation node.
834 * Called from templates.
836 * @since Moodle 3.2
838 public function action() {
839 if ($this->action instanceof moodle_url) {
840 return $this->action;
841 } else if ($this->action instanceof action_link) {
842 return $this->action->url;
844 return $this->action;
848 * Return an array consisting of the additional attributes for the action url.
850 * @return array Formatted array to parse in a template
852 public function actionattributes() {
853 if ($this->action instanceof action_link) {
854 return array_map(function($key, $value) {
855 return [
856 'name' => $key,
857 'value' => $value
859 }, array_keys($this->action->attributes), $this->action->attributes);
862 return [];
866 * Sets whether the node and its children should be added into a "more" menu whenever possible.
868 * @param bool $forceintomoremenu
870 public function set_force_into_more_menu(bool $forceintomoremenu = false) {
871 $this->forceintomoremenu = $forceintomoremenu;
872 foreach ($this->children as $child) {
873 $child->set_force_into_more_menu($forceintomoremenu);
878 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable.
880 * @param bool $show
882 public function set_show_in_secondary_navigation(bool $show = true) {
883 $this->showinsecondarynavigation = $show;
884 foreach ($this->children as $child) {
885 $child->set_show_in_secondary_navigation($show);
890 * Add the menu item to handle locking and unlocking of a conext.
892 * @param \navigation_node $node Node to add
893 * @param \context $context The context to be locked
895 protected function add_context_locking_node(\navigation_node $node, \context $context) {
896 global $CFG;
897 // Manage context locking.
898 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
899 $parentcontext = $context->get_parent_context();
900 if (empty($parentcontext) || !$parentcontext->locked) {
901 if ($context->locked) {
902 $lockicon = 'i/unlock';
903 $lockstring = get_string('managecontextunlock', 'admin');
904 } else {
905 $lockicon = 'i/lock';
906 $lockstring = get_string('managecontextlock', 'admin');
908 $node->add(
909 $lockstring,
910 new moodle_url(
911 '/admin/lock.php',
913 'id' => $context->id,
916 self::TYPE_SETTING,
917 null,
918 'contextlocking',
919 new pix_icon($lockicon, '')
928 * Navigation node collection
930 * This class is responsible for managing a collection of navigation nodes.
931 * It is required because a node's unique identifier is a combination of both its
932 * key and its type.
934 * Originally an array was used with a string key that was a combination of the two
935 * however it was decided that a better solution would be to use a class that
936 * implements the standard IteratorAggregate interface.
938 * @package core
939 * @category navigation
940 * @copyright 2010 Sam Hemelryk
941 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
943 class navigation_node_collection implements IteratorAggregate, Countable {
945 * A multidimensional array to where the first key is the type and the second
946 * key is the nodes key.
947 * @var array
949 protected $collection = array();
951 * An array that contains references to nodes in the same order they were added.
952 * This is maintained as a progressive array.
953 * @var array
955 protected $orderedcollection = array();
957 * A reference to the last node that was added to the collection
958 * @var navigation_node
960 protected $last = null;
962 * The total number of items added to this array.
963 * @var int
965 protected $count = 0;
968 * Label for collection of nodes.
969 * @var string
971 protected $collectionlabel = '';
974 * Adds a navigation node to the collection
976 * @param navigation_node $node Node to add
977 * @param string $beforekey If specified, adds before a node with this key,
978 * otherwise adds at end
979 * @return navigation_node Added node
981 public function add(navigation_node $node, $beforekey=null) {
982 global $CFG;
983 $key = $node->key;
984 $type = $node->type;
986 // First check we have a 2nd dimension for this type
987 if (!array_key_exists($type, $this->orderedcollection)) {
988 $this->orderedcollection[$type] = array();
990 // Check for a collision and report if debugging is turned on
991 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
992 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
995 // Find the key to add before
996 $newindex = $this->count;
997 $last = true;
998 if ($beforekey !== null) {
999 foreach ($this->collection as $index => $othernode) {
1000 if ($othernode->key === $beforekey) {
1001 $newindex = $index;
1002 $last = false;
1003 break;
1006 if ($newindex === $this->count) {
1007 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
1008 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
1012 // Add the node to the appropriate place in the by-type structure (which
1013 // is not ordered, despite the variable name)
1014 $this->orderedcollection[$type][$key] = $node;
1015 if (!$last) {
1016 // Update existing references in the ordered collection (which is the
1017 // one that isn't called 'ordered') to shuffle them along if required
1018 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
1019 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
1022 // Add a reference to the node to the progressive collection.
1023 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
1024 // Update the last property to a reference to this new node.
1025 $this->last = $this->orderedcollection[$type][$key];
1027 // Reorder the array by index if needed
1028 if (!$last) {
1029 ksort($this->collection);
1031 $this->count++;
1032 // Return the reference to the now added node
1033 return $node;
1037 * Return a list of all the keys of all the nodes.
1038 * @return array the keys.
1040 public function get_key_list() {
1041 $keys = array();
1042 foreach ($this->collection as $node) {
1043 $keys[] = $node->key;
1045 return $keys;
1049 * Set a label for this collection.
1051 * @param string $label
1053 public function set_collectionlabel($label) {
1054 $this->collectionlabel = $label;
1058 * Return a label for this collection.
1060 * @return string
1062 public function get_collectionlabel() {
1063 return $this->collectionlabel;
1067 * Fetches a node from this collection.
1069 * @param string|int $key The key of the node we want to find.
1070 * @param int $type One of navigation_node::TYPE_*.
1071 * @return navigation_node|null
1073 public function get($key, $type=null) {
1074 if ($type !== null) {
1075 // If the type is known then we can simply check and fetch
1076 if (!empty($this->orderedcollection[$type][$key])) {
1077 return $this->orderedcollection[$type][$key];
1079 } else {
1080 // Because we don't know the type we look in the progressive array
1081 foreach ($this->collection as $node) {
1082 if ($node->key === $key) {
1083 return $node;
1087 return false;
1091 * Searches for a node with matching key and type.
1093 * This function searches both the nodes in this collection and all of
1094 * the nodes in each collection belonging to the nodes in this collection.
1096 * Recursive.
1098 * @param string|int $key The key of the node we want to find.
1099 * @param int $type One of navigation_node::TYPE_*.
1100 * @return navigation_node|null
1102 public function find($key, $type=null) {
1103 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1104 return $this->orderedcollection[$type][$key];
1105 } else {
1106 $nodes = $this->getIterator();
1107 // Search immediate children first
1108 foreach ($nodes as &$node) {
1109 if ($node->key === $key && ($type === null || $type === $node->type)) {
1110 return $node;
1113 // Now search each childs children
1114 foreach ($nodes as &$node) {
1115 $result = $node->children->find($key, $type);
1116 if ($result !== false) {
1117 return $result;
1121 return false;
1125 * Fetches the last node that was added to this collection
1127 * @return navigation_node
1129 public function last() {
1130 return $this->last;
1134 * Fetches all nodes of a given type from this collection
1136 * @param string|int $type node type being searched for.
1137 * @return array ordered collection
1139 public function type($type) {
1140 if (!array_key_exists($type, $this->orderedcollection)) {
1141 $this->orderedcollection[$type] = array();
1143 return $this->orderedcollection[$type];
1146 * Removes the node with the given key and type from the collection
1148 * @param string|int $key The key of the node we want to find.
1149 * @param int $type
1150 * @return bool
1152 public function remove($key, $type=null) {
1153 $child = $this->get($key, $type);
1154 if ($child !== false) {
1155 foreach ($this->collection as $colkey => $node) {
1156 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1157 unset($this->collection[$colkey]);
1158 $this->collection = array_values($this->collection);
1159 break;
1162 unset($this->orderedcollection[$child->type][$child->key]);
1163 $this->count--;
1164 return true;
1166 return false;
1170 * Gets the number of nodes in this collection
1172 * This option uses an internal count rather than counting the actual options to avoid
1173 * a performance hit through the count function.
1175 * @return int
1177 public function count() {
1178 return $this->count;
1181 * Gets an array iterator for the collection.
1183 * This is required by the IteratorAggregator interface and is used by routines
1184 * such as the foreach loop.
1186 * @return ArrayIterator
1188 public function getIterator() {
1189 return new ArrayIterator($this->collection);
1194 * The global navigation class used for... the global navigation
1196 * This class is used by PAGE to store the global navigation for the site
1197 * and is then used by the settings nav and navbar to save on processing and DB calls
1199 * See
1200 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1201 * {@link lib/ajax/getnavbranch.php} Called by ajax
1203 * @package core
1204 * @category navigation
1205 * @copyright 2009 Sam Hemelryk
1206 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1208 class global_navigation extends navigation_node {
1209 /** @var moodle_page The Moodle page this navigation object belongs to. */
1210 protected $page;
1211 /** @var bool switch to let us know if the navigation object is initialised*/
1212 protected $initialised = false;
1213 /** @var array An array of course information */
1214 protected $mycourses = array();
1215 /** @var navigation_node[] An array for containing root navigation nodes */
1216 protected $rootnodes = array();
1217 /** @var bool A switch for whether to show empty sections in the navigation */
1218 protected $showemptysections = true;
1219 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1220 protected $showcategories = null;
1221 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1222 protected $showmycategories = null;
1223 /** @var array An array of stdClasses for users that the navigation is extended for */
1224 protected $extendforuser = array();
1225 /** @var navigation_cache */
1226 protected $cache;
1227 /** @var array An array of course ids that are present in the navigation */
1228 protected $addedcourses = array();
1229 /** @var bool */
1230 protected $allcategoriesloaded = false;
1231 /** @var array An array of category ids that are included in the navigation */
1232 protected $addedcategories = array();
1233 /** @var int expansion limit */
1234 protected $expansionlimit = 0;
1235 /** @var int userid to allow parent to see child's profile page navigation */
1236 protected $useridtouseforparentchecks = 0;
1237 /** @var cache_session A cache that stores information on expanded courses */
1238 protected $cacheexpandcourse = null;
1240 /** Used when loading categories to load all top level categories [parent = 0] **/
1241 const LOAD_ROOT_CATEGORIES = 0;
1242 /** Used when loading categories to load all categories **/
1243 const LOAD_ALL_CATEGORIES = -1;
1246 * Constructs a new global navigation
1248 * @param moodle_page $page The page this navigation object belongs to
1250 public function __construct(moodle_page $page) {
1251 global $CFG, $SITE, $USER;
1253 if (during_initial_install()) {
1254 return;
1257 if (get_home_page() == HOMEPAGE_SITE) {
1258 // We are using the site home for the root element
1259 $properties = array(
1260 'key' => 'home',
1261 'type' => navigation_node::TYPE_SYSTEM,
1262 'text' => get_string('home'),
1263 'action' => new moodle_url('/'),
1264 'icon' => new pix_icon('i/home', '')
1266 } else {
1267 // We are using the users my moodle for the root element
1268 $properties = array(
1269 'key' => 'myhome',
1270 'type' => navigation_node::TYPE_SYSTEM,
1271 'text' => get_string('myhome'),
1272 'action' => new moodle_url('/my/'),
1273 'icon' => new pix_icon('i/dashboard', '')
1277 // Use the parents constructor.... good good reuse
1278 parent::__construct($properties);
1279 $this->showinflatnavigation = true;
1281 // Initalise and set defaults
1282 $this->page = $page;
1283 $this->forceopen = true;
1284 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1288 * Mutator to set userid to allow parent to see child's profile
1289 * page navigation. See MDL-25805 for initial issue. Linked to it
1290 * is an issue explaining why this is a REALLY UGLY HACK thats not
1291 * for you to use!
1293 * @param int $userid userid of profile page that parent wants to navigate around.
1295 public function set_userid_for_parent_checks($userid) {
1296 $this->useridtouseforparentchecks = $userid;
1301 * Initialises the navigation object.
1303 * This causes the navigation object to look at the current state of the page
1304 * that it is associated with and then load the appropriate content.
1306 * This should only occur the first time that the navigation structure is utilised
1307 * which will normally be either when the navbar is called to be displayed or
1308 * when a block makes use of it.
1310 * @return bool
1312 public function initialise() {
1313 global $CFG, $SITE, $USER;
1314 // Check if it has already been initialised
1315 if ($this->initialised || during_initial_install()) {
1316 return true;
1318 $this->initialised = true;
1320 // Set up the five base root nodes. These are nodes where we will put our
1321 // content and are as follows:
1322 // site: Navigation for the front page.
1323 // myprofile: User profile information goes here.
1324 // currentcourse: The course being currently viewed.
1325 // mycourses: The users courses get added here.
1326 // courses: Additional courses are added here.
1327 // users: Other users information loaded here.
1328 $this->rootnodes = array();
1329 if (get_home_page() == HOMEPAGE_SITE) {
1330 // The home element should be my moodle because the root element is the site
1331 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1332 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1333 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
1334 $this->rootnodes['home']->showinflatnavigation = true;
1336 } else {
1337 // The home element should be the site because the root node is my moodle
1338 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1339 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1340 $this->rootnodes['home']->showinflatnavigation = true;
1341 if (!empty($CFG->defaulthomepage) &&
1342 ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) {
1343 // We need to stop automatic redirection
1344 $this->rootnodes['home']->action->param('redirect', '0');
1347 $this->rootnodes['site'] = $this->add_course($SITE);
1348 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1349 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1350 $this->rootnodes['mycourses'] = $this->add(
1351 get_string('mycourses'),
1352 new moodle_url('/my/courses.php'),
1353 self::TYPE_ROOTNODE,
1354 null,
1355 'mycourses',
1356 new pix_icon('i/course', '')
1358 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1359 if (!core_course_category::user_top()) {
1360 $this->rootnodes['courses']->hide();
1362 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1364 // We always load the frontpage course to ensure it is available without
1365 // JavaScript enabled.
1366 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1367 $this->load_course_sections($SITE, $this->rootnodes['site']);
1369 $course = $this->page->course;
1370 $this->load_courses_enrolled();
1372 // $issite gets set to true if the current pages course is the sites frontpage course
1373 $issite = ($this->page->course->id == $SITE->id);
1375 // Determine if the user is enrolled in any course.
1376 $enrolledinanycourse = enrol_user_sees_own_courses();
1378 $this->rootnodes['currentcourse']->mainnavonly = true;
1379 if ($enrolledinanycourse) {
1380 $this->rootnodes['mycourses']->isexpandable = true;
1381 $this->rootnodes['mycourses']->showinflatnavigation = true;
1382 if ($CFG->navshowallcourses) {
1383 // When we show all courses we need to show both the my courses and the regular courses branch.
1384 $this->rootnodes['courses']->isexpandable = true;
1386 } else {
1387 $this->rootnodes['courses']->isexpandable = true;
1389 $this->rootnodes['mycourses']->forceopen = true;
1391 $canviewcourseprofile = true;
1393 // Next load context specific content into the navigation
1394 switch ($this->page->context->contextlevel) {
1395 case CONTEXT_SYSTEM :
1396 // Nothing left to do here I feel.
1397 break;
1398 case CONTEXT_COURSECAT :
1399 // This is essential, we must load categories.
1400 $this->load_all_categories($this->page->context->instanceid, true);
1401 break;
1402 case CONTEXT_BLOCK :
1403 case CONTEXT_COURSE :
1404 if ($issite) {
1405 // Nothing left to do here.
1406 break;
1409 // Load the course associated with the current page into the navigation.
1410 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1411 // If the course wasn't added then don't try going any further.
1412 if (!$coursenode) {
1413 $canviewcourseprofile = false;
1414 break;
1417 // If the user is not enrolled then we only want to show the
1418 // course node and not populate it.
1420 // Not enrolled, can't view, and hasn't switched roles
1421 if (!can_access_course($course, null, '', true)) {
1422 if ($coursenode->isexpandable === true) {
1423 // Obviously the situation has changed, update the cache and adjust the node.
1424 // This occurs if the user access to a course has been revoked (one way or another) after
1425 // initially logging in for this session.
1426 $this->get_expand_course_cache()->set($course->id, 1);
1427 $coursenode->isexpandable = true;
1428 $coursenode->nodetype = self::NODETYPE_BRANCH;
1430 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1431 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1432 if (!$this->current_user_is_parent_role()) {
1433 $coursenode->make_active();
1434 $canviewcourseprofile = false;
1435 break;
1437 } else if ($coursenode->isexpandable === false) {
1438 // Obviously the situation has changed, update the cache and adjust the node.
1439 // This occurs if the user has been granted access to a course (one way or another) after initially
1440 // logging in for this session.
1441 $this->get_expand_course_cache()->set($course->id, 1);
1442 $coursenode->isexpandable = true;
1443 $coursenode->nodetype = self::NODETYPE_BRANCH;
1446 // Add the essentials such as reports etc...
1447 $this->add_course_essentials($coursenode, $course);
1448 // Extend course navigation with it's sections/activities
1449 $this->load_course_sections($course, $coursenode);
1450 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1451 $coursenode->make_active();
1454 break;
1455 case CONTEXT_MODULE :
1456 if ($issite) {
1457 // If this is the site course then most information will have
1458 // already been loaded.
1459 // However we need to check if there is more content that can
1460 // yet be loaded for the specific module instance.
1461 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1462 if ($activitynode) {
1463 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1465 break;
1468 $course = $this->page->course;
1469 $cm = $this->page->cm;
1471 // Load the course associated with the page into the navigation
1472 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1474 // If the course wasn't added then don't try going any further.
1475 if (!$coursenode) {
1476 $canviewcourseprofile = false;
1477 break;
1480 // If the user is not enrolled then we only want to show the
1481 // course node and not populate it.
1482 if (!can_access_course($course, null, '', true)) {
1483 $coursenode->make_active();
1484 $canviewcourseprofile = false;
1485 break;
1488 $this->add_course_essentials($coursenode, $course);
1490 // Load the course sections into the page
1491 $this->load_course_sections($course, $coursenode, null, $cm);
1492 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1493 if (!empty($activity)) {
1494 // Finally load the cm specific navigaton information
1495 $this->load_activity($cm, $course, $activity);
1496 // Check if we have an active ndoe
1497 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1498 // And make the activity node active.
1499 $activity->make_active();
1502 break;
1503 case CONTEXT_USER :
1504 if ($issite) {
1505 // The users profile information etc is already loaded
1506 // for the front page.
1507 break;
1509 $course = $this->page->course;
1510 // Load the course associated with the user into the navigation
1511 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1513 // If the course wasn't added then don't try going any further.
1514 if (!$coursenode) {
1515 $canviewcourseprofile = false;
1516 break;
1519 // If the user is not enrolled then we only want to show the
1520 // course node and not populate it.
1521 if (!can_access_course($course, null, '', true)) {
1522 $coursenode->make_active();
1523 $canviewcourseprofile = false;
1524 break;
1526 $this->add_course_essentials($coursenode, $course);
1527 $this->load_course_sections($course, $coursenode);
1528 break;
1531 // Load for the current user
1532 $this->load_for_user();
1533 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1534 $this->load_for_user(null, true);
1536 // Load each extending user into the navigation.
1537 foreach ($this->extendforuser as $user) {
1538 if ($user->id != $USER->id) {
1539 $this->load_for_user($user);
1543 // Give the local plugins a chance to include some navigation if they want.
1544 $this->load_local_plugin_navigation();
1546 // Remove any empty root nodes
1547 foreach ($this->rootnodes as $node) {
1548 // Dont remove the home node
1549 /** @var navigation_node $node */
1550 if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) {
1551 $node->remove();
1555 if (!$this->contains_active_node()) {
1556 $this->search_for_active_node();
1559 // If the user is not logged in modify the navigation structure as detailed
1560 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1561 if (!isloggedin()) {
1562 $activities = clone($this->rootnodes['site']->children);
1563 $this->rootnodes['site']->remove();
1564 $children = clone($this->children);
1565 $this->children = new navigation_node_collection();
1566 foreach ($activities as $child) {
1567 $this->children->add($child);
1569 foreach ($children as $child) {
1570 $this->children->add($child);
1573 return true;
1577 * This function gives local plugins an opportunity to modify navigation.
1579 protected function load_local_plugin_navigation() {
1580 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1581 $function($this);
1586 * Returns true if the current user is a parent of the user being currently viewed.
1588 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1589 * other user being viewed this function returns false.
1590 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1592 * @since Moodle 2.4
1593 * @return bool
1595 protected function current_user_is_parent_role() {
1596 global $USER, $DB;
1597 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1598 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1599 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1600 return false;
1602 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1603 return true;
1606 return false;
1610 * Returns true if courses should be shown within categories on the navigation.
1612 * @param bool $ismycourse Set to true if you are calculating this for a course.
1613 * @return bool
1615 protected function show_categories($ismycourse = false) {
1616 global $CFG, $DB;
1617 if ($ismycourse) {
1618 return $this->show_my_categories();
1620 if ($this->showcategories === null) {
1621 $show = false;
1622 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1623 $show = true;
1624 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1625 $show = true;
1627 $this->showcategories = $show;
1629 return $this->showcategories;
1633 * Returns true if we should show categories in the My Courses branch.
1634 * @return bool
1636 protected function show_my_categories() {
1637 global $CFG;
1638 if ($this->showmycategories === null) {
1639 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
1641 return $this->showmycategories;
1645 * Loads the courses in Moodle into the navigation.
1647 * @global moodle_database $DB
1648 * @param string|array $categoryids An array containing categories to load courses
1649 * for, OR null to load courses for all categories.
1650 * @return array An array of navigation_nodes one for each course
1652 protected function load_all_courses($categoryids = null) {
1653 global $CFG, $DB, $SITE;
1655 // Work out the limit of courses.
1656 $limit = 20;
1657 if (!empty($CFG->navcourselimit)) {
1658 $limit = $CFG->navcourselimit;
1661 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1663 // If we are going to show all courses AND we are showing categories then
1664 // to save us repeated DB calls load all of the categories now
1665 if ($this->show_categories()) {
1666 $this->load_all_categories($toload);
1669 // Will be the return of our efforts
1670 $coursenodes = array();
1672 // Check if we need to show categories.
1673 if ($this->show_categories()) {
1674 // Hmmm we need to show categories... this is going to be painful.
1675 // We now need to fetch up to $limit courses for each category to
1676 // be displayed.
1677 if ($categoryids !== null) {
1678 if (!is_array($categoryids)) {
1679 $categoryids = array($categoryids);
1681 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1682 $categorywhere = 'WHERE cc.id '.$categorywhere;
1683 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1684 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1685 $categoryparams = array();
1686 } else {
1687 $categorywhere = '';
1688 $categoryparams = array();
1691 // First up we are going to get the categories that we are going to
1692 // need so that we can determine how best to load the courses from them.
1693 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1694 FROM {course_categories} cc
1695 LEFT JOIN {course} c ON c.category = cc.id
1696 {$categorywhere}
1697 GROUP BY cc.id";
1698 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1699 $fullfetch = array();
1700 $partfetch = array();
1701 foreach ($categories as $category) {
1702 if (!$this->can_add_more_courses_to_category($category->id)) {
1703 continue;
1705 if ($category->coursecount > $limit * 5) {
1706 $partfetch[] = $category->id;
1707 } else if ($category->coursecount > 0) {
1708 $fullfetch[] = $category->id;
1711 $categories->close();
1713 if (count($fullfetch)) {
1714 // First up fetch all of the courses in categories where we know that we are going to
1715 // need the majority of courses.
1716 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1717 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1718 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1719 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1720 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1721 FROM {course} c
1722 $ccjoin
1723 WHERE c.category {$categoryids}
1724 ORDER BY c.sortorder ASC";
1725 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1726 foreach ($coursesrs as $course) {
1727 if ($course->id == $SITE->id) {
1728 // This should not be necessary, frontpage is not in any category.
1729 continue;
1731 if (array_key_exists($course->id, $this->addedcourses)) {
1732 // It is probably better to not include the already loaded courses
1733 // directly in SQL because inequalities may confuse query optimisers
1734 // and may interfere with query caching.
1735 continue;
1737 if (!$this->can_add_more_courses_to_category($course->category)) {
1738 continue;
1740 context_helper::preload_from_record($course);
1741 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1742 continue;
1744 $coursenodes[$course->id] = $this->add_course($course);
1746 $coursesrs->close();
1749 if (count($partfetch)) {
1750 // Next we will work our way through the categories where we will likely only need a small
1751 // proportion of the courses.
1752 foreach ($partfetch as $categoryid) {
1753 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1754 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1755 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1756 FROM {course} c
1757 $ccjoin
1758 WHERE c.category = :categoryid
1759 ORDER BY c.sortorder ASC";
1760 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1761 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1762 foreach ($coursesrs as $course) {
1763 if ($course->id == $SITE->id) {
1764 // This should not be necessary, frontpage is not in any category.
1765 continue;
1767 if (array_key_exists($course->id, $this->addedcourses)) {
1768 // It is probably better to not include the already loaded courses
1769 // directly in SQL because inequalities may confuse query optimisers
1770 // and may interfere with query caching.
1771 // This also helps to respect expected $limit on repeated executions.
1772 continue;
1774 if (!$this->can_add_more_courses_to_category($course->category)) {
1775 break;
1777 context_helper::preload_from_record($course);
1778 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1779 continue;
1781 $coursenodes[$course->id] = $this->add_course($course);
1783 $coursesrs->close();
1786 } else {
1787 // Prepare the SQL to load the courses and their contexts
1788 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1789 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1790 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1791 $courseparams['contextlevel'] = CONTEXT_COURSE;
1792 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1793 FROM {course} c
1794 $ccjoin
1795 WHERE c.id {$courseids}
1796 ORDER BY c.sortorder ASC";
1797 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1798 foreach ($coursesrs as $course) {
1799 if ($course->id == $SITE->id) {
1800 // frotpage is not wanted here
1801 continue;
1803 if ($this->page->course && ($this->page->course->id == $course->id)) {
1804 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1805 continue;
1807 context_helper::preload_from_record($course);
1808 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1809 continue;
1811 $coursenodes[$course->id] = $this->add_course($course);
1812 if (count($coursenodes) >= $limit) {
1813 break;
1816 $coursesrs->close();
1819 return $coursenodes;
1823 * Returns true if more courses can be added to the provided category.
1825 * @param int|navigation_node|stdClass $category
1826 * @return bool
1828 protected function can_add_more_courses_to_category($category) {
1829 global $CFG;
1830 $limit = 20;
1831 if (!empty($CFG->navcourselimit)) {
1832 $limit = (int)$CFG->navcourselimit;
1834 if (is_numeric($category)) {
1835 if (!array_key_exists($category, $this->addedcategories)) {
1836 return true;
1838 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1839 } else if ($category instanceof navigation_node) {
1840 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1841 return false;
1843 $coursecount = count($category->children->type(self::TYPE_COURSE));
1844 } else if (is_object($category) && property_exists($category,'id')) {
1845 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1847 return ($coursecount <= $limit);
1851 * Loads all categories (top level or if an id is specified for that category)
1853 * @param int $categoryid The category id to load or null/0 to load all base level categories
1854 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1855 * as the requested category and any parent categories.
1856 * @return navigation_node|void returns a navigation node if a category has been loaded.
1858 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1859 global $CFG, $DB;
1861 // Check if this category has already been loaded
1862 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1863 return true;
1866 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1867 $sqlselect = "SELECT cc.*, $catcontextsql
1868 FROM {course_categories} cc
1869 JOIN {context} ctx ON cc.id = ctx.instanceid";
1870 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1871 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1872 $params = array();
1874 $categoriestoload = array();
1875 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1876 // We are going to load all categories regardless... prepare to fire
1877 // on the database server!
1878 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1879 // We are going to load all of the first level categories (categories without parents)
1880 $sqlwhere .= " AND cc.parent = 0";
1881 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1882 // The category itself has been loaded already so we just need to ensure its subcategories
1883 // have been loaded
1884 $addedcategories = $this->addedcategories;
1885 unset($addedcategories[$categoryid]);
1886 if (count($addedcategories) > 0) {
1887 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1888 if ($showbasecategories) {
1889 // We need to include categories with parent = 0 as well
1890 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1891 } else {
1892 // All we need is categories that match the parent
1893 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1896 $params['categoryid'] = $categoryid;
1897 } else {
1898 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1899 // and load this category plus all its parents and subcategories
1900 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1901 $categoriestoload = explode('/', trim($category->path, '/'));
1902 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1903 // We are going to use select twice so double the params
1904 $params = array_merge($params, $params);
1905 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1906 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1909 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1910 $categories = array();
1911 foreach ($categoriesrs as $category) {
1912 // Preload the context.. we'll need it when adding the category in order
1913 // to format the category name.
1914 context_helper::preload_from_record($category);
1915 if (array_key_exists($category->id, $this->addedcategories)) {
1916 // Do nothing, its already been added.
1917 } else if ($category->parent == '0') {
1918 // This is a root category lets add it immediately
1919 $this->add_category($category, $this->rootnodes['courses']);
1920 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1921 // This categories parent has already been added we can add this immediately
1922 $this->add_category($category, $this->addedcategories[$category->parent]);
1923 } else {
1924 $categories[] = $category;
1927 $categoriesrs->close();
1929 // Now we have an array of categories we need to add them to the navigation.
1930 while (!empty($categories)) {
1931 $category = reset($categories);
1932 if (array_key_exists($category->id, $this->addedcategories)) {
1933 // Do nothing
1934 } else if ($category->parent == '0') {
1935 $this->add_category($category, $this->rootnodes['courses']);
1936 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1937 $this->add_category($category, $this->addedcategories[$category->parent]);
1938 } else {
1939 // This category isn't in the navigation and niether is it's parent (yet).
1940 // We need to go through the category path and add all of its components in order.
1941 $path = explode('/', trim($category->path, '/'));
1942 foreach ($path as $catid) {
1943 if (!array_key_exists($catid, $this->addedcategories)) {
1944 // This category isn't in the navigation yet so add it.
1945 $subcategory = $categories[$catid];
1946 if ($subcategory->parent == '0') {
1947 // Yay we have a root category - this likely means we will now be able
1948 // to add categories without problems.
1949 $this->add_category($subcategory, $this->rootnodes['courses']);
1950 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1951 // The parent is in the category (as we'd expect) so add it now.
1952 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1953 // Remove the category from the categories array.
1954 unset($categories[$catid]);
1955 } else {
1956 // We should never ever arrive here - if we have then there is a bigger
1957 // problem at hand.
1958 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1963 // Remove the category from the categories array now that we know it has been added.
1964 unset($categories[$category->id]);
1966 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1967 $this->allcategoriesloaded = true;
1969 // Check if there are any categories to load.
1970 if (count($categoriestoload) > 0) {
1971 $readytoloadcourses = array();
1972 foreach ($categoriestoload as $category) {
1973 if ($this->can_add_more_courses_to_category($category)) {
1974 $readytoloadcourses[] = $category;
1977 if (count($readytoloadcourses)) {
1978 $this->load_all_courses($readytoloadcourses);
1982 // Look for all categories which have been loaded
1983 if (!empty($this->addedcategories)) {
1984 $categoryids = array();
1985 foreach ($this->addedcategories as $category) {
1986 if ($this->can_add_more_courses_to_category($category)) {
1987 $categoryids[] = $category->key;
1990 if ($categoryids) {
1991 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1992 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1993 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1994 FROM {course_categories} cc
1995 JOIN {course} c ON c.category = cc.id
1996 WHERE cc.id {$categoriessql}
1997 GROUP BY cc.id
1998 HAVING COUNT(c.id) > :limit";
1999 $excessivecategories = $DB->get_records_sql($sql, $params);
2000 foreach ($categories as &$category) {
2001 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
2002 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
2003 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
2011 * Adds a structured category to the navigation in the correct order/place
2013 * @param stdClass $category category to be added in navigation.
2014 * @param navigation_node $parent parent navigation node
2015 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2016 * @return void.
2018 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
2019 if (array_key_exists($category->id, $this->addedcategories)) {
2020 return;
2022 $canview = core_course_category::can_view_category($category);
2023 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
2024 $context = context_coursecat::instance($category->id);
2025 $categoryname = $canview ? format_string($category->name, true, array('context' => $context)) :
2026 get_string('categoryhidden');
2027 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
2028 if (!$canview) {
2029 // User does not have required capabilities to view category.
2030 $categorynode->display = false;
2031 } else if (!$category->visible) {
2032 // Category is hidden but user has capability to view hidden categories.
2033 $categorynode->hidden = true;
2035 $this->addedcategories[$category->id] = $categorynode;
2039 * Loads the given course into the navigation
2041 * @param stdClass $course
2042 * @return navigation_node
2044 protected function load_course(stdClass $course) {
2045 global $SITE;
2046 if ($course->id == $SITE->id) {
2047 // This is always loaded during initialisation
2048 return $this->rootnodes['site'];
2049 } else if (array_key_exists($course->id, $this->addedcourses)) {
2050 // The course has already been loaded so return a reference
2051 return $this->addedcourses[$course->id];
2052 } else {
2053 // Add the course
2054 return $this->add_course($course);
2059 * Loads all of the courses section into the navigation.
2061 * This function calls method from current course format, see
2062 * core_courseformat\base::extend_course_navigation()
2063 * If course module ($cm) is specified but course format failed to create the node,
2064 * the activity node is created anyway.
2066 * By default course formats call the method global_navigation::load_generic_course_sections()
2068 * @param stdClass $course Database record for the course
2069 * @param navigation_node $coursenode The course node within the navigation
2070 * @param null|int $sectionnum If specified load the contents of section with this relative number
2071 * @param null|cm_info $cm If specified make sure that activity node is created (either
2072 * in containg section or by calling load_stealth_activity() )
2074 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2075 global $CFG, $SITE;
2076 require_once($CFG->dirroot.'/course/lib.php');
2077 if (isset($cm->sectionnum)) {
2078 $sectionnum = $cm->sectionnum;
2080 if ($sectionnum !== null) {
2081 $this->includesectionnum = $sectionnum;
2083 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2084 if (isset($cm->id)) {
2085 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2086 if (empty($activity)) {
2087 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2093 * Generates an array of sections and an array of activities for the given course.
2095 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2097 * @param stdClass $course
2098 * @return array Array($sections, $activities)
2100 protected function generate_sections_and_activities(stdClass $course) {
2101 global $CFG;
2102 require_once($CFG->dirroot.'/course/lib.php');
2104 $modinfo = get_fast_modinfo($course);
2105 $sections = $modinfo->get_section_info_all();
2107 // For course formats using 'numsections' trim the sections list
2108 $courseformatoptions = course_get_format($course)->get_format_options();
2109 if (isset($courseformatoptions['numsections'])) {
2110 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2113 $activities = array();
2115 foreach ($sections as $key => $section) {
2116 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2117 $sections[$key] = clone($section);
2118 unset($sections[$key]->summary);
2119 $sections[$key]->hasactivites = false;
2120 if (!array_key_exists($section->section, $modinfo->sections)) {
2121 continue;
2123 foreach ($modinfo->sections[$section->section] as $cmid) {
2124 $cm = $modinfo->cms[$cmid];
2125 $activity = new stdClass;
2126 $activity->id = $cm->id;
2127 $activity->course = $course->id;
2128 $activity->section = $section->section;
2129 $activity->name = $cm->name;
2130 $activity->icon = $cm->icon;
2131 $activity->iconcomponent = $cm->iconcomponent;
2132 $activity->hidden = (!$cm->visible);
2133 $activity->modname = $cm->modname;
2134 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2135 $activity->onclick = $cm->onclick;
2136 $url = $cm->url;
2137 if (!$url) {
2138 $activity->url = null;
2139 $activity->display = false;
2140 } else {
2141 $activity->url = $url->out();
2142 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2143 if (self::module_extends_navigation($cm->modname)) {
2144 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2147 $activities[$cmid] = $activity;
2148 if ($activity->display) {
2149 $sections[$key]->hasactivites = true;
2154 return array($sections, $activities);
2158 * Generically loads the course sections into the course's navigation.
2160 * @param stdClass $course
2161 * @param navigation_node $coursenode
2162 * @return array An array of course section nodes
2164 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2165 global $CFG, $DB, $USER, $SITE;
2166 require_once($CFG->dirroot.'/course/lib.php');
2168 list($sections, $activities) = $this->generate_sections_and_activities($course);
2170 $navigationsections = array();
2171 foreach ($sections as $sectionid => $section) {
2172 $section = clone($section);
2173 if ($course->id == $SITE->id) {
2174 $this->load_section_activities($coursenode, $section->section, $activities);
2175 } else {
2176 if (!$section->uservisible || (!$this->showemptysections &&
2177 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2178 continue;
2181 $sectionname = get_section_name($course, $section);
2182 $url = course_get_url($course, $section->section, array('navigation' => true));
2184 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2185 null, $section->id, new pix_icon('i/section', ''));
2186 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2187 $sectionnode->hidden = (!$section->visible || !$section->available);
2188 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2189 $this->load_section_activities($sectionnode, $section->section, $activities);
2191 $section->sectionnode = $sectionnode;
2192 $navigationsections[$sectionid] = $section;
2195 return $navigationsections;
2199 * Loads all of the activities for a section into the navigation structure.
2201 * @param navigation_node $sectionnode
2202 * @param int $sectionnumber
2203 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2204 * @param stdClass $course The course object the section and activities relate to.
2205 * @return array Array of activity nodes
2207 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2208 global $CFG, $SITE;
2209 // A static counter for JS function naming
2210 static $legacyonclickcounter = 0;
2212 $activitynodes = array();
2213 if (empty($activities)) {
2214 return $activitynodes;
2217 if (!is_object($course)) {
2218 $activity = reset($activities);
2219 $courseid = $activity->course;
2220 } else {
2221 $courseid = $course->id;
2223 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2225 foreach ($activities as $activity) {
2226 if ($activity->section != $sectionnumber) {
2227 continue;
2229 if ($activity->icon) {
2230 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2231 } else {
2232 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2235 // Prepare the default name and url for the node
2236 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2237 $action = new moodle_url($activity->url);
2239 // Check if the onclick property is set (puke!)
2240 if (!empty($activity->onclick)) {
2241 // Increment the counter so that we have a unique number.
2242 $legacyonclickcounter++;
2243 // Generate the function name we will use
2244 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2245 $propogrationhandler = '';
2246 // Check if we need to cancel propogation. Remember inline onclick
2247 // events would return false if they wanted to prevent propogation and the
2248 // default action.
2249 if (strpos($activity->onclick, 'return false')) {
2250 $propogrationhandler = 'e.halt();';
2252 // Decode the onclick - it has already been encoded for display (puke)
2253 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2254 // Build the JS function the click event will call
2255 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2256 $this->page->requires->js_amd_inline($jscode);
2257 // Override the default url with the new action link
2258 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2261 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2262 $activitynode->title(get_string('modulename', $activity->modname));
2263 $activitynode->hidden = $activity->hidden;
2264 $activitynode->display = $showactivities && $activity->display;
2265 $activitynode->nodetype = $activity->nodetype;
2266 $activitynodes[$activity->id] = $activitynode;
2269 return $activitynodes;
2272 * Loads a stealth module from unavailable section
2273 * @param navigation_node $coursenode
2274 * @param stdClass $modinfo
2275 * @return navigation_node or null if not accessible
2277 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2278 if (empty($modinfo->cms[$this->page->cm->id])) {
2279 return null;
2281 $cm = $modinfo->cms[$this->page->cm->id];
2282 if ($cm->icon) {
2283 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2284 } else {
2285 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2287 $url = $cm->url;
2288 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2289 $activitynode->title(get_string('modulename', $cm->modname));
2290 $activitynode->hidden = (!$cm->visible);
2291 if (!$cm->is_visible_on_course_page()) {
2292 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2293 // Also there may be no exception at all in case when teacher is logged in as student.
2294 $activitynode->display = false;
2295 } else if (!$url) {
2296 // Don't show activities that don't have links!
2297 $activitynode->display = false;
2298 } else if (self::module_extends_navigation($cm->modname)) {
2299 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2301 return $activitynode;
2304 * Loads the navigation structure for the given activity into the activities node.
2306 * This method utilises a callback within the modules lib.php file to load the
2307 * content specific to activity given.
2309 * The callback is a method: {modulename}_extend_navigation()
2310 * Examples:
2311 * * {@link forum_extend_navigation()}
2312 * * {@link workshop_extend_navigation()}
2314 * @param cm_info|stdClass $cm
2315 * @param stdClass $course
2316 * @param navigation_node $activity
2317 * @return bool
2319 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2320 global $CFG, $DB;
2322 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2323 if (!($cm instanceof cm_info)) {
2324 $modinfo = get_fast_modinfo($course);
2325 $cm = $modinfo->get_cm($cm->id);
2327 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2328 $activity->make_active();
2329 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2330 $function = $cm->modname.'_extend_navigation';
2332 if (file_exists($file)) {
2333 require_once($file);
2334 if (function_exists($function)) {
2335 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2336 $function($activity, $course, $activtyrecord, $cm);
2340 // Allow the active advanced grading method plugin to append module navigation
2341 $featuresfunc = $cm->modname.'_supports';
2342 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2343 require_once($CFG->dirroot.'/grade/grading/lib.php');
2344 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2345 $gradingman->extend_navigation($this, $activity);
2348 return $activity->has_children();
2351 * Loads user specific information into the navigation in the appropriate place.
2353 * If no user is provided the current user is assumed.
2355 * @param stdClass $user
2356 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2357 * @return bool
2359 protected function load_for_user($user=null, $forceforcontext=false) {
2360 global $DB, $CFG, $USER, $SITE;
2362 require_once($CFG->dirroot . '/course/lib.php');
2364 if ($user === null) {
2365 // We can't require login here but if the user isn't logged in we don't
2366 // want to show anything
2367 if (!isloggedin() || isguestuser()) {
2368 return false;
2370 $user = $USER;
2371 } else if (!is_object($user)) {
2372 // If the user is not an object then get them from the database
2373 $select = context_helper::get_preload_record_columns_sql('ctx');
2374 $sql = "SELECT u.*, $select
2375 FROM {user} u
2376 JOIN {context} ctx ON u.id = ctx.instanceid
2377 WHERE u.id = :userid AND
2378 ctx.contextlevel = :contextlevel";
2379 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2380 context_helper::preload_from_record($user);
2383 $iscurrentuser = ($user->id == $USER->id);
2385 $usercontext = context_user::instance($user->id);
2387 // Get the course set against the page, by default this will be the site
2388 $course = $this->page->course;
2389 $baseargs = array('id'=>$user->id);
2390 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2391 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2392 $baseargs['course'] = $course->id;
2393 $coursecontext = context_course::instance($course->id);
2394 $issitecourse = false;
2395 } else {
2396 // Load all categories and get the context for the system
2397 $coursecontext = context_system::instance();
2398 $issitecourse = true;
2401 // Create a node to add user information under.
2402 $usersnode = null;
2403 if (!$issitecourse) {
2404 // Not the current user so add it to the participants node for the current course.
2405 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2406 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2407 } else if ($USER->id != $user->id) {
2408 // This is the site so add a users node to the root branch.
2409 $usersnode = $this->rootnodes['users'];
2410 if (course_can_view_participants($coursecontext)) {
2411 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2413 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2415 if (!$usersnode) {
2416 // We should NEVER get here, if the course hasn't been populated
2417 // with a participants node then the navigaiton either wasn't generated
2418 // for it (you are missing a require_login or set_context call) or
2419 // you don't have access.... in the interests of no leaking informatin
2420 // we simply quit...
2421 return false;
2423 // Add a branch for the current user.
2424 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2425 $viewprofile = true;
2426 if (!$iscurrentuser) {
2427 require_once($CFG->dirroot . '/user/lib.php');
2428 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2429 $viewprofile = false;
2430 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2431 $viewprofile = false;
2433 if (!$viewprofile) {
2434 $viewprofile = user_can_view_profile($user, null, $usercontext);
2438 // Now, conditionally add the user node.
2439 if ($viewprofile) {
2440 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2441 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2442 } else {
2443 $usernode = $usersnode->add(get_string('user'));
2446 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2447 $usernode->make_active();
2450 // Add user information to the participants or user node.
2451 if ($issitecourse) {
2453 // If the user is the current user or has permission to view the details of the requested
2454 // user than add a view profile link.
2455 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2456 has_capability('moodle/user:viewdetails', $usercontext)) {
2457 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2458 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2459 } else {
2460 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2464 if (!empty($CFG->navadduserpostslinks)) {
2465 // Add nodes for forum posts and discussions if the user can view either or both
2466 // There are no capability checks here as the content of the page is based
2467 // purely on the forums the current user has access too.
2468 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2469 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2470 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2471 array_merge($baseargs, array('mode' => 'discussions'))));
2474 // Add blog nodes.
2475 if (!empty($CFG->enableblogs)) {
2476 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2477 require_once($CFG->dirroot.'/blog/lib.php');
2478 // Get all options for the user.
2479 $options = blog_get_options_for_user($user);
2480 $this->cache->set('userblogoptions'.$user->id, $options);
2481 } else {
2482 $options = $this->cache->{'userblogoptions'.$user->id};
2485 if (count($options) > 0) {
2486 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2487 foreach ($options as $type => $option) {
2488 if ($type == "rss") {
2489 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2490 new pix_icon('i/rss', ''));
2491 } else {
2492 $blogs->add($option['string'], $option['link']);
2498 // Add the messages link.
2499 // It is context based so can appear in the user's profile and in course participants information.
2500 if (!empty($CFG->messaging)) {
2501 $messageargs = array('user1' => $USER->id);
2502 if ($USER->id != $user->id) {
2503 $messageargs['user2'] = $user->id;
2505 $url = new moodle_url('/message/index.php', $messageargs);
2506 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2509 // Add the "My private files" link.
2510 // This link doesn't have a unique display for course context so only display it under the user's profile.
2511 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2512 $url = new moodle_url('/user/files.php');
2513 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2516 // Add a node to view the users notes if permitted.
2517 if (!empty($CFG->enablenotes) &&
2518 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2519 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2520 if ($coursecontext->instanceid != SITEID) {
2521 $url->param('course', $coursecontext->instanceid);
2523 $usernode->add(get_string('notes', 'notes'), $url);
2526 // Show the grades node.
2527 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2528 require_once($CFG->dirroot . '/user/lib.php');
2529 // Set the grades node to link to the "Grades" page.
2530 if ($course->id == SITEID) {
2531 $url = user_mygrades_url($user->id, $course->id);
2532 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2533 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2535 if ($USER->id != $user->id) {
2536 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2537 } else {
2538 $usernode->add(get_string('grades', 'grades'), $url);
2542 // If the user is the current user add the repositories for the current user.
2543 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2544 if (!$iscurrentuser &&
2545 $course->id == $SITE->id &&
2546 has_capability('moodle/user:viewdetails', $usercontext) &&
2547 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2549 // Add view grade report is permitted.
2550 $reports = core_component::get_plugin_list('gradereport');
2551 arsort($reports); // User is last, we want to test it first.
2553 $userscourses = enrol_get_users_courses($user->id, false, '*');
2554 $userscoursesnode = $usernode->add(get_string('courses'));
2556 $count = 0;
2557 foreach ($userscourses as $usercourse) {
2558 if ($count === (int)$CFG->navcourselimit) {
2559 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2560 $userscoursesnode->add(get_string('showallcourses'), $url);
2561 break;
2563 $count++;
2564 $usercoursecontext = context_course::instance($usercourse->id);
2565 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2566 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2567 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2569 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2570 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2571 foreach ($reports as $plugin => $plugindir) {
2572 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2573 // Stop when the first visible plugin is found.
2574 $gradeavailable = true;
2575 break;
2580 if ($gradeavailable) {
2581 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2582 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2583 new pix_icon('i/grades', ''));
2586 // Add a node to view the users notes if permitted.
2587 if (!empty($CFG->enablenotes) &&
2588 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2589 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2590 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2593 if (can_access_course($usercourse, $user->id, '', true)) {
2594 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2595 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2598 $reporttab = $usercoursenode->add(get_string('activityreports'));
2600 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2601 foreach ($reportfunctions as $reportfunction) {
2602 $reportfunction($reporttab, $user, $usercourse);
2605 $reporttab->trim_if_empty();
2609 // Let plugins hook into user navigation.
2610 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2611 foreach ($pluginsfunction as $plugintype => $plugins) {
2612 if ($plugintype != 'report') {
2613 foreach ($plugins as $pluginfunction) {
2614 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2619 return true;
2623 * This method simply checks to see if a given module can extend the navigation.
2625 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2627 * @param string $modname
2628 * @return bool
2630 public static function module_extends_navigation($modname) {
2631 global $CFG;
2632 static $extendingmodules = array();
2633 if (!array_key_exists($modname, $extendingmodules)) {
2634 $extendingmodules[$modname] = false;
2635 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2636 if (file_exists($file)) {
2637 $function = $modname.'_extend_navigation';
2638 require_once($file);
2639 $extendingmodules[$modname] = (function_exists($function));
2642 return $extendingmodules[$modname];
2645 * Extends the navigation for the given user.
2647 * @param stdClass $user A user from the database
2649 public function extend_for_user($user) {
2650 $this->extendforuser[] = $user;
2654 * Returns all of the users the navigation is being extended for
2656 * @return array An array of extending users.
2658 public function get_extending_users() {
2659 return $this->extendforuser;
2662 * Adds the given course to the navigation structure.
2664 * @param stdClass $course
2665 * @param bool $forcegeneric
2666 * @param bool $ismycourse
2667 * @return navigation_node
2669 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2670 global $CFG, $SITE;
2672 // We found the course... we can return it now :)
2673 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2674 return $this->addedcourses[$course->id];
2677 $coursecontext = context_course::instance($course->id);
2679 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
2680 if (is_role_switched($course->id)) {
2681 // user has to be able to access course in order to switch, let's skip the visibility test here
2682 } else if (!core_course_category::can_view_course_info($course)) {
2683 return false;
2687 $issite = ($course->id == $SITE->id);
2688 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2689 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2690 // This is the name that will be shown for the course.
2691 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2693 if ($coursetype == self::COURSE_CURRENT) {
2694 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2695 return $coursenode;
2696 } else {
2697 $coursetype = self::COURSE_OTHER;
2701 // Can the user expand the course to see its content.
2702 $canexpandcourse = true;
2703 if ($issite) {
2704 $parent = $this;
2705 $url = null;
2706 if (empty($CFG->usesitenameforsitepages)) {
2707 $coursename = get_string('sitepages');
2709 } else if ($coursetype == self::COURSE_CURRENT) {
2710 $parent = $this->rootnodes['currentcourse'];
2711 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2712 $canexpandcourse = $this->can_expand_course($course);
2713 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2714 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2715 // Nothing to do here the above statement set $parent to the category within mycourses.
2716 } else {
2717 $parent = $this->rootnodes['mycourses'];
2719 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2720 } else {
2721 $parent = $this->rootnodes['courses'];
2722 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2723 // They can only expand the course if they can access it.
2724 $canexpandcourse = $this->can_expand_course($course);
2725 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2726 if (!$this->is_category_fully_loaded($course->category)) {
2727 // We need to load the category structure for this course
2728 $this->load_all_categories($course->category, false);
2730 if (array_key_exists($course->category, $this->addedcategories)) {
2731 $parent = $this->addedcategories[$course->category];
2732 // This could lead to the course being created so we should check whether it is the case again
2733 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2734 return $this->addedcourses[$course->id];
2740 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2741 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2743 $coursenode->hidden = (!$course->visible);
2744 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2745 if ($canexpandcourse) {
2746 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2747 $coursenode->nodetype = self::NODETYPE_BRANCH;
2748 $coursenode->isexpandable = true;
2749 } else {
2750 $coursenode->nodetype = self::NODETYPE_LEAF;
2751 $coursenode->isexpandable = false;
2753 if (!$forcegeneric) {
2754 $this->addedcourses[$course->id] = $coursenode;
2757 return $coursenode;
2761 * Returns a cache instance to use for the expand course cache.
2762 * @return cache_session
2764 protected function get_expand_course_cache() {
2765 if ($this->cacheexpandcourse === null) {
2766 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2768 return $this->cacheexpandcourse;
2772 * Checks if a user can expand a course in the navigation.
2774 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2775 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2776 * permits stale data.
2777 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2778 * will be stale.
2779 * It is brought up to date in only one of two ways.
2780 * 1. The user logs out and in again.
2781 * 2. The user browses to the course they've just being given access to.
2783 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2785 * @param stdClass $course
2786 * @return bool
2788 protected function can_expand_course($course) {
2789 $cache = $this->get_expand_course_cache();
2790 $canexpand = $cache->get($course->id);
2791 if ($canexpand === false) {
2792 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2793 $canexpand = (int)$canexpand;
2794 $cache->set($course->id, $canexpand);
2796 return ($canexpand === 1);
2800 * Returns true if the category has already been loaded as have any child categories
2802 * @param int $categoryid
2803 * @return bool
2805 protected function is_category_fully_loaded($categoryid) {
2806 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2810 * Adds essential course nodes to the navigation for the given course.
2812 * This method adds nodes such as reports, blogs and participants
2814 * @param navigation_node $coursenode
2815 * @param stdClass $course
2816 * @return bool returns true on successful addition of a node.
2818 public function add_course_essentials($coursenode, stdClass $course) {
2819 global $CFG, $SITE;
2820 require_once($CFG->dirroot . '/course/lib.php');
2822 if ($course->id == $SITE->id) {
2823 return $this->add_front_page_course_essentials($coursenode, $course);
2826 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2827 return true;
2830 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2832 //Participants
2833 if ($navoptions->participants) {
2834 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2835 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2837 if ($navoptions->blogs) {
2838 $blogsurls = new moodle_url('/blog/index.php');
2839 if ($currentgroup = groups_get_course_group($course, true)) {
2840 $blogsurls->param('groupid', $currentgroup);
2841 } else {
2842 $blogsurls->param('courseid', $course->id);
2844 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2847 if ($navoptions->notes) {
2848 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2850 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2851 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2854 // Badges.
2855 if ($navoptions->badges) {
2856 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2858 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2859 navigation_node::TYPE_SETTING, null, 'badgesview',
2860 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2863 // Check access to the course and competencies page.
2864 if ($navoptions->competencies) {
2865 // Just a link to course competency.
2866 $title = get_string('competencies', 'core_competency');
2867 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2868 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2869 new pix_icon('i/competencies', ''));
2871 if ($navoptions->grades) {
2872 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2873 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2874 'grades', new pix_icon('i/grades', ''));
2875 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2876 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2877 $gradenode->make_active();
2881 return true;
2884 * This generates the structure of the course that won't be generated when
2885 * the modules and sections are added.
2887 * Things such as the reports branch, the participants branch, blogs... get
2888 * added to the course node by this method.
2890 * @param navigation_node $coursenode
2891 * @param stdClass $course
2892 * @return bool True for successfull generation
2894 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2895 global $CFG, $USER, $COURSE, $SITE;
2896 require_once($CFG->dirroot . '/course/lib.php');
2898 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2899 return true;
2902 $systemcontext = context_system::instance();
2903 $navoptions = course_get_user_navigation_options($systemcontext, $course);
2905 // Hidden node that we use to determine if the front page navigation is loaded.
2906 // This required as there are not other guaranteed nodes that may be loaded.
2907 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2909 // Add My courses to the site pages within the navigation structure so the block can read it.
2910 $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses');
2912 // Participants.
2913 if ($navoptions->participants) {
2914 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2917 // Blogs.
2918 if ($navoptions->blogs) {
2919 $blogsurls = new moodle_url('/blog/index.php');
2920 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2923 $filterselect = 0;
2925 // Badges.
2926 if ($navoptions->badges) {
2927 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2928 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2931 // Notes.
2932 if ($navoptions->notes) {
2933 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2934 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2937 // Tags
2938 if ($navoptions->tags) {
2939 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2940 self::TYPE_SETTING, null, 'tags');
2943 // Search.
2944 if ($navoptions->search) {
2945 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2946 self::TYPE_SETTING, null, 'search');
2949 if (isloggedin()) {
2950 $usercontext = context_user::instance($USER->id);
2951 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2952 $url = new moodle_url('/user/files.php');
2953 $node = $coursenode->add(get_string('privatefiles'), $url,
2954 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2955 $node->display = false;
2956 $node->showinflatnavigation = true;
2960 if (isloggedin()) {
2961 $context = $this->page->context;
2962 switch ($context->contextlevel) {
2963 case CONTEXT_COURSECAT:
2964 // OK, expected context level.
2965 break;
2966 case CONTEXT_COURSE:
2967 // OK, expected context level if not on frontpage.
2968 if ($COURSE->id != $SITE->id) {
2969 break;
2971 default:
2972 // If this context is part of a course (excluding frontpage), use the course context.
2973 // Otherwise, use the system context.
2974 $coursecontext = $context->get_course_context(false);
2975 if ($coursecontext && $coursecontext->instanceid !== $SITE->id) {
2976 $context = $coursecontext;
2977 } else {
2978 $context = $systemcontext;
2982 $params = ['contextid' => $context->id];
2983 if (has_capability('moodle/contentbank:access', $context)) {
2984 $url = new moodle_url('/contentbank/index.php', $params);
2985 $node = $coursenode->add(get_string('contentbank'), $url,
2986 self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', ''));
2987 $node->showinflatnavigation = true;
2991 return true;
2995 * Clears the navigation cache
2997 public function clear_cache() {
2998 $this->cache->clear();
3002 * Sets an expansion limit for the navigation
3004 * The expansion limit is used to prevent the display of content that has a type
3005 * greater than the provided $type.
3007 * Can be used to ensure things such as activities or activity content don't get
3008 * shown on the navigation.
3009 * They are still generated in order to ensure the navbar still makes sense.
3011 * @param int $type One of navigation_node::TYPE_*
3012 * @return bool true when complete.
3014 public function set_expansion_limit($type) {
3015 global $SITE;
3016 $nodes = $this->find_all_of_type($type);
3018 // We only want to hide specific types of nodes.
3019 // Only nodes that represent "structure" in the navigation tree should be hidden.
3020 // If we hide all nodes then we risk hiding vital information.
3021 $typestohide = array(
3022 self::TYPE_CATEGORY,
3023 self::TYPE_COURSE,
3024 self::TYPE_SECTION,
3025 self::TYPE_ACTIVITY
3028 foreach ($nodes as $node) {
3029 // We need to generate the full site node
3030 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
3031 continue;
3033 foreach ($node->children as $child) {
3034 $child->hide($typestohide);
3037 return true;
3040 * Attempts to get the navigation with the given key from this nodes children.
3042 * This function only looks at this nodes children, it does NOT look recursivily.
3043 * If the node can't be found then false is returned.
3045 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3047 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3048 * may be of more use to you.
3050 * @param string|int $key The key of the node you wish to receive.
3051 * @param int $type One of navigation_node::TYPE_*
3052 * @return navigation_node|false
3054 public function get($key, $type = null) {
3055 if (!$this->initialised) {
3056 $this->initialise();
3058 return parent::get($key, $type);
3062 * Searches this nodes children and their children to find a navigation node
3063 * with the matching key and type.
3065 * This method is recursive and searches children so until either a node is
3066 * found or there are no more nodes to search.
3068 * If you know that the node being searched for is a child of this node
3069 * then use the {@link global_navigation::get()} method instead.
3071 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3072 * may be of more use to you.
3074 * @param string|int $key The key of the node you wish to receive.
3075 * @param int $type One of navigation_node::TYPE_*
3076 * @return navigation_node|false
3078 public function find($key, $type) {
3079 if (!$this->initialised) {
3080 $this->initialise();
3082 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
3083 return $this->rootnodes[$key];
3085 return parent::find($key, $type);
3089 * They've expanded the 'my courses' branch.
3091 protected function load_courses_enrolled() {
3092 global $CFG;
3094 $limit = (int) $CFG->navcourselimit;
3096 $courses = enrol_get_my_courses('*');
3097 $flatnavcourses = [];
3099 // Go through the courses and see which ones we want to display in the flatnav.
3100 foreach ($courses as $course) {
3101 $classify = course_classify_for_timeline($course);
3103 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3104 $flatnavcourses[$course->id] = $course;
3108 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3109 $numtotalcourses = count($courses);
3110 $numtotalflatnavcourses = count($flatnavcourses);
3112 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3113 $courses = array_slice($courses, 0, $limit, true);
3114 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3116 // Get the number of courses we are going to show for each.
3117 $numshowncourses = count($courses);
3118 $numshownflatnavcourses = count($flatnavcourses);
3119 if ($numshowncourses && $this->show_my_categories()) {
3120 // Generate an array containing unique values of all the courses' categories.
3121 $categoryids = array();
3122 foreach ($courses as $course) {
3123 if (in_array($course->category, $categoryids)) {
3124 continue;
3126 $categoryids[] = $course->category;
3129 // Array of category IDs that include the categories of the user's courses and the related course categories.
3130 $fullpathcategoryids = [];
3131 // Get the course categories for the enrolled courses' category IDs.
3132 $mycoursecategories = core_course_category::get_many($categoryids);
3133 // Loop over each of these categories and build the category tree using each category's path.
3134 foreach ($mycoursecategories as $mycoursecat) {
3135 $pathcategoryids = explode('/', $mycoursecat->path);
3136 // First element of the exploded path is empty since paths begin with '/'.
3137 array_shift($pathcategoryids);
3138 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3139 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3142 // Fetch all of the categories related to the user's courses.
3143 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3144 // Loop over each of these categories and build the category tree.
3145 foreach ($pathcategories as $coursecat) {
3146 // No need to process categories that have already been added.
3147 if (isset($this->addedcategories[$coursecat->id])) {
3148 continue;
3150 // Skip categories that are not visible.
3151 if (!$coursecat->is_uservisible()) {
3152 continue;
3155 // Get this course category's parent node.
3156 $parent = null;
3157 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3158 $parent = $this->addedcategories[$coursecat->parent];
3160 if (!$parent) {
3161 // If it has no parent, then it should be right under the My courses node.
3162 $parent = $this->rootnodes['mycourses'];
3165 // Build the category object based from the coursecat object.
3166 $mycategory = new stdClass();
3167 $mycategory->id = $coursecat->id;
3168 $mycategory->name = $coursecat->name;
3169 $mycategory->visible = $coursecat->visible;
3171 // Add this category to the nav tree.
3172 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3176 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3177 foreach ($courses as $course) {
3178 $node = $this->add_course($course, false, self::COURSE_MY);
3179 if ($node) {
3180 $node->showinflatnavigation = false;
3181 // Check if we should also add this to the flat nav as well.
3182 if (isset($flatnavcourses[$course->id])) {
3183 $node->showinflatnavigation = true;
3188 // Go through each course in the flatnav now.
3189 foreach ($flatnavcourses as $course) {
3190 // Check if we haven't already added it.
3191 if (!isset($courses[$course->id])) {
3192 // Ok, add it to the flatnav only.
3193 $node = $this->add_course($course, false, self::COURSE_MY);
3194 $node->display = false;
3195 $node->showinflatnavigation = true;
3199 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3200 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3201 // Show a link to the course page if there are more courses the user is enrolled in.
3202 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3203 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3204 $url = new moodle_url('/my/');
3205 $parent = $this->rootnodes['mycourses'];
3206 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3208 if ($showmorelinkinnav) {
3209 $coursenode->display = true;
3212 if ($showmorelinkinflatnav) {
3213 $coursenode->showinflatnavigation = true;
3220 * The global navigation class used especially for AJAX requests.
3222 * The primary methods that are used in the global navigation class have been overriden
3223 * to ensure that only the relevant branch is generated at the root of the tree.
3224 * This can be done because AJAX is only used when the backwards structure for the
3225 * requested branch exists.
3226 * This has been done only because it shortens the amounts of information that is generated
3227 * which of course will speed up the response time.. because no one likes laggy AJAX.
3229 * @package core
3230 * @category navigation
3231 * @copyright 2009 Sam Hemelryk
3232 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3234 class global_navigation_for_ajax extends global_navigation {
3236 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3237 protected $branchtype;
3239 /** @var int the instance id */
3240 protected $instanceid;
3242 /** @var array Holds an array of expandable nodes */
3243 protected $expandable = array();
3246 * Constructs the navigation for use in an AJAX request
3248 * @param moodle_page $page moodle_page object
3249 * @param int $branchtype
3250 * @param int $id
3252 public function __construct($page, $branchtype, $id) {
3253 $this->page = $page;
3254 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3255 $this->children = new navigation_node_collection();
3256 $this->branchtype = $branchtype;
3257 $this->instanceid = $id;
3258 $this->initialise();
3261 * Initialise the navigation given the type and id for the branch to expand.
3263 * @return array An array of the expandable nodes
3265 public function initialise() {
3266 global $DB, $SITE;
3268 if ($this->initialised || during_initial_install()) {
3269 return $this->expandable;
3271 $this->initialised = true;
3273 $this->rootnodes = array();
3274 $this->rootnodes['site'] = $this->add_course($SITE);
3275 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3276 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3277 // The courses branch is always displayed, and is always expandable (although may be empty).
3278 // This mimicks what is done during {@link global_navigation::initialise()}.
3279 $this->rootnodes['courses']->isexpandable = true;
3281 // Branchtype will be one of navigation_node::TYPE_*
3282 switch ($this->branchtype) {
3283 case 0:
3284 if ($this->instanceid === 'mycourses') {
3285 $this->load_courses_enrolled();
3286 } else if ($this->instanceid === 'courses') {
3287 $this->load_courses_other();
3289 break;
3290 case self::TYPE_CATEGORY :
3291 $this->load_category($this->instanceid);
3292 break;
3293 case self::TYPE_MY_CATEGORY :
3294 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3295 break;
3296 case self::TYPE_COURSE :
3297 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3298 if (!can_access_course($course, null, '', true)) {
3299 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3300 // add the course node and break. This leads to an empty node.
3301 $this->add_course($course);
3302 break;
3304 require_course_login($course, true, null, false, true);
3305 $this->page->set_context(context_course::instance($course->id));
3306 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3307 $this->add_course_essentials($coursenode, $course);
3308 $this->load_course_sections($course, $coursenode);
3309 break;
3310 case self::TYPE_SECTION :
3311 $sql = 'SELECT c.*, cs.section AS sectionnumber
3312 FROM {course} c
3313 LEFT JOIN {course_sections} cs ON cs.course = c.id
3314 WHERE cs.id = ?';
3315 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3316 require_course_login($course, true, null, false, true);
3317 $this->page->set_context(context_course::instance($course->id));
3318 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3319 $this->add_course_essentials($coursenode, $course);
3320 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3321 break;
3322 case self::TYPE_ACTIVITY :
3323 $sql = "SELECT c.*
3324 FROM {course} c
3325 JOIN {course_modules} cm ON cm.course = c.id
3326 WHERE cm.id = :cmid";
3327 $params = array('cmid' => $this->instanceid);
3328 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3329 $modinfo = get_fast_modinfo($course);
3330 $cm = $modinfo->get_cm($this->instanceid);
3331 require_course_login($course, true, $cm, false, true);
3332 $this->page->set_context(context_module::instance($cm->id));
3333 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3334 $this->load_course_sections($course, $coursenode, null, $cm);
3335 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3336 if ($activitynode) {
3337 $modulenode = $this->load_activity($cm, $course, $activitynode);
3339 break;
3340 default:
3341 throw new Exception('Unknown type');
3342 return $this->expandable;
3345 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3346 $this->load_for_user(null, true);
3349 // Give the local plugins a chance to include some navigation if they want.
3350 $this->load_local_plugin_navigation();
3352 $this->find_expandable($this->expandable);
3353 return $this->expandable;
3357 * They've expanded the general 'courses' branch.
3359 protected function load_courses_other() {
3360 $this->load_all_courses();
3364 * Loads a single category into the AJAX navigation.
3366 * This function is special in that it doesn't concern itself with the parent of
3367 * the requested category or its siblings.
3368 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3369 * request that.
3371 * @global moodle_database $DB
3372 * @param int $categoryid id of category to load in navigation.
3373 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3374 * @return void.
3376 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3377 global $CFG, $DB;
3379 $limit = 20;
3380 if (!empty($CFG->navcourselimit)) {
3381 $limit = (int)$CFG->navcourselimit;
3384 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3385 $sql = "SELECT cc.*, $catcontextsql
3386 FROM {course_categories} cc
3387 JOIN {context} ctx ON cc.id = ctx.instanceid
3388 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3389 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3390 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3391 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3392 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3393 $categorylist = array();
3394 $subcategories = array();
3395 $basecategory = null;
3396 foreach ($categories as $category) {
3397 $categorylist[] = $category->id;
3398 context_helper::preload_from_record($category);
3399 if ($category->id == $categoryid) {
3400 $this->add_category($category, $this, $nodetype);
3401 $basecategory = $this->addedcategories[$category->id];
3402 } else {
3403 $subcategories[$category->id] = $category;
3406 $categories->close();
3409 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3410 // else show all courses.
3411 if ($nodetype === self::TYPE_MY_CATEGORY) {
3412 $courses = enrol_get_my_courses('*');
3413 $categoryids = array();
3415 // Only search for categories if basecategory was found.
3416 if (!is_null($basecategory)) {
3417 // Get course parent category ids.
3418 foreach ($courses as $course) {
3419 $categoryids[] = $course->category;
3422 // Get a unique list of category ids which a part of the path
3423 // to user's courses.
3424 $coursesubcategories = array();
3425 $addedsubcategories = array();
3427 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3428 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3430 foreach ($categories as $category){
3431 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3433 $categories->close();
3434 $coursesubcategories = array_unique($coursesubcategories);
3436 // Only add a subcategory if it is part of the path to user's course and
3437 // wasn't already added.
3438 foreach ($subcategories as $subid => $subcategory) {
3439 if (in_array($subid, $coursesubcategories) &&
3440 !in_array($subid, $addedsubcategories)) {
3441 $this->add_category($subcategory, $basecategory, $nodetype);
3442 $addedsubcategories[] = $subid;
3447 foreach ($courses as $course) {
3448 // Add course if it's in category.
3449 if (in_array($course->category, $categorylist)) {
3450 $this->add_course($course, true, self::COURSE_MY);
3453 } else {
3454 if (!is_null($basecategory)) {
3455 foreach ($subcategories as $key=>$category) {
3456 $this->add_category($category, $basecategory, $nodetype);
3459 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3460 foreach ($courses as $course) {
3461 $this->add_course($course);
3463 $courses->close();
3468 * Returns an array of expandable nodes
3469 * @return array
3471 public function get_expandable() {
3472 return $this->expandable;
3477 * Navbar class
3479 * This class is used to manage the navbar, which is initialised from the navigation
3480 * object held by PAGE
3482 * @package core
3483 * @category navigation
3484 * @copyright 2009 Sam Hemelryk
3485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3487 class navbar extends navigation_node {
3488 /** @var bool A switch for whether the navbar is initialised or not */
3489 protected $initialised = false;
3490 /** @var mixed keys used to reference the nodes on the navbar */
3491 protected $keys = array();
3492 /** @var null|string content of the navbar */
3493 protected $content = null;
3494 /** @var moodle_page object the moodle page that this navbar belongs to */
3495 protected $page;
3496 /** @var bool A switch for whether to ignore the active navigation information */
3497 protected $ignoreactive = false;
3498 /** @var bool A switch to let us know if we are in the middle of an install */
3499 protected $duringinstall = false;
3500 /** @var bool A switch for whether the navbar has items */
3501 protected $hasitems = false;
3502 /** @var array An array of navigation nodes for the navbar */
3503 protected $items;
3504 /** @var array An array of child node objects */
3505 public $children = array();
3506 /** @var bool A switch for whether we want to include the root node in the navbar */
3507 public $includesettingsbase = false;
3508 /** @var breadcrumb_navigation_node[] $prependchildren */
3509 protected $prependchildren = array();
3512 * The almighty constructor
3514 * @param moodle_page $page
3516 public function __construct(moodle_page $page) {
3517 global $CFG;
3518 if (during_initial_install()) {
3519 $this->duringinstall = true;
3520 return false;
3522 $this->page = $page;
3523 $this->text = get_string('home');
3524 $this->shorttext = get_string('home');
3525 $this->action = new moodle_url($CFG->wwwroot);
3526 $this->nodetype = self::NODETYPE_BRANCH;
3527 $this->type = self::TYPE_SYSTEM;
3531 * Quick check to see if the navbar will have items in.
3533 * @return bool Returns true if the navbar will have items, false otherwise
3535 public function has_items() {
3536 if ($this->duringinstall) {
3537 return false;
3538 } else if ($this->hasitems !== false) {
3539 return true;
3541 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3542 // There have been manually added items - there are definitely items.
3543 $outcome = true;
3544 } else if (!$this->ignoreactive) {
3545 // We will need to initialise the navigation structure to check if there are active items.
3546 $this->page->navigation->initialise($this->page);
3547 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3549 $this->hasitems = $outcome;
3550 return $outcome;
3554 * Turn on/off ignore active
3556 * @param bool $setting
3558 public function ignore_active($setting=true) {
3559 $this->ignoreactive = ($setting);
3563 * Gets a navigation node
3565 * @param string|int $key for referencing the navbar nodes
3566 * @param int $type breadcrumb_navigation_node::TYPE_*
3567 * @return breadcrumb_navigation_node|bool
3569 public function get($key, $type = null) {
3570 foreach ($this->children as &$child) {
3571 if ($child->key === $key && ($type == null || $type == $child->type)) {
3572 return $child;
3575 foreach ($this->prependchildren as &$child) {
3576 if ($child->key === $key && ($type == null || $type == $child->type)) {
3577 return $child;
3580 return false;
3583 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3585 * @return array
3587 public function get_items() {
3588 global $CFG;
3589 $items = array();
3590 // Make sure that navigation is initialised
3591 if (!$this->has_items()) {
3592 return $items;
3594 if ($this->items !== null) {
3595 return $this->items;
3598 if (count($this->children) > 0) {
3599 // Add the custom children.
3600 $items = array_reverse($this->children);
3603 // Check if navigation contains the active node
3604 if (!$this->ignoreactive) {
3605 // We will need to ensure the navigation has been initialised.
3606 $this->page->navigation->initialise($this->page);
3607 // Now find the active nodes on both the navigation and settings.
3608 $navigationactivenode = $this->page->navigation->find_active_node();
3609 $settingsactivenode = $this->page->settingsnav->find_active_node();
3611 if ($navigationactivenode && $settingsactivenode) {
3612 // Parse a combined navigation tree
3613 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3614 if (!$settingsactivenode->mainnavonly) {
3615 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3617 $settingsactivenode = $settingsactivenode->parent;
3619 if (!$this->includesettingsbase) {
3620 // Removes the first node from the settings (root node) from the list
3621 array_pop($items);
3623 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3624 if (!$navigationactivenode->mainnavonly) {
3625 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3627 if (!empty($CFG->navshowcategories) &&
3628 $navigationactivenode->type === self::TYPE_COURSE &&
3629 $navigationactivenode->parent->key === 'currentcourse') {
3630 foreach ($this->get_course_categories() as $item) {
3631 $items[] = new breadcrumb_navigation_node($item);
3634 $navigationactivenode = $navigationactivenode->parent;
3636 } else if ($navigationactivenode) {
3637 // Parse the navigation tree to get the active node
3638 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3639 if (!$navigationactivenode->mainnavonly) {
3640 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3642 if (!empty($CFG->navshowcategories) &&
3643 $navigationactivenode->type === self::TYPE_COURSE &&
3644 $navigationactivenode->parent->key === 'currentcourse') {
3645 foreach ($this->get_course_categories() as $item) {
3646 $items[] = new breadcrumb_navigation_node($item);
3649 $navigationactivenode = $navigationactivenode->parent;
3651 } else if ($settingsactivenode) {
3652 // Parse the settings navigation to get the active node
3653 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3654 if (!$settingsactivenode->mainnavonly) {
3655 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3657 $settingsactivenode = $settingsactivenode->parent;
3662 $items[] = new breadcrumb_navigation_node(array(
3663 'text' => $this->page->navigation->text,
3664 'shorttext' => $this->page->navigation->shorttext,
3665 'key' => $this->page->navigation->key,
3666 'action' => $this->page->navigation->action
3669 if (count($this->prependchildren) > 0) {
3670 // Add the custom children
3671 $items = array_merge($items, array_reverse($this->prependchildren));
3674 $last = reset($items);
3675 if ($last) {
3676 $last->set_last(true);
3678 $this->items = array_reverse($items);
3679 return $this->items;
3683 * Get the list of categories leading to this course.
3685 * This function is used by {@link navbar::get_items()} to add back the "courses"
3686 * node and category chain leading to the current course. Note that this is only ever
3687 * called for the current course, so we don't need to bother taking in any parameters.
3689 * @return array
3691 private function get_course_categories() {
3692 global $CFG;
3693 require_once($CFG->dirroot.'/course/lib.php');
3695 $categories = array();
3696 $cap = 'moodle/category:viewhiddencategories';
3697 $showcategories = !core_course_category::is_simple_site();
3699 if ($showcategories) {
3700 foreach ($this->page->categories as $category) {
3701 $context = context_coursecat::instance($category->id);
3702 if (!core_course_category::can_view_category($category)) {
3703 continue;
3705 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3706 $name = format_string($category->name, true, array('context' => $context));
3707 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3708 if (!$category->visible) {
3709 $categorynode->hidden = true;
3711 $categories[] = $categorynode;
3715 // Don't show the 'course' node if enrolled in this course.
3716 $coursecontext = context_course::instance($this->page->course->id);
3717 if (!is_enrolled($coursecontext, null, '', true)) {
3718 $courses = $this->page->navigation->get('courses');
3719 if (!$courses) {
3720 // Courses node may not be present.
3721 $courses = breadcrumb_navigation_node::create(
3722 get_string('courses'),
3723 new moodle_url('/course/index.php'),
3724 self::TYPE_CONTAINER
3727 $categories[] = $courses;
3730 return $categories;
3734 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3736 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3737 * the way nodes get added to allow us to simply call add and have the node added to the
3738 * end of the navbar
3740 * @param string $text
3741 * @param string|moodle_url|action_link $action An action to associate with this node.
3742 * @param int $type One of navigation_node::TYPE_*
3743 * @param string $shorttext
3744 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3745 * @param pix_icon $icon An optional icon to use for this node.
3746 * @return navigation_node
3748 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3749 if ($this->content !== null) {
3750 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3753 // Properties array used when creating the new navigation node
3754 $itemarray = array(
3755 'text' => $text,
3756 'type' => $type
3758 // Set the action if one was provided
3759 if ($action!==null) {
3760 $itemarray['action'] = $action;
3762 // Set the shorttext if one was provided
3763 if ($shorttext!==null) {
3764 $itemarray['shorttext'] = $shorttext;
3766 // Set the icon if one was provided
3767 if ($icon!==null) {
3768 $itemarray['icon'] = $icon;
3770 // Default the key to the number of children if not provided
3771 if ($key === null) {
3772 $key = count($this->children);
3774 // Set the key
3775 $itemarray['key'] = $key;
3776 // Set the parent to this node
3777 $itemarray['parent'] = $this;
3778 // Add the child using the navigation_node_collections add method
3779 $this->children[] = new breadcrumb_navigation_node($itemarray);
3780 return $this;
3784 * Prepends a new navigation_node to the start of the navbar
3786 * @param string $text
3787 * @param string|moodle_url|action_link $action An action to associate with this node.
3788 * @param int $type One of navigation_node::TYPE_*
3789 * @param string $shorttext
3790 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3791 * @param pix_icon $icon An optional icon to use for this node.
3792 * @return navigation_node
3794 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3795 if ($this->content !== null) {
3796 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3798 // Properties array used when creating the new navigation node.
3799 $itemarray = array(
3800 'text' => $text,
3801 'type' => $type
3803 // Set the action if one was provided.
3804 if ($action!==null) {
3805 $itemarray['action'] = $action;
3807 // Set the shorttext if one was provided.
3808 if ($shorttext!==null) {
3809 $itemarray['shorttext'] = $shorttext;
3811 // Set the icon if one was provided.
3812 if ($icon!==null) {
3813 $itemarray['icon'] = $icon;
3815 // Default the key to the number of children if not provided.
3816 if ($key === null) {
3817 $key = count($this->children);
3819 // Set the key.
3820 $itemarray['key'] = $key;
3821 // Set the parent to this node.
3822 $itemarray['parent'] = $this;
3823 // Add the child node to the prepend list.
3824 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3825 return $this;
3830 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3831 * in particular adding extra metadata for search engine robots to leverage.
3833 * @package core
3834 * @category navigation
3835 * @copyright 2015 Brendan Heywood
3836 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3838 class breadcrumb_navigation_node extends navigation_node {
3840 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3841 private $last = false;
3844 * A proxy constructor
3846 * @param mixed $navnode A navigation_node or an array
3848 public function __construct($navnode) {
3849 if (is_array($navnode)) {
3850 parent::__construct($navnode);
3851 } else if ($navnode instanceof navigation_node) {
3853 // Just clone everything.
3854 $objvalues = get_object_vars($navnode);
3855 foreach ($objvalues as $key => $value) {
3856 $this->$key = $value;
3858 } else {
3859 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3864 * Getter for "last"
3865 * @return boolean
3867 public function is_last() {
3868 return $this->last;
3872 * Setter for "last"
3873 * @param $val boolean
3875 public function set_last($val) {
3876 $this->last = $val;
3881 * Subclass of navigation_node allowing different rendering for the flat navigation
3882 * in particular allowing dividers and indents.
3884 * @package core
3885 * @category navigation
3886 * @copyright 2016 Damyon Wiese
3887 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3889 class flat_navigation_node extends navigation_node {
3891 /** @var $indent integer The indent level */
3892 private $indent = 0;
3894 /** @var $showdivider bool Show a divider before this element */
3895 private $showdivider = false;
3897 /** @var $collectionlabel string Label for a group of nodes */
3898 private $collectionlabel = '';
3901 * A proxy constructor
3903 * @param mixed $navnode A navigation_node or an array
3905 public function __construct($navnode, $indent) {
3906 if (is_array($navnode)) {
3907 parent::__construct($navnode);
3908 } else if ($navnode instanceof navigation_node) {
3910 // Just clone everything.
3911 $objvalues = get_object_vars($navnode);
3912 foreach ($objvalues as $key => $value) {
3913 $this->$key = $value;
3915 } else {
3916 throw new coding_exception('Not a valid flat_navigation_node');
3918 $this->indent = $indent;
3922 * Setter, a label is required for a flat navigation node that shows a divider.
3924 * @param string $label
3926 public function set_collectionlabel($label) {
3927 $this->collectionlabel = $label;
3931 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
3933 * @return string
3935 public function get_collectionlabel() {
3936 if (!empty($this->collectionlabel)) {
3937 return $this->collectionlabel;
3939 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) {
3940 return $this->parent->get_collectionlabel();
3942 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3943 return '';
3947 * Does this node represent a course section link.
3948 * @return boolean
3950 public function is_section() {
3951 return $this->type == navigation_node::TYPE_SECTION;
3955 * In flat navigation - sections are active if we are looking at activities in the section.
3956 * @return boolean
3958 public function isactive() {
3959 global $PAGE;
3961 if ($this->is_section()) {
3962 $active = $PAGE->navigation->find_active_node();
3963 while ($active = $active->parent) {
3964 if ($active->key == $this->key && $active->type == $this->type) {
3965 return true;
3969 return $this->isactive;
3973 * Getter for "showdivider"
3974 * @return boolean
3976 public function showdivider() {
3977 return $this->showdivider;
3981 * Setter for "showdivider"
3982 * @param $val boolean
3983 * @param $label string Label for the group of nodes
3985 public function set_showdivider($val, $label = '') {
3986 $this->showdivider = $val;
3987 if ($this->showdivider && empty($label)) {
3988 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3989 } else {
3990 $this->set_collectionlabel($label);
3995 * Getter for "indent"
3996 * @return boolean
3998 public function get_indent() {
3999 return $this->indent;
4003 * Setter for "indent"
4004 * @param $val boolean
4006 public function set_indent($val) {
4007 $this->indent = $val;
4012 * Class used to generate a collection of navigation nodes most closely related
4013 * to the current page.
4015 * @package core
4016 * @copyright 2016 Damyon Wiese
4017 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4019 class flat_navigation extends navigation_node_collection {
4020 /** @var moodle_page the moodle page that the navigation belongs to */
4021 protected $page;
4024 * Constructor.
4026 * @param moodle_page $page
4028 public function __construct(moodle_page &$page) {
4029 if (during_initial_install()) {
4030 return false;
4032 $this->page = $page;
4036 * Build the list of navigation nodes based on the current navigation and settings trees.
4039 public function initialise() {
4040 global $PAGE, $USER, $OUTPUT, $CFG;
4041 if (during_initial_install()) {
4042 return;
4045 $current = false;
4047 $course = $PAGE->course;
4049 $this->page->navigation->initialise();
4051 // First walk the nav tree looking for "flat_navigation" nodes.
4052 if ($course->id > 1) {
4053 // It's a real course.
4054 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4056 $coursecontext = context_course::instance($course->id, MUST_EXIST);
4057 // This is the name that will be shown for the course.
4058 $coursename = empty($CFG->navshowfullcoursenames) ?
4059 format_string($course->shortname, true, array('context' => $coursecontext)) :
4060 format_string($course->fullname, true, array('context' => $coursecontext));
4062 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
4063 $flat->set_collectionlabel($coursename);
4064 $flat->key = 'coursehome';
4065 $flat->icon = new pix_icon('i/course', '');
4067 $courseformat = course_get_format($course);
4068 $coursenode = $PAGE->navigation->find_active_node();
4069 $targettype = navigation_node::TYPE_COURSE;
4071 // Single activity format has no course node - the course node is swapped for the activity node.
4072 if (!$courseformat->has_view_page()) {
4073 $targettype = navigation_node::TYPE_ACTIVITY;
4076 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
4077 $coursenode = $coursenode->parent;
4079 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4080 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4081 if ($coursenode && $coursenode->key != SITEID) {
4082 $this->add($flat);
4083 foreach ($coursenode->children as $child) {
4084 if ($child->action) {
4085 $flat = new flat_navigation_node($child, 0);
4086 $this->add($flat);
4091 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
4092 } else {
4093 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
4096 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
4097 if (!$admin) {
4098 // Try again - crazy nav tree!
4099 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
4101 if ($admin) {
4102 $flat = new flat_navigation_node($admin, 0);
4103 $flat->set_showdivider(true, get_string('sitesettings'));
4104 $flat->key = 'sitesettings';
4105 $flat->icon = new pix_icon('t/preferences', '');
4106 $this->add($flat);
4111 * Override the parent so we can set a label for this collection if it has not been set yet.
4113 * @param navigation_node $node Node to add
4114 * @param string $beforekey If specified, adds before a node with this key,
4115 * otherwise adds at end
4116 * @return navigation_node Added node
4118 public function add(navigation_node $node, $beforekey=null) {
4119 $result = parent::add($node, $beforekey);
4120 // Extend the parent to get a name for the collection of nodes if required.
4121 if (empty($this->collectionlabel)) {
4122 if ($node instanceof flat_navigation_node) {
4123 $this->set_collectionlabel($node->get_collectionlabel());
4127 return $result;
4132 * Class used to manage the settings option for the current page
4134 * This class is used to manage the settings options in a tree format (recursively)
4135 * and was created initially for use with the settings blocks.
4137 * @package core
4138 * @category navigation
4139 * @copyright 2009 Sam Hemelryk
4140 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4142 class settings_navigation extends navigation_node {
4143 /** @var stdClass the current context */
4144 protected $context;
4145 /** @var moodle_page the moodle page that the navigation belongs to */
4146 protected $page;
4147 /** @var string contains administration section navigation_nodes */
4148 protected $adminsection;
4149 /** @var bool A switch to see if the navigation node is initialised */
4150 protected $initialised = false;
4151 /** @var array An array of users that the nodes can extend for. */
4152 protected $userstoextendfor = array();
4153 /** @var navigation_cache **/
4154 protected $cache;
4157 * Sets up the object with basic settings and preparse it for use
4159 * @param moodle_page $page
4161 public function __construct(moodle_page &$page) {
4162 if (during_initial_install()) {
4163 return false;
4165 $this->page = $page;
4166 // Initialise the main navigation. It is most important that this is done
4167 // before we try anything
4168 $this->page->navigation->initialise();
4169 // Initialise the navigation cache
4170 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4171 $this->children = new navigation_node_collection();
4175 * Initialise the settings navigation based on the current context
4177 * This function initialises the settings navigation tree for a given context
4178 * by calling supporting functions to generate major parts of the tree.
4181 public function initialise() {
4182 global $DB, $SESSION, $SITE;
4184 if (during_initial_install()) {
4185 return false;
4186 } else if ($this->initialised) {
4187 return true;
4189 $this->id = 'settingsnav';
4190 $this->context = $this->page->context;
4192 $context = $this->context;
4193 if ($context->contextlevel == CONTEXT_BLOCK) {
4194 $this->load_block_settings();
4195 $context = $context->get_parent_context();
4196 $this->context = $context;
4198 switch ($context->contextlevel) {
4199 case CONTEXT_SYSTEM:
4200 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4201 $this->load_front_page_settings(($context->id == $this->context->id));
4203 break;
4204 case CONTEXT_COURSECAT:
4205 $this->load_category_settings();
4206 break;
4207 case CONTEXT_COURSE:
4208 if ($this->page->course->id != $SITE->id) {
4209 $this->load_course_settings(($context->id == $this->context->id));
4210 } else {
4211 $this->load_front_page_settings(($context->id == $this->context->id));
4213 break;
4214 case CONTEXT_MODULE:
4215 $this->load_module_settings();
4216 $this->load_course_settings();
4217 break;
4218 case CONTEXT_USER:
4219 if ($this->page->course->id != $SITE->id) {
4220 $this->load_course_settings();
4222 break;
4225 $usersettings = $this->load_user_settings($this->page->course->id);
4227 $adminsettings = false;
4228 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4229 $isadminpage = $this->is_admin_tree_needed();
4231 if (has_capability('moodle/site:configview', context_system::instance())) {
4232 if (has_capability('moodle/site:config', context_system::instance())) {
4233 // Make sure this works even if config capability changes on the fly
4234 // and also make it fast for admin right after login.
4235 $SESSION->load_navigation_admin = 1;
4236 if ($isadminpage) {
4237 $adminsettings = $this->load_administration_settings();
4240 } else if (!isset($SESSION->load_navigation_admin)) {
4241 $adminsettings = $this->load_administration_settings();
4242 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4244 } else if ($SESSION->load_navigation_admin) {
4245 if ($isadminpage) {
4246 $adminsettings = $this->load_administration_settings();
4250 // Print empty navigation node, if needed.
4251 if ($SESSION->load_navigation_admin && !$isadminpage) {
4252 if ($adminsettings) {
4253 // Do not print settings tree on pages that do not need it, this helps with performance.
4254 $adminsettings->remove();
4255 $adminsettings = false;
4257 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4258 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4259 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4260 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4261 $siteadminnode->requiresajaxloading = 'true';
4266 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4267 $adminsettings->force_open();
4268 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4269 $usersettings->force_open();
4272 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4273 $this->load_local_plugin_settings();
4275 foreach ($this->children as $key=>$node) {
4276 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4277 // Site administration is shown as link.
4278 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4279 continue;
4281 $node->remove();
4284 $this->initialised = true;
4287 * Override the parent function so that we can add preceeding hr's and set a
4288 * root node class against all first level element
4290 * It does this by first calling the parent's add method {@link navigation_node::add()}
4291 * and then proceeds to use the key to set class and hr
4293 * @param string $text text to be used for the link.
4294 * @param string|moodle_url $url url for the new node
4295 * @param int $type the type of node navigation_node::TYPE_*
4296 * @param string $shorttext
4297 * @param string|int $key a key to access the node by.
4298 * @param pix_icon $icon An icon that appears next to the node.
4299 * @return navigation_node with the new node added to it.
4301 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4302 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4303 $node->add_class('root_node');
4304 return $node;
4308 * This function allows the user to add something to the start of the settings
4309 * navigation, which means it will be at the top of the settings navigation block
4311 * @param string $text text to be used for the link.
4312 * @param string|moodle_url $url url for the new node
4313 * @param int $type the type of node navigation_node::TYPE_*
4314 * @param string $shorttext
4315 * @param string|int $key a key to access the node by.
4316 * @param pix_icon $icon An icon that appears next to the node.
4317 * @return navigation_node $node with the new node added to it.
4319 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4320 $children = $this->children;
4321 $childrenclass = get_class($children);
4322 $this->children = new $childrenclass;
4323 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4324 foreach ($children as $child) {
4325 $this->children->add($child);
4327 return $node;
4331 * Does this page require loading of full admin tree or is
4332 * it enough rely on AJAX?
4334 * @return bool
4336 protected function is_admin_tree_needed() {
4337 if (self::$loadadmintree) {
4338 // Usually external admin page or settings page.
4339 return true;
4342 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4343 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4344 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4345 return false;
4347 return true;
4350 return false;
4354 * Load the site administration tree
4356 * This function loads the site administration tree by using the lib/adminlib library functions
4358 * @param navigation_node $referencebranch A reference to a branch in the settings
4359 * navigation tree
4360 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4361 * tree and start at the beginning
4362 * @return mixed A key to access the admin tree by
4364 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4365 global $CFG;
4367 // Check if we are just starting to generate this navigation.
4368 if ($referencebranch === null) {
4370 // Require the admin lib then get an admin structure
4371 if (!function_exists('admin_get_root')) {
4372 require_once($CFG->dirroot.'/lib/adminlib.php');
4374 $adminroot = admin_get_root(false, false);
4375 // This is the active section identifier
4376 $this->adminsection = $this->page->url->param('section');
4378 // Disable the navigation from automatically finding the active node
4379 navigation_node::$autofindactive = false;
4380 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4381 foreach ($adminroot->children as $adminbranch) {
4382 $this->load_administration_settings($referencebranch, $adminbranch);
4384 navigation_node::$autofindactive = true;
4386 // Use the admin structure to locate the active page
4387 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4388 $currentnode = $this;
4389 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4390 $currentnode = $currentnode->get($pathkey);
4392 if ($currentnode) {
4393 $currentnode->make_active();
4395 } else {
4396 $this->scan_for_active_node($referencebranch);
4398 return $referencebranch;
4399 } else if ($adminbranch->check_access()) {
4400 // We have a reference branch that we can access and is not hidden `hurrah`
4401 // Now we need to display it and any children it may have
4402 $url = null;
4403 $icon = null;
4405 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) {
4406 if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4407 $url = null;
4408 } else {
4409 $url = $adminbranch->get_settings_page_url();
4413 // Add the branch
4414 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4416 if ($adminbranch->is_hidden()) {
4417 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4418 $reference->add_class('hidden');
4419 } else {
4420 $reference->display = false;
4424 // Check if we are generating the admin notifications and whether notificiations exist
4425 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4426 $reference->add_class('criticalnotification');
4428 // Check if this branch has children
4429 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4430 foreach ($adminbranch->children as $branch) {
4431 // Generate the child branches as well now using this branch as the reference
4432 $this->load_administration_settings($reference, $branch);
4434 } else {
4435 $reference->icon = new pix_icon('i/settings', '');
4441 * This function recursivily scans nodes until it finds the active node or there
4442 * are no more nodes.
4443 * @param navigation_node $node
4445 protected function scan_for_active_node(navigation_node $node) {
4446 if (!$node->check_if_active() && $node->children->count()>0) {
4447 foreach ($node->children as &$child) {
4448 $this->scan_for_active_node($child);
4454 * Gets a navigation node given an array of keys that represent the path to
4455 * the desired node.
4457 * @param array $path
4458 * @return navigation_node|false
4460 protected function get_by_path(array $path) {
4461 $node = $this->get(array_shift($path));
4462 foreach ($path as $key) {
4463 $node->get($key);
4465 return $node;
4469 * This function loads the course settings that are available for the user
4471 * @param bool $forceopen If set to true the course node will be forced open
4472 * @return navigation_node|false
4474 protected function load_course_settings($forceopen = false) {
4475 global $CFG, $USER;
4476 require_once($CFG->dirroot . '/course/lib.php');
4478 $course = $this->page->course;
4479 $coursecontext = context_course::instance($course->id);
4480 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4482 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4484 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4485 if ($forceopen) {
4486 $coursenode->force_open();
4490 if ($adminoptions->update) {
4491 // Add the course settings link
4492 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4493 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null,
4494 'editsettings', new pix_icon('i/settings', ''));
4497 if ($adminoptions->editcompletion) {
4498 // Add the course completion settings link
4499 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4500 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion',
4501 new pix_icon('i/settings', ''));
4504 if (!$adminoptions->update && $adminoptions->tags) {
4505 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4506 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4507 $coursenode->get('coursetags')->set_force_into_more_menu();
4510 // add enrol nodes
4511 enrol_add_course_navigation($coursenode, $course);
4513 // Manage filters
4514 if ($adminoptions->filters) {
4515 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4516 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
4517 null, 'filtermanagement', new pix_icon('i/filter', ''));
4520 // View course reports.
4521 if ($adminoptions->reports) {
4522 $reportnav = $coursenode->add(get_string('reports'),
4523 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]),
4524 self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', ''));
4525 $coursereports = core_component::get_plugin_list('coursereport');
4526 foreach ($coursereports as $report => $dir) {
4527 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4528 if (file_exists($libfile)) {
4529 require_once($libfile);
4530 $reportfunction = $report.'_report_extend_navigation';
4531 if (function_exists($report.'_report_extend_navigation')) {
4532 $reportfunction($reportnav, $course, $coursecontext);
4537 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4538 foreach ($reports as $reportfunction) {
4539 $reportfunction($reportnav, $course, $coursecontext);
4543 // Check if we can view the gradebook's setup page.
4544 if ($adminoptions->gradebook) {
4545 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4546 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4547 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4550 // Add the context locking node.
4551 $this->add_context_locking_node($coursenode, $coursecontext);
4553 // Add outcome if permitted
4554 if ($adminoptions->outcomes) {
4555 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4556 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4559 //Add badges navigation
4560 if ($adminoptions->badges) {
4561 require_once($CFG->libdir .'/badgeslib.php');
4562 badges_add_course_navigation($coursenode, $course);
4565 // Import data from other courses.
4566 if ($adminoptions->import) {
4567 $url = new moodle_url('/backup/import.php', array('id' => $course->id));
4568 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4571 // Backup this course
4572 if ($adminoptions->backup) {
4573 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4574 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4577 // Restore to this course
4578 if ($adminoptions->restore) {
4579 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4580 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4583 // Copy this course.
4584 if ($adminoptions->copy) {
4585 $url = new moodle_url('/backup/copy.php', array('id' => $course->id));
4586 $coursenode->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', ''));
4589 // Reset this course
4590 if ($adminoptions->reset) {
4591 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4592 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4595 // Questions
4596 require_once($CFG->libdir . '/questionlib.php');
4597 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4599 if ($adminoptions->update) {
4600 // Repository Instances
4601 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4602 require_once($CFG->dirroot . '/repository/lib.php');
4603 $editabletypes = repository::get_editable_types($coursecontext);
4604 $haseditabletypes = !empty($editabletypes);
4605 unset($editabletypes);
4606 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4607 } else {
4608 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4610 if ($haseditabletypes) {
4611 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4612 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4616 // Manage files
4617 if ($adminoptions->files) {
4618 // hidden in new courses and courses where legacy files were turned off
4619 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4620 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4624 // Let plugins hook into course navigation.
4625 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4626 foreach ($pluginsfunction as $plugintype => $plugins) {
4627 // Ignore the report plugin as it was already loaded above.
4628 if ($plugintype == 'report') {
4629 continue;
4631 foreach ($plugins as $pluginfunction) {
4632 $pluginfunction($coursenode, $course, $coursecontext);
4636 // Prepare data for course content download functionality if it is enabled.
4637 // Will only be included here if the action menu is already in use, otherwise a button will be added to the UI elsewhere.
4638 if (\core\content::can_export_context($coursecontext, $USER) && !empty($coursenode->get_children_key_list())) {
4639 $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext);
4640 $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes);
4642 $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download',
4643 new pix_icon('t/download', ''));
4644 $coursenode->get('download')->set_force_into_more_menu();
4647 // Return we are done
4648 return $coursenode;
4652 * This function calls the module function to inject module settings into the
4653 * settings navigation tree.
4655 * This only gets called if there is a corrosponding function in the modules
4656 * lib file.
4658 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4660 * @return navigation_node|false
4662 protected function load_module_settings() {
4663 global $CFG;
4665 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4666 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4667 $this->page->set_cm($cm, $this->page->course);
4670 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4671 if (file_exists($file)) {
4672 require_once($file);
4675 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4676 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4677 $modulenode->force_open();
4679 // Settings for the module
4680 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4681 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4682 $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
4684 // Assign local roles
4685 if (count(get_assignable_roles($this->page->cm->context))>0) {
4686 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4687 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
4689 // Override roles
4690 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4691 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4692 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
4694 // Check role permissions
4695 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4696 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4697 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
4700 // Add the context locking node.
4701 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4703 // Manage filters
4704 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4705 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4706 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
4708 // Add reports
4709 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4710 foreach ($reports as $reportfunction) {
4711 $reportfunction($modulenode, $this->page->cm);
4713 // Add a backup link
4714 $featuresfunc = $this->page->activityname.'_supports';
4715 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4716 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4717 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4720 // Restore this activity
4721 $featuresfunc = $this->page->activityname.'_supports';
4722 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4723 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4724 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4727 // Allow the active advanced grading method plugin to append its settings
4728 $featuresfunc = $this->page->activityname.'_supports';
4729 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4730 require_once($CFG->dirroot.'/grade/grading/lib.php');
4731 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4732 $gradingman->extend_settings_navigation($this, $modulenode);
4735 $function = $this->page->activityname.'_extend_settings_navigation';
4736 if (function_exists($function)) {
4737 $function($this, $modulenode);
4740 // Remove the module node if there are no children.
4741 if ($modulenode->children->count() <= 0) {
4742 $modulenode->remove();
4745 return $modulenode;
4749 * Loads the user settings block of the settings nav
4751 * This function is simply works out the userid and whether we need to load
4752 * just the current users profile settings, or the current user and the user the
4753 * current user is viewing.
4755 * This function has some very ugly code to work out the user, if anyone has
4756 * any bright ideas please feel free to intervene.
4758 * @param int $courseid The course id of the current course
4759 * @return navigation_node|false
4761 protected function load_user_settings($courseid = SITEID) {
4762 global $USER, $CFG;
4764 if (isguestuser() || !isloggedin()) {
4765 return false;
4768 $navusers = $this->page->navigation->get_extending_users();
4770 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4771 $usernode = null;
4772 foreach ($this->userstoextendfor as $userid) {
4773 if ($userid == $USER->id) {
4774 continue;
4776 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4777 if (is_null($usernode)) {
4778 $usernode = $node;
4781 foreach ($navusers as $user) {
4782 if ($user->id == $USER->id) {
4783 continue;
4785 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4786 if (is_null($usernode)) {
4787 $usernode = $node;
4790 $this->generate_user_settings($courseid, $USER->id);
4791 } else {
4792 $usernode = $this->generate_user_settings($courseid, $USER->id);
4794 return $usernode;
4798 * Extends the settings navigation for the given user.
4800 * Note: This method gets called automatically if you call
4801 * $PAGE->navigation->extend_for_user($userid)
4803 * @param int $userid
4805 public function extend_for_user($userid) {
4806 global $CFG;
4808 if (!in_array($userid, $this->userstoextendfor)) {
4809 $this->userstoextendfor[] = $userid;
4810 if ($this->initialised) {
4811 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4812 $children = array();
4813 foreach ($this->children as $child) {
4814 $children[] = $child;
4816 array_unshift($children, array_pop($children));
4817 $this->children = new navigation_node_collection();
4818 foreach ($children as $child) {
4819 $this->children->add($child);
4826 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4827 * what can be shown/done
4829 * @param int $courseid The current course' id
4830 * @param int $userid The user id to load for
4831 * @param string $gstitle The string to pass to get_string for the branch title
4832 * @return navigation_node|false
4834 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4835 global $DB, $CFG, $USER, $SITE;
4837 if ($courseid != $SITE->id) {
4838 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4839 $course = $this->page->course;
4840 } else {
4841 $select = context_helper::get_preload_record_columns_sql('ctx');
4842 $sql = "SELECT c.*, $select
4843 FROM {course} c
4844 JOIN {context} ctx ON c.id = ctx.instanceid
4845 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4846 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4847 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4848 context_helper::preload_from_record($course);
4850 } else {
4851 $course = $SITE;
4854 $coursecontext = context_course::instance($course->id); // Course context
4855 $systemcontext = context_system::instance();
4856 $currentuser = ($USER->id == $userid);
4858 if ($currentuser) {
4859 $user = $USER;
4860 $usercontext = context_user::instance($user->id); // User context
4861 } else {
4862 $select = context_helper::get_preload_record_columns_sql('ctx');
4863 $sql = "SELECT u.*, $select
4864 FROM {user} u
4865 JOIN {context} ctx ON u.id = ctx.instanceid
4866 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4867 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4868 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4869 if (!$user) {
4870 return false;
4872 context_helper::preload_from_record($user);
4874 // Check that the user can view the profile
4875 $usercontext = context_user::instance($user->id); // User context
4876 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4878 if ($course->id == $SITE->id) {
4879 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4880 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4881 return false;
4883 } else {
4884 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4885 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4886 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4887 return false;
4889 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4890 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4891 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4892 if ($courseid == $this->page->course->id) {
4893 $mygroups = get_fast_modinfo($this->page->course)->groups;
4894 } else {
4895 $mygroups = groups_get_user_groups($courseid);
4897 $usergroups = groups_get_user_groups($courseid, $userid);
4898 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4899 return false;
4905 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4907 $key = $gstitle;
4908 $prefurl = new moodle_url('/user/preferences.php');
4909 if ($gstitle != 'usercurrentsettings') {
4910 $key .= $userid;
4911 $prefurl->param('userid', $userid);
4914 // Add a user setting branch.
4915 if ($gstitle == 'usercurrentsettings') {
4916 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4917 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4918 // breadcrumb.
4919 $dashboard->display = false;
4920 $homepage = get_home_page();
4921 if (($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES)) {
4922 $dashboard->mainnavonly = true;
4925 $iscurrentuser = ($user->id == $USER->id);
4927 $baseargs = array('id' => $user->id);
4928 if ($course->id != $SITE->id && !$iscurrentuser) {
4929 $baseargs['course'] = $course->id;
4930 $issitecourse = false;
4931 } else {
4932 // Load all categories and get the context for the system.
4933 $issitecourse = true;
4936 // Add the user profile to the dashboard.
4937 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4938 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4940 if (!empty($CFG->navadduserpostslinks)) {
4941 // Add nodes for forum posts and discussions if the user can view either or both
4942 // There are no capability checks here as the content of the page is based
4943 // purely on the forums the current user has access too.
4944 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4945 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4946 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4947 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4950 // Add blog nodes.
4951 if (!empty($CFG->enableblogs)) {
4952 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4953 require_once($CFG->dirroot.'/blog/lib.php');
4954 // Get all options for the user.
4955 $options = blog_get_options_for_user($user);
4956 $this->cache->set('userblogoptions'.$user->id, $options);
4957 } else {
4958 $options = $this->cache->{'userblogoptions'.$user->id};
4961 if (count($options) > 0) {
4962 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4963 foreach ($options as $type => $option) {
4964 if ($type == "rss") {
4965 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4966 new pix_icon('i/rss', ''));
4967 } else {
4968 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4974 // Add the messages link.
4975 // It is context based so can appear in the user's profile and in course participants information.
4976 if (!empty($CFG->messaging)) {
4977 $messageargs = array('user1' => $USER->id);
4978 if ($USER->id != $user->id) {
4979 $messageargs['user2'] = $user->id;
4981 $url = new moodle_url('/message/index.php', $messageargs);
4982 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4985 // Add the "My private files" link.
4986 // This link doesn't have a unique display for course context so only display it under the user's profile.
4987 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4988 $url = new moodle_url('/user/files.php');
4989 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
4992 // Add a node to view the users notes if permitted.
4993 if (!empty($CFG->enablenotes) &&
4994 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4995 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4996 if ($coursecontext->instanceid != SITEID) {
4997 $url->param('course', $coursecontext->instanceid);
4999 $profilenode->add(get_string('notes', 'notes'), $url);
5002 // Show the grades node.
5003 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
5004 require_once($CFG->dirroot . '/user/lib.php');
5005 // Set the grades node to link to the "Grades" page.
5006 if ($course->id == SITEID) {
5007 $url = user_mygrades_url($user->id, $course->id);
5008 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
5009 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
5011 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
5014 // Let plugins hook into user navigation.
5015 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5016 foreach ($pluginsfunction as $plugintype => $plugins) {
5017 if ($plugintype != 'report') {
5018 foreach ($plugins as $pluginfunction) {
5019 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5024 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5025 $dashboard->add_node($usersetting);
5026 } else {
5027 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5028 $usersetting->display = false;
5030 $usersetting->id = 'usersettings';
5032 // Check if the user has been deleted.
5033 if ($user->deleted) {
5034 if (!has_capability('moodle/user:update', $coursecontext)) {
5035 // We can't edit the user so just show the user deleted message.
5036 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
5037 } else {
5038 // We can edit the user so show the user deleted message and link it to the profile.
5039 if ($course->id == $SITE->id) {
5040 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
5041 } else {
5042 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
5044 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
5046 return true;
5049 $userauthplugin = false;
5050 if (!empty($user->auth)) {
5051 $userauthplugin = get_auth_plugin($user->auth);
5054 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
5056 // Add the profile edit link.
5057 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5058 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
5059 has_capability('moodle/user:update', $systemcontext)) {
5060 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
5061 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5062 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5063 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5064 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5065 $url = $userauthplugin->edit_profile_url();
5066 if (empty($url)) {
5067 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
5069 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5074 // Change password link.
5075 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
5076 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5077 $passwordchangeurl = $userauthplugin->change_password_url();
5078 if (empty($passwordchangeurl)) {
5079 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
5081 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
5084 // Default homepage.
5085 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER));
5086 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5087 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5088 has_capability('moodle/user:editprofile', $usercontext)) {
5089 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]);
5090 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser');
5094 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5095 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5096 has_capability('moodle/user:editprofile', $usercontext)) {
5097 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
5098 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
5101 $pluginmanager = core_plugin_manager::instance();
5102 $enabled = $pluginmanager->get_enabled_plugins('mod');
5103 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5104 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5105 has_capability('moodle/user:editprofile', $usercontext)) {
5106 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
5107 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
5110 $editors = editors_get_enabled();
5111 if (count($editors) > 1) {
5112 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5113 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5114 has_capability('moodle/user:editprofile', $usercontext)) {
5115 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
5116 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
5121 // Add "Calendar preferences" link.
5122 if (isloggedin() && !isguestuser($user)) {
5123 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5124 has_capability('moodle/user:editprofile', $usercontext)) {
5125 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
5126 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
5130 // Add "Content bank preferences" link.
5131 if (isloggedin() && !isguestuser($user)) {
5132 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5133 has_capability('moodle/user:editprofile', $usercontext)) {
5134 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]);
5135 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING,
5136 null, 'contentbankpreferences');
5140 // View the roles settings.
5141 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5142 'moodle/role:manage'], $usercontext)) {
5143 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
5145 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]);
5146 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
5148 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
5150 if (!empty($assignableroles)) {
5151 $url = new moodle_url('/admin/roles/assign.php',
5152 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5153 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
5156 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
5157 $url = new moodle_url('/admin/roles/permissions.php',
5158 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5159 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5162 $url = new moodle_url('/admin/roles/check.php',
5163 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5164 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5167 // Repositories.
5168 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5169 require_once($CFG->dirroot . '/repository/lib.php');
5170 $editabletypes = repository::get_editable_types($usercontext);
5171 $haseditabletypes = !empty($editabletypes);
5172 unset($editabletypes);
5173 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5174 } else {
5175 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5177 if ($haseditabletypes) {
5178 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5179 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5180 array('contextid' => $usercontext->id)));
5183 // Portfolio.
5184 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5185 require_once($CFG->libdir . '/portfoliolib.php');
5186 if (portfolio_has_visible_instances()) {
5187 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5189 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5190 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5192 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5193 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5197 $enablemanagetokens = false;
5198 if (!empty($CFG->enablerssfeeds)) {
5199 $enablemanagetokens = true;
5200 } else if (!is_siteadmin($USER->id)
5201 && !empty($CFG->enablewebservices)
5202 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5203 $enablemanagetokens = true;
5205 // Security keys.
5206 if ($currentuser && $enablemanagetokens) {
5207 $url = new moodle_url('/user/managetoken.php');
5208 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5211 // Messaging.
5212 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5213 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5214 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5215 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5216 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5217 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5220 // Blogs.
5221 if ($currentuser && !empty($CFG->enableblogs)) {
5222 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5223 if (has_capability('moodle/blog:view', $systemcontext)) {
5224 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5225 navigation_node::TYPE_SETTING);
5227 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5228 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5229 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5230 navigation_node::TYPE_SETTING);
5231 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5232 navigation_node::TYPE_SETTING);
5234 // Remove the blog node if empty.
5235 $blog->trim_if_empty();
5238 // Badges.
5239 if ($currentuser && !empty($CFG->enablebadges)) {
5240 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5241 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5242 $url = new moodle_url('/badges/mybadges.php');
5243 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5245 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5246 navigation_node::TYPE_SETTING);
5247 if (!empty($CFG->badges_allowexternalbackpack)) {
5248 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5249 navigation_node::TYPE_SETTING);
5253 // Let plugins hook into user settings navigation.
5254 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5255 foreach ($pluginsfunction as $plugintype => $plugins) {
5256 foreach ($plugins as $pluginfunction) {
5257 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5261 return $usersetting;
5265 * Loads block specific settings in the navigation
5267 * @return navigation_node
5269 protected function load_block_settings() {
5270 global $CFG;
5272 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5273 $blocknode->force_open();
5275 // Assign local roles
5276 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5277 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5278 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5279 'roles', new pix_icon('i/assignroles', ''));
5282 // Override roles
5283 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5284 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5285 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5286 'permissions', new pix_icon('i/permissions', ''));
5288 // Check role permissions
5289 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5290 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5291 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5292 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5295 // Add the context locking node.
5296 $this->add_context_locking_node($blocknode, $this->context);
5298 return $blocknode;
5302 * Loads category specific settings in the navigation
5304 * @return navigation_node
5306 protected function load_category_settings() {
5307 global $CFG;
5309 // We can land here while being in the context of a block, in which case we
5310 // should get the parent context which should be the category one. See self::initialise().
5311 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5312 $catcontext = $this->context->get_parent_context();
5313 } else {
5314 $catcontext = $this->context;
5317 // Let's make sure that we always have the right context when getting here.
5318 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5319 throw new coding_exception('Unexpected context while loading category settings.');
5322 $categorynodetype = navigation_node::TYPE_CONTAINER;
5323 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5324 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5325 $categorynode->force_open();
5327 if (can_edit_in_category($catcontext->instanceid)) {
5328 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5329 $editstring = get_string('managecategorythis');
5330 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', ''));
5333 if (has_capability('moodle/category:manage', $catcontext)) {
5334 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5335 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5337 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5338 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5341 // Assign local roles
5342 $assignableroles = get_assignable_roles($catcontext);
5343 if (!empty($assignableroles)) {
5344 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5345 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5348 // Override roles
5349 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5350 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5351 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5353 // Check role permissions
5354 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5355 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5356 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5357 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5360 // Add the context locking node.
5361 $this->add_context_locking_node($categorynode, $catcontext);
5363 // Cohorts
5364 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5365 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5366 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5369 // Manage filters
5370 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5371 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5372 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5375 // Restore.
5376 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5377 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5378 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5381 // Let plugins hook into category settings navigation.
5382 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5383 foreach ($pluginsfunction as $plugintype => $plugins) {
5384 foreach ($plugins as $pluginfunction) {
5385 $pluginfunction($categorynode, $catcontext);
5389 return $categorynode;
5393 * Determine whether the user is assuming another role
5395 * This function checks to see if the user is assuming another role by means of
5396 * role switching. In doing this we compare each RSW key (context path) against
5397 * the current context path. This ensures that we can provide the switching
5398 * options against both the course and any page shown under the course.
5400 * @return bool|int The role(int) if the user is in another role, false otherwise
5402 protected function in_alternative_role() {
5403 global $USER;
5404 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5405 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5406 return $USER->access['rsw'][$this->page->context->path];
5408 foreach ($USER->access['rsw'] as $key=>$role) {
5409 if (strpos($this->context->path,$key)===0) {
5410 return $role;
5414 return false;
5418 * This function loads all of the front page settings into the settings navigation.
5419 * This function is called when the user is on the front page, or $COURSE==$SITE
5420 * @param bool $forceopen (optional)
5421 * @return navigation_node
5423 protected function load_front_page_settings($forceopen = false) {
5424 global $SITE, $CFG;
5425 require_once($CFG->dirroot . '/course/lib.php');
5427 $course = clone($SITE);
5428 $coursecontext = context_course::instance($course->id); // Course context
5429 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5431 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5432 if ($forceopen) {
5433 $frontpage->force_open();
5435 $frontpage->id = 'frontpagesettings';
5437 if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) {
5439 // Add the turn on/off settings
5440 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5441 if ($this->page->user_is_editing()) {
5442 $url->param('edit', 'off');
5443 $editstring = get_string('turneditingoff');
5444 } else {
5445 $url->param('edit', 'on');
5446 $editstring = get_string('turneditingon');
5448 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5451 if ($adminoptions->update) {
5452 // Add the course settings link
5453 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5454 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5457 // add enrol nodes
5458 enrol_add_course_navigation($frontpage, $course);
5460 // Manage filters
5461 if ($adminoptions->filters) {
5462 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5463 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5466 // View course reports.
5467 if ($adminoptions->reports) {
5468 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5469 new pix_icon('i/stats', ''));
5470 $coursereports = core_component::get_plugin_list('coursereport');
5471 foreach ($coursereports as $report=>$dir) {
5472 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5473 if (file_exists($libfile)) {
5474 require_once($libfile);
5475 $reportfunction = $report.'_report_extend_navigation';
5476 if (function_exists($report.'_report_extend_navigation')) {
5477 $reportfunction($frontpagenav, $course, $coursecontext);
5482 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5483 foreach ($reports as $reportfunction) {
5484 $reportfunction($frontpagenav, $course, $coursecontext);
5488 // Backup this course
5489 if ($adminoptions->backup) {
5490 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5491 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5494 // Restore to this course
5495 if ($adminoptions->restore) {
5496 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5497 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5500 // Questions
5501 require_once($CFG->libdir . '/questionlib.php');
5502 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5504 // Manage files
5505 if ($adminoptions->files) {
5506 //hiden in new installs
5507 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5508 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5511 // Let plugins hook into frontpage navigation.
5512 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5513 foreach ($pluginsfunction as $plugintype => $plugins) {
5514 foreach ($plugins as $pluginfunction) {
5515 $pluginfunction($frontpage, $course, $coursecontext);
5519 return $frontpage;
5523 * This function gives local plugins an opportunity to modify the settings navigation.
5525 protected function load_local_plugin_settings() {
5527 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5528 $function($this, $this->context);
5533 * This function marks the cache as volatile so it is cleared during shutdown
5535 public function clear_cache() {
5536 $this->cache->volatile();
5540 * Checks to see if there are child nodes available in the specific user's preference node.
5541 * If so, then they have the appropriate permissions view this user's preferences.
5543 * @since Moodle 2.9.3
5544 * @param int $userid The user's ID.
5545 * @return bool True if child nodes exist to view, otherwise false.
5547 public function can_view_user_preferences($userid) {
5548 if (is_siteadmin()) {
5549 return true;
5551 // See if any nodes are present in the preferences section for this user.
5552 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5553 if ($preferencenode && $preferencenode->has_children()) {
5554 // Run through each child node.
5555 foreach ($preferencenode->children as $childnode) {
5556 // If the child node has children then this user has access to a link in the preferences page.
5557 if ($childnode->has_children()) {
5558 return true;
5562 // No links found for the user to access on the preferences page.
5563 return false;
5568 * Class used to populate site admin navigation for ajax.
5570 * @package core
5571 * @category navigation
5572 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5573 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5575 class settings_navigation_ajax extends settings_navigation {
5577 * Constructs the navigation for use in an AJAX request
5579 * @param moodle_page $page
5581 public function __construct(moodle_page &$page) {
5582 $this->page = $page;
5583 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5584 $this->children = new navigation_node_collection();
5585 $this->initialise();
5589 * Initialise the site admin navigation.
5591 * @return array An array of the expandable nodes
5593 public function initialise() {
5594 if ($this->initialised || during_initial_install()) {
5595 return false;
5597 $this->context = $this->page->context;
5598 $this->load_administration_settings();
5600 // Check if local plugins is adding node to site admin.
5601 $this->load_local_plugin_settings();
5603 $this->initialised = true;
5608 * Simple class used to output a navigation branch in XML
5610 * @package core
5611 * @category navigation
5612 * @copyright 2009 Sam Hemelryk
5613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5615 class navigation_json {
5616 /** @var array An array of different node types */
5617 protected $nodetype = array('node','branch');
5618 /** @var array An array of node keys and types */
5619 protected $expandable = array();
5621 * Turns a branch and all of its children into XML
5623 * @param navigation_node $branch
5624 * @return string XML string
5626 public function convert($branch) {
5627 $xml = $this->convert_child($branch);
5628 return $xml;
5631 * Set the expandable items in the array so that we have enough information
5632 * to attach AJAX events
5633 * @param array $expandable
5635 public function set_expandable($expandable) {
5636 foreach ($expandable as $node) {
5637 $this->expandable[$node['key'].':'.$node['type']] = $node;
5641 * Recusively converts a child node and its children to XML for output
5643 * @param navigation_node $child The child to convert
5644 * @param int $depth Pointlessly used to track the depth of the XML structure
5645 * @return string JSON
5647 protected function convert_child($child, $depth=1) {
5648 if (!$child->display) {
5649 return '';
5651 $attributes = array();
5652 $attributes['id'] = $child->id;
5653 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5654 $attributes['type'] = $child->type;
5655 $attributes['key'] = $child->key;
5656 $attributes['class'] = $child->get_css_type();
5657 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5659 if ($child->icon instanceof pix_icon) {
5660 $attributes['icon'] = array(
5661 'component' => $child->icon->component,
5662 'pix' => $child->icon->pix,
5664 foreach ($child->icon->attributes as $key=>$value) {
5665 if ($key == 'class') {
5666 $attributes['icon']['classes'] = explode(' ', $value);
5667 } else if (!array_key_exists($key, $attributes['icon'])) {
5668 $attributes['icon'][$key] = $value;
5672 } else if (!empty($child->icon)) {
5673 $attributes['icon'] = (string)$child->icon;
5676 if ($child->forcetitle || $child->title !== $child->text) {
5677 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5679 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5680 $attributes['expandable'] = $child->key;
5681 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5684 if (count($child->classes)>0) {
5685 $attributes['class'] .= ' '.join(' ',$child->classes);
5687 if (is_string($child->action)) {
5688 $attributes['link'] = $child->action;
5689 } else if ($child->action instanceof moodle_url) {
5690 $attributes['link'] = $child->action->out();
5691 } else if ($child->action instanceof action_link) {
5692 $attributes['link'] = $child->action->url->out();
5694 $attributes['hidden'] = ($child->hidden);
5695 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5696 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5698 if ($child->children->count() > 0) {
5699 $attributes['children'] = array();
5700 foreach ($child->children as $subchild) {
5701 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5705 if ($depth > 1) {
5706 return $attributes;
5707 } else {
5708 return json_encode($attributes);
5714 * The cache class used by global navigation and settings navigation.
5716 * It is basically an easy access point to session with a bit of smarts to make
5717 * sure that the information that is cached is valid still.
5719 * Example use:
5720 * <code php>
5721 * if (!$cache->viewdiscussion()) {
5722 * // Code to do stuff and produce cachable content
5723 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5725 * $content = $cache->viewdiscussion;
5726 * </code>
5728 * @package core
5729 * @category navigation
5730 * @copyright 2009 Sam Hemelryk
5731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5733 class navigation_cache {
5734 /** @var int represents the time created */
5735 protected $creation;
5736 /** @var array An array of session keys */
5737 protected $session;
5739 * The string to use to segregate this particular cache. It can either be
5740 * unique to start a fresh cache or if you want to share a cache then make
5741 * it the string used in the original cache.
5742 * @var string
5744 protected $area;
5745 /** @var int a time that the information will time out */
5746 protected $timeout;
5747 /** @var stdClass The current context */
5748 protected $currentcontext;
5749 /** @var int cache time information */
5750 const CACHETIME = 0;
5751 /** @var int cache user id */
5752 const CACHEUSERID = 1;
5753 /** @var int cache value */
5754 const CACHEVALUE = 2;
5755 /** @var null|array An array of navigation cache areas to expire on shutdown */
5756 public static $volatilecaches;
5759 * Contructor for the cache. Requires two arguments
5761 * @param string $area The string to use to segregate this particular cache
5762 * it can either be unique to start a fresh cache or if you want
5763 * to share a cache then make it the string used in the original
5764 * cache
5765 * @param int $timeout The number of seconds to time the information out after
5767 public function __construct($area, $timeout=1800) {
5768 $this->creation = time();
5769 $this->area = $area;
5770 $this->timeout = time() - $timeout;
5771 if (rand(0,100) === 0) {
5772 $this->garbage_collection();
5777 * Used to set up the cache within the SESSION.
5779 * This is called for each access and ensure that we don't put anything into the session before
5780 * it is required.
5782 protected function ensure_session_cache_initialised() {
5783 global $SESSION;
5784 if (empty($this->session)) {
5785 if (!isset($SESSION->navcache)) {
5786 $SESSION->navcache = new stdClass;
5788 if (!isset($SESSION->navcache->{$this->area})) {
5789 $SESSION->navcache->{$this->area} = array();
5791 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5796 * Magic Method to retrieve something by simply calling using = cache->key
5798 * @param mixed $key The identifier for the information you want out again
5799 * @return void|mixed Either void or what ever was put in
5801 public function __get($key) {
5802 if (!$this->cached($key)) {
5803 return;
5805 $information = $this->session[$key][self::CACHEVALUE];
5806 return unserialize($information);
5810 * Magic method that simply uses {@link set();} to store something in the cache
5812 * @param string|int $key
5813 * @param mixed $information
5815 public function __set($key, $information) {
5816 $this->set($key, $information);
5820 * Sets some information against the cache (session) for later retrieval
5822 * @param string|int $key
5823 * @param mixed $information
5825 public function set($key, $information) {
5826 global $USER;
5827 $this->ensure_session_cache_initialised();
5828 $information = serialize($information);
5829 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5832 * Check the existence of the identifier in the cache
5834 * @param string|int $key
5835 * @return bool
5837 public function cached($key) {
5838 global $USER;
5839 $this->ensure_session_cache_initialised();
5840 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) {
5841 return false;
5843 return true;
5846 * Compare something to it's equivilant in the cache
5848 * @param string $key
5849 * @param mixed $value
5850 * @param bool $serialise Whether to serialise the value before comparison
5851 * this should only be set to false if the value is already
5852 * serialised
5853 * @return bool If the value is the same false if it is not set or doesn't match
5855 public function compare($key, $value, $serialise = true) {
5856 if ($this->cached($key)) {
5857 if ($serialise) {
5858 $value = serialize($value);
5860 if ($this->session[$key][self::CACHEVALUE] === $value) {
5861 return true;
5864 return false;
5867 * Wipes the entire cache, good to force regeneration
5869 public function clear() {
5870 global $SESSION;
5871 unset($SESSION->navcache);
5872 $this->session = null;
5875 * Checks all cache entries and removes any that have expired, good ole cleanup
5877 protected function garbage_collection() {
5878 if (empty($this->session)) {
5879 return true;
5881 foreach ($this->session as $key=>$cachedinfo) {
5882 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5883 unset($this->session[$key]);
5889 * Marks the cache as being volatile (likely to change)
5891 * Any caches marked as volatile will be destroyed at the on shutdown by
5892 * {@link navigation_node::destroy_volatile_caches()} which is registered
5893 * as a shutdown function if any caches are marked as volatile.
5895 * @param bool $setting True to destroy the cache false not too
5897 public function volatile($setting = true) {
5898 if (self::$volatilecaches===null) {
5899 self::$volatilecaches = array();
5900 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5903 if ($setting) {
5904 self::$volatilecaches[$this->area] = $this->area;
5905 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5906 unset(self::$volatilecaches[$this->area]);
5911 * Destroys all caches marked as volatile
5913 * This function is static and works in conjunction with the static volatilecaches
5914 * property of navigation cache.
5915 * Because this function is static it manually resets the cached areas back to an
5916 * empty array.
5918 public static function destroy_volatile_caches() {
5919 global $SESSION;
5920 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5921 foreach (self::$volatilecaches as $area) {
5922 $SESSION->navcache->{$area} = array();
5924 } else {
5925 $SESSION->navcache = new stdClass;