weekly release 2.9.3+
[moodle.git] / lib / navigationlib.php
blobf48ee1351398b50a2a49d3c82bf62b3ecb6bc1d6
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;
88 /** @var int Parameter to aid the coder in tracking [optional] */
89 public $id = null;
90 /** @var string|int The identifier for the node, used to retrieve the node */
91 public $key = null;
92 /** @var string The text to use for the node */
93 public $text = null;
94 /** @var string Short text to use if requested [optional] */
95 public $shorttext = null;
96 /** @var string The title attribute for an action if one is defined */
97 public $title = null;
98 /** @var string A string that can be used to build a help button */
99 public $helpbutton = null;
100 /** @var moodle_url|action_link|null An action for the node (link) */
101 public $action = null;
102 /** @var pix_icon The path to an icon to use for this node */
103 public $icon = null;
104 /** @var int See TYPE_* constants defined for this class */
105 public $type = self::TYPE_UNKNOWN;
106 /** @var int See NODETYPE_* constants defined for this class */
107 public $nodetype = self::NODETYPE_LEAF;
108 /** @var bool If set to true the node will be collapsed by default */
109 public $collapse = false;
110 /** @var bool If set to true the node will be expanded by default */
111 public $forceopen = false;
112 /** @var array An array of CSS classes for the node */
113 public $classes = array();
114 /** @var navigation_node_collection An array of child nodes */
115 public $children = array();
116 /** @var bool If set to true the node will be recognised as active */
117 public $isactive = false;
118 /** @var bool If set to true the node will be dimmed */
119 public $hidden = false;
120 /** @var bool If set to false the node will not be displayed */
121 public $display = true;
122 /** @var bool If set to true then an HR will be printed before the node */
123 public $preceedwithhr = false;
124 /** @var bool If set to true the the navigation bar should ignore this node */
125 public $mainnavonly = false;
126 /** @var bool If set to true a title will be added to the action no matter what */
127 public $forcetitle = false;
128 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
129 public $parent = null;
130 /** @var bool Override to not display the icon even if one is provided **/
131 public $hideicon = false;
132 /** @var bool Set to true if we KNOW that this node can be expanded. */
133 public $isexpandable = false;
134 /** @var array */
135 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting',71=>'siteadmin', 80=>'user');
136 /** @var moodle_url */
137 protected static $fullmeurl = null;
138 /** @var bool toogles auto matching of active node */
139 public static $autofindactive = true;
140 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
141 protected static $loadadmintree = false;
142 /** @var mixed If set to an int, that section will be included even if it has no activities */
143 public $includesectionnum = false;
146 * Constructs a new navigation_node
148 * @param array|string $properties Either an array of properties or a string to use
149 * as the text for the node
151 public function __construct($properties) {
152 if (is_array($properties)) {
153 // Check the array for each property that we allow to set at construction.
154 // text - The main content for the node
155 // shorttext - A short text if required for the node
156 // icon - The icon to display for the node
157 // type - The type of the node
158 // key - The key to use to identify the node
159 // parent - A reference to the nodes parent
160 // action - The action to attribute to this node, usually a URL to link to
161 if (array_key_exists('text', $properties)) {
162 $this->text = $properties['text'];
164 if (array_key_exists('shorttext', $properties)) {
165 $this->shorttext = $properties['shorttext'];
167 if (!array_key_exists('icon', $properties)) {
168 $properties['icon'] = new pix_icon('i/navigationitem', '');
170 $this->icon = $properties['icon'];
171 if ($this->icon instanceof pix_icon) {
172 if (empty($this->icon->attributes['class'])) {
173 $this->icon->attributes['class'] = 'navicon';
174 } else {
175 $this->icon->attributes['class'] .= ' navicon';
178 if (array_key_exists('type', $properties)) {
179 $this->type = $properties['type'];
180 } else {
181 $this->type = self::TYPE_CUSTOM;
183 if (array_key_exists('key', $properties)) {
184 $this->key = $properties['key'];
186 // This needs to happen last because of the check_if_active call that occurs
187 if (array_key_exists('action', $properties)) {
188 $this->action = $properties['action'];
189 if (is_string($this->action)) {
190 $this->action = new moodle_url($this->action);
192 if (self::$autofindactive) {
193 $this->check_if_active();
196 if (array_key_exists('parent', $properties)) {
197 $this->set_parent($properties['parent']);
199 } else if (is_string($properties)) {
200 $this->text = $properties;
202 if ($this->text === null) {
203 throw new coding_exception('You must set the text for the node when you create it.');
205 // Instantiate a new navigation node collection for this nodes children
206 $this->children = new navigation_node_collection();
210 * Checks if this node is the active node.
212 * This is determined by comparing the action for the node against the
213 * defined URL for the page. A match will see this node marked as active.
215 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
216 * @return bool
218 public function check_if_active($strength=URL_MATCH_EXACT) {
219 global $FULLME, $PAGE;
220 // Set fullmeurl if it hasn't already been set
221 if (self::$fullmeurl == null) {
222 if ($PAGE->has_set_url()) {
223 self::override_active_url(new moodle_url($PAGE->url));
224 } else {
225 self::override_active_url(new moodle_url($FULLME));
229 // Compare the action of this node against the fullmeurl
230 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
231 $this->make_active();
232 return true;
234 return false;
238 * This sets the URL that the URL of new nodes get compared to when locating
239 * the active node.
241 * The active node is the node that matches the URL set here. By default this
242 * is either $PAGE->url or if that hasn't been set $FULLME.
244 * @param moodle_url $url The url to use for the fullmeurl.
245 * @param bool $loadadmintree use true if the URL point to administration tree
247 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
248 // Clone the URL, in case the calling script changes their URL later.
249 self::$fullmeurl = new moodle_url($url);
250 // True means we do not want AJAX loaded admin tree, required for all admin pages.
251 if ($loadadmintree) {
252 // Do not change back to false if already set.
253 self::$loadadmintree = true;
258 * Use when page is linked from the admin tree,
259 * if not used navigation could not find the page using current URL
260 * because the tree is not fully loaded.
262 public static function require_admin_tree() {
263 self::$loadadmintree = true;
267 * Creates a navigation node, ready to add it as a child using add_node
268 * function. (The created node needs to be added before you can use it.)
269 * @param string $text
270 * @param moodle_url|action_link $action
271 * @param int $type
272 * @param string $shorttext
273 * @param string|int $key
274 * @param pix_icon $icon
275 * @return navigation_node
277 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
278 $shorttext=null, $key=null, pix_icon $icon=null) {
279 // Properties array used when creating the new navigation node
280 $itemarray = array(
281 'text' => $text,
282 'type' => $type
284 // Set the action if one was provided
285 if ($action!==null) {
286 $itemarray['action'] = $action;
288 // Set the shorttext if one was provided
289 if ($shorttext!==null) {
290 $itemarray['shorttext'] = $shorttext;
292 // Set the icon if one was provided
293 if ($icon!==null) {
294 $itemarray['icon'] = $icon;
296 // Set the key
297 $itemarray['key'] = $key;
298 // Construct and return
299 return new navigation_node($itemarray);
303 * Adds a navigation node as a child of this node.
305 * @param string $text
306 * @param moodle_url|action_link $action
307 * @param int $type
308 * @param string $shorttext
309 * @param string|int $key
310 * @param pix_icon $icon
311 * @return navigation_node
313 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
314 // Create child node
315 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
317 // Add the child to end and return
318 return $this->add_node($childnode);
322 * Adds a navigation node as a child of this one, given a $node object
323 * created using the create function.
324 * @param navigation_node $childnode Node to add
325 * @param string $beforekey
326 * @return navigation_node The added node
328 public function add_node(navigation_node $childnode, $beforekey=null) {
329 // First convert the nodetype for this node to a branch as it will now have children
330 if ($this->nodetype !== self::NODETYPE_BRANCH) {
331 $this->nodetype = self::NODETYPE_BRANCH;
333 // Set the parent to this node
334 $childnode->set_parent($this);
336 // Default the key to the number of children if not provided
337 if ($childnode->key === null) {
338 $childnode->key = $this->children->count();
341 // Add the child using the navigation_node_collections add method
342 $node = $this->children->add($childnode, $beforekey);
344 // If added node is a category node or the user is logged in and it's a course
345 // then mark added node as a branch (makes it expandable by AJAX)
346 $type = $childnode->type;
347 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
348 ($type === self::TYPE_SITE_ADMIN)) {
349 $node->nodetype = self::NODETYPE_BRANCH;
351 // If this node is hidden mark it's children as hidden also
352 if ($this->hidden) {
353 $node->hidden = true;
355 // Return added node (reference returned by $this->children->add()
356 return $node;
360 * Return a list of all the keys of all the child nodes.
361 * @return array the keys.
363 public function get_children_key_list() {
364 return $this->children->get_key_list();
368 * Searches for a node of the given type with the given key.
370 * This searches this node plus all of its children, and their children....
371 * If you know the node you are looking for is a child of this node then please
372 * use the get method instead.
374 * @param int|string $key The key of the node we are looking for
375 * @param int $type One of navigation_node::TYPE_*
376 * @return navigation_node|false
378 public function find($key, $type) {
379 return $this->children->find($key, $type);
383 * Get the child of this node that has the given key + (optional) type.
385 * If you are looking for a node and want to search all children + their children
386 * then please use the find method instead.
388 * @param int|string $key The key of the node we are looking for
389 * @param int $type One of navigation_node::TYPE_*
390 * @return navigation_node|false
392 public function get($key, $type=null) {
393 return $this->children->get($key, $type);
397 * Removes this node.
399 * @return bool
401 public function remove() {
402 return $this->parent->children->remove($this->key, $this->type);
406 * Checks if this node has or could have any children
408 * @return bool Returns true if it has children or could have (by AJAX expansion)
410 public function has_children() {
411 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
415 * Marks this node as active and forces it open.
417 * Important: If you are here because you need to mark a node active to get
418 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
419 * You can use it to specify a different URL to match the active navigation node on
420 * rather than having to locate and manually mark a node active.
422 public function make_active() {
423 $this->isactive = true;
424 $this->add_class('active_tree_node');
425 $this->force_open();
426 if ($this->parent !== null) {
427 $this->parent->make_inactive();
432 * Marks a node as inactive and recusised back to the base of the tree
433 * doing the same to all parents.
435 public function make_inactive() {
436 $this->isactive = false;
437 $this->remove_class('active_tree_node');
438 if ($this->parent !== null) {
439 $this->parent->make_inactive();
444 * Forces this node to be open and at the same time forces open all
445 * parents until the root node.
447 * Recursive.
449 public function force_open() {
450 $this->forceopen = true;
451 if ($this->parent !== null) {
452 $this->parent->force_open();
457 * Adds a CSS class to this node.
459 * @param string $class
460 * @return bool
462 public function add_class($class) {
463 if (!in_array($class, $this->classes)) {
464 $this->classes[] = $class;
466 return true;
470 * Removes a CSS class from this node.
472 * @param string $class
473 * @return bool True if the class was successfully removed.
475 public function remove_class($class) {
476 if (in_array($class, $this->classes)) {
477 $key = array_search($class,$this->classes);
478 if ($key!==false) {
479 unset($this->classes[$key]);
480 return true;
483 return false;
487 * Sets the title for this node and forces Moodle to utilise it.
488 * @param string $title
490 public function title($title) {
491 $this->title = $title;
492 $this->forcetitle = true;
496 * Resets the page specific information on this node if it is being unserialised.
498 public function __wakeup(){
499 $this->forceopen = false;
500 $this->isactive = false;
501 $this->remove_class('active_tree_node');
505 * Checks if this node or any of its children contain the active node.
507 * Recursive.
509 * @return bool
511 public function contains_active_node() {
512 if ($this->isactive) {
513 return true;
514 } else {
515 foreach ($this->children as $child) {
516 if ($child->isactive || $child->contains_active_node()) {
517 return true;
521 return false;
525 * Finds the active node.
527 * Searches this nodes children plus all of the children for the active node
528 * and returns it if found.
530 * Recursive.
532 * @return navigation_node|false
534 public function find_active_node() {
535 if ($this->isactive) {
536 return $this;
537 } else {
538 foreach ($this->children as &$child) {
539 $outcome = $child->find_active_node();
540 if ($outcome !== false) {
541 return $outcome;
545 return false;
549 * Searches all children for the best matching active node
550 * @return navigation_node|false
552 public function search_for_active_node() {
553 if ($this->check_if_active(URL_MATCH_BASE)) {
554 return $this;
555 } else {
556 foreach ($this->children as &$child) {
557 $outcome = $child->search_for_active_node();
558 if ($outcome !== false) {
559 return $outcome;
563 return false;
567 * Gets the content for this node.
569 * @param bool $shorttext If true shorttext is used rather than the normal text
570 * @return string
572 public function get_content($shorttext=false) {
573 if ($shorttext && $this->shorttext!==null) {
574 return format_string($this->shorttext);
575 } else {
576 return format_string($this->text);
581 * Gets the title to use for this node.
583 * @return string
585 public function get_title() {
586 if ($this->forcetitle || $this->action != null){
587 return $this->title;
588 } else {
589 return '';
594 * Gets the CSS class to add to this node to describe its type
596 * @return string
598 public function get_css_type() {
599 if (array_key_exists($this->type, $this->namedtypes)) {
600 return 'type_'.$this->namedtypes[$this->type];
602 return 'type_unknown';
606 * Finds all nodes that are expandable by AJAX
608 * @param array $expandable An array by reference to populate with expandable nodes.
610 public function find_expandable(array &$expandable) {
611 foreach ($this->children as &$child) {
612 if ($child->display && $child->has_children() && $child->children->count() == 0) {
613 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
614 $this->add_class('canexpand');
615 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
617 $child->find_expandable($expandable);
622 * Finds all nodes of a given type (recursive)
624 * @param int $type One of navigation_node::TYPE_*
625 * @return array
627 public function find_all_of_type($type) {
628 $nodes = $this->children->type($type);
629 foreach ($this->children as &$node) {
630 $childnodes = $node->find_all_of_type($type);
631 $nodes = array_merge($nodes, $childnodes);
633 return $nodes;
637 * Removes this node if it is empty
639 public function trim_if_empty() {
640 if ($this->children->count() == 0) {
641 $this->remove();
646 * Creates a tab representation of this nodes children that can be used
647 * with print_tabs to produce the tabs on a page.
649 * call_user_func_array('print_tabs', $node->get_tabs_array());
651 * @param array $inactive
652 * @param bool $return
653 * @return array Array (tabs, selected, inactive, activated, return)
655 public function get_tabs_array(array $inactive=array(), $return=false) {
656 $tabs = array();
657 $rows = array();
658 $selected = null;
659 $activated = array();
660 foreach ($this->children as $node) {
661 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
662 if ($node->contains_active_node()) {
663 if ($node->children->count() > 0) {
664 $activated[] = $node->key;
665 foreach ($node->children as $child) {
666 if ($child->contains_active_node()) {
667 $selected = $child->key;
669 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
671 } else {
672 $selected = $node->key;
676 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
680 * Sets the parent for this node and if this node is active ensures that the tree is properly
681 * adjusted as well.
683 * @param navigation_node $parent
685 public function set_parent(navigation_node $parent) {
686 // Set the parent (thats the easy part)
687 $this->parent = $parent;
688 // Check if this node is active (this is checked during construction)
689 if ($this->isactive) {
690 // Force all of the parent nodes open so you can see this node
691 $this->parent->force_open();
692 // Make all parents inactive so that its clear where we are.
693 $this->parent->make_inactive();
698 * Hides the node and any children it has.
700 * @since Moodle 2.5
701 * @param array $typestohide Optional. An array of node types that should be hidden.
702 * If null all nodes will be hidden.
703 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
704 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
706 public function hide(array $typestohide = null) {
707 if ($typestohide === null || in_array($this->type, $typestohide)) {
708 $this->display = false;
709 if ($this->has_children()) {
710 foreach ($this->children as $child) {
711 $child->hide($typestohide);
719 * Navigation node collection
721 * This class is responsible for managing a collection of navigation nodes.
722 * It is required because a node's unique identifier is a combination of both its
723 * key and its type.
725 * Originally an array was used with a string key that was a combination of the two
726 * however it was decided that a better solution would be to use a class that
727 * implements the standard IteratorAggregate interface.
729 * @package core
730 * @category navigation
731 * @copyright 2010 Sam Hemelryk
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 class navigation_node_collection implements IteratorAggregate {
736 * A multidimensional array to where the first key is the type and the second
737 * key is the nodes key.
738 * @var array
740 protected $collection = array();
742 * An array that contains references to nodes in the same order they were added.
743 * This is maintained as a progressive array.
744 * @var array
746 protected $orderedcollection = array();
748 * A reference to the last node that was added to the collection
749 * @var navigation_node
751 protected $last = null;
753 * The total number of items added to this array.
754 * @var int
756 protected $count = 0;
759 * Adds a navigation node to the collection
761 * @param navigation_node $node Node to add
762 * @param string $beforekey If specified, adds before a node with this key,
763 * otherwise adds at end
764 * @return navigation_node Added node
766 public function add(navigation_node $node, $beforekey=null) {
767 global $CFG;
768 $key = $node->key;
769 $type = $node->type;
771 // First check we have a 2nd dimension for this type
772 if (!array_key_exists($type, $this->orderedcollection)) {
773 $this->orderedcollection[$type] = array();
775 // Check for a collision and report if debugging is turned on
776 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
777 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
780 // Find the key to add before
781 $newindex = $this->count;
782 $last = true;
783 if ($beforekey !== null) {
784 foreach ($this->collection as $index => $othernode) {
785 if ($othernode->key === $beforekey) {
786 $newindex = $index;
787 $last = false;
788 break;
791 if ($newindex === $this->count) {
792 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
793 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
797 // Add the node to the appropriate place in the by-type structure (which
798 // is not ordered, despite the variable name)
799 $this->orderedcollection[$type][$key] = $node;
800 if (!$last) {
801 // Update existing references in the ordered collection (which is the
802 // one that isn't called 'ordered') to shuffle them along if required
803 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
804 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
807 // Add a reference to the node to the progressive collection.
808 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
809 // Update the last property to a reference to this new node.
810 $this->last = $this->orderedcollection[$type][$key];
812 // Reorder the array by index if needed
813 if (!$last) {
814 ksort($this->collection);
816 $this->count++;
817 // Return the reference to the now added node
818 return $node;
822 * Return a list of all the keys of all the nodes.
823 * @return array the keys.
825 public function get_key_list() {
826 $keys = array();
827 foreach ($this->collection as $node) {
828 $keys[] = $node->key;
830 return $keys;
834 * Fetches a node from this collection.
836 * @param string|int $key The key of the node we want to find.
837 * @param int $type One of navigation_node::TYPE_*.
838 * @return navigation_node|null
840 public function get($key, $type=null) {
841 if ($type !== null) {
842 // If the type is known then we can simply check and fetch
843 if (!empty($this->orderedcollection[$type][$key])) {
844 return $this->orderedcollection[$type][$key];
846 } else {
847 // Because we don't know the type we look in the progressive array
848 foreach ($this->collection as $node) {
849 if ($node->key === $key) {
850 return $node;
854 return false;
858 * Searches for a node with matching key and type.
860 * This function searches both the nodes in this collection and all of
861 * the nodes in each collection belonging to the nodes in this collection.
863 * Recursive.
865 * @param string|int $key The key of the node we want to find.
866 * @param int $type One of navigation_node::TYPE_*.
867 * @return navigation_node|null
869 public function find($key, $type=null) {
870 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
871 return $this->orderedcollection[$type][$key];
872 } else {
873 $nodes = $this->getIterator();
874 // Search immediate children first
875 foreach ($nodes as &$node) {
876 if ($node->key === $key && ($type === null || $type === $node->type)) {
877 return $node;
880 // Now search each childs children
881 foreach ($nodes as &$node) {
882 $result = $node->children->find($key, $type);
883 if ($result !== false) {
884 return $result;
888 return false;
892 * Fetches the last node that was added to this collection
894 * @return navigation_node
896 public function last() {
897 return $this->last;
901 * Fetches all nodes of a given type from this collection
903 * @param string|int $type node type being searched for.
904 * @return array ordered collection
906 public function type($type) {
907 if (!array_key_exists($type, $this->orderedcollection)) {
908 $this->orderedcollection[$type] = array();
910 return $this->orderedcollection[$type];
913 * Removes the node with the given key and type from the collection
915 * @param string|int $key The key of the node we want to find.
916 * @param int $type
917 * @return bool
919 public function remove($key, $type=null) {
920 $child = $this->get($key, $type);
921 if ($child !== false) {
922 foreach ($this->collection as $colkey => $node) {
923 if ($node->key === $key && $node->type == $type) {
924 unset($this->collection[$colkey]);
925 $this->collection = array_values($this->collection);
926 break;
929 unset($this->orderedcollection[$child->type][$child->key]);
930 $this->count--;
931 return true;
933 return false;
937 * Gets the number of nodes in this collection
939 * This option uses an internal count rather than counting the actual options to avoid
940 * a performance hit through the count function.
942 * @return int
944 public function count() {
945 return $this->count;
948 * Gets an array iterator for the collection.
950 * This is required by the IteratorAggregator interface and is used by routines
951 * such as the foreach loop.
953 * @return ArrayIterator
955 public function getIterator() {
956 return new ArrayIterator($this->collection);
961 * The global navigation class used for... the global navigation
963 * This class is used by PAGE to store the global navigation for the site
964 * and is then used by the settings nav and navbar to save on processing and DB calls
966 * See
967 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
968 * {@link lib/ajax/getnavbranch.php} Called by ajax
970 * @package core
971 * @category navigation
972 * @copyright 2009 Sam Hemelryk
973 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
975 class global_navigation extends navigation_node {
976 /** @var moodle_page The Moodle page this navigation object belongs to. */
977 protected $page;
978 /** @var bool switch to let us know if the navigation object is initialised*/
979 protected $initialised = false;
980 /** @var array An array of course information */
981 protected $mycourses = array();
982 /** @var navigation_node[] An array for containing root navigation nodes */
983 protected $rootnodes = array();
984 /** @var bool A switch for whether to show empty sections in the navigation */
985 protected $showemptysections = true;
986 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
987 protected $showcategories = null;
988 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
989 protected $showmycategories = null;
990 /** @var array An array of stdClasses for users that the navigation is extended for */
991 protected $extendforuser = array();
992 /** @var navigation_cache */
993 protected $cache;
994 /** @var array An array of course ids that are present in the navigation */
995 protected $addedcourses = array();
996 /** @var bool */
997 protected $allcategoriesloaded = false;
998 /** @var array An array of category ids that are included in the navigation */
999 protected $addedcategories = array();
1000 /** @var int expansion limit */
1001 protected $expansionlimit = 0;
1002 /** @var int userid to allow parent to see child's profile page navigation */
1003 protected $useridtouseforparentchecks = 0;
1004 /** @var cache_session A cache that stores information on expanded courses */
1005 protected $cacheexpandcourse = null;
1007 /** Used when loading categories to load all top level categories [parent = 0] **/
1008 const LOAD_ROOT_CATEGORIES = 0;
1009 /** Used when loading categories to load all categories **/
1010 const LOAD_ALL_CATEGORIES = -1;
1013 * Constructs a new global navigation
1015 * @param moodle_page $page The page this navigation object belongs to
1017 public function __construct(moodle_page $page) {
1018 global $CFG, $SITE, $USER;
1020 if (during_initial_install()) {
1021 return;
1024 if (get_home_page() == HOMEPAGE_SITE) {
1025 // We are using the site home for the root element
1026 $properties = array(
1027 'key' => 'home',
1028 'type' => navigation_node::TYPE_SYSTEM,
1029 'text' => get_string('home'),
1030 'action' => new moodle_url('/')
1032 } else {
1033 // We are using the users my moodle for the root element
1034 $properties = array(
1035 'key' => 'myhome',
1036 'type' => navigation_node::TYPE_SYSTEM,
1037 'text' => get_string('myhome'),
1038 'action' => new moodle_url('/my/')
1042 // Use the parents constructor.... good good reuse
1043 parent::__construct($properties);
1045 // Initalise and set defaults
1046 $this->page = $page;
1047 $this->forceopen = true;
1048 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1052 * Mutator to set userid to allow parent to see child's profile
1053 * page navigation. See MDL-25805 for initial issue. Linked to it
1054 * is an issue explaining why this is a REALLY UGLY HACK thats not
1055 * for you to use!
1057 * @param int $userid userid of profile page that parent wants to navigate around.
1059 public function set_userid_for_parent_checks($userid) {
1060 $this->useridtouseforparentchecks = $userid;
1065 * Initialises the navigation object.
1067 * This causes the navigation object to look at the current state of the page
1068 * that it is associated with and then load the appropriate content.
1070 * This should only occur the first time that the navigation structure is utilised
1071 * which will normally be either when the navbar is called to be displayed or
1072 * when a block makes use of it.
1074 * @return bool
1076 public function initialise() {
1077 global $CFG, $SITE, $USER;
1078 // Check if it has already been initialised
1079 if ($this->initialised || during_initial_install()) {
1080 return true;
1082 $this->initialised = true;
1084 // Set up the five base root nodes. These are nodes where we will put our
1085 // content and are as follows:
1086 // site: Navigation for the front page.
1087 // myprofile: User profile information goes here.
1088 // currentcourse: The course being currently viewed.
1089 // mycourses: The users courses get added here.
1090 // courses: Additional courses are added here.
1091 // users: Other users information loaded here.
1092 $this->rootnodes = array();
1093 if (get_home_page() == HOMEPAGE_SITE) {
1094 // The home element should be my moodle because the root element is the site
1095 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1096 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1098 } else {
1099 // The home element should be the site because the root node is my moodle
1100 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1101 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1102 // We need to stop automatic redirection
1103 $this->rootnodes['home']->action->param('redirect', '0');
1106 $this->rootnodes['site'] = $this->add_course($SITE);
1107 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1108 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1109 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
1110 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1111 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1113 // We always load the frontpage course to ensure it is available without
1114 // JavaScript enabled.
1115 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1116 $this->load_course_sections($SITE, $this->rootnodes['site']);
1118 $course = $this->page->course;
1120 // $issite gets set to true if the current pages course is the sites frontpage course
1121 $issite = ($this->page->course->id == $SITE->id);
1122 // Determine if the user is enrolled in any course.
1123 $enrolledinanycourse = enrol_user_sees_own_courses();
1125 $this->rootnodes['currentcourse']->mainnavonly = true;
1126 if ($enrolledinanycourse) {
1127 $this->rootnodes['mycourses']->isexpandable = true;
1128 if ($CFG->navshowallcourses) {
1129 // When we show all courses we need to show both the my courses and the regular courses branch.
1130 $this->rootnodes['courses']->isexpandable = true;
1132 } else {
1133 $this->rootnodes['courses']->isexpandable = true;
1136 // Load the users enrolled courses if they are viewing the My Moodle page AND the admin has not
1137 // set that they wish to keep the My Courses branch collapsed by default.
1138 if (!empty($CFG->navexpandmycourses) && $this->page->pagelayout === 'mydashboard'){
1139 $this->rootnodes['mycourses']->forceopen = true;
1140 $this->load_courses_enrolled();
1141 } else {
1142 $this->rootnodes['mycourses']->collapse = true;
1143 $this->rootnodes['mycourses']->make_inactive();
1146 $canviewcourseprofile = true;
1148 // Next load context specific content into the navigation
1149 switch ($this->page->context->contextlevel) {
1150 case CONTEXT_SYSTEM :
1151 // Nothing left to do here I feel.
1152 break;
1153 case CONTEXT_COURSECAT :
1154 // This is essential, we must load categories.
1155 $this->load_all_categories($this->page->context->instanceid, true);
1156 break;
1157 case CONTEXT_BLOCK :
1158 case CONTEXT_COURSE :
1159 if ($issite) {
1160 // Nothing left to do here.
1161 break;
1164 // Load the course associated with the current page into the navigation.
1165 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1166 // If the course wasn't added then don't try going any further.
1167 if (!$coursenode) {
1168 $canviewcourseprofile = false;
1169 break;
1172 // If the user is not enrolled then we only want to show the
1173 // course node and not populate it.
1175 // Not enrolled, can't view, and hasn't switched roles
1176 if (!can_access_course($course, null, '', true)) {
1177 if ($coursenode->isexpandable === true) {
1178 // Obviously the situation has changed, update the cache and adjust the node.
1179 // This occurs if the user access to a course has been revoked (one way or another) after
1180 // initially logging in for this session.
1181 $this->get_expand_course_cache()->set($course->id, 1);
1182 $coursenode->isexpandable = true;
1183 $coursenode->nodetype = self::NODETYPE_BRANCH;
1185 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1186 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1187 if (!$this->current_user_is_parent_role()) {
1188 $coursenode->make_active();
1189 $canviewcourseprofile = false;
1190 break;
1192 } else if ($coursenode->isexpandable === false) {
1193 // Obviously the situation has changed, update the cache and adjust the node.
1194 // This occurs if the user has been granted access to a course (one way or another) after initially
1195 // logging in for this session.
1196 $this->get_expand_course_cache()->set($course->id, 1);
1197 $coursenode->isexpandable = true;
1198 $coursenode->nodetype = self::NODETYPE_BRANCH;
1201 // Add the essentials such as reports etc...
1202 $this->add_course_essentials($coursenode, $course);
1203 // Extend course navigation with it's sections/activities
1204 $this->load_course_sections($course, $coursenode);
1205 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1206 $coursenode->make_active();
1209 break;
1210 case CONTEXT_MODULE :
1211 if ($issite) {
1212 // If this is the site course then most information will have
1213 // already been loaded.
1214 // However we need to check if there is more content that can
1215 // yet be loaded for the specific module instance.
1216 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1217 if ($activitynode) {
1218 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1220 break;
1223 $course = $this->page->course;
1224 $cm = $this->page->cm;
1226 // Load the course associated with the page into the navigation
1227 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1229 // If the course wasn't added then don't try going any further.
1230 if (!$coursenode) {
1231 $canviewcourseprofile = false;
1232 break;
1235 // If the user is not enrolled then we only want to show the
1236 // course node and not populate it.
1237 if (!can_access_course($course, null, '', true)) {
1238 $coursenode->make_active();
1239 $canviewcourseprofile = false;
1240 break;
1243 $this->add_course_essentials($coursenode, $course);
1245 // Load the course sections into the page
1246 $this->load_course_sections($course, $coursenode, null, $cm);
1247 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1248 if (!empty($activity)) {
1249 // Finally load the cm specific navigaton information
1250 $this->load_activity($cm, $course, $activity);
1251 // Check if we have an active ndoe
1252 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1253 // And make the activity node active.
1254 $activity->make_active();
1257 break;
1258 case CONTEXT_USER :
1259 if ($issite) {
1260 // The users profile information etc is already loaded
1261 // for the front page.
1262 break;
1264 $course = $this->page->course;
1265 // Load the course associated with the user into the navigation
1266 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1268 // If the course wasn't added then don't try going any further.
1269 if (!$coursenode) {
1270 $canviewcourseprofile = false;
1271 break;
1274 // If the user is not enrolled then we only want to show the
1275 // course node and not populate it.
1276 if (!can_access_course($course, null, '', true)) {
1277 $coursenode->make_active();
1278 $canviewcourseprofile = false;
1279 break;
1281 $this->add_course_essentials($coursenode, $course);
1282 $this->load_course_sections($course, $coursenode);
1283 break;
1286 // Load for the current user
1287 $this->load_for_user();
1288 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1289 $this->load_for_user(null, true);
1291 // Load each extending user into the navigation.
1292 foreach ($this->extendforuser as $user) {
1293 if ($user->id != $USER->id) {
1294 $this->load_for_user($user);
1298 // Give the local plugins a chance to include some navigation if they want.
1299 foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $unused) {
1300 $function = "local_{$plugin}_extend_navigation";
1301 $oldfunction = "local_{$plugin}_extends_navigation";
1303 if (function_exists($function)) {
1304 $function($this);
1306 } else if (function_exists($oldfunction)) {
1307 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. ".
1308 "Support for the old callback will be dropped in Moodle 3.1", DEBUG_DEVELOPER);
1309 $oldfunction($this);
1313 // Remove any empty root nodes
1314 foreach ($this->rootnodes as $node) {
1315 // Dont remove the home node
1316 /** @var navigation_node $node */
1317 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1318 $node->remove();
1322 if (!$this->contains_active_node()) {
1323 $this->search_for_active_node();
1326 // If the user is not logged in modify the navigation structure as detailed
1327 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1328 if (!isloggedin()) {
1329 $activities = clone($this->rootnodes['site']->children);
1330 $this->rootnodes['site']->remove();
1331 $children = clone($this->children);
1332 $this->children = new navigation_node_collection();
1333 foreach ($activities as $child) {
1334 $this->children->add($child);
1336 foreach ($children as $child) {
1337 $this->children->add($child);
1340 return true;
1344 * Returns true if the current user is a parent of the user being currently viewed.
1346 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1347 * other user being viewed this function returns false.
1348 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1350 * @since Moodle 2.4
1351 * @return bool
1353 protected function current_user_is_parent_role() {
1354 global $USER, $DB;
1355 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1356 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1357 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1358 return false;
1360 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1361 return true;
1364 return false;
1368 * Returns true if courses should be shown within categories on the navigation.
1370 * @param bool $ismycourse Set to true if you are calculating this for a course.
1371 * @return bool
1373 protected function show_categories($ismycourse = false) {
1374 global $CFG, $DB;
1375 if ($ismycourse) {
1376 return $this->show_my_categories();
1378 if ($this->showcategories === null) {
1379 $show = false;
1380 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1381 $show = true;
1382 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1383 $show = true;
1385 $this->showcategories = $show;
1387 return $this->showcategories;
1391 * Returns true if we should show categories in the My Courses branch.
1392 * @return bool
1394 protected function show_my_categories() {
1395 global $CFG, $DB;
1396 if ($this->showmycategories === null) {
1397 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1399 return $this->showmycategories;
1403 * Loads the courses in Moodle into the navigation.
1405 * @global moodle_database $DB
1406 * @param string|array $categoryids An array containing categories to load courses
1407 * for, OR null to load courses for all categories.
1408 * @return array An array of navigation_nodes one for each course
1410 protected function load_all_courses($categoryids = null) {
1411 global $CFG, $DB, $SITE;
1413 // Work out the limit of courses.
1414 $limit = 20;
1415 if (!empty($CFG->navcourselimit)) {
1416 $limit = $CFG->navcourselimit;
1419 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1421 // If we are going to show all courses AND we are showing categories then
1422 // to save us repeated DB calls load all of the categories now
1423 if ($this->show_categories()) {
1424 $this->load_all_categories($toload);
1427 // Will be the return of our efforts
1428 $coursenodes = array();
1430 // Check if we need to show categories.
1431 if ($this->show_categories()) {
1432 // Hmmm we need to show categories... this is going to be painful.
1433 // We now need to fetch up to $limit courses for each category to
1434 // be displayed.
1435 if ($categoryids !== null) {
1436 if (!is_array($categoryids)) {
1437 $categoryids = array($categoryids);
1439 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1440 $categorywhere = 'WHERE cc.id '.$categorywhere;
1441 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1442 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1443 $categoryparams = array();
1444 } else {
1445 $categorywhere = '';
1446 $categoryparams = array();
1449 // First up we are going to get the categories that we are going to
1450 // need so that we can determine how best to load the courses from them.
1451 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1452 FROM {course_categories} cc
1453 LEFT JOIN {course} c ON c.category = cc.id
1454 {$categorywhere}
1455 GROUP BY cc.id";
1456 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1457 $fullfetch = array();
1458 $partfetch = array();
1459 foreach ($categories as $category) {
1460 if (!$this->can_add_more_courses_to_category($category->id)) {
1461 continue;
1463 if ($category->coursecount > $limit * 5) {
1464 $partfetch[] = $category->id;
1465 } else if ($category->coursecount > 0) {
1466 $fullfetch[] = $category->id;
1469 $categories->close();
1471 if (count($fullfetch)) {
1472 // First up fetch all of the courses in categories where we know that we are going to
1473 // need the majority of courses.
1474 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1475 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1476 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1477 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1478 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1479 FROM {course} c
1480 $ccjoin
1481 WHERE c.category {$categoryids}
1482 ORDER BY c.sortorder ASC";
1483 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1484 foreach ($coursesrs as $course) {
1485 if ($course->id == $SITE->id) {
1486 // This should not be necessary, frontpage is not in any category.
1487 continue;
1489 if (array_key_exists($course->id, $this->addedcourses)) {
1490 // It is probably better to not include the already loaded courses
1491 // directly in SQL because inequalities may confuse query optimisers
1492 // and may interfere with query caching.
1493 continue;
1495 if (!$this->can_add_more_courses_to_category($course->category)) {
1496 continue;
1498 context_helper::preload_from_record($course);
1499 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1500 continue;
1502 $coursenodes[$course->id] = $this->add_course($course);
1504 $coursesrs->close();
1507 if (count($partfetch)) {
1508 // Next we will work our way through the categories where we will likely only need a small
1509 // proportion of the courses.
1510 foreach ($partfetch as $categoryid) {
1511 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1512 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1513 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1514 FROM {course} c
1515 $ccjoin
1516 WHERE c.category = :categoryid
1517 ORDER BY c.sortorder ASC";
1518 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1519 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1520 foreach ($coursesrs as $course) {
1521 if ($course->id == $SITE->id) {
1522 // This should not be necessary, frontpage is not in any category.
1523 continue;
1525 if (array_key_exists($course->id, $this->addedcourses)) {
1526 // It is probably better to not include the already loaded courses
1527 // directly in SQL because inequalities may confuse query optimisers
1528 // and may interfere with query caching.
1529 // This also helps to respect expected $limit on repeated executions.
1530 continue;
1532 if (!$this->can_add_more_courses_to_category($course->category)) {
1533 break;
1535 context_helper::preload_from_record($course);
1536 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1537 continue;
1539 $coursenodes[$course->id] = $this->add_course($course);
1541 $coursesrs->close();
1544 } else {
1545 // Prepare the SQL to load the courses and their contexts
1546 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1547 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1548 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1549 $courseparams['contextlevel'] = CONTEXT_COURSE;
1550 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1551 FROM {course} c
1552 $ccjoin
1553 WHERE c.id {$courseids}
1554 ORDER BY c.sortorder ASC";
1555 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1556 foreach ($coursesrs as $course) {
1557 if ($course->id == $SITE->id) {
1558 // frotpage is not wanted here
1559 continue;
1561 if ($this->page->course && ($this->page->course->id == $course->id)) {
1562 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1563 continue;
1565 context_helper::preload_from_record($course);
1566 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1567 continue;
1569 $coursenodes[$course->id] = $this->add_course($course);
1570 if (count($coursenodes) >= $limit) {
1571 break;
1574 $coursesrs->close();
1577 return $coursenodes;
1581 * Returns true if more courses can be added to the provided category.
1583 * @param int|navigation_node|stdClass $category
1584 * @return bool
1586 protected function can_add_more_courses_to_category($category) {
1587 global $CFG;
1588 $limit = 20;
1589 if (!empty($CFG->navcourselimit)) {
1590 $limit = (int)$CFG->navcourselimit;
1592 if (is_numeric($category)) {
1593 if (!array_key_exists($category, $this->addedcategories)) {
1594 return true;
1596 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1597 } else if ($category instanceof navigation_node) {
1598 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1599 return false;
1601 $coursecount = count($category->children->type(self::TYPE_COURSE));
1602 } else if (is_object($category) && property_exists($category,'id')) {
1603 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1605 return ($coursecount <= $limit);
1609 * Loads all categories (top level or if an id is specified for that category)
1611 * @param int $categoryid The category id to load or null/0 to load all base level categories
1612 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1613 * as the requested category and any parent categories.
1614 * @return navigation_node|void returns a navigation node if a category has been loaded.
1616 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1617 global $CFG, $DB;
1619 // Check if this category has already been loaded
1620 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1621 return true;
1624 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1625 $sqlselect = "SELECT cc.*, $catcontextsql
1626 FROM {course_categories} cc
1627 JOIN {context} ctx ON cc.id = ctx.instanceid";
1628 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1629 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1630 $params = array();
1632 $categoriestoload = array();
1633 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1634 // We are going to load all categories regardless... prepare to fire
1635 // on the database server!
1636 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1637 // We are going to load all of the first level categories (categories without parents)
1638 $sqlwhere .= " AND cc.parent = 0";
1639 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1640 // The category itself has been loaded already so we just need to ensure its subcategories
1641 // have been loaded
1642 $addedcategories = $this->addedcategories;
1643 unset($addedcategories[$categoryid]);
1644 if (count($addedcategories) > 0) {
1645 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1646 if ($showbasecategories) {
1647 // We need to include categories with parent = 0 as well
1648 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1649 } else {
1650 // All we need is categories that match the parent
1651 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1654 $params['categoryid'] = $categoryid;
1655 } else {
1656 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1657 // and load this category plus all its parents and subcategories
1658 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1659 $categoriestoload = explode('/', trim($category->path, '/'));
1660 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1661 // We are going to use select twice so double the params
1662 $params = array_merge($params, $params);
1663 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1664 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1667 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1668 $categories = array();
1669 foreach ($categoriesrs as $category) {
1670 // Preload the context.. we'll need it when adding the category in order
1671 // to format the category name.
1672 context_helper::preload_from_record($category);
1673 if (array_key_exists($category->id, $this->addedcategories)) {
1674 // Do nothing, its already been added.
1675 } else if ($category->parent == '0') {
1676 // This is a root category lets add it immediately
1677 $this->add_category($category, $this->rootnodes['courses']);
1678 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1679 // This categories parent has already been added we can add this immediately
1680 $this->add_category($category, $this->addedcategories[$category->parent]);
1681 } else {
1682 $categories[] = $category;
1685 $categoriesrs->close();
1687 // Now we have an array of categories we need to add them to the navigation.
1688 while (!empty($categories)) {
1689 $category = reset($categories);
1690 if (array_key_exists($category->id, $this->addedcategories)) {
1691 // Do nothing
1692 } else if ($category->parent == '0') {
1693 $this->add_category($category, $this->rootnodes['courses']);
1694 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1695 $this->add_category($category, $this->addedcategories[$category->parent]);
1696 } else {
1697 // This category isn't in the navigation and niether is it's parent (yet).
1698 // We need to go through the category path and add all of its components in order.
1699 $path = explode('/', trim($category->path, '/'));
1700 foreach ($path as $catid) {
1701 if (!array_key_exists($catid, $this->addedcategories)) {
1702 // This category isn't in the navigation yet so add it.
1703 $subcategory = $categories[$catid];
1704 if ($subcategory->parent == '0') {
1705 // Yay we have a root category - this likely means we will now be able
1706 // to add categories without problems.
1707 $this->add_category($subcategory, $this->rootnodes['courses']);
1708 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1709 // The parent is in the category (as we'd expect) so add it now.
1710 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1711 // Remove the category from the categories array.
1712 unset($categories[$catid]);
1713 } else {
1714 // We should never ever arrive here - if we have then there is a bigger
1715 // problem at hand.
1716 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1721 // Remove the category from the categories array now that we know it has been added.
1722 unset($categories[$category->id]);
1724 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1725 $this->allcategoriesloaded = true;
1727 // Check if there are any categories to load.
1728 if (count($categoriestoload) > 0) {
1729 $readytoloadcourses = array();
1730 foreach ($categoriestoload as $category) {
1731 if ($this->can_add_more_courses_to_category($category)) {
1732 $readytoloadcourses[] = $category;
1735 if (count($readytoloadcourses)) {
1736 $this->load_all_courses($readytoloadcourses);
1740 // Look for all categories which have been loaded
1741 if (!empty($this->addedcategories)) {
1742 $categoryids = array();
1743 foreach ($this->addedcategories as $category) {
1744 if ($this->can_add_more_courses_to_category($category)) {
1745 $categoryids[] = $category->key;
1748 if ($categoryids) {
1749 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1750 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1751 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1752 FROM {course_categories} cc
1753 JOIN {course} c ON c.category = cc.id
1754 WHERE cc.id {$categoriessql}
1755 GROUP BY cc.id
1756 HAVING COUNT(c.id) > :limit";
1757 $excessivecategories = $DB->get_records_sql($sql, $params);
1758 foreach ($categories as &$category) {
1759 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1760 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1761 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1769 * Adds a structured category to the navigation in the correct order/place
1771 * @param stdClass $category category to be added in navigation.
1772 * @param navigation_node $parent parent navigation node
1773 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1774 * @return void.
1776 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1777 if (array_key_exists($category->id, $this->addedcategories)) {
1778 return;
1780 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1781 $context = context_coursecat::instance($category->id);
1782 $categoryname = format_string($category->name, true, array('context' => $context));
1783 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1784 if (empty($category->visible)) {
1785 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1786 $categorynode->hidden = true;
1787 } else {
1788 $categorynode->display = false;
1791 $this->addedcategories[$category->id] = $categorynode;
1795 * Loads the given course into the navigation
1797 * @param stdClass $course
1798 * @return navigation_node
1800 protected function load_course(stdClass $course) {
1801 global $SITE;
1802 if ($course->id == $SITE->id) {
1803 // This is always loaded during initialisation
1804 return $this->rootnodes['site'];
1805 } else if (array_key_exists($course->id, $this->addedcourses)) {
1806 // The course has already been loaded so return a reference
1807 return $this->addedcourses[$course->id];
1808 } else {
1809 // Add the course
1810 return $this->add_course($course);
1815 * Loads all of the courses section into the navigation.
1817 * This function calls method from current course format, see
1818 * {@link format_base::extend_course_navigation()}
1819 * If course module ($cm) is specified but course format failed to create the node,
1820 * the activity node is created anyway.
1822 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1824 * @param stdClass $course Database record for the course
1825 * @param navigation_node $coursenode The course node within the navigation
1826 * @param null|int $sectionnum If specified load the contents of section with this relative number
1827 * @param null|cm_info $cm If specified make sure that activity node is created (either
1828 * in containg section or by calling load_stealth_activity() )
1830 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1831 global $CFG, $SITE;
1832 require_once($CFG->dirroot.'/course/lib.php');
1833 if (isset($cm->sectionnum)) {
1834 $sectionnum = $cm->sectionnum;
1836 if ($sectionnum !== null) {
1837 $this->includesectionnum = $sectionnum;
1839 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1840 if (isset($cm->id)) {
1841 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1842 if (empty($activity)) {
1843 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1849 * Generates an array of sections and an array of activities for the given course.
1851 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1853 * @param stdClass $course
1854 * @return array Array($sections, $activities)
1856 protected function generate_sections_and_activities(stdClass $course) {
1857 global $CFG;
1858 require_once($CFG->dirroot.'/course/lib.php');
1860 $modinfo = get_fast_modinfo($course);
1861 $sections = $modinfo->get_section_info_all();
1863 // For course formats using 'numsections' trim the sections list
1864 $courseformatoptions = course_get_format($course)->get_format_options();
1865 if (isset($courseformatoptions['numsections'])) {
1866 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1869 $activities = array();
1871 foreach ($sections as $key => $section) {
1872 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1873 $sections[$key] = clone($section);
1874 unset($sections[$key]->summary);
1875 $sections[$key]->hasactivites = false;
1876 if (!array_key_exists($section->section, $modinfo->sections)) {
1877 continue;
1879 foreach ($modinfo->sections[$section->section] as $cmid) {
1880 $cm = $modinfo->cms[$cmid];
1881 $activity = new stdClass;
1882 $activity->id = $cm->id;
1883 $activity->course = $course->id;
1884 $activity->section = $section->section;
1885 $activity->name = $cm->name;
1886 $activity->icon = $cm->icon;
1887 $activity->iconcomponent = $cm->iconcomponent;
1888 $activity->hidden = (!$cm->visible);
1889 $activity->modname = $cm->modname;
1890 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1891 $activity->onclick = $cm->onclick;
1892 $url = $cm->url;
1893 if (!$url) {
1894 $activity->url = null;
1895 $activity->display = false;
1896 } else {
1897 $activity->url = $url->out();
1898 $activity->display = $cm->uservisible ? true : false;
1899 if (self::module_extends_navigation($cm->modname)) {
1900 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1903 $activities[$cmid] = $activity;
1904 if ($activity->display) {
1905 $sections[$key]->hasactivites = true;
1910 return array($sections, $activities);
1914 * Generically loads the course sections into the course's navigation.
1916 * @param stdClass $course
1917 * @param navigation_node $coursenode
1918 * @return array An array of course section nodes
1920 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1921 global $CFG, $DB, $USER, $SITE;
1922 require_once($CFG->dirroot.'/course/lib.php');
1924 list($sections, $activities) = $this->generate_sections_and_activities($course);
1926 $navigationsections = array();
1927 foreach ($sections as $sectionid => $section) {
1928 $section = clone($section);
1929 if ($course->id == $SITE->id) {
1930 $this->load_section_activities($coursenode, $section->section, $activities);
1931 } else {
1932 if (!$section->uservisible || (!$this->showemptysections &&
1933 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1934 continue;
1937 $sectionname = get_section_name($course, $section);
1938 $url = course_get_url($course, $section->section, array('navigation' => true));
1940 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1941 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1942 $sectionnode->hidden = (!$section->visible || !$section->available);
1943 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1944 $this->load_section_activities($sectionnode, $section->section, $activities);
1946 $section->sectionnode = $sectionnode;
1947 $navigationsections[$sectionid] = $section;
1950 return $navigationsections;
1954 * Loads all of the activities for a section into the navigation structure.
1956 * @param navigation_node $sectionnode
1957 * @param int $sectionnumber
1958 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1959 * @param stdClass $course The course object the section and activities relate to.
1960 * @return array Array of activity nodes
1962 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1963 global $CFG, $SITE;
1964 // A static counter for JS function naming
1965 static $legacyonclickcounter = 0;
1967 $activitynodes = array();
1968 if (empty($activities)) {
1969 return $activitynodes;
1972 if (!is_object($course)) {
1973 $activity = reset($activities);
1974 $courseid = $activity->course;
1975 } else {
1976 $courseid = $course->id;
1978 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1980 foreach ($activities as $activity) {
1981 if ($activity->section != $sectionnumber) {
1982 continue;
1984 if ($activity->icon) {
1985 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1986 } else {
1987 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1990 // Prepare the default name and url for the node
1991 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1992 $action = new moodle_url($activity->url);
1994 // Check if the onclick property is set (puke!)
1995 if (!empty($activity->onclick)) {
1996 // Increment the counter so that we have a unique number.
1997 $legacyonclickcounter++;
1998 // Generate the function name we will use
1999 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2000 $propogrationhandler = '';
2001 // Check if we need to cancel propogation. Remember inline onclick
2002 // events would return false if they wanted to prevent propogation and the
2003 // default action.
2004 if (strpos($activity->onclick, 'return false')) {
2005 $propogrationhandler = 'e.halt();';
2007 // Decode the onclick - it has already been encoded for display (puke)
2008 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2009 // Build the JS function the click event will call
2010 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2011 $this->page->requires->js_init_code($jscode);
2012 // Override the default url with the new action link
2013 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2016 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2017 $activitynode->title(get_string('modulename', $activity->modname));
2018 $activitynode->hidden = $activity->hidden;
2019 $activitynode->display = $showactivities && $activity->display;
2020 $activitynode->nodetype = $activity->nodetype;
2021 $activitynodes[$activity->id] = $activitynode;
2024 return $activitynodes;
2027 * Loads a stealth module from unavailable section
2028 * @param navigation_node $coursenode
2029 * @param stdClass $modinfo
2030 * @return navigation_node or null if not accessible
2032 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2033 if (empty($modinfo->cms[$this->page->cm->id])) {
2034 return null;
2036 $cm = $modinfo->cms[$this->page->cm->id];
2037 if ($cm->icon) {
2038 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2039 } else {
2040 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2042 $url = $cm->url;
2043 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2044 $activitynode->title(get_string('modulename', $cm->modname));
2045 $activitynode->hidden = (!$cm->visible);
2046 if (!$cm->uservisible) {
2047 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2048 // Also there may be no exception at all in case when teacher is logged in as student.
2049 $activitynode->display = false;
2050 } else if (!$url) {
2051 // Don't show activities that don't have links!
2052 $activitynode->display = false;
2053 } else if (self::module_extends_navigation($cm->modname)) {
2054 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2056 return $activitynode;
2059 * Loads the navigation structure for the given activity into the activities node.
2061 * This method utilises a callback within the modules lib.php file to load the
2062 * content specific to activity given.
2064 * The callback is a method: {modulename}_extend_navigation()
2065 * Examples:
2066 * * {@link forum_extend_navigation()}
2067 * * {@link workshop_extend_navigation()}
2069 * @param cm_info|stdClass $cm
2070 * @param stdClass $course
2071 * @param navigation_node $activity
2072 * @return bool
2074 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2075 global $CFG, $DB;
2077 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2078 if (!($cm instanceof cm_info)) {
2079 $modinfo = get_fast_modinfo($course);
2080 $cm = $modinfo->get_cm($cm->id);
2082 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2083 $activity->make_active();
2084 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2085 $function = $cm->modname.'_extend_navigation';
2087 if (file_exists($file)) {
2088 require_once($file);
2089 if (function_exists($function)) {
2090 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2091 $function($activity, $course, $activtyrecord, $cm);
2095 // Allow the active advanced grading method plugin to append module navigation
2096 $featuresfunc = $cm->modname.'_supports';
2097 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2098 require_once($CFG->dirroot.'/grade/grading/lib.php');
2099 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2100 $gradingman->extend_navigation($this, $activity);
2103 return $activity->has_children();
2106 * Loads user specific information into the navigation in the appropriate place.
2108 * If no user is provided the current user is assumed.
2110 * @param stdClass $user
2111 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2112 * @return bool
2114 protected function load_for_user($user=null, $forceforcontext=false) {
2115 global $DB, $CFG, $USER, $SITE;
2117 if ($user === null) {
2118 // We can't require login here but if the user isn't logged in we don't
2119 // want to show anything
2120 if (!isloggedin() || isguestuser()) {
2121 return false;
2123 $user = $USER;
2124 } else if (!is_object($user)) {
2125 // If the user is not an object then get them from the database
2126 $select = context_helper::get_preload_record_columns_sql('ctx');
2127 $sql = "SELECT u.*, $select
2128 FROM {user} u
2129 JOIN {context} ctx ON u.id = ctx.instanceid
2130 WHERE u.id = :userid AND
2131 ctx.contextlevel = :contextlevel";
2132 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2133 context_helper::preload_from_record($user);
2136 $iscurrentuser = ($user->id == $USER->id);
2138 $usercontext = context_user::instance($user->id);
2140 // Get the course set against the page, by default this will be the site
2141 $course = $this->page->course;
2142 $baseargs = array('id'=>$user->id);
2143 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2144 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2145 $baseargs['course'] = $course->id;
2146 $coursecontext = context_course::instance($course->id);
2147 $issitecourse = false;
2148 } else {
2149 // Load all categories and get the context for the system
2150 $coursecontext = context_system::instance();
2151 $issitecourse = true;
2154 // Create a node to add user information under.
2155 $usersnode = null;
2156 if (!$issitecourse) {
2157 // Not the current user so add it to the participants node for the current course.
2158 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2159 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2160 } else if ($USER->id != $user->id) {
2161 // This is the site so add a users node to the root branch.
2162 $usersnode = $this->rootnodes['users'];
2163 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2164 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2166 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2168 if (!$usersnode) {
2169 // We should NEVER get here, if the course hasn't been populated
2170 // with a participants node then the navigaiton either wasn't generated
2171 // for it (you are missing a require_login or set_context call) or
2172 // you don't have access.... in the interests of no leaking informatin
2173 // we simply quit...
2174 return false;
2176 // Add a branch for the current user.
2177 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2178 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2179 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2180 $usernode->make_active();
2183 // Add user information to the participants or user node.
2184 if ($issitecourse) {
2186 // If the user is the current user or has permission to view the details of the requested
2187 // user than add a view profile link.
2188 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2189 has_capability('moodle/user:viewdetails', $usercontext)) {
2190 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2191 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2192 } else {
2193 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2197 if (!empty($CFG->navadduserpostslinks)) {
2198 // Add nodes for forum posts and discussions if the user can view either or both
2199 // There are no capability checks here as the content of the page is based
2200 // purely on the forums the current user has access too.
2201 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2202 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2203 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2204 array_merge($baseargs, array('mode' => 'discussions'))));
2207 // Add blog nodes.
2208 if (!empty($CFG->enableblogs)) {
2209 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2210 require_once($CFG->dirroot.'/blog/lib.php');
2211 // Get all options for the user.
2212 $options = blog_get_options_for_user($user);
2213 $this->cache->set('userblogoptions'.$user->id, $options);
2214 } else {
2215 $options = $this->cache->{'userblogoptions'.$user->id};
2218 if (count($options) > 0) {
2219 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2220 foreach ($options as $type => $option) {
2221 if ($type == "rss") {
2222 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2223 new pix_icon('i/rss', ''));
2224 } else {
2225 $blogs->add($option['string'], $option['link']);
2231 // Add the messages link.
2232 // It is context based so can appear in the user's profile and in course participants information.
2233 if (!empty($CFG->messaging)) {
2234 $messageargs = array('user1' => $USER->id);
2235 if ($USER->id != $user->id) {
2236 $messageargs['user2'] = $user->id;
2238 if ($course->id != $SITE->id) {
2239 $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
2241 $url = new moodle_url('/message/index.php', $messageargs);
2242 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2245 // Add the "My private files" link.
2246 // This link doesn't have a unique display for course context so only display it under the user's profile.
2247 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2248 $url = new moodle_url('/user/files.php');
2249 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
2252 // Add a node to view the users notes if permitted.
2253 if (!empty($CFG->enablenotes) &&
2254 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2255 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2256 if ($coursecontext->instanceid != SITEID) {
2257 $url->param('course', $coursecontext->instanceid);
2259 $usernode->add(get_string('notes', 'notes'), $url);
2262 // Show the grades node.
2263 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2264 require_once($CFG->dirroot . '/user/lib.php');
2265 // Set the grades node to link to the "Grades" page.
2266 if ($course->id == SITEID) {
2267 $url = user_mygrades_url($user->id, $course->id);
2268 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2269 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2271 if ($USER->id != $user->id) {
2272 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2273 } else {
2274 $usernode->add(get_string('grades', 'grades'), $url);
2278 // If the user is the current user add the repositories for the current user.
2279 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2280 if (!$iscurrentuser &&
2281 $course->id == $SITE->id &&
2282 has_capability('moodle/user:viewdetails', $usercontext) &&
2283 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2285 // Add view grade report is permitted.
2286 $reports = core_component::get_plugin_list('gradereport');
2287 arsort($reports); // User is last, we want to test it first.
2289 $userscourses = enrol_get_users_courses($user->id);
2290 $userscoursesnode = $usernode->add(get_string('courses'));
2292 $count = 0;
2293 foreach ($userscourses as $usercourse) {
2294 if ($count === (int)$CFG->navcourselimit) {
2295 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2296 $userscoursesnode->add(get_string('showallcourses'), $url);
2297 break;
2299 $count++;
2300 $usercoursecontext = context_course::instance($usercourse->id);
2301 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2302 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2303 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2305 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2306 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2307 foreach ($reports as $plugin => $plugindir) {
2308 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2309 // Stop when the first visible plugin is found.
2310 $gradeavailable = true;
2311 break;
2316 if ($gradeavailable) {
2317 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2318 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2319 new pix_icon('i/grades', ''));
2322 // Add a node to view the users notes if permitted.
2323 if (!empty($CFG->enablenotes) &&
2324 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2325 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2326 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2329 if (can_access_course($usercourse, $user->id, '', true)) {
2330 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2331 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2334 $reporttab = $usercoursenode->add(get_string('activityreports'));
2336 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2337 foreach ($reports as $reportfunction) {
2338 $reportfunction($reporttab, $user, $usercourse);
2341 $reporttab->trim_if_empty();
2346 return true;
2350 * This method simply checks to see if a given module can extend the navigation.
2352 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2354 * @param string $modname
2355 * @return bool
2357 public static function module_extends_navigation($modname) {
2358 global $CFG;
2359 static $extendingmodules = array();
2360 if (!array_key_exists($modname, $extendingmodules)) {
2361 $extendingmodules[$modname] = false;
2362 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2363 if (file_exists($file)) {
2364 $function = $modname.'_extend_navigation';
2365 require_once($file);
2366 $extendingmodules[$modname] = (function_exists($function));
2369 return $extendingmodules[$modname];
2372 * Extends the navigation for the given user.
2374 * @param stdClass $user A user from the database
2376 public function extend_for_user($user) {
2377 $this->extendforuser[] = $user;
2381 * Returns all of the users the navigation is being extended for
2383 * @return array An array of extending users.
2385 public function get_extending_users() {
2386 return $this->extendforuser;
2389 * Adds the given course to the navigation structure.
2391 * @param stdClass $course
2392 * @param bool $forcegeneric
2393 * @param bool $ismycourse
2394 * @return navigation_node
2396 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2397 global $CFG, $SITE;
2399 // We found the course... we can return it now :)
2400 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2401 return $this->addedcourses[$course->id];
2404 $coursecontext = context_course::instance($course->id);
2406 if ($course->id != $SITE->id && !$course->visible) {
2407 if (is_role_switched($course->id)) {
2408 // user has to be able to access course in order to switch, let's skip the visibility test here
2409 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2410 return false;
2414 $issite = ($course->id == $SITE->id);
2415 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2416 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2417 // This is the name that will be shown for the course.
2418 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2420 // Can the user expand the course to see its content.
2421 $canexpandcourse = true;
2422 if ($issite) {
2423 $parent = $this;
2424 $url = null;
2425 if (empty($CFG->usesitenameforsitepages)) {
2426 $coursename = get_string('sitepages');
2428 } else if ($coursetype == self::COURSE_CURRENT) {
2429 $parent = $this->rootnodes['currentcourse'];
2430 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2431 $canexpandcourse = $this->can_expand_course($course);
2432 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2433 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2434 // Nothing to do here the above statement set $parent to the category within mycourses.
2435 } else {
2436 $parent = $this->rootnodes['mycourses'];
2438 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2439 } else {
2440 $parent = $this->rootnodes['courses'];
2441 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2442 // They can only expand the course if they can access it.
2443 $canexpandcourse = $this->can_expand_course($course);
2444 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2445 if (!$this->is_category_fully_loaded($course->category)) {
2446 // We need to load the category structure for this course
2447 $this->load_all_categories($course->category, false);
2449 if (array_key_exists($course->category, $this->addedcategories)) {
2450 $parent = $this->addedcategories[$course->category];
2451 // This could lead to the course being created so we should check whether it is the case again
2452 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2453 return $this->addedcourses[$course->id];
2459 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2460 $coursenode->hidden = (!$course->visible);
2461 // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
2462 // later.
2463 $coursenode->title(str_replace('&amp;', '&', $fullname));
2464 if ($canexpandcourse) {
2465 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2466 $coursenode->nodetype = self::NODETYPE_BRANCH;
2467 $coursenode->isexpandable = true;
2468 } else {
2469 $coursenode->nodetype = self::NODETYPE_LEAF;
2470 $coursenode->isexpandable = false;
2472 if (!$forcegeneric) {
2473 $this->addedcourses[$course->id] = $coursenode;
2476 return $coursenode;
2480 * Returns a cache instance to use for the expand course cache.
2481 * @return cache_session
2483 protected function get_expand_course_cache() {
2484 if ($this->cacheexpandcourse === null) {
2485 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2487 return $this->cacheexpandcourse;
2491 * Checks if a user can expand a course in the navigation.
2493 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2494 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2495 * permits stale data.
2496 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2497 * will be stale.
2498 * It is brought up to date in only one of two ways.
2499 * 1. The user logs out and in again.
2500 * 2. The user browses to the course they've just being given access to.
2502 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2504 * @param stdClass $course
2505 * @return bool
2507 protected function can_expand_course($course) {
2508 $cache = $this->get_expand_course_cache();
2509 $canexpand = $cache->get($course->id);
2510 if ($canexpand === false) {
2511 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2512 $canexpand = (int)$canexpand;
2513 $cache->set($course->id, $canexpand);
2515 return ($canexpand === 1);
2519 * Returns true if the category has already been loaded as have any child categories
2521 * @param int $categoryid
2522 * @return bool
2524 protected function is_category_fully_loaded($categoryid) {
2525 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2529 * Adds essential course nodes to the navigation for the given course.
2531 * This method adds nodes such as reports, blogs and participants
2533 * @param navigation_node $coursenode
2534 * @param stdClass $course
2535 * @return bool returns true on successful addition of a node.
2537 public function add_course_essentials($coursenode, stdClass $course) {
2538 global $CFG, $SITE;
2540 if ($course->id == $SITE->id) {
2541 return $this->add_front_page_course_essentials($coursenode, $course);
2544 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2545 return true;
2548 //Participants
2549 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2550 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2551 if (!empty($CFG->enableblogs)) {
2552 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2553 and has_capability('moodle/blog:view', context_system::instance())) {
2554 $blogsurls = new moodle_url('/blog/index.php');
2555 if ($currentgroup = groups_get_course_group($course, true)) {
2556 $blogsurls->param('groupid', $currentgroup);
2557 } else {
2558 $blogsurls->param('courseid', $course->id);
2560 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2563 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2564 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2566 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2567 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2570 // Badges.
2571 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2572 has_capability('moodle/badges:viewbadges', $this->page->context)) {
2573 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2575 $coursenode->add(get_string('coursebadges', 'badges'), null,
2576 navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2577 $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2578 navigation_node::TYPE_SETTING, null, 'badgesview',
2579 new pix_icon('i/badge', get_string('badgesview', 'badges')));
2582 return true;
2585 * This generates the structure of the course that won't be generated when
2586 * the modules and sections are added.
2588 * Things such as the reports branch, the participants branch, blogs... get
2589 * added to the course node by this method.
2591 * @param navigation_node $coursenode
2592 * @param stdClass $course
2593 * @return bool True for successfull generation
2595 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2596 global $CFG;
2598 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2599 return true;
2602 $sitecontext = context_system::instance();
2604 // Hidden node that we use to determine if the front page navigation is loaded.
2605 // This required as there are not other guaranteed nodes that may be loaded.
2606 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2608 // Participants.
2609 // If this is the site course, they need to have moodle/site:viewparticipants at the site level.
2610 // If no, then they need to have moodle/course:viewparticipants at the course level.
2611 if ((($course->id == SITEID) && has_capability('moodle/site:viewparticipants', $sitecontext)) ||
2612 has_capability('moodle/course:viewparticipants', context_course::instance($course->id))) {
2613 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2616 // Blogs.
2617 if (!empty($CFG->enableblogs)
2618 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2619 and has_capability('moodle/blog:view', $sitecontext)) {
2620 $blogsurls = new moodle_url('/blog/index.php');
2621 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2624 $filterselect = 0;
2626 // Badges.
2627 if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext)) {
2628 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2629 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2632 // Notes.
2633 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $sitecontext)) {
2634 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2635 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2638 // Tags
2639 if (!empty($CFG->usetags) && isloggedin()) {
2640 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2641 self::TYPE_SETTING, null, 'tags');
2644 if (isloggedin()) {
2645 // Calendar
2646 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2647 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2650 return true;
2654 * Clears the navigation cache
2656 public function clear_cache() {
2657 $this->cache->clear();
2661 * Sets an expansion limit for the navigation
2663 * The expansion limit is used to prevent the display of content that has a type
2664 * greater than the provided $type.
2666 * Can be used to ensure things such as activities or activity content don't get
2667 * shown on the navigation.
2668 * They are still generated in order to ensure the navbar still makes sense.
2670 * @param int $type One of navigation_node::TYPE_*
2671 * @return bool true when complete.
2673 public function set_expansion_limit($type) {
2674 global $SITE;
2675 $nodes = $this->find_all_of_type($type);
2677 // We only want to hide specific types of nodes.
2678 // Only nodes that represent "structure" in the navigation tree should be hidden.
2679 // If we hide all nodes then we risk hiding vital information.
2680 $typestohide = array(
2681 self::TYPE_CATEGORY,
2682 self::TYPE_COURSE,
2683 self::TYPE_SECTION,
2684 self::TYPE_ACTIVITY
2687 foreach ($nodes as $node) {
2688 // We need to generate the full site node
2689 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2690 continue;
2692 foreach ($node->children as $child) {
2693 $child->hide($typestohide);
2696 return true;
2699 * Attempts to get the navigation with the given key from this nodes children.
2701 * This function only looks at this nodes children, it does NOT look recursivily.
2702 * If the node can't be found then false is returned.
2704 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2706 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2707 * may be of more use to you.
2709 * @param string|int $key The key of the node you wish to receive.
2710 * @param int $type One of navigation_node::TYPE_*
2711 * @return navigation_node|false
2713 public function get($key, $type = null) {
2714 if (!$this->initialised) {
2715 $this->initialise();
2717 return parent::get($key, $type);
2721 * Searches this nodes children and their children to find a navigation node
2722 * with the matching key and type.
2724 * This method is recursive and searches children so until either a node is
2725 * found or there are no more nodes to search.
2727 * If you know that the node being searched for is a child of this node
2728 * then use the {@link global_navigation::get()} method instead.
2730 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2731 * may be of more use to you.
2733 * @param string|int $key The key of the node you wish to receive.
2734 * @param int $type One of navigation_node::TYPE_*
2735 * @return navigation_node|false
2737 public function find($key, $type) {
2738 if (!$this->initialised) {
2739 $this->initialise();
2741 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2742 return $this->rootnodes[$key];
2744 return parent::find($key, $type);
2748 * They've expanded the 'my courses' branch.
2750 protected function load_courses_enrolled() {
2751 global $CFG, $DB;
2752 $sortorder = 'visible DESC';
2753 // Prevent undefined $CFG->navsortmycoursessort errors.
2754 if (empty($CFG->navsortmycoursessort)) {
2755 $CFG->navsortmycoursessort = 'sortorder';
2757 // Append the chosen sortorder.
2758 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2759 $courses = enrol_get_my_courses(null, $sortorder);
2760 if (count($courses) && $this->show_my_categories()) {
2761 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2762 // In order to make sure we load everything required we must first find the categories that are not
2763 // base categories and work out the bottom category in thier path.
2764 $categoryids = array();
2765 foreach ($courses as $course) {
2766 $categoryids[] = $course->category;
2768 $categoryids = array_unique($categoryids);
2769 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2770 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2771 foreach ($categories as $category) {
2772 $bits = explode('/', trim($category->path,'/'));
2773 $categoryids[] = array_shift($bits);
2775 $categoryids = array_unique($categoryids);
2776 $categories->close();
2778 // Now we load the base categories.
2779 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2780 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2781 foreach ($categories as $category) {
2782 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2784 $categories->close();
2785 } else {
2786 foreach ($courses as $course) {
2787 $this->add_course($course, false, self::COURSE_MY);
2794 * The global navigation class used especially for AJAX requests.
2796 * The primary methods that are used in the global navigation class have been overriden
2797 * to ensure that only the relevant branch is generated at the root of the tree.
2798 * This can be done because AJAX is only used when the backwards structure for the
2799 * requested branch exists.
2800 * This has been done only because it shortens the amounts of information that is generated
2801 * which of course will speed up the response time.. because no one likes laggy AJAX.
2803 * @package core
2804 * @category navigation
2805 * @copyright 2009 Sam Hemelryk
2806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2808 class global_navigation_for_ajax extends global_navigation {
2810 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2811 protected $branchtype;
2813 /** @var int the instance id */
2814 protected $instanceid;
2816 /** @var array Holds an array of expandable nodes */
2817 protected $expandable = array();
2820 * Constructs the navigation for use in an AJAX request
2822 * @param moodle_page $page moodle_page object
2823 * @param int $branchtype
2824 * @param int $id
2826 public function __construct($page, $branchtype, $id) {
2827 $this->page = $page;
2828 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2829 $this->children = new navigation_node_collection();
2830 $this->branchtype = $branchtype;
2831 $this->instanceid = $id;
2832 $this->initialise();
2835 * Initialise the navigation given the type and id for the branch to expand.
2837 * @return array An array of the expandable nodes
2839 public function initialise() {
2840 global $DB, $SITE;
2842 if ($this->initialised || during_initial_install()) {
2843 return $this->expandable;
2845 $this->initialised = true;
2847 $this->rootnodes = array();
2848 $this->rootnodes['site'] = $this->add_course($SITE);
2849 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2850 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2851 // The courses branch is always displayed, and is always expandable (although may be empty).
2852 // This mimicks what is done during {@link global_navigation::initialise()}.
2853 $this->rootnodes['courses']->isexpandable = true;
2855 // Branchtype will be one of navigation_node::TYPE_*
2856 switch ($this->branchtype) {
2857 case 0:
2858 if ($this->instanceid === 'mycourses') {
2859 $this->load_courses_enrolled();
2860 } else if ($this->instanceid === 'courses') {
2861 $this->load_courses_other();
2863 break;
2864 case self::TYPE_CATEGORY :
2865 $this->load_category($this->instanceid);
2866 break;
2867 case self::TYPE_MY_CATEGORY :
2868 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2869 break;
2870 case self::TYPE_COURSE :
2871 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2872 if (!can_access_course($course, null, '', true)) {
2873 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
2874 // add the course node and break. This leads to an empty node.
2875 $this->add_course($course);
2876 break;
2878 require_course_login($course, true, null, false, true);
2879 $this->page->set_context(context_course::instance($course->id));
2880 $coursenode = $this->add_course($course);
2881 $this->add_course_essentials($coursenode, $course);
2882 $this->load_course_sections($course, $coursenode);
2883 break;
2884 case self::TYPE_SECTION :
2885 $sql = 'SELECT c.*, cs.section AS sectionnumber
2886 FROM {course} c
2887 LEFT JOIN {course_sections} cs ON cs.course = c.id
2888 WHERE cs.id = ?';
2889 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2890 require_course_login($course, true, null, false, true);
2891 $this->page->set_context(context_course::instance($course->id));
2892 $coursenode = $this->add_course($course);
2893 $this->add_course_essentials($coursenode, $course);
2894 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2895 break;
2896 case self::TYPE_ACTIVITY :
2897 $sql = "SELECT c.*
2898 FROM {course} c
2899 JOIN {course_modules} cm ON cm.course = c.id
2900 WHERE cm.id = :cmid";
2901 $params = array('cmid' => $this->instanceid);
2902 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2903 $modinfo = get_fast_modinfo($course);
2904 $cm = $modinfo->get_cm($this->instanceid);
2905 require_course_login($course, true, $cm, false, true);
2906 $this->page->set_context(context_module::instance($cm->id));
2907 $coursenode = $this->load_course($course);
2908 $this->load_course_sections($course, $coursenode, null, $cm);
2909 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2910 if ($activitynode) {
2911 $modulenode = $this->load_activity($cm, $course, $activitynode);
2913 break;
2914 default:
2915 throw new Exception('Unknown type');
2916 return $this->expandable;
2919 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2920 $this->load_for_user(null, true);
2923 $this->find_expandable($this->expandable);
2924 return $this->expandable;
2928 * They've expanded the general 'courses' branch.
2930 protected function load_courses_other() {
2931 $this->load_all_courses();
2935 * Loads a single category into the AJAX navigation.
2937 * This function is special in that it doesn't concern itself with the parent of
2938 * the requested category or its siblings.
2939 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2940 * request that.
2942 * @global moodle_database $DB
2943 * @param int $categoryid id of category to load in navigation.
2944 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2945 * @return void.
2947 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2948 global $CFG, $DB;
2950 $limit = 20;
2951 if (!empty($CFG->navcourselimit)) {
2952 $limit = (int)$CFG->navcourselimit;
2955 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2956 $sql = "SELECT cc.*, $catcontextsql
2957 FROM {course_categories} cc
2958 JOIN {context} ctx ON cc.id = ctx.instanceid
2959 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2960 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2961 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2962 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2963 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2964 $categorylist = array();
2965 $subcategories = array();
2966 $basecategory = null;
2967 foreach ($categories as $category) {
2968 $categorylist[] = $category->id;
2969 context_helper::preload_from_record($category);
2970 if ($category->id == $categoryid) {
2971 $this->add_category($category, $this, $nodetype);
2972 $basecategory = $this->addedcategories[$category->id];
2973 } else {
2974 $subcategories[$category->id] = $category;
2977 $categories->close();
2980 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2981 // else show all courses.
2982 if ($nodetype === self::TYPE_MY_CATEGORY) {
2983 $courses = enrol_get_my_courses();
2984 $categoryids = array();
2986 // Only search for categories if basecategory was found.
2987 if (!is_null($basecategory)) {
2988 // Get course parent category ids.
2989 foreach ($courses as $course) {
2990 $categoryids[] = $course->category;
2993 // Get a unique list of category ids which a part of the path
2994 // to user's courses.
2995 $coursesubcategories = array();
2996 $addedsubcategories = array();
2998 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2999 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3001 foreach ($categories as $category){
3002 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3004 $coursesubcategories = array_unique($coursesubcategories);
3006 // Only add a subcategory if it is part of the path to user's course and
3007 // wasn't already added.
3008 foreach ($subcategories as $subid => $subcategory) {
3009 if (in_array($subid, $coursesubcategories) &&
3010 !in_array($subid, $addedsubcategories)) {
3011 $this->add_category($subcategory, $basecategory, $nodetype);
3012 $addedsubcategories[] = $subid;
3017 foreach ($courses as $course) {
3018 // Add course if it's in category.
3019 if (in_array($course->category, $categorylist)) {
3020 $this->add_course($course, true, self::COURSE_MY);
3023 } else {
3024 if (!is_null($basecategory)) {
3025 foreach ($subcategories as $key=>$category) {
3026 $this->add_category($category, $basecategory, $nodetype);
3029 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3030 foreach ($courses as $course) {
3031 $this->add_course($course);
3033 $courses->close();
3038 * Returns an array of expandable nodes
3039 * @return array
3041 public function get_expandable() {
3042 return $this->expandable;
3047 * Navbar class
3049 * This class is used to manage the navbar, which is initialised from the navigation
3050 * object held by PAGE
3052 * @package core
3053 * @category navigation
3054 * @copyright 2009 Sam Hemelryk
3055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3057 class navbar extends navigation_node {
3058 /** @var bool A switch for whether the navbar is initialised or not */
3059 protected $initialised = false;
3060 /** @var mixed keys used to reference the nodes on the navbar */
3061 protected $keys = array();
3062 /** @var null|string content of the navbar */
3063 protected $content = null;
3064 /** @var moodle_page object the moodle page that this navbar belongs to */
3065 protected $page;
3066 /** @var bool A switch for whether to ignore the active navigation information */
3067 protected $ignoreactive = false;
3068 /** @var bool A switch to let us know if we are in the middle of an install */
3069 protected $duringinstall = false;
3070 /** @var bool A switch for whether the navbar has items */
3071 protected $hasitems = false;
3072 /** @var array An array of navigation nodes for the navbar */
3073 protected $items;
3074 /** @var array An array of child node objects */
3075 public $children = array();
3076 /** @var bool A switch for whether we want to include the root node in the navbar */
3077 public $includesettingsbase = false;
3078 /** @var navigation_node[] $prependchildren */
3079 protected $prependchildren = array();
3081 * The almighty constructor
3083 * @param moodle_page $page
3085 public function __construct(moodle_page $page) {
3086 global $CFG;
3087 if (during_initial_install()) {
3088 $this->duringinstall = true;
3089 return false;
3091 $this->page = $page;
3092 $this->text = get_string('home');
3093 $this->shorttext = get_string('home');
3094 $this->action = new moodle_url($CFG->wwwroot);
3095 $this->nodetype = self::NODETYPE_BRANCH;
3096 $this->type = self::TYPE_SYSTEM;
3100 * Quick check to see if the navbar will have items in.
3102 * @return bool Returns true if the navbar will have items, false otherwise
3104 public function has_items() {
3105 if ($this->duringinstall) {
3106 return false;
3107 } else if ($this->hasitems !== false) {
3108 return true;
3110 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3111 // There have been manually added items - there are definitely items.
3112 $outcome = true;
3113 } else if (!$this->ignoreactive) {
3114 // We will need to initialise the navigation structure to check if there are active items.
3115 $this->page->navigation->initialise($this->page);
3116 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3118 $this->hasitems = $outcome;
3119 return $outcome;
3123 * Turn on/off ignore active
3125 * @param bool $setting
3127 public function ignore_active($setting=true) {
3128 $this->ignoreactive = ($setting);
3132 * Gets a navigation node
3134 * @param string|int $key for referencing the navbar nodes
3135 * @param int $type navigation_node::TYPE_*
3136 * @return navigation_node|bool
3138 public function get($key, $type = null) {
3139 foreach ($this->children as &$child) {
3140 if ($child->key === $key && ($type == null || $type == $child->type)) {
3141 return $child;
3144 foreach ($this->prependchildren as &$child) {
3145 if ($child->key === $key && ($type == null || $type == $child->type)) {
3146 return $child;
3149 return false;
3152 * Returns an array of navigation_node's that make up the navbar.
3154 * @return array
3156 public function get_items() {
3157 global $CFG;
3158 $items = array();
3159 // Make sure that navigation is initialised
3160 if (!$this->has_items()) {
3161 return $items;
3163 if ($this->items !== null) {
3164 return $this->items;
3167 if (count($this->children) > 0) {
3168 // Add the custom children.
3169 $items = array_reverse($this->children);
3172 // Check if navigation contains the active node
3173 if (!$this->ignoreactive) {
3174 // We will need to ensure the navigation has been initialised.
3175 $this->page->navigation->initialise($this->page);
3176 // Now find the active nodes on both the navigation and settings.
3177 $navigationactivenode = $this->page->navigation->find_active_node();
3178 $settingsactivenode = $this->page->settingsnav->find_active_node();
3180 if ($navigationactivenode && $settingsactivenode) {
3181 // Parse a combined navigation tree
3182 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3183 if (!$settingsactivenode->mainnavonly) {
3184 $items[] = $settingsactivenode;
3186 $settingsactivenode = $settingsactivenode->parent;
3188 if (!$this->includesettingsbase) {
3189 // Removes the first node from the settings (root node) from the list
3190 array_pop($items);
3192 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3193 if (!$navigationactivenode->mainnavonly) {
3194 $items[] = $navigationactivenode;
3196 if (!empty($CFG->navshowcategories) &&
3197 $navigationactivenode->type === self::TYPE_COURSE &&
3198 $navigationactivenode->parent->key === 'currentcourse') {
3199 $items = array_merge($items, $this->get_course_categories());
3201 $navigationactivenode = $navigationactivenode->parent;
3203 } else if ($navigationactivenode) {
3204 // Parse the navigation tree to get the active node
3205 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3206 if (!$navigationactivenode->mainnavonly) {
3207 $items[] = $navigationactivenode;
3209 if (!empty($CFG->navshowcategories) &&
3210 $navigationactivenode->type === self::TYPE_COURSE &&
3211 $navigationactivenode->parent->key === 'currentcourse') {
3212 $items = array_merge($items, $this->get_course_categories());
3214 $navigationactivenode = $navigationactivenode->parent;
3216 } else if ($settingsactivenode) {
3217 // Parse the settings navigation to get the active node
3218 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3219 if (!$settingsactivenode->mainnavonly) {
3220 $items[] = $settingsactivenode;
3222 $settingsactivenode = $settingsactivenode->parent;
3227 $items[] = new navigation_node(array(
3228 'text'=>$this->page->navigation->text,
3229 'shorttext'=>$this->page->navigation->shorttext,
3230 'key'=>$this->page->navigation->key,
3231 'action'=>$this->page->navigation->action
3234 if (count($this->prependchildren) > 0) {
3235 // Add the custom children
3236 $items = array_merge($items, array_reverse($this->prependchildren));
3239 $this->items = array_reverse($items);
3240 return $this->items;
3244 * Get the list of categories leading to this course.
3246 * This function is used by {@link navbar::get_items()} to add back the "courses"
3247 * node and category chain leading to the current course. Note that this is only ever
3248 * called for the current course, so we don't need to bother taking in any parameters.
3250 * @return array
3252 private function get_course_categories() {
3253 global $CFG;
3254 require_once($CFG->dirroot.'/course/lib.php');
3255 require_once($CFG->libdir.'/coursecatlib.php');
3257 $categories = array();
3258 $cap = 'moodle/category:viewhiddencategories';
3259 $showcategories = coursecat::count_all() > 1;
3261 if ($showcategories) {
3262 foreach ($this->page->categories as $category) {
3263 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3264 continue;
3266 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3267 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3268 $categorynode = navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3269 if (!$category->visible) {
3270 $categorynode->hidden = true;
3272 $categories[] = $categorynode;
3276 // Don't show the 'course' node if enrolled in this course.
3277 if (!is_enrolled(context_course::instance($this->page->course->id, null, '', true))) {
3278 $courses = $this->page->navigation->get('courses');
3279 if (!$courses) {
3280 // Courses node may not be present.
3281 $courses = navigation_node::create(
3282 get_string('courses'),
3283 new moodle_url('/course/index.php'),
3284 self::TYPE_CONTAINER
3287 $categories[] = $courses;
3290 return $categories;
3294 * Add a new navigation_node to the navbar, overrides parent::add
3296 * This function overrides {@link navigation_node::add()} so that we can change
3297 * the way nodes get added to allow us to simply call add and have the node added to the
3298 * end of the navbar
3300 * @param string $text
3301 * @param string|moodle_url|action_link $action An action to associate with this node.
3302 * @param int $type One of navigation_node::TYPE_*
3303 * @param string $shorttext
3304 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3305 * @param pix_icon $icon An optional icon to use for this node.
3306 * @return navigation_node
3308 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3309 if ($this->content !== null) {
3310 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3313 // Properties array used when creating the new navigation node
3314 $itemarray = array(
3315 'text' => $text,
3316 'type' => $type
3318 // Set the action if one was provided
3319 if ($action!==null) {
3320 $itemarray['action'] = $action;
3322 // Set the shorttext if one was provided
3323 if ($shorttext!==null) {
3324 $itemarray['shorttext'] = $shorttext;
3326 // Set the icon if one was provided
3327 if ($icon!==null) {
3328 $itemarray['icon'] = $icon;
3330 // Default the key to the number of children if not provided
3331 if ($key === null) {
3332 $key = count($this->children);
3334 // Set the key
3335 $itemarray['key'] = $key;
3336 // Set the parent to this node
3337 $itemarray['parent'] = $this;
3338 // Add the child using the navigation_node_collections add method
3339 $this->children[] = new navigation_node($itemarray);
3340 return $this;
3344 * Prepends a new navigation_node to the start of the navbar
3346 * @param string $text
3347 * @param string|moodle_url|action_link $action An action to associate with this node.
3348 * @param int $type One of navigation_node::TYPE_*
3349 * @param string $shorttext
3350 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3351 * @param pix_icon $icon An optional icon to use for this node.
3352 * @return navigation_node
3354 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3355 if ($this->content !== null) {
3356 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3358 // Properties array used when creating the new navigation node.
3359 $itemarray = array(
3360 'text' => $text,
3361 'type' => $type
3363 // Set the action if one was provided.
3364 if ($action!==null) {
3365 $itemarray['action'] = $action;
3367 // Set the shorttext if one was provided.
3368 if ($shorttext!==null) {
3369 $itemarray['shorttext'] = $shorttext;
3371 // Set the icon if one was provided.
3372 if ($icon!==null) {
3373 $itemarray['icon'] = $icon;
3375 // Default the key to the number of children if not provided.
3376 if ($key === null) {
3377 $key = count($this->children);
3379 // Set the key.
3380 $itemarray['key'] = $key;
3381 // Set the parent to this node.
3382 $itemarray['parent'] = $this;
3383 // Add the child node to the prepend list.
3384 $this->prependchildren[] = new navigation_node($itemarray);
3385 return $this;
3390 * Class used to manage the settings option for the current page
3392 * This class is used to manage the settings options in a tree format (recursively)
3393 * and was created initially for use with the settings blocks.
3395 * @package core
3396 * @category navigation
3397 * @copyright 2009 Sam Hemelryk
3398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3400 class settings_navigation extends navigation_node {
3401 /** @var stdClass the current context */
3402 protected $context;
3403 /** @var moodle_page the moodle page that the navigation belongs to */
3404 protected $page;
3405 /** @var string contains administration section navigation_nodes */
3406 protected $adminsection;
3407 /** @var bool A switch to see if the navigation node is initialised */
3408 protected $initialised = false;
3409 /** @var array An array of users that the nodes can extend for. */
3410 protected $userstoextendfor = array();
3411 /** @var navigation_cache **/
3412 protected $cache;
3415 * Sets up the object with basic settings and preparse it for use
3417 * @param moodle_page $page
3419 public function __construct(moodle_page &$page) {
3420 if (during_initial_install()) {
3421 return false;
3423 $this->page = $page;
3424 // Initialise the main navigation. It is most important that this is done
3425 // before we try anything
3426 $this->page->navigation->initialise();
3427 // Initialise the navigation cache
3428 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3429 $this->children = new navigation_node_collection();
3432 * Initialise the settings navigation based on the current context
3434 * This function initialises the settings navigation tree for a given context
3435 * by calling supporting functions to generate major parts of the tree.
3438 public function initialise() {
3439 global $DB, $SESSION, $SITE;
3441 if (during_initial_install()) {
3442 return false;
3443 } else if ($this->initialised) {
3444 return true;
3446 $this->id = 'settingsnav';
3447 $this->context = $this->page->context;
3449 $context = $this->context;
3450 if ($context->contextlevel == CONTEXT_BLOCK) {
3451 $this->load_block_settings();
3452 $context = $context->get_parent_context();
3454 switch ($context->contextlevel) {
3455 case CONTEXT_SYSTEM:
3456 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3457 $this->load_front_page_settings(($context->id == $this->context->id));
3459 break;
3460 case CONTEXT_COURSECAT:
3461 $this->load_category_settings();
3462 break;
3463 case CONTEXT_COURSE:
3464 if ($this->page->course->id != $SITE->id) {
3465 $this->load_course_settings(($context->id == $this->context->id));
3466 } else {
3467 $this->load_front_page_settings(($context->id == $this->context->id));
3469 break;
3470 case CONTEXT_MODULE:
3471 $this->load_module_settings();
3472 $this->load_course_settings();
3473 break;
3474 case CONTEXT_USER:
3475 if ($this->page->course->id != $SITE->id) {
3476 $this->load_course_settings();
3478 break;
3481 $usersettings = $this->load_user_settings($this->page->course->id);
3483 $adminsettings = false;
3484 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
3485 $isadminpage = $this->is_admin_tree_needed();
3487 if (has_capability('moodle/site:config', context_system::instance())) {
3488 // Make sure this works even if config capability changes on the fly
3489 // and also make it fast for admin right after login.
3490 $SESSION->load_navigation_admin = 1;
3491 if ($isadminpage) {
3492 $adminsettings = $this->load_administration_settings();
3495 } else if (!isset($SESSION->load_navigation_admin)) {
3496 $adminsettings = $this->load_administration_settings();
3497 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
3499 } else if ($SESSION->load_navigation_admin) {
3500 if ($isadminpage) {
3501 $adminsettings = $this->load_administration_settings();
3505 // Print empty navigation node, if needed.
3506 if ($SESSION->load_navigation_admin && !$isadminpage) {
3507 if ($adminsettings) {
3508 // Do not print settings tree on pages that do not need it, this helps with performance.
3509 $adminsettings->remove();
3510 $adminsettings = false;
3512 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin'), self::TYPE_SITE_ADMIN, null, 'siteadministration');
3513 $siteadminnode->id = 'expandable_branch_'.$siteadminnode->type.'_'.clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
3514 $this->page->requires->data_for_js('siteadminexpansion', $siteadminnode);
3518 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
3519 $adminsettings->force_open();
3520 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
3521 $usersettings->force_open();
3524 // Check if the user is currently logged in as another user
3525 if (\core\session\manager::is_loggedinas()) {
3526 // Get the actual user, we need this so we can display an informative return link
3527 $realuser = \core\session\manager::get_realuser();
3528 // Add the informative return to original user link
3529 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3530 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3533 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3534 $this->load_local_plugin_settings();
3536 foreach ($this->children as $key=>$node) {
3537 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3538 // Site administration is shown as link.
3539 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
3540 continue;
3542 $node->remove();
3545 $this->initialised = true;
3548 * Override the parent function so that we can add preceeding hr's and set a
3549 * root node class against all first level element
3551 * It does this by first calling the parent's add method {@link navigation_node::add()}
3552 * and then proceeds to use the key to set class and hr
3554 * @param string $text text to be used for the link.
3555 * @param string|moodle_url $url url for the new node
3556 * @param int $type the type of node navigation_node::TYPE_*
3557 * @param string $shorttext
3558 * @param string|int $key a key to access the node by.
3559 * @param pix_icon $icon An icon that appears next to the node.
3560 * @return navigation_node with the new node added to it.
3562 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3563 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3564 $node->add_class('root_node');
3565 return $node;
3569 * This function allows the user to add something to the start of the settings
3570 * navigation, which means it will be at the top of the settings navigation block
3572 * @param string $text text to be used for the link.
3573 * @param string|moodle_url $url url for the new node
3574 * @param int $type the type of node navigation_node::TYPE_*
3575 * @param string $shorttext
3576 * @param string|int $key a key to access the node by.
3577 * @param pix_icon $icon An icon that appears next to the node.
3578 * @return navigation_node $node with the new node added to it.
3580 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3581 $children = $this->children;
3582 $childrenclass = get_class($children);
3583 $this->children = new $childrenclass;
3584 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3585 foreach ($children as $child) {
3586 $this->children->add($child);
3588 return $node;
3592 * Does this page require loading of full admin tree or is
3593 * it enough rely on AJAX?
3595 * @return bool
3597 protected function is_admin_tree_needed() {
3598 if (self::$loadadmintree) {
3599 // Usually external admin page or settings page.
3600 return true;
3603 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
3604 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
3605 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
3606 return false;
3608 return true;
3611 return false;
3615 * Load the site administration tree
3617 * This function loads the site administration tree by using the lib/adminlib library functions
3619 * @param navigation_node $referencebranch A reference to a branch in the settings
3620 * navigation tree
3621 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3622 * tree and start at the beginning
3623 * @return mixed A key to access the admin tree by
3625 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3626 global $CFG;
3628 // Check if we are just starting to generate this navigation.
3629 if ($referencebranch === null) {
3631 // Require the admin lib then get an admin structure
3632 if (!function_exists('admin_get_root')) {
3633 require_once($CFG->dirroot.'/lib/adminlib.php');
3635 $adminroot = admin_get_root(false, false);
3636 // This is the active section identifier
3637 $this->adminsection = $this->page->url->param('section');
3639 // Disable the navigation from automatically finding the active node
3640 navigation_node::$autofindactive = false;
3641 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SITE_ADMIN, null, 'root');
3642 foreach ($adminroot->children as $adminbranch) {
3643 $this->load_administration_settings($referencebranch, $adminbranch);
3645 navigation_node::$autofindactive = true;
3647 // Use the admin structure to locate the active page
3648 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3649 $currentnode = $this;
3650 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3651 $currentnode = $currentnode->get($pathkey);
3653 if ($currentnode) {
3654 $currentnode->make_active();
3656 } else {
3657 $this->scan_for_active_node($referencebranch);
3659 return $referencebranch;
3660 } else if ($adminbranch->check_access()) {
3661 // We have a reference branch that we can access and is not hidden `hurrah`
3662 // Now we need to display it and any children it may have
3663 $url = null;
3664 $icon = null;
3665 if ($adminbranch instanceof admin_settingpage) {
3666 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3667 } else if ($adminbranch instanceof admin_externalpage) {
3668 $url = $adminbranch->url;
3669 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3670 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3673 // Add the branch
3674 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3676 if ($adminbranch->is_hidden()) {
3677 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3678 $reference->add_class('hidden');
3679 } else {
3680 $reference->display = false;
3684 // Check if we are generating the admin notifications and whether notificiations exist
3685 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3686 $reference->add_class('criticalnotification');
3688 // Check if this branch has children
3689 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3690 foreach ($adminbranch->children as $branch) {
3691 // Generate the child branches as well now using this branch as the reference
3692 $this->load_administration_settings($reference, $branch);
3694 } else {
3695 $reference->icon = new pix_icon('i/settings', '');
3701 * This function recursivily scans nodes until it finds the active node or there
3702 * are no more nodes.
3703 * @param navigation_node $node
3705 protected function scan_for_active_node(navigation_node $node) {
3706 if (!$node->check_if_active() && $node->children->count()>0) {
3707 foreach ($node->children as &$child) {
3708 $this->scan_for_active_node($child);
3714 * Gets a navigation node given an array of keys that represent the path to
3715 * the desired node.
3717 * @param array $path
3718 * @return navigation_node|false
3720 protected function get_by_path(array $path) {
3721 $node = $this->get(array_shift($path));
3722 foreach ($path as $key) {
3723 $node->get($key);
3725 return $node;
3729 * This function loads the course settings that are available for the user
3731 * @param bool $forceopen If set to true the course node will be forced open
3732 * @return navigation_node|false
3734 protected function load_course_settings($forceopen = false) {
3735 global $CFG;
3737 $course = $this->page->course;
3738 $coursecontext = context_course::instance($course->id);
3740 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3742 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3743 if ($forceopen) {
3744 $coursenode->force_open();
3747 if ($this->page->user_allowed_editing()) {
3748 // Add the turn on/off settings
3750 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3751 // We are on the course page, retain the current page params e.g. section.
3752 $baseurl = clone($this->page->url);
3753 $baseurl->param('sesskey', sesskey());
3754 } else {
3755 // Edit on the main course page.
3756 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3759 $editurl = clone($baseurl);
3760 if ($this->page->user_is_editing()) {
3761 $editurl->param('edit', 'off');
3762 $editstring = get_string('turneditingoff');
3763 } else {
3764 $editurl->param('edit', 'on');
3765 $editstring = get_string('turneditingon');
3767 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
3770 if (has_capability('moodle/course:update', $coursecontext)) {
3771 // Add the course settings link
3772 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3773 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
3775 // Add the course completion settings link
3776 if ($CFG->enablecompletion && $course->enablecompletion) {
3777 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3778 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3782 // add enrol nodes
3783 enrol_add_course_navigation($coursenode, $course);
3785 // Manage filters
3786 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3787 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3788 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3791 // View course reports.
3792 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
3793 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'coursereports',
3794 new pix_icon('i/stats', ''));
3795 $coursereports = core_component::get_plugin_list('coursereport');
3796 foreach ($coursereports as $report => $dir) {
3797 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
3798 if (file_exists($libfile)) {
3799 require_once($libfile);
3800 $reportfunction = $report.'_report_extend_navigation';
3801 if (function_exists($report.'_report_extend_navigation')) {
3802 $reportfunction($reportnav, $course, $coursecontext);
3807 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
3808 foreach ($reports as $reportfunction) {
3809 $reportfunction($reportnav, $course, $coursecontext);
3813 // Add view grade report is permitted
3814 $reportavailable = false;
3815 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3816 $reportavailable = true;
3817 } else if (!empty($course->showgrades)) {
3818 $reports = core_component::get_plugin_list('gradereport');
3819 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3820 arsort($reports); // user is last, we want to test it first
3821 foreach ($reports as $plugin => $plugindir) {
3822 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3823 //stop when the first visible plugin is found
3824 $reportavailable = true;
3825 break;
3830 if ($reportavailable) {
3831 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3832 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3835 // Add outcome if permitted
3836 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3837 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3838 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3841 //Add badges navigation
3842 require_once($CFG->libdir .'/badgeslib.php');
3843 badges_add_course_navigation($coursenode, $course);
3845 // Backup this course
3846 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3847 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3848 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3851 // Restore to this course
3852 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3853 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3854 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3857 // Import data from other courses
3858 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3859 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3860 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
3863 // Publish course on a hub
3864 if (has_capability('moodle/course:publish', $coursecontext)) {
3865 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3866 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3869 // Reset this course
3870 if (has_capability('moodle/course:reset', $coursecontext)) {
3871 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3872 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3875 // Questions
3876 require_once($CFG->libdir . '/questionlib.php');
3877 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3879 if (has_capability('moodle/course:update', $coursecontext)) {
3880 // Repository Instances
3881 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3882 require_once($CFG->dirroot . '/repository/lib.php');
3883 $editabletypes = repository::get_editable_types($coursecontext);
3884 $haseditabletypes = !empty($editabletypes);
3885 unset($editabletypes);
3886 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3887 } else {
3888 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3890 if ($haseditabletypes) {
3891 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3892 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3896 // Manage files
3897 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3898 // hidden in new courses and courses where legacy files were turned off
3899 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3900 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
3904 // Switch roles
3905 $roles = array();
3906 $assumedrole = $this->in_alternative_role();
3907 if ($assumedrole !== false) {
3908 $roles[0] = get_string('switchrolereturn');
3910 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3911 $availableroles = get_switchable_roles($coursecontext);
3912 if (is_array($availableroles)) {
3913 foreach ($availableroles as $key=>$role) {
3914 if ($assumedrole == (int)$key) {
3915 continue;
3917 $roles[$key] = $role;
3921 if (is_array($roles) && count($roles)>0) {
3922 $switchroles = $this->add(get_string('switchroleto'));
3923 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3924 $switchroles->force_open();
3926 foreach ($roles as $key => $name) {
3927 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$this->page->url->out_as_local_url(false)));
3928 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
3932 // Let admin tools hook into course navigation.
3933 $tools = get_plugin_list_with_function('tool', 'extend_navigation_course', 'lib.php');
3934 foreach ($tools as $toolfunction) {
3935 $toolfunction($coursenode, $course, $coursecontext);
3938 // Return we are done
3939 return $coursenode;
3943 * This function calls the module function to inject module settings into the
3944 * settings navigation tree.
3946 * This only gets called if there is a corrosponding function in the modules
3947 * lib file.
3949 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3951 * @return navigation_node|false
3953 protected function load_module_settings() {
3954 global $CFG;
3956 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3957 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3958 $this->page->set_cm($cm, $this->page->course);
3961 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3962 if (file_exists($file)) {
3963 require_once($file);
3966 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
3967 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
3968 $modulenode->force_open();
3970 // Settings for the module
3971 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3972 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
3973 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3975 // Assign local roles
3976 if (count(get_assignable_roles($this->page->cm->context))>0) {
3977 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3978 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3980 // Override roles
3981 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3982 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3983 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3985 // Check role permissions
3986 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3987 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3988 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3990 // Manage filters
3991 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3992 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3993 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3995 // Add reports
3996 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3997 foreach ($reports as $reportfunction) {
3998 $reportfunction($modulenode, $this->page->cm);
4000 // Add a backup link
4001 $featuresfunc = $this->page->activityname.'_supports';
4002 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4003 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4004 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4007 // Restore this activity
4008 $featuresfunc = $this->page->activityname.'_supports';
4009 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4010 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4011 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4014 // Allow the active advanced grading method plugin to append its settings
4015 $featuresfunc = $this->page->activityname.'_supports';
4016 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4017 require_once($CFG->dirroot.'/grade/grading/lib.php');
4018 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4019 $gradingman->extend_settings_navigation($this, $modulenode);
4022 $function = $this->page->activityname.'_extend_settings_navigation';
4023 if (function_exists($function)) {
4024 $function($this, $modulenode);
4027 // Remove the module node if there are no children.
4028 if ($modulenode->children->count() <= 0) {
4029 $modulenode->remove();
4032 return $modulenode;
4036 * Loads the user settings block of the settings nav
4038 * This function is simply works out the userid and whether we need to load
4039 * just the current users profile settings, or the current user and the user the
4040 * current user is viewing.
4042 * This function has some very ugly code to work out the user, if anyone has
4043 * any bright ideas please feel free to intervene.
4045 * @param int $courseid The course id of the current course
4046 * @return navigation_node|false
4048 protected function load_user_settings($courseid = SITEID) {
4049 global $USER, $CFG;
4051 if (isguestuser() || !isloggedin()) {
4052 return false;
4055 $navusers = $this->page->navigation->get_extending_users();
4057 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4058 $usernode = null;
4059 foreach ($this->userstoextendfor as $userid) {
4060 if ($userid == $USER->id) {
4061 continue;
4063 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4064 if (is_null($usernode)) {
4065 $usernode = $node;
4068 foreach ($navusers as $user) {
4069 if ($user->id == $USER->id) {
4070 continue;
4072 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4073 if (is_null($usernode)) {
4074 $usernode = $node;
4077 $this->generate_user_settings($courseid, $USER->id);
4078 } else {
4079 $usernode = $this->generate_user_settings($courseid, $USER->id);
4081 return $usernode;
4085 * Extends the settings navigation for the given user.
4087 * Note: This method gets called automatically if you call
4088 * $PAGE->navigation->extend_for_user($userid)
4090 * @param int $userid
4092 public function extend_for_user($userid) {
4093 global $CFG;
4095 if (!in_array($userid, $this->userstoextendfor)) {
4096 $this->userstoextendfor[] = $userid;
4097 if ($this->initialised) {
4098 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4099 $children = array();
4100 foreach ($this->children as $child) {
4101 $children[] = $child;
4103 array_unshift($children, array_pop($children));
4104 $this->children = new navigation_node_collection();
4105 foreach ($children as $child) {
4106 $this->children->add($child);
4113 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4114 * what can be shown/done
4116 * @param int $courseid The current course' id
4117 * @param int $userid The user id to load for
4118 * @param string $gstitle The string to pass to get_string for the branch title
4119 * @return navigation_node|false
4121 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4122 global $DB, $CFG, $USER, $SITE;
4124 if ($courseid != $SITE->id) {
4125 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4126 $course = $this->page->course;
4127 } else {
4128 $select = context_helper::get_preload_record_columns_sql('ctx');
4129 $sql = "SELECT c.*, $select
4130 FROM {course} c
4131 JOIN {context} ctx ON c.id = ctx.instanceid
4132 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4133 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4134 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4135 context_helper::preload_from_record($course);
4137 } else {
4138 $course = $SITE;
4141 $coursecontext = context_course::instance($course->id); // Course context
4142 $systemcontext = context_system::instance();
4143 $currentuser = ($USER->id == $userid);
4145 if ($currentuser) {
4146 $user = $USER;
4147 $usercontext = context_user::instance($user->id); // User context
4148 } else {
4149 $select = context_helper::get_preload_record_columns_sql('ctx');
4150 $sql = "SELECT u.*, $select
4151 FROM {user} u
4152 JOIN {context} ctx ON u.id = ctx.instanceid
4153 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4154 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4155 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4156 if (!$user) {
4157 return false;
4159 context_helper::preload_from_record($user);
4161 // Check that the user can view the profile
4162 $usercontext = context_user::instance($user->id); // User context
4163 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4165 if ($course->id == $SITE->id) {
4166 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4167 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4168 return false;
4170 } else {
4171 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4172 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4173 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4174 return false;
4176 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4177 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4178 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4179 if ($courseid == $this->page->course->id) {
4180 $mygroups = get_fast_modinfo($this->page->course)->groups;
4181 } else {
4182 $mygroups = groups_get_user_groups($courseid);
4184 $usergroups = groups_get_user_groups($courseid, $userid);
4185 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4186 return false;
4192 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4194 $key = $gstitle;
4195 $prefurl = new moodle_url('/user/preferences.php');
4196 if ($gstitle != 'usercurrentsettings') {
4197 $key .= $userid;
4198 $prefurl->param('userid', $userid);
4201 // Add a user setting branch.
4202 if ($gstitle == 'usercurrentsettings') {
4203 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4204 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4205 // breadcrumb.
4206 $dashboard->display = false;
4207 if (get_home_page() == HOMEPAGE_MY) {
4208 $dashboard->mainnavonly = true;
4211 $iscurrentuser = ($user->id == $USER->id);
4213 $baseargs = array('id' => $user->id);
4214 if ($course->id != $SITE->id && !$iscurrentuser) {
4215 $baseargs['course'] = $course->id;
4216 $issitecourse = false;
4217 } else {
4218 // Load all categories and get the context for the system.
4219 $issitecourse = true;
4222 // Add the user profile to the dashboard.
4223 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4224 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4226 if (!empty($CFG->navadduserpostslinks)) {
4227 // Add nodes for forum posts and discussions if the user can view either or both
4228 // There are no capability checks here as the content of the page is based
4229 // purely on the forums the current user has access too.
4230 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4231 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4232 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4233 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4236 // Add blog nodes.
4237 if (!empty($CFG->enableblogs)) {
4238 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4239 require_once($CFG->dirroot.'/blog/lib.php');
4240 // Get all options for the user.
4241 $options = blog_get_options_for_user($user);
4242 $this->cache->set('userblogoptions'.$user->id, $options);
4243 } else {
4244 $options = $this->cache->{'userblogoptions'.$user->id};
4247 if (count($options) > 0) {
4248 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4249 foreach ($options as $type => $option) {
4250 if ($type == "rss") {
4251 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4252 new pix_icon('i/rss', ''));
4253 } else {
4254 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4260 // Add the messages link.
4261 // It is context based so can appear in the user's profile and in course participants information.
4262 if (!empty($CFG->messaging)) {
4263 $messageargs = array('user1' => $USER->id);
4264 if ($USER->id != $user->id) {
4265 $messageargs['user2'] = $user->id;
4267 if ($course->id != $SITE->id) {
4268 $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
4270 $url = new moodle_url('/message/index.php', $messageargs);
4271 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4274 // Add the "My private files" link.
4275 // This link doesn't have a unique display for course context so only display it under the user's profile.
4276 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4277 $url = new moodle_url('/user/files.php');
4278 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
4281 // Add a node to view the users notes if permitted.
4282 if (!empty($CFG->enablenotes) &&
4283 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4284 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4285 if ($coursecontext->instanceid != SITEID) {
4286 $url->param('course', $coursecontext->instanceid);
4288 $profilenode->add(get_string('notes', 'notes'), $url);
4291 // Show the grades node.
4292 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
4293 require_once($CFG->dirroot . '/user/lib.php');
4294 // Set the grades node to link to the "Grades" page.
4295 if ($course->id == SITEID) {
4296 $url = user_mygrades_url($user->id, $course->id);
4297 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4298 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
4300 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
4302 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4303 $dashboard->add_node($usersetting);
4304 } else {
4305 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4306 $usersetting->display = false;
4308 $usersetting->id = 'usersettings';
4310 // Check if the user has been deleted.
4311 if ($user->deleted) {
4312 if (!has_capability('moodle/user:update', $coursecontext)) {
4313 // We can't edit the user so just show the user deleted message.
4314 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4315 } else {
4316 // We can edit the user so show the user deleted message and link it to the profile.
4317 if ($course->id == $SITE->id) {
4318 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4319 } else {
4320 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4322 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4324 return true;
4327 $userauthplugin = false;
4328 if (!empty($user->auth)) {
4329 $userauthplugin = get_auth_plugin($user->auth);
4332 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
4334 // Add the profile edit link.
4335 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4336 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
4337 has_capability('moodle/user:update', $systemcontext)) {
4338 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4339 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4340 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4341 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4342 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4343 $url = $userauthplugin->edit_profile_url();
4344 if (empty($url)) {
4345 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4347 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4352 // Change password link.
4353 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
4354 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4355 $passwordchangeurl = $userauthplugin->change_password_url();
4356 if (empty($passwordchangeurl)) {
4357 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4359 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
4362 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4363 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4364 has_capability('moodle/user:editprofile', $usercontext)) {
4365 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
4366 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
4369 $pluginmanager = core_plugin_manager::instance();
4370 $enabled = $pluginmanager->get_enabled_plugins('mod');
4371 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4372 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4373 has_capability('moodle/user:editprofile', $usercontext)) {
4374 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
4375 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
4378 $editors = editors_get_enabled();
4379 if (count($editors) > 1) {
4380 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4381 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4382 has_capability('moodle/user:editprofile', $usercontext)) {
4383 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
4384 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
4389 // View the roles settings.
4390 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
4391 'moodle/role:manage'), $usercontext)) {
4392 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4394 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4395 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4397 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4399 if (!empty($assignableroles)) {
4400 $url = new moodle_url('/admin/roles/assign.php',
4401 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4402 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4405 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4406 $url = new moodle_url('/admin/roles/permissions.php',
4407 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4408 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4411 $url = new moodle_url('/admin/roles/check.php',
4412 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4413 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4416 // Repositories.
4417 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
4418 require_once($CFG->dirroot . '/repository/lib.php');
4419 $editabletypes = repository::get_editable_types($usercontext);
4420 $haseditabletypes = !empty($editabletypes);
4421 unset($editabletypes);
4422 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
4423 } else {
4424 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
4426 if ($haseditabletypes) {
4427 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
4428 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
4429 array('contextid' => $usercontext->id)));
4432 // Portfolio.
4433 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4434 require_once($CFG->libdir . '/portfoliolib.php');
4435 if (portfolio_has_visible_instances()) {
4436 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4438 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4439 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4441 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4442 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4446 $enablemanagetokens = false;
4447 if (!empty($CFG->enablerssfeeds)) {
4448 $enablemanagetokens = true;
4449 } else if (!is_siteadmin($USER->id)
4450 && !empty($CFG->enablewebservices)
4451 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4452 $enablemanagetokens = true;
4454 // Security keys.
4455 if ($currentuser && $enablemanagetokens) {
4456 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4457 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4460 // Messaging.
4461 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
4462 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4463 $url = new moodle_url('/message/edit.php', array('id'=>$user->id));
4464 $useraccount->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
4467 // Blogs.
4468 if ($currentuser && !empty($CFG->enableblogs)) {
4469 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4470 if (has_capability('moodle/blog:view', $systemcontext)) {
4471 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
4472 navigation_node::TYPE_SETTING);
4474 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
4475 has_capability('moodle/blog:manageexternal', $systemcontext)) {
4476 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
4477 navigation_node::TYPE_SETTING);
4478 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
4479 navigation_node::TYPE_SETTING);
4481 // Remove the blog node if empty.
4482 $blog->trim_if_empty();
4485 // Badges.
4486 if ($currentuser && !empty($CFG->enablebadges)) {
4487 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
4488 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
4489 $url = new moodle_url('/badges/mybadges.php');
4490 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
4492 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
4493 navigation_node::TYPE_SETTING);
4494 if (!empty($CFG->badges_allowexternalbackpack)) {
4495 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
4496 navigation_node::TYPE_SETTING);
4500 // Let admin tools hook into user settings navigation.
4501 $tools = get_plugin_list_with_function('tool', 'extend_navigation_user_settings', 'lib.php');
4502 foreach ($tools as $toolfunction) {
4503 $toolfunction($usersetting, $user, $usercontext, $course, $coursecontext);
4506 return $usersetting;
4510 * Loads block specific settings in the navigation
4512 * @return navigation_node
4514 protected function load_block_settings() {
4515 global $CFG;
4517 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
4518 $blocknode->force_open();
4520 // Assign local roles
4521 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4522 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4524 // Override roles
4525 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4526 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4527 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4529 // Check role permissions
4530 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4531 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4532 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4535 return $blocknode;
4539 * Loads category specific settings in the navigation
4541 * @return navigation_node
4543 protected function load_category_settings() {
4544 global $CFG;
4546 // We can land here while being in the context of a block, in which case we
4547 // should get the parent context which should be the category one. See self::initialise().
4548 if ($this->context->contextlevel == CONTEXT_BLOCK) {
4549 $catcontext = $this->context->get_parent_context();
4550 } else {
4551 $catcontext = $this->context;
4554 // Let's make sure that we always have the right context when getting here.
4555 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
4556 throw new coding_exception('Unexpected context while loading category settings.');
4559 $categorynode = $this->add($catcontext->get_context_name(), null, null, null, 'categorysettings');
4560 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
4561 $categorynode->force_open();
4563 if (can_edit_in_category($catcontext->instanceid)) {
4564 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
4565 $editstring = get_string('managecategorythis');
4566 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4569 if (has_capability('moodle/category:manage', $catcontext)) {
4570 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
4571 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4573 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
4574 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4577 // Assign local roles
4578 $assignableroles = get_assignable_roles($catcontext);
4579 if (!empty($assignableroles)) {
4580 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
4581 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4584 // Override roles
4585 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
4586 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
4587 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4589 // Check role permissions
4590 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
4591 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
4592 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
4593 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4596 // Cohorts
4597 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
4598 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
4599 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
4602 // Manage filters
4603 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
4604 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
4605 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4608 // Restore.
4609 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
4610 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
4611 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
4614 return $categorynode;
4618 * Determine whether the user is assuming another role
4620 * This function checks to see if the user is assuming another role by means of
4621 * role switching. In doing this we compare each RSW key (context path) against
4622 * the current context path. This ensures that we can provide the switching
4623 * options against both the course and any page shown under the course.
4625 * @return bool|int The role(int) if the user is in another role, false otherwise
4627 protected function in_alternative_role() {
4628 global $USER;
4629 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4630 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4631 return $USER->access['rsw'][$this->page->context->path];
4633 foreach ($USER->access['rsw'] as $key=>$role) {
4634 if (strpos($this->context->path,$key)===0) {
4635 return $role;
4639 return false;
4643 * This function loads all of the front page settings into the settings navigation.
4644 * This function is called when the user is on the front page, or $COURSE==$SITE
4645 * @param bool $forceopen (optional)
4646 * @return navigation_node
4648 protected function load_front_page_settings($forceopen = false) {
4649 global $SITE, $CFG;
4651 $course = clone($SITE);
4652 $coursecontext = context_course::instance($course->id); // Course context
4654 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4655 if ($forceopen) {
4656 $frontpage->force_open();
4658 $frontpage->id = 'frontpagesettings';
4660 if ($this->page->user_allowed_editing()) {
4662 // Add the turn on/off settings
4663 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4664 if ($this->page->user_is_editing()) {
4665 $url->param('edit', 'off');
4666 $editstring = get_string('turneditingoff');
4667 } else {
4668 $url->param('edit', 'on');
4669 $editstring = get_string('turneditingon');
4671 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4674 if (has_capability('moodle/course:update', $coursecontext)) {
4675 // Add the course settings link
4676 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4677 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4680 // add enrol nodes
4681 enrol_add_course_navigation($frontpage, $course);
4683 // Manage filters
4684 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4685 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4686 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4689 // View course reports.
4690 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
4691 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
4692 new pix_icon('i/stats', ''));
4693 $coursereports = core_component::get_plugin_list('coursereport');
4694 foreach ($coursereports as $report=>$dir) {
4695 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4696 if (file_exists($libfile)) {
4697 require_once($libfile);
4698 $reportfunction = $report.'_report_extend_navigation';
4699 if (function_exists($report.'_report_extend_navigation')) {
4700 $reportfunction($frontpagenav, $course, $coursecontext);
4705 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4706 foreach ($reports as $reportfunction) {
4707 $reportfunction($frontpagenav, $course, $coursecontext);
4711 // Backup this course
4712 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4713 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4714 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4717 // Restore to this course
4718 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4719 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4720 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4723 // Questions
4724 require_once($CFG->libdir . '/questionlib.php');
4725 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4727 // Manage files
4728 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4729 //hiden in new installs
4730 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4731 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
4734 // Let admin tools hook into frontpage navigation.
4735 $tools = get_plugin_list_with_function('tool', 'extend_navigation_frontpage', 'lib.php');
4736 foreach ($tools as $toolfunction) {
4737 $toolfunction($frontpage, $course, $coursecontext);
4740 return $frontpage;
4744 * This function gives local plugins an opportunity to modify the settings navigation.
4746 protected function load_local_plugin_settings() {
4748 foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $unused) {
4749 $function = "local_{$plugin}_extend_settings_navigation";
4750 $oldfunction = "local_{$plugin}_extends_settings_navigation";
4752 if (function_exists($function)) {
4753 $function($this, $this->context);
4755 } else if (function_exists($oldfunction)) {
4756 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. ".
4757 "Support for the old callback will be dropped in Moodle 3.1", DEBUG_DEVELOPER);
4758 $oldfunction($this, $this->context);
4764 * This function marks the cache as volatile so it is cleared during shutdown
4766 public function clear_cache() {
4767 $this->cache->volatile();
4771 * Checks to see if there are child nodes available in the specific user's preference node.
4772 * If so, then they have the appropriate permissions view this user's preferences.
4774 * @since Moodle 2.9.3
4775 * @param int $userid The user's ID.
4776 * @return bool True if child nodes exist to view, otherwise false.
4778 public function can_view_user_preferences($userid) {
4779 if (is_siteadmin()) {
4780 return true;
4782 // See if any nodes are present in the preferences section for this user.
4783 $preferencenode = $this->find('userviewingsettings' . $userid, null);
4784 if ($preferencenode && $preferencenode->has_children()) {
4785 // Run through each child node.
4786 foreach ($preferencenode->children as $childnode) {
4787 // If the child node has children then this user has access to a link in the preferences page.
4788 if ($childnode->has_children()) {
4789 return true;
4793 // No links found for the user to access on the preferences page.
4794 return false;
4799 * Class used to populate site admin navigation for ajax.
4801 * @package core
4802 * @category navigation
4803 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
4804 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4806 class settings_navigation_ajax extends settings_navigation {
4808 * Constructs the navigation for use in an AJAX request
4810 * @param moodle_page $page
4812 public function __construct(moodle_page &$page) {
4813 $this->page = $page;
4814 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4815 $this->children = new navigation_node_collection();
4816 $this->initialise();
4820 * Initialise the site admin navigation.
4822 * @return array An array of the expandable nodes
4824 public function initialise() {
4825 if ($this->initialised || during_initial_install()) {
4826 return false;
4828 $this->context = $this->page->context;
4829 $this->load_administration_settings();
4831 // Check if local plugins is adding node to site admin.
4832 $this->load_local_plugin_settings();
4834 $this->initialised = true;
4839 * Simple class used to output a navigation branch in XML
4841 * @package core
4842 * @category navigation
4843 * @copyright 2009 Sam Hemelryk
4844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4846 class navigation_json {
4847 /** @var array An array of different node types */
4848 protected $nodetype = array('node','branch');
4849 /** @var array An array of node keys and types */
4850 protected $expandable = array();
4852 * Turns a branch and all of its children into XML
4854 * @param navigation_node $branch
4855 * @return string XML string
4857 public function convert($branch) {
4858 $xml = $this->convert_child($branch);
4859 return $xml;
4862 * Set the expandable items in the array so that we have enough information
4863 * to attach AJAX events
4864 * @param array $expandable
4866 public function set_expandable($expandable) {
4867 foreach ($expandable as $node) {
4868 $this->expandable[$node['key'].':'.$node['type']] = $node;
4872 * Recusively converts a child node and its children to XML for output
4874 * @param navigation_node $child The child to convert
4875 * @param int $depth Pointlessly used to track the depth of the XML structure
4876 * @return string JSON
4878 protected function convert_child($child, $depth=1) {
4879 if (!$child->display) {
4880 return '';
4882 $attributes = array();
4883 $attributes['id'] = $child->id;
4884 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
4885 $attributes['type'] = $child->type;
4886 $attributes['key'] = $child->key;
4887 $attributes['class'] = $child->get_css_type();
4889 if ($child->icon instanceof pix_icon) {
4890 $attributes['icon'] = array(
4891 'component' => $child->icon->component,
4892 'pix' => $child->icon->pix,
4894 foreach ($child->icon->attributes as $key=>$value) {
4895 if ($key == 'class') {
4896 $attributes['icon']['classes'] = explode(' ', $value);
4897 } else if (!array_key_exists($key, $attributes['icon'])) {
4898 $attributes['icon'][$key] = $value;
4902 } else if (!empty($child->icon)) {
4903 $attributes['icon'] = (string)$child->icon;
4906 if ($child->forcetitle || $child->title !== $child->text) {
4907 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
4909 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4910 $attributes['expandable'] = $child->key;
4911 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4914 if (count($child->classes)>0) {
4915 $attributes['class'] .= ' '.join(' ',$child->classes);
4917 if (is_string($child->action)) {
4918 $attributes['link'] = $child->action;
4919 } else if ($child->action instanceof moodle_url) {
4920 $attributes['link'] = $child->action->out();
4921 } else if ($child->action instanceof action_link) {
4922 $attributes['link'] = $child->action->url->out();
4924 $attributes['hidden'] = ($child->hidden);
4925 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4926 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
4928 if ($child->children->count() > 0) {
4929 $attributes['children'] = array();
4930 foreach ($child->children as $subchild) {
4931 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4935 if ($depth > 1) {
4936 return $attributes;
4937 } else {
4938 return json_encode($attributes);
4944 * The cache class used by global navigation and settings navigation.
4946 * It is basically an easy access point to session with a bit of smarts to make
4947 * sure that the information that is cached is valid still.
4949 * Example use:
4950 * <code php>
4951 * if (!$cache->viewdiscussion()) {
4952 * // Code to do stuff and produce cachable content
4953 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4955 * $content = $cache->viewdiscussion;
4956 * </code>
4958 * @package core
4959 * @category navigation
4960 * @copyright 2009 Sam Hemelryk
4961 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4963 class navigation_cache {
4964 /** @var int represents the time created */
4965 protected $creation;
4966 /** @var array An array of session keys */
4967 protected $session;
4969 * The string to use to segregate this particular cache. It can either be
4970 * unique to start a fresh cache or if you want to share a cache then make
4971 * it the string used in the original cache.
4972 * @var string
4974 protected $area;
4975 /** @var int a time that the information will time out */
4976 protected $timeout;
4977 /** @var stdClass The current context */
4978 protected $currentcontext;
4979 /** @var int cache time information */
4980 const CACHETIME = 0;
4981 /** @var int cache user id */
4982 const CACHEUSERID = 1;
4983 /** @var int cache value */
4984 const CACHEVALUE = 2;
4985 /** @var null|array An array of navigation cache areas to expire on shutdown */
4986 public static $volatilecaches;
4989 * Contructor for the cache. Requires two arguments
4991 * @param string $area The string to use to segregate this particular cache
4992 * it can either be unique to start a fresh cache or if you want
4993 * to share a cache then make it the string used in the original
4994 * cache
4995 * @param int $timeout The number of seconds to time the information out after
4997 public function __construct($area, $timeout=1800) {
4998 $this->creation = time();
4999 $this->area = $area;
5000 $this->timeout = time() - $timeout;
5001 if (rand(0,100) === 0) {
5002 $this->garbage_collection();
5007 * Used to set up the cache within the SESSION.
5009 * This is called for each access and ensure that we don't put anything into the session before
5010 * it is required.
5012 protected function ensure_session_cache_initialised() {
5013 global $SESSION;
5014 if (empty($this->session)) {
5015 if (!isset($SESSION->navcache)) {
5016 $SESSION->navcache = new stdClass;
5018 if (!isset($SESSION->navcache->{$this->area})) {
5019 $SESSION->navcache->{$this->area} = array();
5021 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5026 * Magic Method to retrieve something by simply calling using = cache->key
5028 * @param mixed $key The identifier for the information you want out again
5029 * @return void|mixed Either void or what ever was put in
5031 public function __get($key) {
5032 if (!$this->cached($key)) {
5033 return;
5035 $information = $this->session[$key][self::CACHEVALUE];
5036 return unserialize($information);
5040 * Magic method that simply uses {@link set();} to store something in the cache
5042 * @param string|int $key
5043 * @param mixed $information
5045 public function __set($key, $information) {
5046 $this->set($key, $information);
5050 * Sets some information against the cache (session) for later retrieval
5052 * @param string|int $key
5053 * @param mixed $information
5055 public function set($key, $information) {
5056 global $USER;
5057 $this->ensure_session_cache_initialised();
5058 $information = serialize($information);
5059 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5062 * Check the existence of the identifier in the cache
5064 * @param string|int $key
5065 * @return bool
5067 public function cached($key) {
5068 global $USER;
5069 $this->ensure_session_cache_initialised();
5070 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) {
5071 return false;
5073 return true;
5076 * Compare something to it's equivilant in the cache
5078 * @param string $key
5079 * @param mixed $value
5080 * @param bool $serialise Whether to serialise the value before comparison
5081 * this should only be set to false if the value is already
5082 * serialised
5083 * @return bool If the value is the same false if it is not set or doesn't match
5085 public function compare($key, $value, $serialise = true) {
5086 if ($this->cached($key)) {
5087 if ($serialise) {
5088 $value = serialize($value);
5090 if ($this->session[$key][self::CACHEVALUE] === $value) {
5091 return true;
5094 return false;
5097 * Wipes the entire cache, good to force regeneration
5099 public function clear() {
5100 global $SESSION;
5101 unset($SESSION->navcache);
5102 $this->session = null;
5105 * Checks all cache entries and removes any that have expired, good ole cleanup
5107 protected function garbage_collection() {
5108 if (empty($this->session)) {
5109 return true;
5111 foreach ($this->session as $key=>$cachedinfo) {
5112 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5113 unset($this->session[$key]);
5119 * Marks the cache as being volatile (likely to change)
5121 * Any caches marked as volatile will be destroyed at the on shutdown by
5122 * {@link navigation_node::destroy_volatile_caches()} which is registered
5123 * as a shutdown function if any caches are marked as volatile.
5125 * @param bool $setting True to destroy the cache false not too
5127 public function volatile($setting = true) {
5128 if (self::$volatilecaches===null) {
5129 self::$volatilecaches = array();
5130 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5133 if ($setting) {
5134 self::$volatilecaches[$this->area] = $this->area;
5135 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5136 unset(self::$volatilecaches[$this->area]);
5141 * Destroys all caches marked as volatile
5143 * This function is static and works in conjunction with the static volatilecaches
5144 * property of navigation cache.
5145 * Because this function is static it manually resets the cached areas back to an
5146 * empty array.
5148 public static function destroy_volatile_caches() {
5149 global $SESSION;
5150 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5151 foreach (self::$volatilecaches as $area) {
5152 $SESSION->navcache->{$area} = array();
5154 } else {
5155 $SESSION->navcache = new stdClass;