Moodle release 2.7.12
[moodle.git] / lib / navigationlib.php
blob9a06452cfd937f2679fb35379383736609c8fb65
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 + thier 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 array 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('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1108 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1109 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
1110 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1111 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
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 if ($this->rootnodes['mycourses']->isactive) {
1137 $this->load_courses_enrolled();
1140 $canviewcourseprofile = true;
1142 // Next load context specific content into the navigation
1143 switch ($this->page->context->contextlevel) {
1144 case CONTEXT_SYSTEM :
1145 // Nothing left to do here I feel.
1146 break;
1147 case CONTEXT_COURSECAT :
1148 // This is essential, we must load categories.
1149 $this->load_all_categories($this->page->context->instanceid, true);
1150 break;
1151 case CONTEXT_BLOCK :
1152 case CONTEXT_COURSE :
1153 if ($issite) {
1154 // Nothing left to do here.
1155 break;
1158 // Load the course associated with the current page into the navigation.
1159 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1160 // If the course wasn't added then don't try going any further.
1161 if (!$coursenode) {
1162 $canviewcourseprofile = false;
1163 break;
1166 // If the user is not enrolled then we only want to show the
1167 // course node and not populate it.
1169 // Not enrolled, can't view, and hasn't switched roles
1170 if (!can_access_course($course, null, '', true)) {
1171 if ($coursenode->isexpandable === true) {
1172 // Obviously the situation has changed, update the cache and adjust the node.
1173 // This occurs if the user access to a course has been revoked (one way or another) after
1174 // initially logging in for this session.
1175 $this->get_expand_course_cache()->set($course->id, 1);
1176 $coursenode->isexpandable = true;
1177 $coursenode->nodetype = self::NODETYPE_BRANCH;
1179 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1180 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1181 if (!$this->current_user_is_parent_role()) {
1182 $coursenode->make_active();
1183 $canviewcourseprofile = false;
1184 break;
1186 } else if ($coursenode->isexpandable === false) {
1187 // Obviously the situation has changed, update the cache and adjust the node.
1188 // This occurs if the user has been granted access to a course (one way or another) after initially
1189 // logging in for this session.
1190 $this->get_expand_course_cache()->set($course->id, 1);
1191 $coursenode->isexpandable = true;
1192 $coursenode->nodetype = self::NODETYPE_BRANCH;
1195 // Add the essentials such as reports etc...
1196 $this->add_course_essentials($coursenode, $course);
1197 // Extend course navigation with it's sections/activities
1198 $this->load_course_sections($course, $coursenode);
1199 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1200 $coursenode->make_active();
1203 break;
1204 case CONTEXT_MODULE :
1205 if ($issite) {
1206 // If this is the site course then most information will have
1207 // already been loaded.
1208 // However we need to check if there is more content that can
1209 // yet be loaded for the specific module instance.
1210 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1211 if ($activitynode) {
1212 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1214 break;
1217 $course = $this->page->course;
1218 $cm = $this->page->cm;
1220 // Load the course associated with the page into the navigation
1221 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1223 // If the course wasn't added then don't try going any further.
1224 if (!$coursenode) {
1225 $canviewcourseprofile = false;
1226 break;
1229 // If the user is not enrolled then we only want to show the
1230 // course node and not populate it.
1231 if (!can_access_course($course, null, '', true)) {
1232 $coursenode->make_active();
1233 $canviewcourseprofile = false;
1234 break;
1237 $this->add_course_essentials($coursenode, $course);
1239 // Load the course sections into the page
1240 $this->load_course_sections($course, $coursenode, null, $cm);
1241 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1242 if (!empty($activity)) {
1243 // Finally load the cm specific navigaton information
1244 $this->load_activity($cm, $course, $activity);
1245 // Check if we have an active ndoe
1246 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1247 // And make the activity node active.
1248 $activity->make_active();
1251 break;
1252 case CONTEXT_USER :
1253 if ($issite) {
1254 // The users profile information etc is already loaded
1255 // for the front page.
1256 break;
1258 $course = $this->page->course;
1259 // Load the course associated with the user into the navigation
1260 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1262 // If the course wasn't added then don't try going any further.
1263 if (!$coursenode) {
1264 $canviewcourseprofile = false;
1265 break;
1268 // If the user is not enrolled then we only want to show the
1269 // course node and not populate it.
1270 if (!can_access_course($course, null, '', true)) {
1271 $coursenode->make_active();
1272 $canviewcourseprofile = false;
1273 break;
1275 $this->add_course_essentials($coursenode, $course);
1276 $this->load_course_sections($course, $coursenode);
1277 break;
1280 // Load for the current user
1281 $this->load_for_user();
1282 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1283 $this->load_for_user(null, true);
1285 // Load each extending user into the navigation.
1286 foreach ($this->extendforuser as $user) {
1287 if ($user->id != $USER->id) {
1288 $this->load_for_user($user);
1292 // Give the local plugins a chance to include some navigation if they want.
1293 foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1294 $function = "local_{$plugin}_extends_navigation";
1295 $oldfunction = "{$plugin}_extends_navigation";
1296 if (function_exists($function)) {
1297 // This is the preferred function name as there is less chance of conflicts
1298 $function($this);
1299 } else if (function_exists($oldfunction)) {
1300 // We continue to support the old function name to ensure backwards compatibility
1301 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. Support for the old callback will be dropped after the release of 2.4", DEBUG_DEVELOPER);
1302 $oldfunction($this);
1306 // Remove any empty root nodes
1307 foreach ($this->rootnodes as $node) {
1308 // Dont remove the home node
1309 /** @var navigation_node $node */
1310 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1311 $node->remove();
1315 if (!$this->contains_active_node()) {
1316 $this->search_for_active_node();
1319 // If the user is not logged in modify the navigation structure as detailed
1320 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1321 if (!isloggedin()) {
1322 $activities = clone($this->rootnodes['site']->children);
1323 $this->rootnodes['site']->remove();
1324 $children = clone($this->children);
1325 $this->children = new navigation_node_collection();
1326 foreach ($activities as $child) {
1327 $this->children->add($child);
1329 foreach ($children as $child) {
1330 $this->children->add($child);
1333 return true;
1337 * Returns true if the current user is a parent of the user being currently viewed.
1339 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1340 * other user being viewed this function returns false.
1341 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1343 * @since Moodle 2.4
1344 * @return bool
1346 protected function current_user_is_parent_role() {
1347 global $USER, $DB;
1348 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1349 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1350 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1351 return false;
1353 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1354 return true;
1357 return false;
1361 * Returns true if courses should be shown within categories on the navigation.
1363 * @param bool $ismycourse Set to true if you are calculating this for a course.
1364 * @return bool
1366 protected function show_categories($ismycourse = false) {
1367 global $CFG, $DB;
1368 if ($ismycourse) {
1369 return $this->show_my_categories();
1371 if ($this->showcategories === null) {
1372 $show = false;
1373 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1374 $show = true;
1375 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1376 $show = true;
1378 $this->showcategories = $show;
1380 return $this->showcategories;
1384 * Returns true if we should show categories in the My Courses branch.
1385 * @return bool
1387 protected function show_my_categories() {
1388 global $CFG, $DB;
1389 if ($this->showmycategories === null) {
1390 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1392 return $this->showmycategories;
1396 * Loads the courses in Moodle into the navigation.
1398 * @global moodle_database $DB
1399 * @param string|array $categoryids An array containing categories to load courses
1400 * for, OR null to load courses for all categories.
1401 * @return array An array of navigation_nodes one for each course
1403 protected function load_all_courses($categoryids = null) {
1404 global $CFG, $DB, $SITE;
1406 // Work out the limit of courses.
1407 $limit = 20;
1408 if (!empty($CFG->navcourselimit)) {
1409 $limit = $CFG->navcourselimit;
1412 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1414 // If we are going to show all courses AND we are showing categories then
1415 // to save us repeated DB calls load all of the categories now
1416 if ($this->show_categories()) {
1417 $this->load_all_categories($toload);
1420 // Will be the return of our efforts
1421 $coursenodes = array();
1423 // Check if we need to show categories.
1424 if ($this->show_categories()) {
1425 // Hmmm we need to show categories... this is going to be painful.
1426 // We now need to fetch up to $limit courses for each category to
1427 // be displayed.
1428 if ($categoryids !== null) {
1429 if (!is_array($categoryids)) {
1430 $categoryids = array($categoryids);
1432 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1433 $categorywhere = 'WHERE cc.id '.$categorywhere;
1434 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1435 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1436 $categoryparams = array();
1437 } else {
1438 $categorywhere = '';
1439 $categoryparams = array();
1442 // First up we are going to get the categories that we are going to
1443 // need so that we can determine how best to load the courses from them.
1444 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1445 FROM {course_categories} cc
1446 LEFT JOIN {course} c ON c.category = cc.id
1447 {$categorywhere}
1448 GROUP BY cc.id";
1449 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1450 $fullfetch = array();
1451 $partfetch = array();
1452 foreach ($categories as $category) {
1453 if (!$this->can_add_more_courses_to_category($category->id)) {
1454 continue;
1456 if ($category->coursecount > $limit * 5) {
1457 $partfetch[] = $category->id;
1458 } else if ($category->coursecount > 0) {
1459 $fullfetch[] = $category->id;
1462 $categories->close();
1464 if (count($fullfetch)) {
1465 // First up fetch all of the courses in categories where we know that we are going to
1466 // need the majority of courses.
1467 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1468 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1469 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1470 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1471 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1472 FROM {course} c
1473 $ccjoin
1474 WHERE c.category {$categoryids}
1475 ORDER BY c.sortorder ASC";
1476 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1477 foreach ($coursesrs as $course) {
1478 if ($course->id == $SITE->id) {
1479 // This should not be necessary, frontpage is not in any category.
1480 continue;
1482 if (array_key_exists($course->id, $this->addedcourses)) {
1483 // It is probably better to not include the already loaded courses
1484 // directly in SQL because inequalities may confuse query optimisers
1485 // and may interfere with query caching.
1486 continue;
1488 if (!$this->can_add_more_courses_to_category($course->category)) {
1489 continue;
1491 context_helper::preload_from_record($course);
1492 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1493 continue;
1495 $coursenodes[$course->id] = $this->add_course($course);
1497 $coursesrs->close();
1500 if (count($partfetch)) {
1501 // Next we will work our way through the categories where we will likely only need a small
1502 // proportion of the courses.
1503 foreach ($partfetch as $categoryid) {
1504 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1505 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1506 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1507 FROM {course} c
1508 $ccjoin
1509 WHERE c.category = :categoryid
1510 ORDER BY c.sortorder ASC";
1511 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1512 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1513 foreach ($coursesrs as $course) {
1514 if ($course->id == $SITE->id) {
1515 // This should not be necessary, frontpage is not in any category.
1516 continue;
1518 if (array_key_exists($course->id, $this->addedcourses)) {
1519 // It is probably better to not include the already loaded courses
1520 // directly in SQL because inequalities may confuse query optimisers
1521 // and may interfere with query caching.
1522 // This also helps to respect expected $limit on repeated executions.
1523 continue;
1525 if (!$this->can_add_more_courses_to_category($course->category)) {
1526 break;
1528 context_helper::preload_from_record($course);
1529 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1530 continue;
1532 $coursenodes[$course->id] = $this->add_course($course);
1534 $coursesrs->close();
1537 } else {
1538 // Prepare the SQL to load the courses and their contexts
1539 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1540 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1541 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1542 $courseparams['contextlevel'] = CONTEXT_COURSE;
1543 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1544 FROM {course} c
1545 $ccjoin
1546 WHERE c.id {$courseids}
1547 ORDER BY c.sortorder ASC";
1548 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1549 foreach ($coursesrs as $course) {
1550 if ($course->id == $SITE->id) {
1551 // frotpage is not wanted here
1552 continue;
1554 if ($this->page->course && ($this->page->course->id == $course->id)) {
1555 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1556 continue;
1558 context_helper::preload_from_record($course);
1559 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1560 continue;
1562 $coursenodes[$course->id] = $this->add_course($course);
1563 if (count($coursenodes) >= $limit) {
1564 break;
1567 $coursesrs->close();
1570 return $coursenodes;
1574 * Returns true if more courses can be added to the provided category.
1576 * @param int|navigation_node|stdClass $category
1577 * @return bool
1579 protected function can_add_more_courses_to_category($category) {
1580 global $CFG;
1581 $limit = 20;
1582 if (!empty($CFG->navcourselimit)) {
1583 $limit = (int)$CFG->navcourselimit;
1585 if (is_numeric($category)) {
1586 if (!array_key_exists($category, $this->addedcategories)) {
1587 return true;
1589 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1590 } else if ($category instanceof navigation_node) {
1591 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1592 return false;
1594 $coursecount = count($category->children->type(self::TYPE_COURSE));
1595 } else if (is_object($category) && property_exists($category,'id')) {
1596 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1598 return ($coursecount <= $limit);
1602 * Loads all categories (top level or if an id is specified for that category)
1604 * @param int $categoryid The category id to load or null/0 to load all base level categories
1605 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1606 * as the requested category and any parent categories.
1607 * @return navigation_node|void returns a navigation node if a category has been loaded.
1609 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1610 global $CFG, $DB;
1612 // Check if this category has already been loaded
1613 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1614 return true;
1617 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1618 $sqlselect = "SELECT cc.*, $catcontextsql
1619 FROM {course_categories} cc
1620 JOIN {context} ctx ON cc.id = ctx.instanceid";
1621 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1622 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1623 $params = array();
1625 $categoriestoload = array();
1626 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1627 // We are going to load all categories regardless... prepare to fire
1628 // on the database server!
1629 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1630 // We are going to load all of the first level categories (categories without parents)
1631 $sqlwhere .= " AND cc.parent = 0";
1632 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1633 // The category itself has been loaded already so we just need to ensure its subcategories
1634 // have been loaded
1635 $addedcategories = $this->addedcategories;
1636 unset($addedcategories[$categoryid]);
1637 if (count($addedcategories) > 0) {
1638 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1639 if ($showbasecategories) {
1640 // We need to include categories with parent = 0 as well
1641 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1642 } else {
1643 // All we need is categories that match the parent
1644 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1647 $params['categoryid'] = $categoryid;
1648 } else {
1649 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1650 // and load this category plus all its parents and subcategories
1651 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1652 $categoriestoload = explode('/', trim($category->path, '/'));
1653 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1654 // We are going to use select twice so double the params
1655 $params = array_merge($params, $params);
1656 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1657 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1660 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1661 $categories = array();
1662 foreach ($categoriesrs as $category) {
1663 // Preload the context.. we'll need it when adding the category in order
1664 // to format the category name.
1665 context_helper::preload_from_record($category);
1666 if (array_key_exists($category->id, $this->addedcategories)) {
1667 // Do nothing, its already been added.
1668 } else if ($category->parent == '0') {
1669 // This is a root category lets add it immediately
1670 $this->add_category($category, $this->rootnodes['courses']);
1671 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1672 // This categories parent has already been added we can add this immediately
1673 $this->add_category($category, $this->addedcategories[$category->parent]);
1674 } else {
1675 $categories[] = $category;
1678 $categoriesrs->close();
1680 // Now we have an array of categories we need to add them to the navigation.
1681 while (!empty($categories)) {
1682 $category = reset($categories);
1683 if (array_key_exists($category->id, $this->addedcategories)) {
1684 // Do nothing
1685 } else if ($category->parent == '0') {
1686 $this->add_category($category, $this->rootnodes['courses']);
1687 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1688 $this->add_category($category, $this->addedcategories[$category->parent]);
1689 } else {
1690 // This category isn't in the navigation and niether is it's parent (yet).
1691 // We need to go through the category path and add all of its components in order.
1692 $path = explode('/', trim($category->path, '/'));
1693 foreach ($path as $catid) {
1694 if (!array_key_exists($catid, $this->addedcategories)) {
1695 // This category isn't in the navigation yet so add it.
1696 $subcategory = $categories[$catid];
1697 if ($subcategory->parent == '0') {
1698 // Yay we have a root category - this likely means we will now be able
1699 // to add categories without problems.
1700 $this->add_category($subcategory, $this->rootnodes['courses']);
1701 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1702 // The parent is in the category (as we'd expect) so add it now.
1703 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1704 // Remove the category from the categories array.
1705 unset($categories[$catid]);
1706 } else {
1707 // We should never ever arrive here - if we have then there is a bigger
1708 // problem at hand.
1709 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1714 // Remove the category from the categories array now that we know it has been added.
1715 unset($categories[$category->id]);
1717 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1718 $this->allcategoriesloaded = true;
1720 // Check if there are any categories to load.
1721 if (count($categoriestoload) > 0) {
1722 $readytoloadcourses = array();
1723 foreach ($categoriestoload as $category) {
1724 if ($this->can_add_more_courses_to_category($category)) {
1725 $readytoloadcourses[] = $category;
1728 if (count($readytoloadcourses)) {
1729 $this->load_all_courses($readytoloadcourses);
1733 // Look for all categories which have been loaded
1734 if (!empty($this->addedcategories)) {
1735 $categoryids = array();
1736 foreach ($this->addedcategories as $category) {
1737 if ($this->can_add_more_courses_to_category($category)) {
1738 $categoryids[] = $category->key;
1741 if ($categoryids) {
1742 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1743 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1744 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1745 FROM {course_categories} cc
1746 JOIN {course} c ON c.category = cc.id
1747 WHERE cc.id {$categoriessql}
1748 GROUP BY cc.id
1749 HAVING COUNT(c.id) > :limit";
1750 $excessivecategories = $DB->get_records_sql($sql, $params);
1751 foreach ($categories as &$category) {
1752 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1753 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1754 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1762 * Adds a structured category to the navigation in the correct order/place
1764 * @param stdClass $category category to be added in navigation.
1765 * @param navigation_node $parent parent navigation node
1766 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1767 * @return void.
1769 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1770 if (array_key_exists($category->id, $this->addedcategories)) {
1771 return;
1773 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1774 $context = context_coursecat::instance($category->id);
1775 $categoryname = format_string($category->name, true, array('context' => $context));
1776 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1777 if (empty($category->visible)) {
1778 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1779 $categorynode->hidden = true;
1780 } else {
1781 $categorynode->display = false;
1784 $this->addedcategories[$category->id] = $categorynode;
1788 * Loads the given course into the navigation
1790 * @param stdClass $course
1791 * @return navigation_node
1793 protected function load_course(stdClass $course) {
1794 global $SITE;
1795 if ($course->id == $SITE->id) {
1796 // This is always loaded during initialisation
1797 return $this->rootnodes['site'];
1798 } else if (array_key_exists($course->id, $this->addedcourses)) {
1799 // The course has already been loaded so return a reference
1800 return $this->addedcourses[$course->id];
1801 } else {
1802 // Add the course
1803 return $this->add_course($course);
1808 * Loads all of the courses section into the navigation.
1810 * This function calls method from current course format, see
1811 * {@link format_base::extend_course_navigation()}
1812 * If course module ($cm) is specified but course format failed to create the node,
1813 * the activity node is created anyway.
1815 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1817 * @param stdClass $course Database record for the course
1818 * @param navigation_node $coursenode The course node within the navigation
1819 * @param null|int $sectionnum If specified load the contents of section with this relative number
1820 * @param null|cm_info $cm If specified make sure that activity node is created (either
1821 * in containg section or by calling load_stealth_activity() )
1823 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1824 global $CFG, $SITE;
1825 require_once($CFG->dirroot.'/course/lib.php');
1826 if (isset($cm->sectionnum)) {
1827 $sectionnum = $cm->sectionnum;
1829 if ($sectionnum !== null) {
1830 $this->includesectionnum = $sectionnum;
1832 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1833 if (isset($cm->id)) {
1834 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1835 if (empty($activity)) {
1836 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1842 * Generates an array of sections and an array of activities for the given course.
1844 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1846 * @param stdClass $course
1847 * @return array Array($sections, $activities)
1849 protected function generate_sections_and_activities(stdClass $course) {
1850 global $CFG;
1851 require_once($CFG->dirroot.'/course/lib.php');
1853 $modinfo = get_fast_modinfo($course);
1854 $sections = $modinfo->get_section_info_all();
1856 // For course formats using 'numsections' trim the sections list
1857 $courseformatoptions = course_get_format($course)->get_format_options();
1858 if (isset($courseformatoptions['numsections'])) {
1859 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1862 $activities = array();
1864 foreach ($sections as $key => $section) {
1865 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1866 $sections[$key] = clone($section);
1867 unset($sections[$key]->summary);
1868 $sections[$key]->hasactivites = false;
1869 if (!array_key_exists($section->section, $modinfo->sections)) {
1870 continue;
1872 foreach ($modinfo->sections[$section->section] as $cmid) {
1873 $cm = $modinfo->cms[$cmid];
1874 $activity = new stdClass;
1875 $activity->id = $cm->id;
1876 $activity->course = $course->id;
1877 $activity->section = $section->section;
1878 $activity->name = $cm->name;
1879 $activity->icon = $cm->icon;
1880 $activity->iconcomponent = $cm->iconcomponent;
1881 $activity->hidden = (!$cm->visible);
1882 $activity->modname = $cm->modname;
1883 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1884 $activity->onclick = $cm->onclick;
1885 $url = $cm->url;
1886 if (!$url) {
1887 $activity->url = null;
1888 $activity->display = false;
1889 } else {
1890 $activity->url = $url->out();
1891 $activity->display = $cm->uservisible ? true : false;
1892 if (self::module_extends_navigation($cm->modname)) {
1893 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1896 $activities[$cmid] = $activity;
1897 if ($activity->display) {
1898 $sections[$key]->hasactivites = true;
1903 return array($sections, $activities);
1907 * Generically loads the course sections into the course's navigation.
1909 * @param stdClass $course
1910 * @param navigation_node $coursenode
1911 * @return array An array of course section nodes
1913 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1914 global $CFG, $DB, $USER, $SITE;
1915 require_once($CFG->dirroot.'/course/lib.php');
1917 list($sections, $activities) = $this->generate_sections_and_activities($course);
1919 $navigationsections = array();
1920 foreach ($sections as $sectionid => $section) {
1921 $section = clone($section);
1922 if ($course->id == $SITE->id) {
1923 $this->load_section_activities($coursenode, $section->section, $activities);
1924 } else {
1925 if (!$section->uservisible || (!$this->showemptysections &&
1926 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1927 continue;
1930 $sectionname = get_section_name($course, $section);
1931 $url = course_get_url($course, $section->section, array('navigation' => true));
1933 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1934 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1935 $sectionnode->hidden = (!$section->visible || !$section->available);
1936 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1937 $this->load_section_activities($sectionnode, $section->section, $activities);
1939 $section->sectionnode = $sectionnode;
1940 $navigationsections[$sectionid] = $section;
1943 return $navigationsections;
1947 * Loads all of the activities for a section into the navigation structure.
1949 * @param navigation_node $sectionnode
1950 * @param int $sectionnumber
1951 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1952 * @param stdClass $course The course object the section and activities relate to.
1953 * @return array Array of activity nodes
1955 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1956 global $CFG, $SITE;
1957 // A static counter for JS function naming
1958 static $legacyonclickcounter = 0;
1960 $activitynodes = array();
1961 if (empty($activities)) {
1962 return $activitynodes;
1965 if (!is_object($course)) {
1966 $activity = reset($activities);
1967 $courseid = $activity->course;
1968 } else {
1969 $courseid = $course->id;
1971 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1973 foreach ($activities as $activity) {
1974 if ($activity->section != $sectionnumber) {
1975 continue;
1977 if ($activity->icon) {
1978 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1979 } else {
1980 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1983 // Prepare the default name and url for the node
1984 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1985 $action = new moodle_url($activity->url);
1987 // Check if the onclick property is set (puke!)
1988 if (!empty($activity->onclick)) {
1989 // Increment the counter so that we have a unique number.
1990 $legacyonclickcounter++;
1991 // Generate the function name we will use
1992 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1993 $propogrationhandler = '';
1994 // Check if we need to cancel propogation. Remember inline onclick
1995 // events would return false if they wanted to prevent propogation and the
1996 // default action.
1997 if (strpos($activity->onclick, 'return false')) {
1998 $propogrationhandler = 'e.halt();';
2000 // Decode the onclick - it has already been encoded for display (puke)
2001 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2002 // Build the JS function the click event will call
2003 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2004 $this->page->requires->js_init_code($jscode);
2005 // Override the default url with the new action link
2006 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2009 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2010 $activitynode->title(get_string('modulename', $activity->modname));
2011 $activitynode->hidden = $activity->hidden;
2012 $activitynode->display = $showactivities && $activity->display;
2013 $activitynode->nodetype = $activity->nodetype;
2014 $activitynodes[$activity->id] = $activitynode;
2017 return $activitynodes;
2020 * Loads a stealth module from unavailable section
2021 * @param navigation_node $coursenode
2022 * @param stdClass $modinfo
2023 * @return navigation_node or null if not accessible
2025 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2026 if (empty($modinfo->cms[$this->page->cm->id])) {
2027 return null;
2029 $cm = $modinfo->cms[$this->page->cm->id];
2030 if ($cm->icon) {
2031 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2032 } else {
2033 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2035 $url = $cm->url;
2036 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2037 $activitynode->title(get_string('modulename', $cm->modname));
2038 $activitynode->hidden = (!$cm->visible);
2039 if (!$cm->uservisible) {
2040 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2041 // Also there may be no exception at all in case when teacher is logged in as student.
2042 $activitynode->display = false;
2043 } else if (!$url) {
2044 // Don't show activities that don't have links!
2045 $activitynode->display = false;
2046 } else if (self::module_extends_navigation($cm->modname)) {
2047 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2049 return $activitynode;
2052 * Loads the navigation structure for the given activity into the activities node.
2054 * This method utilises a callback within the modules lib.php file to load the
2055 * content specific to activity given.
2057 * The callback is a method: {modulename}_extend_navigation()
2058 * Examples:
2059 * * {@link forum_extend_navigation()}
2060 * * {@link workshop_extend_navigation()}
2062 * @param cm_info|stdClass $cm
2063 * @param stdClass $course
2064 * @param navigation_node $activity
2065 * @return bool
2067 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2068 global $CFG, $DB;
2070 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2071 if (!($cm instanceof cm_info)) {
2072 $modinfo = get_fast_modinfo($course);
2073 $cm = $modinfo->get_cm($cm->id);
2075 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2076 $activity->make_active();
2077 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2078 $function = $cm->modname.'_extend_navigation';
2080 if (file_exists($file)) {
2081 require_once($file);
2082 if (function_exists($function)) {
2083 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2084 $function($activity, $course, $activtyrecord, $cm);
2088 // Allow the active advanced grading method plugin to append module navigation
2089 $featuresfunc = $cm->modname.'_supports';
2090 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2091 require_once($CFG->dirroot.'/grade/grading/lib.php');
2092 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2093 $gradingman->extend_navigation($this, $activity);
2096 return $activity->has_children();
2099 * Loads user specific information into the navigation in the appropriate place.
2101 * If no user is provided the current user is assumed.
2103 * @param stdClass $user
2104 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2105 * @return bool
2107 protected function load_for_user($user=null, $forceforcontext=false) {
2108 global $DB, $CFG, $USER, $SITE;
2110 if ($user === null) {
2111 // We can't require login here but if the user isn't logged in we don't
2112 // want to show anything
2113 if (!isloggedin() || isguestuser()) {
2114 return false;
2116 $user = $USER;
2117 } else if (!is_object($user)) {
2118 // If the user is not an object then get them from the database
2119 $select = context_helper::get_preload_record_columns_sql('ctx');
2120 $sql = "SELECT u.*, $select
2121 FROM {user} u
2122 JOIN {context} ctx ON u.id = ctx.instanceid
2123 WHERE u.id = :userid AND
2124 ctx.contextlevel = :contextlevel";
2125 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2126 context_helper::preload_from_record($user);
2129 $iscurrentuser = ($user->id == $USER->id);
2131 $usercontext = context_user::instance($user->id);
2133 // Get the course set against the page, by default this will be the site
2134 $course = $this->page->course;
2135 $baseargs = array('id'=>$user->id);
2136 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2137 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2138 $baseargs['course'] = $course->id;
2139 $coursecontext = context_course::instance($course->id);
2140 $issitecourse = false;
2141 } else {
2142 // Load all categories and get the context for the system
2143 $coursecontext = context_system::instance();
2144 $issitecourse = true;
2147 // Create a node to add user information under.
2148 if ($iscurrentuser && !$forceforcontext) {
2149 // If it's the current user the information will go under the profile root node
2150 $usernode = $this->rootnodes['myprofile'];
2151 $course = get_site();
2152 $coursecontext = context_course::instance($course->id);
2153 $issitecourse = true;
2154 } else {
2155 if (!$issitecourse) {
2156 // Not the current user so add it to the participants node for the current course
2157 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2158 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2159 } else {
2160 // This is the site so add a users node to the root branch
2161 $usersnode = $this->rootnodes['users'];
2162 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2163 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2165 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2167 if (!$usersnode) {
2168 // We should NEVER get here, if the course hasn't been populated
2169 // with a participants node then the navigaiton either wasn't generated
2170 // for it (you are missing a require_login or set_context call) or
2171 // you don't have access.... in the interests of no leaking informatin
2172 // we simply quit...
2173 return false;
2175 // Add a branch for the current user
2176 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2177 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2179 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2180 $usernode->make_active();
2184 // If the user is the current user or has permission to view the details of the requested
2185 // user than add a view profile link.
2186 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2187 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2188 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2189 } else {
2190 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2194 if (!empty($CFG->navadduserpostslinks)) {
2195 // Add nodes for forum posts and discussions if the user can view either or both
2196 // There are no capability checks here as the content of the page is based
2197 // purely on the forums the current user has access too.
2198 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2199 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2200 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2203 // Add blog nodes
2204 if (!empty($CFG->enableblogs)) {
2205 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2206 require_once($CFG->dirroot.'/blog/lib.php');
2207 // Get all options for the user
2208 $options = blog_get_options_for_user($user);
2209 $this->cache->set('userblogoptions'.$user->id, $options);
2210 } else {
2211 $options = $this->cache->{'userblogoptions'.$user->id};
2214 if (count($options) > 0) {
2215 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2216 foreach ($options as $type => $option) {
2217 if ($type == "rss") {
2218 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2219 } else {
2220 $blogs->add($option['string'], $option['link']);
2226 // Add the messages link.
2227 // It is context based so can appear in "My profile" and in course participants information.
2228 if (!empty($CFG->messaging)) {
2229 $messageargs = array('user1' => $USER->id);
2230 if ($USER->id != $user->id) {
2231 $messageargs['user2'] = $user->id;
2233 if ($course->id != $SITE->id) {
2234 $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
2236 $url = new moodle_url('/message/index.php',$messageargs);
2237 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2240 // Add the "My private files" link.
2241 // This link doesn't have a unique display for course context so only display it under "My profile".
2242 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2243 $url = new moodle_url('/user/files.php');
2244 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2247 if (!empty($CFG->enablebadges) && $iscurrentuser &&
2248 has_capability('moodle/badges:manageownbadges', $usercontext)) {
2249 $url = new moodle_url('/badges/mybadges.php');
2250 $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2253 // Add a node to view the users notes if permitted
2254 if (!empty($CFG->enablenotes) && 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 // If the user is the current user add the repositories for the current user
2263 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2264 if ($iscurrentuser) {
2265 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2266 require_once($CFG->dirroot . '/repository/lib.php');
2267 $editabletypes = repository::get_editable_types($usercontext);
2268 $haseditabletypes = !empty($editabletypes);
2269 unset($editabletypes);
2270 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2271 } else {
2272 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2274 if ($haseditabletypes) {
2275 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2277 } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2279 // Add view grade report is permitted
2280 $reports = core_component::get_plugin_list('gradereport');
2281 arsort($reports); // user is last, we want to test it first
2283 $userscourses = enrol_get_users_courses($user->id);
2284 $userscoursesnode = $usernode->add(get_string('courses'));
2286 $count = 0;
2287 foreach ($userscourses as $usercourse) {
2288 if ($count === (int)$CFG->navcourselimit) {
2289 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2290 $userscoursesnode->add(get_string('showallcourses'), $url);
2291 break;
2293 $count++;
2294 $usercoursecontext = context_course::instance($usercourse->id);
2295 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2296 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2298 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2299 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2300 foreach ($reports as $plugin => $plugindir) {
2301 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2302 //stop when the first visible plugin is found
2303 $gradeavailable = true;
2304 break;
2309 if ($gradeavailable) {
2310 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2311 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2314 // Add a node to view the users notes if permitted
2315 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2316 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2317 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2320 if (can_access_course($usercourse, $user->id, '', true)) {
2321 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id'=>$usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2324 $reporttab = $usercoursenode->add(get_string('activityreports'));
2326 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2327 foreach ($reports as $reportfunction) {
2328 $reportfunction($reporttab, $user, $usercourse);
2331 $reporttab->trim_if_empty();
2334 return true;
2338 * This method simply checks to see if a given module can extend the navigation.
2340 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2342 * @param string $modname
2343 * @return bool
2345 public static function module_extends_navigation($modname) {
2346 global $CFG;
2347 static $extendingmodules = array();
2348 if (!array_key_exists($modname, $extendingmodules)) {
2349 $extendingmodules[$modname] = false;
2350 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2351 if (file_exists($file)) {
2352 $function = $modname.'_extend_navigation';
2353 require_once($file);
2354 $extendingmodules[$modname] = (function_exists($function));
2357 return $extendingmodules[$modname];
2360 * Extends the navigation for the given user.
2362 * @param stdClass $user A user from the database
2364 public function extend_for_user($user) {
2365 $this->extendforuser[] = $user;
2369 * Returns all of the users the navigation is being extended for
2371 * @return array An array of extending users.
2373 public function get_extending_users() {
2374 return $this->extendforuser;
2377 * Adds the given course to the navigation structure.
2379 * @param stdClass $course
2380 * @param bool $forcegeneric
2381 * @param bool $ismycourse
2382 * @return navigation_node
2384 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2385 global $CFG, $SITE;
2387 // We found the course... we can return it now :)
2388 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2389 return $this->addedcourses[$course->id];
2392 $coursecontext = context_course::instance($course->id);
2394 if ($course->id != $SITE->id && !$course->visible) {
2395 if (is_role_switched($course->id)) {
2396 // user has to be able to access course in order to switch, let's skip the visibility test here
2397 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2398 return false;
2402 $issite = ($course->id == $SITE->id);
2403 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2404 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2405 // This is the name that will be shown for the course.
2406 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2408 // Can the user expand the course to see its content.
2409 $canexpandcourse = true;
2410 if ($issite) {
2411 $parent = $this;
2412 $url = null;
2413 if (empty($CFG->usesitenameforsitepages)) {
2414 $coursename = get_string('sitepages');
2416 } else if ($coursetype == self::COURSE_CURRENT) {
2417 $parent = $this->rootnodes['currentcourse'];
2418 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2419 $canexpandcourse = $this->can_expand_course($course);
2420 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2421 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2422 // Nothing to do here the above statement set $parent to the category within mycourses.
2423 } else {
2424 $parent = $this->rootnodes['mycourses'];
2426 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2427 } else {
2428 $parent = $this->rootnodes['courses'];
2429 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2430 // They can only expand the course if they can access it.
2431 $canexpandcourse = $this->can_expand_course($course);
2432 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2433 if (!$this->is_category_fully_loaded($course->category)) {
2434 // We need to load the category structure for this course
2435 $this->load_all_categories($course->category, false);
2437 if (array_key_exists($course->category, $this->addedcategories)) {
2438 $parent = $this->addedcategories[$course->category];
2439 // This could lead to the course being created so we should check whether it is the case again
2440 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2441 return $this->addedcourses[$course->id];
2447 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2448 $coursenode->hidden = (!$course->visible);
2449 // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
2450 // later.
2451 $coursenode->title(str_replace('&amp;', '&', $fullname));
2452 if ($canexpandcourse) {
2453 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2454 $coursenode->nodetype = self::NODETYPE_BRANCH;
2455 $coursenode->isexpandable = true;
2456 } else {
2457 $coursenode->nodetype = self::NODETYPE_LEAF;
2458 $coursenode->isexpandable = false;
2460 if (!$forcegeneric) {
2461 $this->addedcourses[$course->id] = $coursenode;
2464 return $coursenode;
2468 * Returns a cache instance to use for the expand course cache.
2469 * @return cache_session
2471 protected function get_expand_course_cache() {
2472 if ($this->cacheexpandcourse === null) {
2473 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2475 return $this->cacheexpandcourse;
2479 * Checks if a user can expand a course in the navigation.
2481 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2482 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2483 * permits stale data.
2484 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2485 * will be stale.
2486 * It is brought up to date in only one of two ways.
2487 * 1. The user logs out and in again.
2488 * 2. The user browses to the course they've just being given access to.
2490 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2492 * @param stdClass $course
2493 * @return bool
2495 protected function can_expand_course($course) {
2496 $cache = $this->get_expand_course_cache();
2497 $canexpand = $cache->get($course->id);
2498 if ($canexpand === false) {
2499 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2500 $canexpand = (int)$canexpand;
2501 $cache->set($course->id, $canexpand);
2503 return ($canexpand === 1);
2507 * Returns true if the category has already been loaded as have any child categories
2509 * @param int $categoryid
2510 * @return bool
2512 protected function is_category_fully_loaded($categoryid) {
2513 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2517 * Adds essential course nodes to the navigation for the given course.
2519 * This method adds nodes such as reports, blogs and participants
2521 * @param navigation_node $coursenode
2522 * @param stdClass $course
2523 * @return bool returns true on successful addition of a node.
2525 public function add_course_essentials($coursenode, stdClass $course) {
2526 global $CFG, $SITE;
2528 if ($course->id == $SITE->id) {
2529 return $this->add_front_page_course_essentials($coursenode, $course);
2532 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2533 return true;
2536 //Participants
2537 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2538 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2539 if (!empty($CFG->enableblogs)) {
2540 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2541 and has_capability('moodle/blog:view', context_system::instance())) {
2542 $blogsurls = new moodle_url('/blog/index.php');
2543 if ($course->id == $SITE->id) {
2544 $blogsurls->param('courseid', 0);
2545 } else if ($currentgroup = groups_get_course_group($course, true)) {
2546 $blogsurls->param('groupid', $currentgroup);
2547 } else {
2548 $blogsurls->param('courseid', $course->id);
2550 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2553 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2554 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2556 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2557 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2560 // Badges.
2561 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2562 has_capability('moodle/badges:viewbadges', $this->page->context)) {
2563 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2565 $coursenode->add(get_string('coursebadges', 'badges'), null,
2566 navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2567 $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2568 navigation_node::TYPE_SETTING, null, 'badgesview',
2569 new pix_icon('i/badge', get_string('badgesview', 'badges')));
2572 return true;
2575 * This generates the structure of the course that won't be generated when
2576 * the modules and sections are added.
2578 * Things such as the reports branch, the participants branch, blogs... get
2579 * added to the course node by this method.
2581 * @param navigation_node $coursenode
2582 * @param stdClass $course
2583 * @return bool True for successfull generation
2585 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2586 global $CFG;
2588 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2589 return true;
2592 // Hidden node that we use to determine if the front page navigation is loaded.
2593 // This required as there are not other guaranteed nodes that may be loaded.
2594 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2596 //Participants
2597 if (has_capability('moodle/course:viewparticipants', context_system::instance())) {
2598 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2601 $filterselect = 0;
2603 // Blogs
2604 if (!empty($CFG->enableblogs)
2605 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2606 and has_capability('moodle/blog:view', context_system::instance())) {
2607 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2608 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2611 //Badges
2612 if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2613 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2614 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2617 // Notes
2618 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2619 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2622 // Tags
2623 if (!empty($CFG->usetags) && isloggedin()) {
2624 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2627 if (isloggedin()) {
2628 // Calendar
2629 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2630 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2633 return true;
2637 * Clears the navigation cache
2639 public function clear_cache() {
2640 $this->cache->clear();
2644 * Sets an expansion limit for the navigation
2646 * The expansion limit is used to prevent the display of content that has a type
2647 * greater than the provided $type.
2649 * Can be used to ensure things such as activities or activity content don't get
2650 * shown on the navigation.
2651 * They are still generated in order to ensure the navbar still makes sense.
2653 * @param int $type One of navigation_node::TYPE_*
2654 * @return bool true when complete.
2656 public function set_expansion_limit($type) {
2657 global $SITE;
2658 $nodes = $this->find_all_of_type($type);
2660 // We only want to hide specific types of nodes.
2661 // Only nodes that represent "structure" in the navigation tree should be hidden.
2662 // If we hide all nodes then we risk hiding vital information.
2663 $typestohide = array(
2664 self::TYPE_CATEGORY,
2665 self::TYPE_COURSE,
2666 self::TYPE_SECTION,
2667 self::TYPE_ACTIVITY
2670 foreach ($nodes as $node) {
2671 // We need to generate the full site node
2672 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2673 continue;
2675 foreach ($node->children as $child) {
2676 $child->hide($typestohide);
2679 return true;
2682 * Attempts to get the navigation with the given key from this nodes children.
2684 * This function only looks at this nodes children, it does NOT look recursivily.
2685 * If the node can't be found then false is returned.
2687 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2689 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2690 * may be of more use to you.
2692 * @param string|int $key The key of the node you wish to receive.
2693 * @param int $type One of navigation_node::TYPE_*
2694 * @return navigation_node|false
2696 public function get($key, $type = null) {
2697 if (!$this->initialised) {
2698 $this->initialise();
2700 return parent::get($key, $type);
2704 * Searches this nodes children and their children to find a navigation node
2705 * with the matching key and type.
2707 * This method is recursive and searches children so until either a node is
2708 * found or there are no more nodes to search.
2710 * If you know that the node being searched for is a child of this node
2711 * then use the {@link global_navigation::get()} method instead.
2713 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2714 * may be of more use to you.
2716 * @param string|int $key The key of the node you wish to receive.
2717 * @param int $type One of navigation_node::TYPE_*
2718 * @return navigation_node|false
2720 public function find($key, $type) {
2721 if (!$this->initialised) {
2722 $this->initialise();
2724 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2725 return $this->rootnodes[$key];
2727 return parent::find($key, $type);
2731 * They've expanded the 'my courses' branch.
2733 protected function load_courses_enrolled() {
2734 global $CFG, $DB;
2735 $sortorder = 'visible DESC';
2736 // Prevent undefined $CFG->navsortmycoursessort errors.
2737 if (empty($CFG->navsortmycoursessort)) {
2738 $CFG->navsortmycoursessort = 'sortorder';
2740 // Append the chosen sortorder.
2741 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2742 $courses = enrol_get_my_courses(null, $sortorder);
2743 if (count($courses) && $this->show_my_categories()) {
2744 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2745 // In order to make sure we load everything required we must first find the categories that are not
2746 // base categories and work out the bottom category in thier path.
2747 $categoryids = array();
2748 foreach ($courses as $course) {
2749 $categoryids[] = $course->category;
2751 $categoryids = array_unique($categoryids);
2752 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2753 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2754 foreach ($categories as $category) {
2755 $bits = explode('/', trim($category->path,'/'));
2756 $categoryids[] = array_shift($bits);
2758 $categoryids = array_unique($categoryids);
2759 $categories->close();
2761 // Now we load the base categories.
2762 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2763 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2764 foreach ($categories as $category) {
2765 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2767 $categories->close();
2768 } else {
2769 foreach ($courses as $course) {
2770 $this->add_course($course, false, self::COURSE_MY);
2777 * The global navigation class used especially for AJAX requests.
2779 * The primary methods that are used in the global navigation class have been overriden
2780 * to ensure that only the relevant branch is generated at the root of the tree.
2781 * This can be done because AJAX is only used when the backwards structure for the
2782 * requested branch exists.
2783 * This has been done only because it shortens the amounts of information that is generated
2784 * which of course will speed up the response time.. because no one likes laggy AJAX.
2786 * @package core
2787 * @category navigation
2788 * @copyright 2009 Sam Hemelryk
2789 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2791 class global_navigation_for_ajax extends global_navigation {
2793 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2794 protected $branchtype;
2796 /** @var int the instance id */
2797 protected $instanceid;
2799 /** @var array Holds an array of expandable nodes */
2800 protected $expandable = array();
2803 * Constructs the navigation for use in an AJAX request
2805 * @param moodle_page $page moodle_page object
2806 * @param int $branchtype
2807 * @param int $id
2809 public function __construct($page, $branchtype, $id) {
2810 $this->page = $page;
2811 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2812 $this->children = new navigation_node_collection();
2813 $this->branchtype = $branchtype;
2814 $this->instanceid = $id;
2815 $this->initialise();
2818 * Initialise the navigation given the type and id for the branch to expand.
2820 * @return array An array of the expandable nodes
2822 public function initialise() {
2823 global $DB, $SITE;
2825 if ($this->initialised || during_initial_install()) {
2826 return $this->expandable;
2828 $this->initialised = true;
2830 $this->rootnodes = array();
2831 $this->rootnodes['site'] = $this->add_course($SITE);
2832 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2833 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2834 // The courses branch is always displayed, and is always expandable (although may be empty).
2835 // This mimicks what is done during {@link global_navigation::initialise()}.
2836 $this->rootnodes['courses']->isexpandable = true;
2838 // Branchtype will be one of navigation_node::TYPE_*
2839 switch ($this->branchtype) {
2840 case 0:
2841 if ($this->instanceid === 'mycourses') {
2842 $this->load_courses_enrolled();
2843 } else if ($this->instanceid === 'courses') {
2844 $this->load_courses_other();
2846 break;
2847 case self::TYPE_CATEGORY :
2848 $this->load_category($this->instanceid);
2849 break;
2850 case self::TYPE_MY_CATEGORY :
2851 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2852 break;
2853 case self::TYPE_COURSE :
2854 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2855 if (!can_access_course($course, null, '', true)) {
2856 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
2857 // add the course node and break. This leads to an empty node.
2858 $this->add_course($course);
2859 break;
2861 require_course_login($course, true, null, false, true);
2862 $this->page->set_context(context_course::instance($course->id));
2863 $coursenode = $this->add_course($course);
2864 $this->add_course_essentials($coursenode, $course);
2865 $this->load_course_sections($course, $coursenode);
2866 break;
2867 case self::TYPE_SECTION :
2868 $sql = 'SELECT c.*, cs.section AS sectionnumber
2869 FROM {course} c
2870 LEFT JOIN {course_sections} cs ON cs.course = c.id
2871 WHERE cs.id = ?';
2872 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2873 require_course_login($course, true, null, false, true);
2874 $this->page->set_context(context_course::instance($course->id));
2875 $coursenode = $this->add_course($course);
2876 $this->add_course_essentials($coursenode, $course);
2877 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2878 break;
2879 case self::TYPE_ACTIVITY :
2880 $sql = "SELECT c.*
2881 FROM {course} c
2882 JOIN {course_modules} cm ON cm.course = c.id
2883 WHERE cm.id = :cmid";
2884 $params = array('cmid' => $this->instanceid);
2885 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2886 $modinfo = get_fast_modinfo($course);
2887 $cm = $modinfo->get_cm($this->instanceid);
2888 require_course_login($course, true, $cm, false, true);
2889 $this->page->set_context(context_module::instance($cm->id));
2890 $coursenode = $this->load_course($course);
2891 $this->load_course_sections($course, $coursenode, null, $cm);
2892 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2893 if ($activitynode) {
2894 $modulenode = $this->load_activity($cm, $course, $activitynode);
2896 break;
2897 default:
2898 throw new Exception('Unknown type');
2899 return $this->expandable;
2902 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2903 $this->load_for_user(null, true);
2906 $this->find_expandable($this->expandable);
2907 return $this->expandable;
2911 * They've expanded the general 'courses' branch.
2913 protected function load_courses_other() {
2914 $this->load_all_courses();
2918 * Loads a single category into the AJAX navigation.
2920 * This function is special in that it doesn't concern itself with the parent of
2921 * the requested category or its siblings.
2922 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2923 * request that.
2925 * @global moodle_database $DB
2926 * @param int $categoryid id of category to load in navigation.
2927 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2928 * @return void.
2930 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2931 global $CFG, $DB;
2933 $limit = 20;
2934 if (!empty($CFG->navcourselimit)) {
2935 $limit = (int)$CFG->navcourselimit;
2938 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2939 $sql = "SELECT cc.*, $catcontextsql
2940 FROM {course_categories} cc
2941 JOIN {context} ctx ON cc.id = ctx.instanceid
2942 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2943 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2944 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2945 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2946 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2947 $categorylist = array();
2948 $subcategories = array();
2949 $basecategory = null;
2950 foreach ($categories as $category) {
2951 $categorylist[] = $category->id;
2952 context_helper::preload_from_record($category);
2953 if ($category->id == $categoryid) {
2954 $this->add_category($category, $this, $nodetype);
2955 $basecategory = $this->addedcategories[$category->id];
2956 } else {
2957 $subcategories[$category->id] = $category;
2960 $categories->close();
2963 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2964 // else show all courses.
2965 if ($nodetype === self::TYPE_MY_CATEGORY) {
2966 $courses = enrol_get_my_courses();
2967 $categoryids = array();
2969 // Only search for categories if basecategory was found.
2970 if (!is_null($basecategory)) {
2971 // Get course parent category ids.
2972 foreach ($courses as $course) {
2973 $categoryids[] = $course->category;
2976 // Get a unique list of category ids which a part of the path
2977 // to user's courses.
2978 $coursesubcategories = array();
2979 $addedsubcategories = array();
2981 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2982 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
2984 foreach ($categories as $category){
2985 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
2987 $coursesubcategories = array_unique($coursesubcategories);
2989 // Only add a subcategory if it is part of the path to user's course and
2990 // wasn't already added.
2991 foreach ($subcategories as $subid => $subcategory) {
2992 if (in_array($subid, $coursesubcategories) &&
2993 !in_array($subid, $addedsubcategories)) {
2994 $this->add_category($subcategory, $basecategory, $nodetype);
2995 $addedsubcategories[] = $subid;
3000 foreach ($courses as $course) {
3001 // Add course if it's in category.
3002 if (in_array($course->category, $categorylist)) {
3003 $this->add_course($course, true, self::COURSE_MY);
3006 } else {
3007 if (!is_null($basecategory)) {
3008 foreach ($subcategories as $key=>$category) {
3009 $this->add_category($category, $basecategory, $nodetype);
3012 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3013 foreach ($courses as $course) {
3014 $this->add_course($course);
3016 $courses->close();
3021 * Returns an array of expandable nodes
3022 * @return array
3024 public function get_expandable() {
3025 return $this->expandable;
3030 * Navbar class
3032 * This class is used to manage the navbar, which is initialised from the navigation
3033 * object held by PAGE
3035 * @package core
3036 * @category navigation
3037 * @copyright 2009 Sam Hemelryk
3038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3040 class navbar extends navigation_node {
3041 /** @var bool A switch for whether the navbar is initialised or not */
3042 protected $initialised = false;
3043 /** @var mixed keys used to reference the nodes on the navbar */
3044 protected $keys = array();
3045 /** @var null|string content of the navbar */
3046 protected $content = null;
3047 /** @var moodle_page object the moodle page that this navbar belongs to */
3048 protected $page;
3049 /** @var bool A switch for whether to ignore the active navigation information */
3050 protected $ignoreactive = false;
3051 /** @var bool A switch to let us know if we are in the middle of an install */
3052 protected $duringinstall = false;
3053 /** @var bool A switch for whether the navbar has items */
3054 protected $hasitems = false;
3055 /** @var array An array of navigation nodes for the navbar */
3056 protected $items;
3057 /** @var array An array of child node objects */
3058 public $children = array();
3059 /** @var bool A switch for whether we want to include the root node in the navbar */
3060 public $includesettingsbase = false;
3061 /** @var navigation_node[] $prependchildren */
3062 protected $prependchildren = array();
3064 * The almighty constructor
3066 * @param moodle_page $page
3068 public function __construct(moodle_page $page) {
3069 global $CFG;
3070 if (during_initial_install()) {
3071 $this->duringinstall = true;
3072 return false;
3074 $this->page = $page;
3075 $this->text = get_string('home');
3076 $this->shorttext = get_string('home');
3077 $this->action = new moodle_url($CFG->wwwroot);
3078 $this->nodetype = self::NODETYPE_BRANCH;
3079 $this->type = self::TYPE_SYSTEM;
3083 * Quick check to see if the navbar will have items in.
3085 * @return bool Returns true if the navbar will have items, false otherwise
3087 public function has_items() {
3088 if ($this->duringinstall) {
3089 return false;
3090 } else if ($this->hasitems !== false) {
3091 return true;
3093 $this->page->navigation->initialise($this->page);
3095 $activenodefound = ($this->page->navigation->contains_active_node() ||
3096 $this->page->settingsnav->contains_active_node());
3098 $outcome = (count($this->children) > 0 || count($this->prependchildren) || (!$this->ignoreactive && $activenodefound));
3099 $this->hasitems = $outcome;
3100 return $outcome;
3104 * Turn on/off ignore active
3106 * @param bool $setting
3108 public function ignore_active($setting=true) {
3109 $this->ignoreactive = ($setting);
3113 * Gets a navigation node
3115 * @param string|int $key for referencing the navbar nodes
3116 * @param int $type navigation_node::TYPE_*
3117 * @return navigation_node|bool
3119 public function get($key, $type = null) {
3120 foreach ($this->children as &$child) {
3121 if ($child->key === $key && ($type == null || $type == $child->type)) {
3122 return $child;
3125 foreach ($this->prependchildren as &$child) {
3126 if ($child->key === $key && ($type == null || $type == $child->type)) {
3127 return $child;
3130 return false;
3133 * Returns an array of navigation_node's that make up the navbar.
3135 * @return array
3137 public function get_items() {
3138 global $CFG;
3139 $items = array();
3140 // Make sure that navigation is initialised
3141 if (!$this->has_items()) {
3142 return $items;
3144 if ($this->items !== null) {
3145 return $this->items;
3148 if (count($this->children) > 0) {
3149 // Add the custom children.
3150 $items = array_reverse($this->children);
3153 $navigationactivenode = $this->page->navigation->find_active_node();
3154 $settingsactivenode = $this->page->settingsnav->find_active_node();
3156 // Check if navigation contains the active node
3157 if (!$this->ignoreactive) {
3159 if ($navigationactivenode && $settingsactivenode) {
3160 // Parse a combined navigation tree
3161 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3162 if (!$settingsactivenode->mainnavonly) {
3163 $items[] = $settingsactivenode;
3165 $settingsactivenode = $settingsactivenode->parent;
3167 if (!$this->includesettingsbase) {
3168 // Removes the first node from the settings (root node) from the list
3169 array_pop($items);
3171 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3172 if (!$navigationactivenode->mainnavonly) {
3173 $items[] = $navigationactivenode;
3175 if (!empty($CFG->navshowcategories) &&
3176 $navigationactivenode->type === self::TYPE_COURSE &&
3177 $navigationactivenode->parent->key === 'currentcourse') {
3178 $items = array_merge($items, $this->get_course_categories());
3180 $navigationactivenode = $navigationactivenode->parent;
3182 } else if ($navigationactivenode) {
3183 // Parse the navigation tree to get the active node
3184 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3185 if (!$navigationactivenode->mainnavonly) {
3186 $items[] = $navigationactivenode;
3188 if (!empty($CFG->navshowcategories) &&
3189 $navigationactivenode->type === self::TYPE_COURSE &&
3190 $navigationactivenode->parent->key === 'currentcourse') {
3191 $items = array_merge($items, $this->get_course_categories());
3193 $navigationactivenode = $navigationactivenode->parent;
3195 } else if ($settingsactivenode) {
3196 // Parse the settings navigation to get the active node
3197 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3198 if (!$settingsactivenode->mainnavonly) {
3199 $items[] = $settingsactivenode;
3201 $settingsactivenode = $settingsactivenode->parent;
3206 $items[] = new navigation_node(array(
3207 'text'=>$this->page->navigation->text,
3208 'shorttext'=>$this->page->navigation->shorttext,
3209 'key'=>$this->page->navigation->key,
3210 'action'=>$this->page->navigation->action
3213 if (count($this->prependchildren) > 0) {
3214 // Add the custom children
3215 $items = array_merge($items, array_reverse($this->prependchildren));
3218 $this->items = array_reverse($items);
3219 return $this->items;
3223 * Get the list of categories leading to this course.
3225 * This function is used by {@link navbar::get_items()} to add back the "courses"
3226 * node and category chain leading to the current course. Note that this is only ever
3227 * called for the current course, so we don't need to bother taking in any parameters.
3229 * @return array
3231 private function get_course_categories() {
3232 global $CFG;
3234 require_once($CFG->dirroot.'/course/lib.php');
3235 $categories = array();
3236 $cap = 'moodle/category:viewhiddencategories';
3237 foreach ($this->page->categories as $category) {
3238 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3239 continue;
3241 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3242 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3243 $categorynode = navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3244 if (!$category->visible) {
3245 $categorynode->hidden = true;
3247 $categories[] = $categorynode;
3249 if (is_enrolled(context_course::instance($this->page->course->id), null, '', true)) {
3250 $courses = $this->page->navigation->get('mycourses');
3251 } else {
3252 $courses = $this->page->navigation->get('courses');
3254 if (!$courses) {
3255 // Courses node may not be present.
3256 $courses = navigation_node::create(
3257 get_string('courses'),
3258 new moodle_url('/course/index.php'),
3259 self::TYPE_CONTAINER
3262 $categories[] = $courses;
3263 return $categories;
3267 * Add a new navigation_node to the navbar, overrides parent::add
3269 * This function overrides {@link navigation_node::add()} so that we can change
3270 * the way nodes get added to allow us to simply call add and have the node added to the
3271 * end of the navbar
3273 * @param string $text
3274 * @param string|moodle_url|action_link $action An action to associate with this node.
3275 * @param int $type One of navigation_node::TYPE_*
3276 * @param string $shorttext
3277 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3278 * @param pix_icon $icon An optional icon to use for this node.
3279 * @return navigation_node
3281 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3282 if ($this->content !== null) {
3283 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3286 // Properties array used when creating the new navigation node
3287 $itemarray = array(
3288 'text' => $text,
3289 'type' => $type
3291 // Set the action if one was provided
3292 if ($action!==null) {
3293 $itemarray['action'] = $action;
3295 // Set the shorttext if one was provided
3296 if ($shorttext!==null) {
3297 $itemarray['shorttext'] = $shorttext;
3299 // Set the icon if one was provided
3300 if ($icon!==null) {
3301 $itemarray['icon'] = $icon;
3303 // Default the key to the number of children if not provided
3304 if ($key === null) {
3305 $key = count($this->children);
3307 // Set the key
3308 $itemarray['key'] = $key;
3309 // Set the parent to this node
3310 $itemarray['parent'] = $this;
3311 // Add the child using the navigation_node_collections add method
3312 $this->children[] = new navigation_node($itemarray);
3313 return $this;
3317 * Prepends a new navigation_node to the start of the navbar
3319 * @param string $text
3320 * @param string|moodle_url|action_link $action An action to associate with this node.
3321 * @param int $type One of navigation_node::TYPE_*
3322 * @param string $shorttext
3323 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3324 * @param pix_icon $icon An optional icon to use for this node.
3325 * @return navigation_node
3327 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3328 if ($this->content !== null) {
3329 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3331 // Properties array used when creating the new navigation node.
3332 $itemarray = array(
3333 'text' => $text,
3334 'type' => $type
3336 // Set the action if one was provided.
3337 if ($action!==null) {
3338 $itemarray['action'] = $action;
3340 // Set the shorttext if one was provided.
3341 if ($shorttext!==null) {
3342 $itemarray['shorttext'] = $shorttext;
3344 // Set the icon if one was provided.
3345 if ($icon!==null) {
3346 $itemarray['icon'] = $icon;
3348 // Default the key to the number of children if not provided.
3349 if ($key === null) {
3350 $key = count($this->children);
3352 // Set the key.
3353 $itemarray['key'] = $key;
3354 // Set the parent to this node.
3355 $itemarray['parent'] = $this;
3356 // Add the child node to the prepend list.
3357 $this->prependchildren[] = new navigation_node($itemarray);
3358 return $this;
3363 * Class used to manage the settings option for the current page
3365 * This class is used to manage the settings options in a tree format (recursively)
3366 * and was created initially for use with the settings blocks.
3368 * @package core
3369 * @category navigation
3370 * @copyright 2009 Sam Hemelryk
3371 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3373 class settings_navigation extends navigation_node {
3374 /** @var stdClass the current context */
3375 protected $context;
3376 /** @var moodle_page the moodle page that the navigation belongs to */
3377 protected $page;
3378 /** @var string contains administration section navigation_nodes */
3379 protected $adminsection;
3380 /** @var bool A switch to see if the navigation node is initialised */
3381 protected $initialised = false;
3382 /** @var array An array of users that the nodes can extend for. */
3383 protected $userstoextendfor = array();
3384 /** @var navigation_cache **/
3385 protected $cache;
3388 * Sets up the object with basic settings and preparse it for use
3390 * @param moodle_page $page
3392 public function __construct(moodle_page &$page) {
3393 if (during_initial_install()) {
3394 return false;
3396 $this->page = $page;
3397 // Initialise the main navigation. It is most important that this is done
3398 // before we try anything
3399 $this->page->navigation->initialise();
3400 // Initialise the navigation cache
3401 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3402 $this->children = new navigation_node_collection();
3405 * Initialise the settings navigation based on the current context
3407 * This function initialises the settings navigation tree for a given context
3408 * by calling supporting functions to generate major parts of the tree.
3411 public function initialise() {
3412 global $DB, $SESSION, $SITE;
3414 if (during_initial_install()) {
3415 return false;
3416 } else if ($this->initialised) {
3417 return true;
3419 $this->id = 'settingsnav';
3420 $this->context = $this->page->context;
3422 $context = $this->context;
3423 if ($context->contextlevel == CONTEXT_BLOCK) {
3424 $this->load_block_settings();
3425 $context = $context->get_parent_context();
3427 switch ($context->contextlevel) {
3428 case CONTEXT_SYSTEM:
3429 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3430 $this->load_front_page_settings(($context->id == $this->context->id));
3432 break;
3433 case CONTEXT_COURSECAT:
3434 $this->load_category_settings();
3435 break;
3436 case CONTEXT_COURSE:
3437 if ($this->page->course->id != $SITE->id) {
3438 $this->load_course_settings(($context->id == $this->context->id));
3439 } else {
3440 $this->load_front_page_settings(($context->id == $this->context->id));
3442 break;
3443 case CONTEXT_MODULE:
3444 $this->load_module_settings();
3445 $this->load_course_settings();
3446 break;
3447 case CONTEXT_USER:
3448 if ($this->page->course->id != $SITE->id) {
3449 $this->load_course_settings();
3451 break;
3454 $usersettings = $this->load_user_settings($this->page->course->id);
3456 $adminsettings = false;
3457 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
3458 $isadminpage = $this->is_admin_tree_needed();
3460 if (has_capability('moodle/site:config', context_system::instance())) {
3461 // Make sure this works even if config capability changes on the fly
3462 // and also make it fast for admin right after login.
3463 $SESSION->load_navigation_admin = 1;
3464 if ($isadminpage) {
3465 $adminsettings = $this->load_administration_settings();
3468 } else if (!isset($SESSION->load_navigation_admin)) {
3469 $adminsettings = $this->load_administration_settings();
3470 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
3472 } else if ($SESSION->load_navigation_admin) {
3473 if ($isadminpage) {
3474 $adminsettings = $this->load_administration_settings();
3478 // Print empty navigation node, if needed.
3479 if ($SESSION->load_navigation_admin && !$isadminpage) {
3480 if ($adminsettings) {
3481 // Do not print settings tree on pages that do not need it, this helps with performance.
3482 $adminsettings->remove();
3483 $adminsettings = false;
3485 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin'), self::TYPE_SITE_ADMIN, null, 'siteadministration');
3486 $siteadminnode->id = 'expandable_branch_'.$siteadminnode->type.'_'.clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
3487 $this->page->requires->data_for_js('siteadminexpansion', $siteadminnode);
3491 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
3492 $adminsettings->force_open();
3493 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
3494 $usersettings->force_open();
3497 // Check if the user is currently logged in as another user
3498 if (\core\session\manager::is_loggedinas()) {
3499 // Get the actual user, we need this so we can display an informative return link
3500 $realuser = \core\session\manager::get_realuser();
3501 // Add the informative return to original user link
3502 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3503 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3506 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3507 $this->load_local_plugin_settings();
3509 foreach ($this->children as $key=>$node) {
3510 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3511 // Site administration is shown as link.
3512 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
3513 continue;
3515 $node->remove();
3518 $this->initialised = true;
3521 * Override the parent function so that we can add preceeding hr's and set a
3522 * root node class against all first level element
3524 * It does this by first calling the parent's add method {@link navigation_node::add()}
3525 * and then proceeds to use the key to set class and hr
3527 * @param string $text text to be used for the link.
3528 * @param string|moodle_url $url url for the new node
3529 * @param int $type the type of node navigation_node::TYPE_*
3530 * @param string $shorttext
3531 * @param string|int $key a key to access the node by.
3532 * @param pix_icon $icon An icon that appears next to the node.
3533 * @return navigation_node with the new node added to it.
3535 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3536 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3537 $node->add_class('root_node');
3538 return $node;
3542 * This function allows the user to add something to the start of the settings
3543 * navigation, which means it will be at the top of the settings navigation block
3545 * @param string $text text to be used for the link.
3546 * @param string|moodle_url $url url for the new node
3547 * @param int $type the type of node navigation_node::TYPE_*
3548 * @param string $shorttext
3549 * @param string|int $key a key to access the node by.
3550 * @param pix_icon $icon An icon that appears next to the node.
3551 * @return navigation_node $node with the new node added to it.
3553 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3554 $children = $this->children;
3555 $childrenclass = get_class($children);
3556 $this->children = new $childrenclass;
3557 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3558 foreach ($children as $child) {
3559 $this->children->add($child);
3561 return $node;
3565 * Does this page require loading of full admin tree or is
3566 * it enough rely on AJAX?
3568 * @return bool
3570 protected function is_admin_tree_needed() {
3571 if (self::$loadadmintree) {
3572 // Usually external admin page or settings page.
3573 return true;
3576 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
3577 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
3578 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
3579 return false;
3581 return true;
3584 return false;
3588 * Load the site administration tree
3590 * This function loads the site administration tree by using the lib/adminlib library functions
3592 * @param navigation_node $referencebranch A reference to a branch in the settings
3593 * navigation tree
3594 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3595 * tree and start at the beginning
3596 * @return mixed A key to access the admin tree by
3598 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3599 global $CFG;
3601 // Check if we are just starting to generate this navigation.
3602 if ($referencebranch === null) {
3604 // Require the admin lib then get an admin structure
3605 if (!function_exists('admin_get_root')) {
3606 require_once($CFG->dirroot.'/lib/adminlib.php');
3608 $adminroot = admin_get_root(false, false);
3609 // This is the active section identifier
3610 $this->adminsection = $this->page->url->param('section');
3612 // Disable the navigation from automatically finding the active node
3613 navigation_node::$autofindactive = false;
3614 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SITE_ADMIN, null, 'root');
3615 foreach ($adminroot->children as $adminbranch) {
3616 $this->load_administration_settings($referencebranch, $adminbranch);
3618 navigation_node::$autofindactive = true;
3620 // Use the admin structure to locate the active page
3621 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3622 $currentnode = $this;
3623 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3624 $currentnode = $currentnode->get($pathkey);
3626 if ($currentnode) {
3627 $currentnode->make_active();
3629 } else {
3630 $this->scan_for_active_node($referencebranch);
3632 return $referencebranch;
3633 } else if ($adminbranch->check_access()) {
3634 // We have a reference branch that we can access and is not hidden `hurrah`
3635 // Now we need to display it and any children it may have
3636 $url = null;
3637 $icon = null;
3638 if ($adminbranch instanceof admin_settingpage) {
3639 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3640 } else if ($adminbranch instanceof admin_externalpage) {
3641 $url = $adminbranch->url;
3642 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3643 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3646 // Add the branch
3647 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3649 if ($adminbranch->is_hidden()) {
3650 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3651 $reference->add_class('hidden');
3652 } else {
3653 $reference->display = false;
3657 // Check if we are generating the admin notifications and whether notificiations exist
3658 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3659 $reference->add_class('criticalnotification');
3661 // Check if this branch has children
3662 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3663 foreach ($adminbranch->children as $branch) {
3664 // Generate the child branches as well now using this branch as the reference
3665 $this->load_administration_settings($reference, $branch);
3667 } else {
3668 $reference->icon = new pix_icon('i/settings', '');
3674 * This function recursivily scans nodes until it finds the active node or there
3675 * are no more nodes.
3676 * @param navigation_node $node
3678 protected function scan_for_active_node(navigation_node $node) {
3679 if (!$node->check_if_active() && $node->children->count()>0) {
3680 foreach ($node->children as &$child) {
3681 $this->scan_for_active_node($child);
3687 * Gets a navigation node given an array of keys that represent the path to
3688 * the desired node.
3690 * @param array $path
3691 * @return navigation_node|false
3693 protected function get_by_path(array $path) {
3694 $node = $this->get(array_shift($path));
3695 foreach ($path as $key) {
3696 $node->get($key);
3698 return $node;
3702 * This function loads the course settings that are available for the user
3704 * @param bool $forceopen If set to true the course node will be forced open
3705 * @return navigation_node|false
3707 protected function load_course_settings($forceopen = false) {
3708 global $CFG;
3710 $course = $this->page->course;
3711 $coursecontext = context_course::instance($course->id);
3713 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3715 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3716 if ($forceopen) {
3717 $coursenode->force_open();
3720 if ($this->page->user_allowed_editing()) {
3721 // Add the turn on/off settings
3723 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3724 // We are on the course page, retain the current page params e.g. section.
3725 $baseurl = clone($this->page->url);
3726 $baseurl->param('sesskey', sesskey());
3727 } else {
3728 // Edit on the main course page.
3729 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3732 $editurl = clone($baseurl);
3733 if ($this->page->user_is_editing()) {
3734 $editurl->param('edit', 'off');
3735 $editstring = get_string('turneditingoff');
3736 } else {
3737 $editurl->param('edit', 'on');
3738 $editstring = get_string('turneditingon');
3740 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
3743 if (has_capability('moodle/course:update', $coursecontext)) {
3744 // Add the course settings link
3745 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3746 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
3748 // Add the course completion settings link
3749 if ($CFG->enablecompletion && $course->enablecompletion) {
3750 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3751 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3755 // add enrol nodes
3756 enrol_add_course_navigation($coursenode, $course);
3758 // Manage filters
3759 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3760 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3761 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3764 // View course reports.
3765 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
3766 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
3767 new pix_icon('i/stats', ''));
3768 $coursereports = core_component::get_plugin_list('coursereport');
3769 foreach ($coursereports as $report => $dir) {
3770 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
3771 if (file_exists($libfile)) {
3772 require_once($libfile);
3773 $reportfunction = $report.'_report_extend_navigation';
3774 if (function_exists($report.'_report_extend_navigation')) {
3775 $reportfunction($reportnav, $course, $coursecontext);
3780 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
3781 foreach ($reports as $reportfunction) {
3782 $reportfunction($reportnav, $course, $coursecontext);
3786 // Add view grade report is permitted
3787 $reportavailable = false;
3788 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3789 $reportavailable = true;
3790 } else if (!empty($course->showgrades)) {
3791 $reports = core_component::get_plugin_list('gradereport');
3792 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3793 arsort($reports); // user is last, we want to test it first
3794 foreach ($reports as $plugin => $plugindir) {
3795 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3796 //stop when the first visible plugin is found
3797 $reportavailable = true;
3798 break;
3803 if ($reportavailable) {
3804 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3805 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3808 // Add outcome if permitted
3809 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3810 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3811 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3814 //Add badges navigation
3815 require_once($CFG->libdir .'/badgeslib.php');
3816 badges_add_course_navigation($coursenode, $course);
3818 // Backup this course
3819 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3820 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3821 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3824 // Restore to this course
3825 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3826 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3827 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3830 // Import data from other courses
3831 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3832 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3833 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
3836 // Publish course on a hub
3837 if (has_capability('moodle/course:publish', $coursecontext)) {
3838 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3839 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3842 // Reset this course
3843 if (has_capability('moodle/course:reset', $coursecontext)) {
3844 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3845 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3848 // Questions
3849 require_once($CFG->libdir . '/questionlib.php');
3850 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3852 if (has_capability('moodle/course:update', $coursecontext)) {
3853 // Repository Instances
3854 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3855 require_once($CFG->dirroot . '/repository/lib.php');
3856 $editabletypes = repository::get_editable_types($coursecontext);
3857 $haseditabletypes = !empty($editabletypes);
3858 unset($editabletypes);
3859 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3860 } else {
3861 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3863 if ($haseditabletypes) {
3864 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3865 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3869 // Manage files
3870 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3871 // hidden in new courses and courses where legacy files were turned off
3872 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3873 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
3877 // Switch roles
3878 $roles = array();
3879 $assumedrole = $this->in_alternative_role();
3880 if ($assumedrole !== false) {
3881 $roles[0] = get_string('switchrolereturn');
3883 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3884 $availableroles = get_switchable_roles($coursecontext);
3885 if (is_array($availableroles)) {
3886 foreach ($availableroles as $key=>$role) {
3887 if ($assumedrole == (int)$key) {
3888 continue;
3890 $roles[$key] = $role;
3894 if (is_array($roles) && count($roles)>0) {
3895 $switchroles = $this->add(get_string('switchroleto'));
3896 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3897 $switchroles->force_open();
3899 foreach ($roles as $key => $name) {
3900 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$this->page->url->out_as_local_url(false)));
3901 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
3904 // Return we are done
3905 return $coursenode;
3909 * This function calls the module function to inject module settings into the
3910 * settings navigation tree.
3912 * This only gets called if there is a corrosponding function in the modules
3913 * lib file.
3915 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3917 * @return navigation_node|false
3919 protected function load_module_settings() {
3920 global $CFG;
3922 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3923 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3924 $this->page->set_cm($cm, $this->page->course);
3927 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3928 if (file_exists($file)) {
3929 require_once($file);
3932 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
3933 $modulenode->force_open();
3935 // Settings for the module
3936 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3937 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
3938 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3940 // Assign local roles
3941 if (count(get_assignable_roles($this->page->cm->context))>0) {
3942 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3943 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3945 // Override roles
3946 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3947 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3948 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3950 // Check role permissions
3951 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3952 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3953 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3955 // Manage filters
3956 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3957 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3958 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3960 // Add reports
3961 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3962 foreach ($reports as $reportfunction) {
3963 $reportfunction($modulenode, $this->page->cm);
3965 // Add a backup link
3966 $featuresfunc = $this->page->activityname.'_supports';
3967 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3968 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3969 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3972 // Restore this activity
3973 $featuresfunc = $this->page->activityname.'_supports';
3974 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3975 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3976 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3979 // Allow the active advanced grading method plugin to append its settings
3980 $featuresfunc = $this->page->activityname.'_supports';
3981 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3982 require_once($CFG->dirroot.'/grade/grading/lib.php');
3983 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
3984 $gradingman->extend_settings_navigation($this, $modulenode);
3987 $function = $this->page->activityname.'_extend_settings_navigation';
3988 if (!function_exists($function)) {
3989 return $modulenode;
3992 $function($this, $modulenode);
3994 // Remove the module node if there are no children
3995 if (empty($modulenode->children)) {
3996 $modulenode->remove();
3999 return $modulenode;
4003 * Loads the user settings block of the settings nav
4005 * This function is simply works out the userid and whether we need to load
4006 * just the current users profile settings, or the current user and the user the
4007 * current user is viewing.
4009 * This function has some very ugly code to work out the user, if anyone has
4010 * any bright ideas please feel free to intervene.
4012 * @param int $courseid The course id of the current course
4013 * @return navigation_node|false
4015 protected function load_user_settings($courseid = SITEID) {
4016 global $USER, $CFG;
4018 if (isguestuser() || !isloggedin()) {
4019 return false;
4022 $navusers = $this->page->navigation->get_extending_users();
4024 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4025 $usernode = null;
4026 foreach ($this->userstoextendfor as $userid) {
4027 if ($userid == $USER->id) {
4028 continue;
4030 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4031 if (is_null($usernode)) {
4032 $usernode = $node;
4035 foreach ($navusers as $user) {
4036 if ($user->id == $USER->id) {
4037 continue;
4039 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4040 if (is_null($usernode)) {
4041 $usernode = $node;
4044 $this->generate_user_settings($courseid, $USER->id);
4045 } else {
4046 $usernode = $this->generate_user_settings($courseid, $USER->id);
4048 return $usernode;
4052 * Extends the settings navigation for the given user.
4054 * Note: This method gets called automatically if you call
4055 * $PAGE->navigation->extend_for_user($userid)
4057 * @param int $userid
4059 public function extend_for_user($userid) {
4060 global $CFG;
4062 if (!in_array($userid, $this->userstoextendfor)) {
4063 $this->userstoextendfor[] = $userid;
4064 if ($this->initialised) {
4065 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4066 $children = array();
4067 foreach ($this->children as $child) {
4068 $children[] = $child;
4070 array_unshift($children, array_pop($children));
4071 $this->children = new navigation_node_collection();
4072 foreach ($children as $child) {
4073 $this->children->add($child);
4080 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4081 * what can be shown/done
4083 * @param int $courseid The current course' id
4084 * @param int $userid The user id to load for
4085 * @param string $gstitle The string to pass to get_string for the branch title
4086 * @return navigation_node|false
4088 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4089 global $DB, $CFG, $USER, $SITE;
4091 if ($courseid != $SITE->id) {
4092 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4093 $course = $this->page->course;
4094 } else {
4095 $select = context_helper::get_preload_record_columns_sql('ctx');
4096 $sql = "SELECT c.*, $select
4097 FROM {course} c
4098 JOIN {context} ctx ON c.id = ctx.instanceid
4099 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4100 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4101 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4102 context_helper::preload_from_record($course);
4104 } else {
4105 $course = $SITE;
4108 $coursecontext = context_course::instance($course->id); // Course context
4109 $systemcontext = context_system::instance();
4110 $currentuser = ($USER->id == $userid);
4112 if ($currentuser) {
4113 $user = $USER;
4114 $usercontext = context_user::instance($user->id); // User context
4115 } else {
4116 $select = context_helper::get_preload_record_columns_sql('ctx');
4117 $sql = "SELECT u.*, $select
4118 FROM {user} u
4119 JOIN {context} ctx ON u.id = ctx.instanceid
4120 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4121 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4122 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4123 if (!$user) {
4124 return false;
4126 context_helper::preload_from_record($user);
4128 // Check that the user can view the profile
4129 $usercontext = context_user::instance($user->id); // User context
4130 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4132 if ($course->id == $SITE->id) {
4133 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4134 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4135 return false;
4137 } else {
4138 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4139 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4140 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4141 return false;
4143 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4144 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4145 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4146 if ($courseid == $this->page->course->id) {
4147 $mygroups = get_fast_modinfo($this->page->course)->groups;
4148 } else {
4149 $mygroups = groups_get_user_groups($courseid);
4151 $usergroups = groups_get_user_groups($courseid, $userid);
4152 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4153 return false;
4159 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4161 $key = $gstitle;
4162 if ($gstitle != 'usercurrentsettings') {
4163 $key .= $userid;
4166 // Add a user setting branch
4167 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
4168 $usersetting->id = 'usersettings';
4169 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
4170 // Automatically start by making it active
4171 $usersetting->make_active();
4174 // Check if the user has been deleted
4175 if ($user->deleted) {
4176 if (!has_capability('moodle/user:update', $coursecontext)) {
4177 // We can't edit the user so just show the user deleted message
4178 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4179 } else {
4180 // We can edit the user so show the user deleted message and link it to the profile
4181 if ($course->id == $SITE->id) {
4182 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4183 } else {
4184 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4186 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4188 return true;
4191 $userauthplugin = false;
4192 if (!empty($user->auth)) {
4193 $userauthplugin = get_auth_plugin($user->auth);
4196 // Add the profile edit link
4197 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4198 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
4199 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4200 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4201 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4202 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4203 $url = $userauthplugin->edit_profile_url();
4204 if (empty($url)) {
4205 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4207 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4212 // Change password link
4213 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4214 $passwordchangeurl = $userauthplugin->change_password_url();
4215 if (empty($passwordchangeurl)) {
4216 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4218 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
4221 // View the roles settings
4222 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
4223 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4225 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4226 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4228 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4230 if (!empty($assignableroles)) {
4231 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4232 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4235 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4236 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4237 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4240 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4241 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4244 // Portfolio
4245 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4246 require_once($CFG->libdir . '/portfoliolib.php');
4247 if (portfolio_has_visible_instances()) {
4248 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4250 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4251 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4253 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4254 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4258 $enablemanagetokens = false;
4259 if (!empty($CFG->enablerssfeeds)) {
4260 $enablemanagetokens = true;
4261 } else if (!is_siteadmin($USER->id)
4262 && !empty($CFG->enablewebservices)
4263 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4264 $enablemanagetokens = true;
4266 // Security keys
4267 if ($currentuser && $enablemanagetokens) {
4268 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4269 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4272 // Messaging
4273 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4274 $url = new moodle_url('/message/edit.php', array('id'=>$user->id));
4275 $usersetting->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
4278 // Blogs
4279 if ($currentuser && !empty($CFG->enableblogs)) {
4280 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4281 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
4282 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
4283 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
4284 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
4288 // Badges.
4289 if ($currentuser && !empty($CFG->enablebadges)) {
4290 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
4291 $badges->add(get_string('preferences'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
4292 if (!empty($CFG->badges_allowexternalbackpack)) {
4293 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
4297 // Add reports node.
4298 $reporttab = $usersetting->add(get_string('activityreports'));
4299 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
4300 foreach ($reports as $reportfunction) {
4301 $reportfunction($reporttab, $user, $course);
4303 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
4304 if ($anyreport || ($course->showreports && $currentuser)) {
4305 // Add grade hardcoded grade report if necessary.
4306 $gradeaccess = false;
4307 if (has_capability('moodle/grade:viewall', $coursecontext)) {
4308 // Can view all course grades.
4309 $gradeaccess = true;
4310 } else if ($course->showgrades) {
4311 if ($currentuser && has_capability('moodle/grade:view', $coursecontext)) {
4312 // Can view own grades.
4313 $gradeaccess = true;
4314 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
4315 // Can view grades of this user - parent most probably.
4316 $gradeaccess = true;
4317 } else if ($anyreport) {
4318 // Can view grades of this user - parent most probably.
4319 $gradeaccess = true;
4322 if ($gradeaccess) {
4323 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id,
4324 'user'=>$usercontext->instanceid)));
4327 // Check the number of nodes in the report node... if there are none remove the node
4328 $reporttab->trim_if_empty();
4330 // Login as ...
4331 if (!$user->deleted and !$currentuser && !\core\session\manager::is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
4332 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
4333 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
4336 return $usersetting;
4340 * Loads block specific settings in the navigation
4342 * @return navigation_node
4344 protected function load_block_settings() {
4345 global $CFG;
4347 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
4348 $blocknode->force_open();
4350 // Assign local roles
4351 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4352 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4354 // Override roles
4355 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4356 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4357 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4359 // Check role permissions
4360 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4361 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4362 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4365 return $blocknode;
4369 * Loads category specific settings in the navigation
4371 * @return navigation_node
4373 protected function load_category_settings() {
4374 global $CFG;
4376 // We can land here while being in the context of a block, in which case we
4377 // should get the parent context which should be the category one. See self::initialise().
4378 if ($this->context->contextlevel == CONTEXT_BLOCK) {
4379 $catcontext = $this->context->get_parent_context();
4380 } else {
4381 $catcontext = $this->context;
4384 // Let's make sure that we always have the right context when getting here.
4385 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
4386 throw new coding_exception('Unexpected context while loading category settings.');
4389 $categorynode = $this->add($catcontext->get_context_name(), null, null, null, 'categorysettings');
4390 $categorynode->force_open();
4392 if (can_edit_in_category($catcontext->instanceid)) {
4393 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
4394 $editstring = get_string('managecategorythis');
4395 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4398 if (has_capability('moodle/category:manage', $catcontext)) {
4399 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
4400 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4402 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
4403 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4406 // Assign local roles
4407 $assignableroles = get_assignable_roles($catcontext);
4408 if (!empty($assignableroles)) {
4409 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
4410 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4413 // Override roles
4414 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
4415 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
4416 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4418 // Check role permissions
4419 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
4420 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
4421 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
4422 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4425 // Cohorts
4426 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
4427 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
4428 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
4431 // Manage filters
4432 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
4433 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
4434 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4437 // Restore.
4438 if (has_capability('moodle/course:create', $catcontext)) {
4439 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
4440 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
4443 return $categorynode;
4447 * Determine whether the user is assuming another role
4449 * This function checks to see if the user is assuming another role by means of
4450 * role switching. In doing this we compare each RSW key (context path) against
4451 * the current context path. This ensures that we can provide the switching
4452 * options against both the course and any page shown under the course.
4454 * @return bool|int The role(int) if the user is in another role, false otherwise
4456 protected function in_alternative_role() {
4457 global $USER;
4458 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4459 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4460 return $USER->access['rsw'][$this->page->context->path];
4462 foreach ($USER->access['rsw'] as $key=>$role) {
4463 if (strpos($this->context->path,$key)===0) {
4464 return $role;
4468 return false;
4472 * This function loads all of the front page settings into the settings navigation.
4473 * This function is called when the user is on the front page, or $COURSE==$SITE
4474 * @param bool $forceopen (optional)
4475 * @return navigation_node
4477 protected function load_front_page_settings($forceopen = false) {
4478 global $SITE, $CFG;
4480 $course = clone($SITE);
4481 $coursecontext = context_course::instance($course->id); // Course context
4483 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4484 if ($forceopen) {
4485 $frontpage->force_open();
4487 $frontpage->id = 'frontpagesettings';
4489 if ($this->page->user_allowed_editing()) {
4491 // Add the turn on/off settings
4492 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4493 if ($this->page->user_is_editing()) {
4494 $url->param('edit', 'off');
4495 $editstring = get_string('turneditingoff');
4496 } else {
4497 $url->param('edit', 'on');
4498 $editstring = get_string('turneditingon');
4500 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4503 if (has_capability('moodle/course:update', $coursecontext)) {
4504 // Add the course settings link
4505 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4506 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4509 // add enrol nodes
4510 enrol_add_course_navigation($frontpage, $course);
4512 // Manage filters
4513 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4514 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4515 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4518 // View course reports.
4519 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
4520 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
4521 new pix_icon('i/stats', ''));
4522 $coursereports = core_component::get_plugin_list('coursereport');
4523 foreach ($coursereports as $report=>$dir) {
4524 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4525 if (file_exists($libfile)) {
4526 require_once($libfile);
4527 $reportfunction = $report.'_report_extend_navigation';
4528 if (function_exists($report.'_report_extend_navigation')) {
4529 $reportfunction($frontpagenav, $course, $coursecontext);
4534 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4535 foreach ($reports as $reportfunction) {
4536 $reportfunction($frontpagenav, $course, $coursecontext);
4540 // Backup this course
4541 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4542 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4543 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4546 // Restore to this course
4547 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4548 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4549 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4552 // Questions
4553 require_once($CFG->libdir . '/questionlib.php');
4554 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4556 // Manage files
4557 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4558 //hiden in new installs
4559 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4560 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
4562 return $frontpage;
4566 * This function gives local plugins an opportunity to modify the settings navigation.
4568 protected function load_local_plugin_settings() {
4569 // Get all local plugins with an extend_settings_navigation function in their lib.php file
4570 foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
4571 // Call each function providing this (the settings navigation) and the current context.
4572 $function($this, $this->context);
4577 * This function marks the cache as volatile so it is cleared during shutdown
4579 public function clear_cache() {
4580 $this->cache->volatile();
4585 * Class used to populate site admin navigation for ajax.
4587 * @package core
4588 * @category navigation
4589 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
4590 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4592 class settings_navigation_ajax extends settings_navigation {
4594 * Constructs the navigation for use in an AJAX request
4596 * @param moodle_page $page
4598 public function __construct(moodle_page &$page) {
4599 $this->page = $page;
4600 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4601 $this->children = new navigation_node_collection();
4602 $this->initialise();
4606 * Initialise the site admin navigation.
4608 * @return array An array of the expandable nodes
4610 public function initialise() {
4611 if ($this->initialised || during_initial_install()) {
4612 return false;
4614 $this->context = $this->page->context;
4615 $this->load_administration_settings();
4617 // Check if local plugins is adding node to site admin.
4618 $this->load_local_plugin_settings();
4620 $this->initialised = true;
4625 * Simple class used to output a navigation branch in XML
4627 * @package core
4628 * @category navigation
4629 * @copyright 2009 Sam Hemelryk
4630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4632 class navigation_json {
4633 /** @var array An array of different node types */
4634 protected $nodetype = array('node','branch');
4635 /** @var array An array of node keys and types */
4636 protected $expandable = array();
4638 * Turns a branch and all of its children into XML
4640 * @param navigation_node $branch
4641 * @return string XML string
4643 public function convert($branch) {
4644 $xml = $this->convert_child($branch);
4645 return $xml;
4648 * Set the expandable items in the array so that we have enough information
4649 * to attach AJAX events
4650 * @param array $expandable
4652 public function set_expandable($expandable) {
4653 foreach ($expandable as $node) {
4654 $this->expandable[$node['key'].':'.$node['type']] = $node;
4658 * Recusively converts a child node and its children to XML for output
4660 * @param navigation_node $child The child to convert
4661 * @param int $depth Pointlessly used to track the depth of the XML structure
4662 * @return string JSON
4664 protected function convert_child($child, $depth=1) {
4665 if (!$child->display) {
4666 return '';
4668 $attributes = array();
4669 $attributes['id'] = $child->id;
4670 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
4671 $attributes['type'] = $child->type;
4672 $attributes['key'] = $child->key;
4673 $attributes['class'] = $child->get_css_type();
4675 if ($child->icon instanceof pix_icon) {
4676 $attributes['icon'] = array(
4677 'component' => $child->icon->component,
4678 'pix' => $child->icon->pix,
4680 foreach ($child->icon->attributes as $key=>$value) {
4681 if ($key == 'class') {
4682 $attributes['icon']['classes'] = explode(' ', $value);
4683 } else if (!array_key_exists($key, $attributes['icon'])) {
4684 $attributes['icon'][$key] = $value;
4688 } else if (!empty($child->icon)) {
4689 $attributes['icon'] = (string)$child->icon;
4692 if ($child->forcetitle || $child->title !== $child->text) {
4693 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
4695 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4696 $attributes['expandable'] = $child->key;
4697 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4700 if (count($child->classes)>0) {
4701 $attributes['class'] .= ' '.join(' ',$child->classes);
4703 if (is_string($child->action)) {
4704 $attributes['link'] = $child->action;
4705 } else if ($child->action instanceof moodle_url) {
4706 $attributes['link'] = $child->action->out();
4707 } else if ($child->action instanceof action_link) {
4708 $attributes['link'] = $child->action->url->out();
4710 $attributes['hidden'] = ($child->hidden);
4711 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4712 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
4714 if ($child->children->count() > 0) {
4715 $attributes['children'] = array();
4716 foreach ($child->children as $subchild) {
4717 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4721 if ($depth > 1) {
4722 return $attributes;
4723 } else {
4724 return json_encode($attributes);
4730 * The cache class used by global navigation and settings navigation.
4732 * It is basically an easy access point to session with a bit of smarts to make
4733 * sure that the information that is cached is valid still.
4735 * Example use:
4736 * <code php>
4737 * if (!$cache->viewdiscussion()) {
4738 * // Code to do stuff and produce cachable content
4739 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4741 * $content = $cache->viewdiscussion;
4742 * </code>
4744 * @package core
4745 * @category navigation
4746 * @copyright 2009 Sam Hemelryk
4747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4749 class navigation_cache {
4750 /** @var int represents the time created */
4751 protected $creation;
4752 /** @var array An array of session keys */
4753 protected $session;
4755 * The string to use to segregate this particular cache. It can either be
4756 * unique to start a fresh cache or if you want to share a cache then make
4757 * it the string used in the original cache.
4758 * @var string
4760 protected $area;
4761 /** @var int a time that the information will time out */
4762 protected $timeout;
4763 /** @var stdClass The current context */
4764 protected $currentcontext;
4765 /** @var int cache time information */
4766 const CACHETIME = 0;
4767 /** @var int cache user id */
4768 const CACHEUSERID = 1;
4769 /** @var int cache value */
4770 const CACHEVALUE = 2;
4771 /** @var null|array An array of navigation cache areas to expire on shutdown */
4772 public static $volatilecaches;
4775 * Contructor for the cache. Requires two arguments
4777 * @param string $area The string to use to segregate this particular cache
4778 * it can either be unique to start a fresh cache or if you want
4779 * to share a cache then make it the string used in the original
4780 * cache
4781 * @param int $timeout The number of seconds to time the information out after
4783 public function __construct($area, $timeout=1800) {
4784 $this->creation = time();
4785 $this->area = $area;
4786 $this->timeout = time() - $timeout;
4787 if (rand(0,100) === 0) {
4788 $this->garbage_collection();
4793 * Used to set up the cache within the SESSION.
4795 * This is called for each access and ensure that we don't put anything into the session before
4796 * it is required.
4798 protected function ensure_session_cache_initialised() {
4799 global $SESSION;
4800 if (empty($this->session)) {
4801 if (!isset($SESSION->navcache)) {
4802 $SESSION->navcache = new stdClass;
4804 if (!isset($SESSION->navcache->{$this->area})) {
4805 $SESSION->navcache->{$this->area} = array();
4807 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
4812 * Magic Method to retrieve something by simply calling using = cache->key
4814 * @param mixed $key The identifier for the information you want out again
4815 * @return void|mixed Either void or what ever was put in
4817 public function __get($key) {
4818 if (!$this->cached($key)) {
4819 return;
4821 $information = $this->session[$key][self::CACHEVALUE];
4822 return unserialize($information);
4826 * Magic method that simply uses {@link set();} to store something in the cache
4828 * @param string|int $key
4829 * @param mixed $information
4831 public function __set($key, $information) {
4832 $this->set($key, $information);
4836 * Sets some information against the cache (session) for later retrieval
4838 * @param string|int $key
4839 * @param mixed $information
4841 public function set($key, $information) {
4842 global $USER;
4843 $this->ensure_session_cache_initialised();
4844 $information = serialize($information);
4845 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4848 * Check the existence of the identifier in the cache
4850 * @param string|int $key
4851 * @return bool
4853 public function cached($key) {
4854 global $USER;
4855 $this->ensure_session_cache_initialised();
4856 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) {
4857 return false;
4859 return true;
4862 * Compare something to it's equivilant in the cache
4864 * @param string $key
4865 * @param mixed $value
4866 * @param bool $serialise Whether to serialise the value before comparison
4867 * this should only be set to false if the value is already
4868 * serialised
4869 * @return bool If the value is the same false if it is not set or doesn't match
4871 public function compare($key, $value, $serialise = true) {
4872 if ($this->cached($key)) {
4873 if ($serialise) {
4874 $value = serialize($value);
4876 if ($this->session[$key][self::CACHEVALUE] === $value) {
4877 return true;
4880 return false;
4883 * Wipes the entire cache, good to force regeneration
4885 public function clear() {
4886 global $SESSION;
4887 unset($SESSION->navcache);
4888 $this->session = null;
4891 * Checks all cache entries and removes any that have expired, good ole cleanup
4893 protected function garbage_collection() {
4894 if (empty($this->session)) {
4895 return true;
4897 foreach ($this->session as $key=>$cachedinfo) {
4898 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4899 unset($this->session[$key]);
4905 * Marks the cache as being volatile (likely to change)
4907 * Any caches marked as volatile will be destroyed at the on shutdown by
4908 * {@link navigation_node::destroy_volatile_caches()} which is registered
4909 * as a shutdown function if any caches are marked as volatile.
4911 * @param bool $setting True to destroy the cache false not too
4913 public function volatile($setting = true) {
4914 if (self::$volatilecaches===null) {
4915 self::$volatilecaches = array();
4916 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
4919 if ($setting) {
4920 self::$volatilecaches[$this->area] = $this->area;
4921 } else if (array_key_exists($this->area, self::$volatilecaches)) {
4922 unset(self::$volatilecaches[$this->area]);
4927 * Destroys all caches marked as volatile
4929 * This function is static and works in conjunction with the static volatilecaches
4930 * property of navigation cache.
4931 * Because this function is static it manually resets the cached areas back to an
4932 * empty array.
4934 public static function destroy_volatile_caches() {
4935 global $SESSION;
4936 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4937 foreach (self::$volatilecaches as $area) {
4938 $SESSION->navcache->{$area} = array();
4940 } else {
4941 $SESSION->navcache = new stdClass;