Merge branch 'MDL-32657-master-1' of git://git.luns.net.uk/moodle
[moodle.git] / lib / navigationlib.php
blob51b6efa16ed380a9c67999319cc87d4bb8bff226
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * This file contains classes used to manage the navigation structures in Moodle
20 * and was introduced as part of the changes occuring in Moodle 2.0
22 * @since 2.0
23 * @package core
24 * @copyright 2009 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * The name that will be used to separate the navigation cache within SESSION
33 define('NAVIGATION_CACHE_NAME', 'navigation');
35 /**
36 * This class is used to represent a node in a navigation tree
38 * This class is used to represent a node in a navigation tree within Moodle,
39 * the tree could be one of global navigation, settings navigation, or the navbar.
40 * Each node can be one of two types either a Leaf (default) or a branch.
41 * When a node is first created it is created as a leaf, when/if children are added
42 * the node then becomes a branch.
44 * @package core
45 * @category navigation
46 * @copyright 2009 Sam Hemelryk
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 class navigation_node implements renderable {
50 /** @var int Used to identify this node a leaf (default) 0 */
51 const NODETYPE_LEAF = 0;
52 /** @var int Used to identify this node a branch, happens with children 1 */
53 const NODETYPE_BRANCH = 1;
54 /** @var null Unknown node type null */
55 const TYPE_UNKNOWN = null;
56 /** @var int System node type 0 */
57 const TYPE_ROOTNODE = 0;
58 /** @var int System node type 1 */
59 const TYPE_SYSTEM = 1;
60 /** @var int Category node type 10 */
61 const TYPE_CATEGORY = 10;
62 /** @var int Course node type 20 */
63 const TYPE_COURSE = 20;
64 /** @var int Course Structure node type 30 */
65 const TYPE_SECTION = 30;
66 /** @var int Activity node type, e.g. Forum, Quiz 40 */
67 const TYPE_ACTIVITY = 40;
68 /** @var int Resource node type, e.g. Link to a file, or label 50 */
69 const TYPE_RESOURCE = 50;
70 /** @var int A custom node type, default when adding without specifing type 60 */
71 const TYPE_CUSTOM = 60;
72 /** @var int Setting node type, used only within settings nav 70 */
73 const TYPE_SETTING = 70;
74 /** @var int Setting node type, used only within settings nav 80 */
75 const TYPE_USER = 80;
76 /** @var int Setting node type, used for containers of no importance 90 */
77 const TYPE_CONTAINER = 90;
79 /** @var int Parameter to aid the coder in tracking [optional] */
80 public $id = null;
81 /** @var string|int The identifier for the node, used to retrieve the node */
82 public $key = null;
83 /** @var string The text to use for the node */
84 public $text = null;
85 /** @var string Short text to use if requested [optional] */
86 public $shorttext = null;
87 /** @var string The title attribute for an action if one is defined */
88 public $title = null;
89 /** @var string A string that can be used to build a help button */
90 public $helpbutton = null;
91 /** @var moodle_url|action_link|null An action for the node (link) */
92 public $action = null;
93 /** @var pix_icon The path to an icon to use for this node */
94 public $icon = null;
95 /** @var int See TYPE_* constants defined for this class */
96 public $type = self::TYPE_UNKNOWN;
97 /** @var int See NODETYPE_* constants defined for this class */
98 public $nodetype = self::NODETYPE_LEAF;
99 /** @var bool If set to true the node will be collapsed by default */
100 public $collapse = false;
101 /** @var bool If set to true the node will be expanded by default */
102 public $forceopen = false;
103 /** @var array An array of CSS classes for the node */
104 public $classes = array();
105 /** @var navigation_node_collection An array of child nodes */
106 public $children = array();
107 /** @var bool If set to true the node will be recognised as active */
108 public $isactive = false;
109 /** @var bool If set to true the node will be dimmed */
110 public $hidden = false;
111 /** @var bool If set to false the node will not be displayed */
112 public $display = true;
113 /** @var bool If set to true then an HR will be printed before the node */
114 public $preceedwithhr = false;
115 /** @var bool If set to true the the navigation bar should ignore this node */
116 public $mainnavonly = false;
117 /** @var bool If set to true a title will be added to the action no matter what */
118 public $forcetitle = false;
119 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
120 public $parent = null;
121 /** @var bool Override to not display the icon even if one is provided **/
122 public $hideicon = false;
123 /** @var array */
124 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
125 /** @var moodle_url */
126 protected static $fullmeurl = null;
127 /** @var bool toogles auto matching of active node */
128 public static $autofindactive = true;
129 /** @var mixed If set to an int, that section will be included even if it has no activities */
130 public $includesectionnum = false;
133 * Constructs a new navigation_node
135 * @param array|string $properties Either an array of properties or a string to use
136 * as the text for the node
138 public function __construct($properties) {
139 if (is_array($properties)) {
140 // Check the array for each property that we allow to set at construction.
141 // text - The main content for the node
142 // shorttext - A short text if required for the node
143 // icon - The icon to display for the node
144 // type - The type of the node
145 // key - The key to use to identify the node
146 // parent - A reference to the nodes parent
147 // action - The action to attribute to this node, usually a URL to link to
148 if (array_key_exists('text', $properties)) {
149 $this->text = $properties['text'];
151 if (array_key_exists('shorttext', $properties)) {
152 $this->shorttext = $properties['shorttext'];
154 if (!array_key_exists('icon', $properties)) {
155 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
157 $this->icon = $properties['icon'];
158 if ($this->icon instanceof pix_icon) {
159 if (empty($this->icon->attributes['class'])) {
160 $this->icon->attributes['class'] = 'navicon';
161 } else {
162 $this->icon->attributes['class'] .= ' navicon';
165 if (array_key_exists('type', $properties)) {
166 $this->type = $properties['type'];
167 } else {
168 $this->type = self::TYPE_CUSTOM;
170 if (array_key_exists('key', $properties)) {
171 $this->key = $properties['key'];
173 // This needs to happen last because of the check_if_active call that occurs
174 if (array_key_exists('action', $properties)) {
175 $this->action = $properties['action'];
176 if (is_string($this->action)) {
177 $this->action = new moodle_url($this->action);
179 if (self::$autofindactive) {
180 $this->check_if_active();
183 if (array_key_exists('parent', $properties)) {
184 $this->set_parent($properties['parent']);
186 } else if (is_string($properties)) {
187 $this->text = $properties;
189 if ($this->text === null) {
190 throw new coding_exception('You must set the text for the node when you create it.');
192 // Default the title to the text
193 $this->title = $this->text;
194 // Instantiate a new navigation node collection for this nodes children
195 $this->children = new navigation_node_collection();
199 * Checks if this node is the active node.
201 * This is determined by comparing the action for the node against the
202 * defined URL for the page. A match will see this node marked as active.
204 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
205 * @return bool
207 public function check_if_active($strength=URL_MATCH_EXACT) {
208 global $FULLME, $PAGE;
209 // Set fullmeurl if it hasn't already been set
210 if (self::$fullmeurl == null) {
211 if ($PAGE->has_set_url()) {
212 self::override_active_url(new moodle_url($PAGE->url));
213 } else {
214 self::override_active_url(new moodle_url($FULLME));
218 // Compare the action of this node against the fullmeurl
219 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
220 $this->make_active();
221 return true;
223 return false;
227 * This sets the URL that the URL of new nodes get compared to when locating
228 * the active node.
230 * The active node is the node that matches the URL set here. By default this
231 * is either $PAGE->url or if that hasn't been set $FULLME.
233 * @param moodle_url $url The url to use for the fullmeurl.
235 public static function override_active_url(moodle_url $url) {
236 // Clone the URL, in case the calling script changes their URL later.
237 self::$fullmeurl = new moodle_url($url);
241 * Creates a navigation node, ready to add it as a child using add_node
242 * function. (The created node needs to be added before you can use it.)
243 * @param string $text
244 * @param moodle_url|action_link $action
245 * @param int $type
246 * @param string $shorttext
247 * @param string|int $key
248 * @param pix_icon $icon
249 * @return navigation_node
251 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
252 $shorttext=null, $key=null, pix_icon $icon=null) {
253 // Properties array used when creating the new navigation node
254 $itemarray = array(
255 'text' => $text,
256 'type' => $type
258 // Set the action if one was provided
259 if ($action!==null) {
260 $itemarray['action'] = $action;
262 // Set the shorttext if one was provided
263 if ($shorttext!==null) {
264 $itemarray['shorttext'] = $shorttext;
266 // Set the icon if one was provided
267 if ($icon!==null) {
268 $itemarray['icon'] = $icon;
270 // Set the key
271 $itemarray['key'] = $key;
272 // Construct and return
273 return new navigation_node($itemarray);
277 * Adds a navigation node as a child of this node.
279 * @param string $text
280 * @param moodle_url|action_link $action
281 * @param int $type
282 * @param string $shorttext
283 * @param string|int $key
284 * @param pix_icon $icon
285 * @return navigation_node
287 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
288 // Create child node
289 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
291 // Add the child to end and return
292 return $this->add_node($childnode);
296 * Adds a navigation node as a child of this one, given a $node object
297 * created using the create function.
298 * @param navigation_node $childnode Node to add
299 * @param string $beforekey
300 * @return navigation_node The added node
302 public function add_node(navigation_node $childnode, $beforekey=null) {
303 // First convert the nodetype for this node to a branch as it will now have children
304 if ($this->nodetype !== self::NODETYPE_BRANCH) {
305 $this->nodetype = self::NODETYPE_BRANCH;
307 // Set the parent to this node
308 $childnode->set_parent($this);
310 // Default the key to the number of children if not provided
311 if ($childnode->key === null) {
312 $childnode->key = $this->children->count();
315 // Add the child using the navigation_node_collections add method
316 $node = $this->children->add($childnode, $beforekey);
318 // If added node is a category node or the user is logged in and it's a course
319 // then mark added node as a branch (makes it expandable by AJAX)
320 $type = $childnode->type;
321 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
322 $node->nodetype = self::NODETYPE_BRANCH;
324 // If this node is hidden mark it's children as hidden also
325 if ($this->hidden) {
326 $node->hidden = true;
328 // Return added node (reference returned by $this->children->add()
329 return $node;
333 * Return a list of all the keys of all the child nodes.
334 * @return array the keys.
336 public function get_children_key_list() {
337 return $this->children->get_key_list();
341 * Searches for a node of the given type with the given key.
343 * This searches this node plus all of its children, and their children....
344 * If you know the node you are looking for is a child of this node then please
345 * use the get method instead.
347 * @param int|string $key The key of the node we are looking for
348 * @param int $type One of navigation_node::TYPE_*
349 * @return navigation_node|false
351 public function find($key, $type) {
352 return $this->children->find($key, $type);
356 * Get the child of this node that has the given key + (optional) type.
358 * If you are looking for a node and want to search all children + thier children
359 * then please use the find method instead.
361 * @param int|string $key The key of the node we are looking for
362 * @param int $type One of navigation_node::TYPE_*
363 * @return navigation_node|false
365 public function get($key, $type=null) {
366 return $this->children->get($key, $type);
370 * Removes this node.
372 * @return bool
374 public function remove() {
375 return $this->parent->children->remove($this->key, $this->type);
379 * Checks if this node has or could have any children
381 * @return bool Returns true if it has children or could have (by AJAX expansion)
383 public function has_children() {
384 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
388 * Marks this node as active and forces it open.
390 * Important: If you are here because you need to mark a node active to get
391 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
392 * You can use it to specify a different URL to match the active navigation node on
393 * rather than having to locate and manually mark a node active.
395 public function make_active() {
396 $this->isactive = true;
397 $this->add_class('active_tree_node');
398 $this->force_open();
399 if ($this->parent !== null) {
400 $this->parent->make_inactive();
405 * Marks a node as inactive and recusised back to the base of the tree
406 * doing the same to all parents.
408 public function make_inactive() {
409 $this->isactive = false;
410 $this->remove_class('active_tree_node');
411 if ($this->parent !== null) {
412 $this->parent->make_inactive();
417 * Forces this node to be open and at the same time forces open all
418 * parents until the root node.
420 * Recursive.
422 public function force_open() {
423 $this->forceopen = true;
424 if ($this->parent !== null) {
425 $this->parent->force_open();
430 * Adds a CSS class to this node.
432 * @param string $class
433 * @return bool
435 public function add_class($class) {
436 if (!in_array($class, $this->classes)) {
437 $this->classes[] = $class;
439 return true;
443 * Removes a CSS class from this node.
445 * @param string $class
446 * @return bool True if the class was successfully removed.
448 public function remove_class($class) {
449 if (in_array($class, $this->classes)) {
450 $key = array_search($class,$this->classes);
451 if ($key!==false) {
452 unset($this->classes[$key]);
453 return true;
456 return false;
460 * Sets the title for this node and forces Moodle to utilise it.
461 * @param string $title
463 public function title($title) {
464 $this->title = $title;
465 $this->forcetitle = true;
469 * Resets the page specific information on this node if it is being unserialised.
471 public function __wakeup(){
472 $this->forceopen = false;
473 $this->isactive = false;
474 $this->remove_class('active_tree_node');
478 * Checks if this node or any of its children contain the active node.
480 * Recursive.
482 * @return bool
484 public function contains_active_node() {
485 if ($this->isactive) {
486 return true;
487 } else {
488 foreach ($this->children as $child) {
489 if ($child->isactive || $child->contains_active_node()) {
490 return true;
494 return false;
498 * Finds the active node.
500 * Searches this nodes children plus all of the children for the active node
501 * and returns it if found.
503 * Recursive.
505 * @return navigation_node|false
507 public function find_active_node() {
508 if ($this->isactive) {
509 return $this;
510 } else {
511 foreach ($this->children as &$child) {
512 $outcome = $child->find_active_node();
513 if ($outcome !== false) {
514 return $outcome;
518 return false;
522 * Searches all children for the best matching active node
523 * @return navigation_node|false
525 public function search_for_active_node() {
526 if ($this->check_if_active(URL_MATCH_BASE)) {
527 return $this;
528 } else {
529 foreach ($this->children as &$child) {
530 $outcome = $child->search_for_active_node();
531 if ($outcome !== false) {
532 return $outcome;
536 return false;
540 * Gets the content for this node.
542 * @param bool $shorttext If true shorttext is used rather than the normal text
543 * @return string
545 public function get_content($shorttext=false) {
546 if ($shorttext && $this->shorttext!==null) {
547 return format_string($this->shorttext);
548 } else {
549 return format_string($this->text);
554 * Gets the title to use for this node.
556 * @return string
558 public function get_title() {
559 if ($this->forcetitle || $this->action != null){
560 return $this->title;
561 } else {
562 return '';
567 * Gets the CSS class to add to this node to describe its type
569 * @return string
571 public function get_css_type() {
572 if (array_key_exists($this->type, $this->namedtypes)) {
573 return 'type_'.$this->namedtypes[$this->type];
575 return 'type_unknown';
579 * Finds all nodes that are expandable by AJAX
581 * @param array $expandable An array by reference to populate with expandable nodes.
583 public function find_expandable(array &$expandable) {
584 foreach ($this->children as &$child) {
585 if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count() == 0 && $child->display) {
586 $child->id = 'expandable_branch_'.(count($expandable)+1);
587 $this->add_class('canexpand');
588 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
590 $child->find_expandable($expandable);
595 * Finds all nodes of a given type (recursive)
597 * @param int $type One of navigation_node::TYPE_*
598 * @return array
600 public function find_all_of_type($type) {
601 $nodes = $this->children->type($type);
602 foreach ($this->children as &$node) {
603 $childnodes = $node->find_all_of_type($type);
604 $nodes = array_merge($nodes, $childnodes);
606 return $nodes;
610 * Removes this node if it is empty
612 public function trim_if_empty() {
613 if ($this->children->count() == 0) {
614 $this->remove();
619 * Creates a tab representation of this nodes children that can be used
620 * with print_tabs to produce the tabs on a page.
622 * call_user_func_array('print_tabs', $node->get_tabs_array());
624 * @param array $inactive
625 * @param bool $return
626 * @return array Array (tabs, selected, inactive, activated, return)
628 public function get_tabs_array(array $inactive=array(), $return=false) {
629 $tabs = array();
630 $rows = array();
631 $selected = null;
632 $activated = array();
633 foreach ($this->children as $node) {
634 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
635 if ($node->contains_active_node()) {
636 if ($node->children->count() > 0) {
637 $activated[] = $node->key;
638 foreach ($node->children as $child) {
639 if ($child->contains_active_node()) {
640 $selected = $child->key;
642 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
644 } else {
645 $selected = $node->key;
649 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
653 * Sets the parent for this node and if this node is active ensures that the tree is properly
654 * adjusted as well.
656 * @param navigation_node $parent
658 public function set_parent(navigation_node $parent) {
659 // Set the parent (thats the easy part)
660 $this->parent = $parent;
661 // Check if this node is active (this is checked during construction)
662 if ($this->isactive) {
663 // Force all of the parent nodes open so you can see this node
664 $this->parent->force_open();
665 // Make all parents inactive so that its clear where we are.
666 $this->parent->make_inactive();
672 * Navigation node collection
674 * This class is responsible for managing a collection of navigation nodes.
675 * It is required because a node's unique identifier is a combination of both its
676 * key and its type.
678 * Originally an array was used with a string key that was a combination of the two
679 * however it was decided that a better solution would be to use a class that
680 * implements the standard IteratorAggregate interface.
682 * @package core
683 * @category navigation
684 * @copyright 2010 Sam Hemelryk
685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
687 class navigation_node_collection implements IteratorAggregate {
689 * A multidimensional array to where the first key is the type and the second
690 * key is the nodes key.
691 * @var array
693 protected $collection = array();
695 * An array that contains references to nodes in the same order they were added.
696 * This is maintained as a progressive array.
697 * @var array
699 protected $orderedcollection = array();
701 * A reference to the last node that was added to the collection
702 * @var navigation_node
704 protected $last = null;
706 * The total number of items added to this array.
707 * @var int
709 protected $count = 0;
712 * Adds a navigation node to the collection
714 * @param navigation_node $node Node to add
715 * @param string $beforekey If specified, adds before a node with this key,
716 * otherwise adds at end
717 * @return navigation_node Added node
719 public function add(navigation_node $node, $beforekey=null) {
720 global $CFG;
721 $key = $node->key;
722 $type = $node->type;
724 // First check we have a 2nd dimension for this type
725 if (!array_key_exists($type, $this->orderedcollection)) {
726 $this->orderedcollection[$type] = array();
728 // Check for a collision and report if debugging is turned on
729 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
730 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
733 // Find the key to add before
734 $newindex = $this->count;
735 $last = true;
736 if ($beforekey !== null) {
737 foreach ($this->collection as $index => $othernode) {
738 if ($othernode->key === $beforekey) {
739 $newindex = $index;
740 $last = false;
741 break;
744 if ($newindex === $this->count) {
745 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
746 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
750 // Add the node to the appropriate place in the by-type structure (which
751 // is not ordered, despite the variable name)
752 $this->orderedcollection[$type][$key] = $node;
753 if (!$last) {
754 // Update existing references in the ordered collection (which is the
755 // one that isn't called 'ordered') to shuffle them along if required
756 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
757 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
760 // Add a reference to the node to the progressive collection.
761 $this->collection[$newindex] = &$this->orderedcollection[$type][$key];
762 // Update the last property to a reference to this new node.
763 $this->last = &$this->orderedcollection[$type][$key];
765 // Reorder the array by index if needed
766 if (!$last) {
767 ksort($this->collection);
769 $this->count++;
770 // Return the reference to the now added node
771 return $node;
775 * Return a list of all the keys of all the nodes.
776 * @return array the keys.
778 public function get_key_list() {
779 $keys = array();
780 foreach ($this->collection as $node) {
781 $keys[] = $node->key;
783 return $keys;
787 * Fetches a node from this collection.
789 * @param string|int $key The key of the node we want to find.
790 * @param int $type One of navigation_node::TYPE_*.
791 * @return navigation_node|null
793 public function get($key, $type=null) {
794 if ($type !== null) {
795 // If the type is known then we can simply check and fetch
796 if (!empty($this->orderedcollection[$type][$key])) {
797 return $this->orderedcollection[$type][$key];
799 } else {
800 // Because we don't know the type we look in the progressive array
801 foreach ($this->collection as $node) {
802 if ($node->key === $key) {
803 return $node;
807 return false;
811 * Searches for a node with matching key and type.
813 * This function searches both the nodes in this collection and all of
814 * the nodes in each collection belonging to the nodes in this collection.
816 * Recursive.
818 * @param string|int $key The key of the node we want to find.
819 * @param int $type One of navigation_node::TYPE_*.
820 * @return navigation_node|null
822 public function find($key, $type=null) {
823 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
824 return $this->orderedcollection[$type][$key];
825 } else {
826 $nodes = $this->getIterator();
827 // Search immediate children first
828 foreach ($nodes as &$node) {
829 if ($node->key === $key && ($type === null || $type === $node->type)) {
830 return $node;
833 // Now search each childs children
834 foreach ($nodes as &$node) {
835 $result = $node->children->find($key, $type);
836 if ($result !== false) {
837 return $result;
841 return false;
845 * Fetches the last node that was added to this collection
847 * @return navigation_node
849 public function last() {
850 return $this->last;
854 * Fetches all nodes of a given type from this collection
856 * @param string|int $type node type being searched for.
857 * @return array ordered collection
859 public function type($type) {
860 if (!array_key_exists($type, $this->orderedcollection)) {
861 $this->orderedcollection[$type] = array();
863 return $this->orderedcollection[$type];
866 * Removes the node with the given key and type from the collection
868 * @param string|int $key The key of the node we want to find.
869 * @param int $type
870 * @return bool
872 public function remove($key, $type=null) {
873 $child = $this->get($key, $type);
874 if ($child !== false) {
875 foreach ($this->collection as $colkey => $node) {
876 if ($node->key == $key && $node->type == $type) {
877 unset($this->collection[$colkey]);
878 break;
881 unset($this->orderedcollection[$child->type][$child->key]);
882 $this->count--;
883 return true;
885 return false;
889 * Gets the number of nodes in this collection
891 * This option uses an internal count rather than counting the actual options to avoid
892 * a performance hit through the count function.
894 * @return int
896 public function count() {
897 return $this->count;
900 * Gets an array iterator for the collection.
902 * This is required by the IteratorAggregator interface and is used by routines
903 * such as the foreach loop.
905 * @return ArrayIterator
907 public function getIterator() {
908 return new ArrayIterator($this->collection);
913 * The global navigation class used for... the global navigation
915 * This class is used by PAGE to store the global navigation for the site
916 * and is then used by the settings nav and navbar to save on processing and DB calls
918 * See
919 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
920 * {@link lib/ajax/getnavbranch.php} Called by ajax
922 * @package core
923 * @category navigation
924 * @copyright 2009 Sam Hemelryk
925 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
927 class global_navigation extends navigation_node {
928 /** @var moodle_page The Moodle page this navigation object belongs to. */
929 protected $page;
930 /** @var bool switch to let us know if the navigation object is initialised*/
931 protected $initialised = false;
932 /** @var array An array of course information */
933 protected $mycourses = array();
934 /** @var array An array for containing root navigation nodes */
935 protected $rootnodes = array();
936 /** @var bool A switch for whether to show empty sections in the navigation */
937 protected $showemptysections = false;
938 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
939 protected $showcategories = null;
940 /** @var array An array of stdClasses for users that the navigation is extended for */
941 protected $extendforuser = array();
942 /** @var navigation_cache */
943 protected $cache;
944 /** @var array An array of course ids that are present in the navigation */
945 protected $addedcourses = array();
946 /** @var array An array of category ids that are included in the navigation */
947 protected $addedcategories = array();
948 /** @var int expansion limit */
949 protected $expansionlimit = 0;
950 /** @var int userid to allow parent to see child's profile page navigation */
951 protected $useridtouseforparentchecks = 0;
954 * Constructs a new global navigation
956 * @param moodle_page $page The page this navigation object belongs to
958 public function __construct(moodle_page $page) {
959 global $CFG, $SITE, $USER;
961 if (during_initial_install()) {
962 return;
965 if (get_home_page() == HOMEPAGE_SITE) {
966 // We are using the site home for the root element
967 $properties = array(
968 'key' => 'home',
969 'type' => navigation_node::TYPE_SYSTEM,
970 'text' => get_string('home'),
971 'action' => new moodle_url('/')
973 } else {
974 // We are using the users my moodle for the root element
975 $properties = array(
976 'key' => 'myhome',
977 'type' => navigation_node::TYPE_SYSTEM,
978 'text' => get_string('myhome'),
979 'action' => new moodle_url('/my/')
983 // Use the parents constructor.... good good reuse
984 parent::__construct($properties);
986 // Initalise and set defaults
987 $this->page = $page;
988 $this->forceopen = true;
989 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
993 * Mutator to set userid to allow parent to see child's profile
994 * page navigation. See MDL-25805 for initial issue. Linked to it
995 * is an issue explaining why this is a REALLY UGLY HACK thats not
996 * for you to use!
998 * @param int $userid userid of profile page that parent wants to navigate around.
1000 public function set_userid_for_parent_checks($userid) {
1001 $this->useridtouseforparentchecks = $userid;
1006 * Initialises the navigation object.
1008 * This causes the navigation object to look at the current state of the page
1009 * that it is associated with and then load the appropriate content.
1011 * This should only occur the first time that the navigation structure is utilised
1012 * which will normally be either when the navbar is called to be displayed or
1013 * when a block makes use of it.
1015 * @return bool
1017 public function initialise() {
1018 global $CFG, $SITE, $USER, $DB;
1019 // Check if it has alread been initialised
1020 if ($this->initialised || during_initial_install()) {
1021 return true;
1023 $this->initialised = true;
1025 // Set up the five base root nodes. These are nodes where we will put our
1026 // content and are as follows:
1027 // site: Navigation for the front page.
1028 // myprofile: User profile information goes here.
1029 // mycourses: The users courses get added here.
1030 // courses: Additional courses are added here.
1031 // users: Other users information loaded here.
1032 $this->rootnodes = array();
1033 if (get_home_page() == HOMEPAGE_SITE) {
1034 // The home element should be my moodle because the root element is the site
1035 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1036 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1038 } else {
1039 // The home element should be the site because the root node is my moodle
1040 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1041 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1042 // We need to stop automatic redirection
1043 $this->rootnodes['home']->action->param('redirect', '0');
1046 $this->rootnodes['site'] = $this->add_course($SITE);
1047 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1048 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
1049 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1050 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1052 // Fetch all of the users courses.
1053 $limit = 20;
1054 if (!empty($CFG->navcourselimit)) {
1055 $limit = $CFG->navcourselimit;
1058 $mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC');
1059 $showallcourses = (count($mycourses) == 0 || !empty($CFG->navshowallcourses));
1060 // When checking if we are to show categories there is an additional override.
1061 // If the user is viewing a category then we will load it regardless of settings.
1062 // to ensure that the navigation is consistent.
1063 $showcategories = $this->page->context->contextlevel == CONTEXT_COURSECAT || ($showallcourses && $this->show_categories());
1064 $issite = ($this->page->course->id == SITEID);
1065 $ismycourse = (array_key_exists($this->page->course->id, $mycourses));
1067 // Check if any courses were returned.
1068 if (count($mycourses) > 0) {
1070 // Check if categories should be displayed within the my courses branch
1071 if (!empty($CFG->navshowmycoursecategories)) {
1073 // Find the category of each mycourse
1074 $categories = array();
1075 foreach ($mycourses as $course) {
1076 $categories[] = $course->category;
1079 // Do a single DB query to get the categories immediately associated with
1080 // courses the user is enrolled in.
1081 $categories = $DB->get_records_list('course_categories', 'id', array_unique($categories), 'depth ASC, sortorder ASC');
1082 // Work out the parent categories that we need to load that we havn't
1083 // already got.
1084 $categoryids = array();
1085 foreach ($categories as $category) {
1086 $categoryids = array_merge($categoryids, explode('/', trim($category->path, '/')));
1088 $categoryids = array_unique($categoryids);
1089 $categoryids = array_diff($categoryids, array_keys($categories));
1091 if (count($categoryids)) {
1092 // Fetch any other categories we need.
1093 $allcategories = $DB->get_records_list('course_categories', 'id', $categoryids, 'depth ASC, sortorder ASC');
1094 if (is_array($allcategories) && count($allcategories) > 0) {
1095 $categories = array_merge($categories, $allcategories);
1099 // We ONLY want the categories, we need to get rid of the keys
1100 $categories = array_values($categories);
1101 $addedcategories = array();
1102 while (($category = array_shift($categories)) !== null) {
1103 if ($category->parent == '0') {
1104 $categoryparent = $this->rootnodes['mycourses'];
1105 } else if (array_key_exists($category->parent, $addedcategories)) {
1106 $categoryparent = $addedcategories[$category->parent];
1107 } else {
1108 // Prepare to count iterations. We don't want to loop forever
1109 // accidentally if for some reason a category can't be placed.
1110 if (!isset($category->loopcount)) {
1111 $category->loopcount = 0;
1113 $category->loopcount++;
1114 if ($category->loopcount > 5) {
1115 // This is a pretty serious problem and this should never happen.
1116 // If it does then for some reason a category has been loaded but
1117 // its parents have now. It could be data corruption.
1118 debugging('Category '.$category->id.' could not be placed within the navigation', DEBUG_DEVELOPER);
1119 } else {
1120 // Add it back to the end of the categories array
1121 array_push($categories, $category);
1123 continue;
1126 $url = new moodle_url('/course/category.php', array('id' => $category->id));
1127 $addedcategories[$category->id] = $categoryparent->add($category->name, $url, self::TYPE_CATEGORY, $category->name, $category->id);
1129 if (!$category->visible) {
1130 if (!has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_COURSECAT, $category->parent))) {
1131 $addedcategories[$category->id]->display = false;
1132 } else {
1133 $addedcategories[$category->id]->hidden = true;
1139 // Add all of the users courses to the navigation.
1140 foreach ($mycourses as $course) {
1141 $course->coursenode = $this->add_course($course, false, true);
1145 if ($showallcourses) {
1146 // Load all courses
1147 $this->load_all_courses();
1150 // We always load the frontpage course to ensure it is available without
1151 // JavaScript enabled.
1152 $frontpagecourse = $this->load_course($SITE);
1153 $this->add_front_page_course_essentials($frontpagecourse, $SITE);
1154 $this->load_course_sections($SITE, $frontpagecourse);
1156 $canviewcourseprofile = true;
1158 // Next load context specific content into the navigation
1159 switch ($this->page->context->contextlevel) {
1160 case CONTEXT_SYSTEM :
1161 // This has already been loaded we just need to map the variable
1162 $coursenode = $frontpagecourse;
1163 $this->load_all_categories(null, $showcategories);
1164 break;
1165 case CONTEXT_COURSECAT :
1166 // This has already been loaded we just need to map the variable
1167 $coursenode = $frontpagecourse;
1168 $this->load_all_categories($this->page->context->instanceid, $showcategories);
1169 if (array_key_exists($this->page->context->instanceid, $this->addedcategories)) {
1170 $this->addedcategories[$this->page->context->instanceid]->make_active();
1172 break;
1173 case CONTEXT_BLOCK :
1174 case CONTEXT_COURSE :
1175 if ($issite) {
1176 // If it is the front page course, or a block on it then
1177 // everything has already been loaded.
1178 break;
1180 // Load the course associated with the page into the navigation
1181 $course = $this->page->course;
1182 if ($showcategories && !$ismycourse) {
1183 $this->load_all_categories($course->category, $showcategories);
1185 $coursenode = $this->load_course($course);
1187 // If the course wasn't added then don't try going any further.
1188 if (!$coursenode) {
1189 $canviewcourseprofile = false;
1190 break;
1193 // If the user is not enrolled then we only want to show the
1194 // course node and not populate it.
1196 // Not enrolled, can't view, and hasn't switched roles
1197 if (!can_access_course($course)) {
1198 // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1199 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1200 $isparent = false;
1201 if ($this->useridtouseforparentchecks) {
1202 if ($this->useridtouseforparentchecks != $USER->id) {
1203 $usercontext = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST);
1204 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))
1205 and has_capability('moodle/user:viewdetails', $usercontext)) {
1206 $isparent = true;
1211 if (!$isparent) {
1212 $coursenode->make_active();
1213 $canviewcourseprofile = false;
1214 break;
1217 // Add the essentials such as reports etc...
1218 $this->add_course_essentials($coursenode, $course);
1219 if ($this->format_display_course_content($course->format)) {
1220 // Load the course sections
1221 $sections = $this->load_course_sections($course, $coursenode);
1223 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1224 $coursenode->make_active();
1226 break;
1227 case CONTEXT_MODULE :
1228 if ($issite) {
1229 // If this is the site course then most information will have
1230 // already been loaded.
1231 // However we need to check if there is more content that can
1232 // yet be loaded for the specific module instance.
1233 $activitynode = $this->rootnodes['site']->get($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1234 if ($activitynode) {
1235 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1237 break;
1240 $course = $this->page->course;
1241 $cm = $this->page->cm;
1243 if ($showcategories && !$ismycourse) {
1244 $this->load_all_categories($course->category, $showcategories);
1247 // Load the course associated with the page into the navigation
1248 $coursenode = $this->load_course($course);
1250 // If the course wasn't added then don't try going any further.
1251 if (!$coursenode) {
1252 $canviewcourseprofile = false;
1253 break;
1256 // If the user is not enrolled then we only want to show the
1257 // course node and not populate it.
1258 if (!can_access_course($course)) {
1259 $coursenode->make_active();
1260 $canviewcourseprofile = false;
1261 break;
1264 $this->add_course_essentials($coursenode, $course);
1266 // Get section number from $cm (if provided) - we need this
1267 // before loading sections in order to tell it to load this section
1268 // even if it would not normally display (=> it contains only
1269 // a label, which we are now editing)
1270 $sectionnum = isset($cm->sectionnum) ? $cm->sectionnum : 0;
1271 if ($sectionnum) {
1272 // This value has to be stored in a member variable because
1273 // otherwise we would have to pass it through a public API
1274 // to course formats and they would need to change their
1275 // functions to pass it along again...
1276 $this->includesectionnum = $sectionnum;
1277 } else {
1278 $this->includesectionnum = false;
1281 // Load the course sections into the page
1282 $sections = $this->load_course_sections($course, $coursenode);
1283 if ($course->id != SITEID) {
1284 // Find the section for the $CM associated with the page and collect
1285 // its section number.
1286 if ($sectionnum) {
1287 $cm->sectionnumber = $sectionnum;
1288 } else {
1289 foreach ($sections as $section) {
1290 if ($section->id == $cm->section) {
1291 $cm->sectionnumber = $section->section;
1292 break;
1297 // Load all of the section activities for the section the cm belongs to.
1298 if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) {
1299 list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
1300 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, $activityarray);
1301 } else {
1302 $activities = array();
1303 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1304 // "stealth" activity from unavailable section
1305 $activities[$cm->id] = $activity;
1308 } else {
1309 $activities = array();
1310 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1312 if (!empty($activities[$cm->id])) {
1313 // Finally load the cm specific navigaton information
1314 $this->load_activity($cm, $course, $activities[$cm->id]);
1315 // Check if we have an active ndoe
1316 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1317 // And make the activity node active.
1318 $activities[$cm->id]->make_active();
1320 } else {
1321 //TODO: something is wrong, what to do? (Skodak)
1323 break;
1324 case CONTEXT_USER :
1325 if ($issite) {
1326 // The users profile information etc is already loaded
1327 // for the front page.
1328 break;
1330 $course = $this->page->course;
1331 if ($showcategories && !$ismycourse) {
1332 $this->load_all_categories($course->category, $showcategories);
1334 // Load the course associated with the user into the navigation
1335 $coursenode = $this->load_course($course);
1337 // If the course wasn't added then don't try going any further.
1338 if (!$coursenode) {
1339 $canviewcourseprofile = false;
1340 break;
1343 // If the user is not enrolled then we only want to show the
1344 // course node and not populate it.
1345 if (!can_access_course($course)) {
1346 $coursenode->make_active();
1347 $canviewcourseprofile = false;
1348 break;
1350 $this->add_course_essentials($coursenode, $course);
1351 $sections = $this->load_course_sections($course, $coursenode);
1352 break;
1355 $limit = 20;
1356 if (!empty($CFG->navcourselimit)) {
1357 $limit = $CFG->navcourselimit;
1359 if ($showcategories) {
1360 $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1361 foreach ($categories as &$category) {
1362 if ($category->children->count() >= $limit) {
1363 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1364 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1367 } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1368 $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1371 // Load for the current user
1372 $this->load_for_user();
1373 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) {
1374 $this->load_for_user(null, true);
1376 // Load each extending user into the navigation.
1377 foreach ($this->extendforuser as $user) {
1378 if ($user->id != $USER->id) {
1379 $this->load_for_user($user);
1383 // Give the local plugins a chance to include some navigation if they want.
1384 foreach (get_list_of_plugins('local') as $plugin) {
1385 if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1386 continue;
1388 require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1389 $function = $plugin.'_extends_navigation';
1390 if (function_exists($function)) {
1391 $function($this);
1395 // Remove any empty root nodes
1396 foreach ($this->rootnodes as $node) {
1397 // Dont remove the home node
1398 if ($node->key !== 'home' && !$node->has_children()) {
1399 $node->remove();
1403 if (!$this->contains_active_node()) {
1404 $this->search_for_active_node();
1407 // If the user is not logged in modify the navigation structure as detailed
1408 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1409 if (!isloggedin()) {
1410 $activities = clone($this->rootnodes['site']->children);
1411 $this->rootnodes['site']->remove();
1412 $children = clone($this->children);
1413 $this->children = new navigation_node_collection();
1414 foreach ($activities as $child) {
1415 $this->children->add($child);
1417 foreach ($children as $child) {
1418 $this->children->add($child);
1421 return true;
1425 * Returns true if courses should be shown within categories on the navigation.
1427 * @return bool
1429 protected function show_categories() {
1430 global $CFG, $DB;
1431 if ($this->showcategories === null) {
1432 $show = $this->page->context->contextlevel == CONTEXT_COURSECAT;
1433 $show = $show || (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1);
1434 $this->showcategories = $show;
1436 return $this->showcategories;
1440 * Checks the course format to see whether it wants the navigation to load
1441 * additional information for the course.
1443 * This function utilises a callback that can exist within the course format lib.php file
1444 * The callback should be a function called:
1445 * callback_{formatname}_display_content()
1446 * It doesn't get any arguments and should return true if additional content is
1447 * desired. If the callback doesn't exist we assume additional content is wanted.
1449 * @param string $format The course format
1450 * @return bool
1452 protected function format_display_course_content($format) {
1453 global $CFG;
1454 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1455 if (file_exists($formatlib)) {
1456 require_once($formatlib);
1457 $displayfunc = 'callback_'.$format.'_display_content';
1458 if (function_exists($displayfunc) && !$displayfunc()) {
1459 return $displayfunc();
1462 return true;
1466 * Loads the courses in Moodle into the navigation.
1468 * @param mixed $categoryids Either a string or array of category ids to load courses for
1469 * @return array An array of navigation_node
1471 protected function load_all_courses($categoryids=null) {
1472 global $CFG, $DB, $USER;
1474 if ($categoryids !== null) {
1475 if (is_array($categoryids)) {
1476 list ($categoryselect, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'catid');
1477 } else {
1478 $categoryselect = '= :categoryid';
1479 $params = array('categoryid', $categoryids);
1481 $params['siteid'] = SITEID;
1482 $categoryselect = ' AND c.category '.$categoryselect;
1483 } else {
1484 $params = array('siteid' => SITEID);
1485 $categoryselect = '';
1488 $ccselect = context_helper::get_preload_record_columns_sql('ctx');
1489 $params['contextlevel'] = CONTEXT_COURSE;
1490 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses) + array(SITEID), SQL_PARAMS_NAMED, 'lcourse', false);
1491 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category, cat.path AS categorypath, $ccselect
1492 FROM {course} c
1493 JOIN {context} ctx ON c.id = ctx.instanceid
1494 LEFT JOIN {course_categories} cat ON cat.id=c.category
1495 WHERE c.id {$courseids} AND
1496 ctx.contextlevel = :contextlevel
1497 {$categoryselect}
1498 ORDER BY c.sortorder ASC";
1499 $limit = 20;
1500 if (!empty($CFG->navcourselimit)) {
1501 $limit = $CFG->navcourselimit;
1503 $courses = $DB->get_records_sql($sql, $params + $courseparams, 0, $limit);
1505 $coursenodes = array();
1506 foreach ($courses as $course) {
1507 context_helper::preload_from_record($course);
1508 $coursenodes[$course->id] = $this->add_course($course);
1510 return $coursenodes;
1514 * Loads all categories (top level or if an id is specified for that category)
1516 * @param int $categoryid The category id to load or null/0 to load all base level categories
1517 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1518 * as the requested category and any parent categories.
1519 * @return navigation_node|void returns a navigation node if a category has been loaded.
1521 protected function load_all_categories($categoryid = null, $showbasecategories = false) {
1522 global $DB;
1524 // Check if this category has already been loaded
1525 if ($categoryid !== null && array_key_exists($categoryid, $this->addedcategories) && $this->addedcategories[$categoryid]->children->count() > 0) {
1526 return $this->addedcategories[$categoryid];
1529 $coursestoload = array();
1530 if (empty($categoryid)) { // can be 0
1531 // We are going to load all of the first level categories (categories without parents)
1532 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder ASC, id ASC');
1533 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1534 // The category itself has been loaded already so we just need to ensure its subcategories
1535 // have been loaded
1536 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1537 if ($showbasecategories) {
1538 // We need to include categories with parent = 0 as well
1539 $sql = "SELECT *
1540 FROM {course_categories} cc
1541 WHERE (parent = :categoryid OR parent = 0) AND
1542 parent {$sql}
1543 ORDER BY depth DESC, sortorder ASC, id ASC";
1544 } else {
1545 $sql = "SELECT *
1546 FROM {course_categories} cc
1547 WHERE parent = :categoryid AND
1548 parent {$sql}
1549 ORDER BY depth DESC, sortorder ASC, id ASC";
1551 $params['categoryid'] = $categoryid;
1552 $categories = $DB->get_records_sql($sql, $params);
1553 if (count($categories) == 0) {
1554 // There are no further categories that require loading.
1555 return;
1557 } else {
1558 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1559 // and load this category plus all its parents and subcategories
1560 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1561 $coursestoload = explode('/', trim($category->path, '/'));
1562 list($select, $params) = $DB->get_in_or_equal($coursestoload);
1563 $select = 'id '.$select.' OR parent '.$select;
1564 if ($showbasecategories) {
1565 $select .= ' OR parent = 0';
1567 $params = array_merge($params, $params);
1568 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1571 // Now we have an array of categories we need to add them to the navigation.
1572 while (!empty($categories)) {
1573 $category = reset($categories);
1574 if (array_key_exists($category->id, $this->addedcategories)) {
1575 // Do nothing
1576 } else if ($category->parent == '0') {
1577 $this->add_category($category, $this->rootnodes['courses']);
1578 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1579 $this->add_category($category, $this->addedcategories[$category->parent]);
1580 } else {
1581 // This category isn't in the navigation and niether is it's parent (yet).
1582 // We need to go through the category path and add all of its components in order.
1583 $path = explode('/', trim($category->path, '/'));
1584 foreach ($path as $catid) {
1585 if (!array_key_exists($catid, $this->addedcategories)) {
1586 // This category isn't in the navigation yet so add it.
1587 $subcategory = $categories[$catid];
1588 if ($subcategory->parent == '0') {
1589 // Yay we have a root category - this likely means we will now be able
1590 // to add categories without problems.
1591 $this->add_category($subcategory, $this->rootnodes['courses']);
1592 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1593 // The parent is in the category (as we'd expect) so add it now.
1594 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1595 // Remove the category from the categories array.
1596 unset($categories[$catid]);
1597 } else {
1598 // We should never ever arrive here - if we have then there is a bigger
1599 // problem at hand.
1600 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1605 // Remove the category from the categories array now that we know it has been added.
1606 unset($categories[$category->id]);
1608 // Check if there are any categories to load.
1609 if (count($coursestoload) > 0) {
1610 $this->load_all_courses($coursestoload);
1615 * Adds a structured category to the navigation in the correct order/place
1617 * @param stdClass $category
1618 * @param navigation_node $parent
1620 protected function add_category(stdClass $category, navigation_node $parent) {
1621 if (array_key_exists($category->id, $this->addedcategories)) {
1622 return;
1624 $url = new moodle_url('/course/category.php', array('id' => $category->id));
1625 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
1626 $categoryname = format_string($category->name, true, array('context' => $context));
1627 $categorynode = $parent->add($categoryname, $url, self::TYPE_CATEGORY, $categoryname, $category->id);
1628 if (empty($category->visible)) {
1629 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1630 $categorynode->hidden = true;
1631 } else {
1632 $categorynode->display = false;
1635 $this->addedcategories[$category->id] = &$categorynode;
1639 * Loads the given course into the navigation
1641 * @param stdClass $course
1642 * @return navigation_node
1644 protected function load_course(stdClass $course) {
1645 if ($course->id == SITEID) {
1646 return $this->rootnodes['site'];
1647 } else if (array_key_exists($course->id, $this->addedcourses)) {
1648 return $this->addedcourses[$course->id];
1649 } else {
1650 return $this->add_course($course);
1655 * Loads all of the courses section into the navigation.
1657 * This function utilisies a callback that can be implemented within the course
1658 * formats lib.php file to customise the navigation that is generated at this
1659 * point for the course.
1661 * By default (if not defined) the method {@link global_navigation::load_generic_course_sections()} is
1662 * called instead.
1664 * @param stdClass $course Database record for the course
1665 * @param navigation_node $coursenode The course node within the navigation
1666 * @return array Array of navigation nodes for the section with key = section id
1668 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1669 global $CFG;
1670 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1671 $structurefunc = 'callback_'.$course->format.'_load_content';
1672 if (function_exists($structurefunc)) {
1673 return $structurefunc($this, $course, $coursenode);
1674 } else if (file_exists($structurefile)) {
1675 require_once $structurefile;
1676 if (function_exists($structurefunc)) {
1677 return $structurefunc($this, $course, $coursenode);
1678 } else {
1679 return $this->load_generic_course_sections($course, $coursenode);
1681 } else {
1682 return $this->load_generic_course_sections($course, $coursenode);
1687 * Generates an array of sections and an array of activities for the given course.
1689 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1691 * @param stdClass $course
1692 * @return array Array($sections, $activities)
1694 protected function generate_sections_and_activities(stdClass $course) {
1695 global $CFG;
1696 require_once($CFG->dirroot.'/course/lib.php');
1698 $modinfo = get_fast_modinfo($course);
1700 $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1701 $activities = array();
1703 foreach ($sections as $key => $section) {
1704 $sections[$key]->hasactivites = false;
1705 if (!array_key_exists($section->section, $modinfo->sections)) {
1706 continue;
1708 foreach ($modinfo->sections[$section->section] as $cmid) {
1709 $cm = $modinfo->cms[$cmid];
1710 if (!$cm->uservisible) {
1711 continue;
1713 $activity = new stdClass;
1714 $activity->id = $cm->id;
1715 $activity->course = $course->id;
1716 $activity->section = $section->section;
1717 $activity->name = $cm->name;
1718 $activity->icon = $cm->icon;
1719 $activity->iconcomponent = $cm->iconcomponent;
1720 $activity->hidden = (!$cm->visible);
1721 $activity->modname = $cm->modname;
1722 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1723 $activity->onclick = $cm->get_on_click();
1724 $url = $cm->get_url();
1725 if (!$url) {
1726 $activity->url = null;
1727 $activity->display = false;
1728 } else {
1729 $activity->url = $cm->get_url()->out();
1730 $activity->display = true;
1731 if (self::module_extends_navigation($cm->modname)) {
1732 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1735 $activities[$cmid] = $activity;
1736 if ($activity->display) {
1737 $sections[$key]->hasactivites = true;
1742 return array($sections, $activities);
1746 * Generically loads the course sections into the course's navigation.
1748 * @param stdClass $course
1749 * @param navigation_node $coursenode
1750 * @param string $courseformat The course format
1751 * @return array An array of course section nodes
1753 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1754 global $CFG, $DB, $USER;
1755 require_once($CFG->dirroot.'/course/lib.php');
1757 list($sections, $activities) = $this->generate_sections_and_activities($course);
1759 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1760 $namingfunctionexists = (function_exists($namingfunction));
1762 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1764 $urlfunction = 'callback_'.$courseformat.'_get_section_url';
1765 if (empty($CFG->navlinkcoursesections) || !function_exists($urlfunction)) {
1766 $urlfunction = null;
1769 $keyfunction = 'callback_'.$courseformat.'_request_key';
1770 $key = course_get_display($course->id);
1771 if (defined('AJAX_SCRIPT') && AJAX_SCRIPT == '0' && function_exists($keyfunction) && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1772 $key = optional_param($keyfunction(), $key, PARAM_INT);
1775 $navigationsections = array();
1776 foreach ($sections as $sectionid => $section) {
1777 $section = clone($section);
1778 if ($course->id == SITEID) {
1779 $this->load_section_activities($coursenode, $section->section, $activities);
1780 } else {
1781 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections &&
1782 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1783 continue;
1785 if ($namingfunctionexists) {
1786 $sectionname = $namingfunction($course, $section, $sections);
1787 } else {
1788 $sectionname = get_string('section').' '.$section->section;
1791 $url = null;
1792 if (!empty($urlfunction)) {
1793 $url = $urlfunction($course->id, $section->section);
1795 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1796 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1797 $sectionnode->hidden = (!$section->visible);
1798 if ($key != '0' && $section->section != '0' && $section->section == $key && $this->page->context->contextlevel != CONTEXT_MODULE && $section->hasactivites) {
1799 $sectionnode->make_active();
1800 $this->load_section_activities($sectionnode, $section->section, $activities);
1802 $section->sectionnode = $sectionnode;
1803 $navigationsections[$sectionid] = $section;
1806 return $navigationsections;
1809 * Loads all of the activities for a section into the navigation structure.
1811 * @param navigation_node $sectionnode
1812 * @param int $sectionnumber
1813 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1814 * @param stdClass $course The course object the section and activities relate to.
1815 * @return array Array of activity nodes
1817 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1818 global $CFG;
1819 // A static counter for JS function naming
1820 static $legacyonclickcounter = 0;
1822 $activitynodes = array();
1823 if (empty($activities)) {
1824 return $activitynodes;
1827 if (!is_object($course)) {
1828 $activity = reset($activities);
1829 $courseid = $activity->course;
1830 } else {
1831 $courseid = $course->id;
1833 $showactivities = ($courseid != SITEID || !empty($CFG->navshowfrontpagemods));
1835 foreach ($activities as $activity) {
1836 if ($activity->section != $sectionnumber) {
1837 continue;
1839 if ($activity->icon) {
1840 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1841 } else {
1842 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1845 // Prepare the default name and url for the node
1846 $activityname = format_string($activity->name, true, array('context' => get_context_instance(CONTEXT_MODULE, $activity->id)));
1847 $action = new moodle_url($activity->url);
1849 // Check if the onclick property is set (puke!)
1850 if (!empty($activity->onclick)) {
1851 // Increment the counter so that we have a unique number.
1852 $legacyonclickcounter++;
1853 // Generate the function name we will use
1854 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1855 $propogrationhandler = '';
1856 // Check if we need to cancel propogation. Remember inline onclick
1857 // events would return false if they wanted to prevent propogation and the
1858 // default action.
1859 if (strpos($activity->onclick, 'return false')) {
1860 $propogrationhandler = 'e.halt();';
1862 // Decode the onclick - it has already been encoded for display (puke)
1863 $onclick = htmlspecialchars_decode($activity->onclick);
1864 // Build the JS function the click event will call
1865 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1866 $this->page->requires->js_init_code($jscode);
1867 // Override the default url with the new action link
1868 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1871 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1872 $activitynode->title(get_string('modulename', $activity->modname));
1873 $activitynode->hidden = $activity->hidden;
1874 $activitynode->display = $showactivities && $activity->display;
1875 $activitynode->nodetype = $activity->nodetype;
1876 $activitynodes[$activity->id] = $activitynode;
1879 return $activitynodes;
1882 * Loads a stealth module from unavailable section
1883 * @param navigation_node $coursenode
1884 * @param stdClass $modinfo
1885 * @return navigation_node or null if not accessible
1887 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1888 if (empty($modinfo->cms[$this->page->cm->id])) {
1889 return null;
1891 $cm = $modinfo->cms[$this->page->cm->id];
1892 if (!$cm->uservisible) {
1893 return null;
1895 if ($cm->icon) {
1896 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1897 } else {
1898 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1900 $url = $cm->get_url();
1901 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1902 $activitynode->title(get_string('modulename', $cm->modname));
1903 $activitynode->hidden = (!$cm->visible);
1904 if (!$url) {
1905 // Don't show activities that don't have links!
1906 $activitynode->display = false;
1907 } else if (self::module_extends_navigation($cm->modname)) {
1908 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1910 return $activitynode;
1913 * Loads the navigation structure for the given activity into the activities node.
1915 * This method utilises a callback within the modules lib.php file to load the
1916 * content specific to activity given.
1918 * The callback is a method: {modulename}_extend_navigation()
1919 * Examples:
1920 * * {@link forum_extend_navigation()}
1921 * * {@link workshop_extend_navigation()}
1923 * @param cm_info|stdClass $cm
1924 * @param stdClass $course
1925 * @param navigation_node $activity
1926 * @return bool
1928 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
1929 global $CFG, $DB;
1931 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
1932 if (!($cm instanceof cm_info)) {
1933 $modinfo = get_fast_modinfo($course);
1934 $cm = $modinfo->get_cm($cm->id);
1937 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1938 $activity->make_active();
1939 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1940 $function = $cm->modname.'_extend_navigation';
1942 if (file_exists($file)) {
1943 require_once($file);
1944 if (function_exists($function)) {
1945 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1946 $function($activity, $course, $activtyrecord, $cm);
1950 // Allow the active advanced grading method plugin to append module navigation
1951 $featuresfunc = $cm->modname.'_supports';
1952 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
1953 require_once($CFG->dirroot.'/grade/grading/lib.php');
1954 $gradingman = get_grading_manager($cm->context, $cm->modname);
1955 $gradingman->extend_navigation($this, $activity);
1958 return $activity->has_children();
1961 * Loads user specific information into the navigation in the appropriate place.
1963 * If no user is provided the current user is assumed.
1965 * @param stdClass $user
1966 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
1967 * @return bool
1969 protected function load_for_user($user=null, $forceforcontext=false) {
1970 global $DB, $CFG, $USER;
1972 if ($user === null) {
1973 // We can't require login here but if the user isn't logged in we don't
1974 // want to show anything
1975 if (!isloggedin() || isguestuser()) {
1976 return false;
1978 $user = $USER;
1979 } else if (!is_object($user)) {
1980 // If the user is not an object then get them from the database
1981 $select = context_helper::get_preload_record_columns_sql('ctx');
1982 $sql = "SELECT u.*, $select
1983 FROM {user} u
1984 JOIN {context} ctx ON u.id = ctx.instanceid
1985 WHERE u.id = :userid AND
1986 ctx.contextlevel = :contextlevel";
1987 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
1988 context_helper::preload_from_record($user);
1991 $iscurrentuser = ($user->id == $USER->id);
1993 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1995 // Get the course set against the page, by default this will be the site
1996 $course = $this->page->course;
1997 $baseargs = array('id'=>$user->id);
1998 if ($course->id != SITEID && (!$iscurrentuser || $forceforcontext)) {
1999 $coursenode = $this->load_course($course);
2000 $baseargs['course'] = $course->id;
2001 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2002 $issitecourse = false;
2003 } else {
2004 // Load all categories and get the context for the system
2005 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
2006 $issitecourse = true;
2009 // Create a node to add user information under.
2010 if ($iscurrentuser && !$forceforcontext) {
2011 // If it's the current user the information will go under the profile root node
2012 $usernode = $this->rootnodes['myprofile'];
2013 $course = get_site();
2014 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2015 $issitecourse = true;
2016 } else {
2017 if (!$issitecourse) {
2018 // Not the current user so add it to the participants node for the current course
2019 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2020 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2021 } else {
2022 // This is the site so add a users node to the root branch
2023 $usersnode = $this->rootnodes['users'];
2024 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2025 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2027 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2029 if (!$usersnode) {
2030 // We should NEVER get here, if the course hasn't been populated
2031 // with a participants node then the navigaiton either wasn't generated
2032 // for it (you are missing a require_login or set_context call) or
2033 // you don't have access.... in the interests of no leaking informatin
2034 // we simply quit...
2035 return false;
2037 // Add a branch for the current user
2038 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2039 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2041 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2042 $usernode->make_active();
2046 // If the user is the current user or has permission to view the details of the requested
2047 // user than add a view profile link.
2048 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2049 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2050 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2051 } else {
2052 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2056 if (!empty($CFG->navadduserpostslinks)) {
2057 // Add nodes for forum posts and discussions if the user can view either or both
2058 // There are no capability checks here as the content of the page is based
2059 // purely on the forums the current user has access too.
2060 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2061 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2062 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2065 // Add blog nodes
2066 if (!empty($CFG->bloglevel)) {
2067 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2068 require_once($CFG->dirroot.'/blog/lib.php');
2069 // Get all options for the user
2070 $options = blog_get_options_for_user($user);
2071 $this->cache->set('userblogoptions'.$user->id, $options);
2072 } else {
2073 $options = $this->cache->{'userblogoptions'.$user->id};
2076 if (count($options) > 0) {
2077 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2078 foreach ($options as $type => $option) {
2079 if ($type == "rss") {
2080 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2081 } else {
2082 $blogs->add($option['string'], $option['link']);
2088 if (!empty($CFG->messaging)) {
2089 $messageargs = null;
2090 if ($USER->id!=$user->id) {
2091 $messageargs = array('id'=>$user->id);
2093 $url = new moodle_url('/message/index.php',$messageargs);
2094 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2097 $context = get_context_instance(CONTEXT_USER, $USER->id);
2098 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
2099 $url = new moodle_url('/user/files.php');
2100 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2103 // Add a node to view the users notes if permitted
2104 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2105 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2106 if ($coursecontext->instanceid) {
2107 $url->param('course', $coursecontext->instanceid);
2109 $usernode->add(get_string('notes', 'notes'), $url);
2112 // Add reports node
2113 $reporttab = $usernode->add(get_string('activityreports'));
2114 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2115 foreach ($reports as $reportfunction) {
2116 $reportfunction($reporttab, $user, $course);
2118 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
2119 if ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext)) {
2120 // Add grade hardcoded grade report if necessary
2121 $gradeaccess = false;
2122 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2123 //ok - can view all course grades
2124 $gradeaccess = true;
2125 } else if ($course->showgrades) {
2126 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
2127 //ok - can view own grades
2128 $gradeaccess = true;
2129 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
2130 // ok - can view grades of this user - parent most probably
2131 $gradeaccess = true;
2132 } else if ($anyreport) {
2133 // ok - can view grades of this user - parent most probably
2134 $gradeaccess = true;
2137 if ($gradeaccess) {
2138 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id, 'user'=>$usercontext->instanceid)));
2141 // Check the number of nodes in the report node... if there are none remove the node
2142 $reporttab->trim_if_empty();
2144 // If the user is the current user add the repositories for the current user
2145 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2146 if ($iscurrentuser) {
2147 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2148 require_once($CFG->dirroot . '/repository/lib.php');
2149 $editabletypes = repository::get_editable_types($usercontext);
2150 $haseditabletypes = !empty($editabletypes);
2151 unset($editabletypes);
2152 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2153 } else {
2154 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2156 if ($haseditabletypes) {
2157 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2159 } else if ($course->id == SITEID && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2161 // Add view grade report is permitted
2162 $reports = get_plugin_list('gradereport');
2163 arsort($reports); // user is last, we want to test it first
2165 $userscourses = enrol_get_users_courses($user->id);
2166 $userscoursesnode = $usernode->add(get_string('courses'));
2168 foreach ($userscourses as $usercourse) {
2169 $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id);
2170 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2171 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2173 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2174 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2175 foreach ($reports as $plugin => $plugindir) {
2176 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2177 //stop when the first visible plugin is found
2178 $gradeavailable = true;
2179 break;
2184 if ($gradeavailable) {
2185 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2186 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2189 // Add a node to view the users notes if permitted
2190 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2191 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2192 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2195 if (can_access_course($usercourse, $user->id)) {
2196 $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', ''));
2199 $reporttab = $usercoursenode->add(get_string('activityreports'));
2201 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2202 foreach ($reports as $reportfunction) {
2203 $reportfunction($reporttab, $user, $usercourse);
2206 $reporttab->trim_if_empty();
2209 return true;
2213 * This method simply checks to see if a given module can extend the navigation.
2215 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2217 * @param string $modname
2218 * @return bool
2220 protected static function module_extends_navigation($modname) {
2221 global $CFG;
2222 static $extendingmodules = array();
2223 if (!array_key_exists($modname, $extendingmodules)) {
2224 $extendingmodules[$modname] = false;
2225 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2226 if (file_exists($file)) {
2227 $function = $modname.'_extend_navigation';
2228 require_once($file);
2229 $extendingmodules[$modname] = (function_exists($function));
2232 return $extendingmodules[$modname];
2235 * Extends the navigation for the given user.
2237 * @param stdClass $user A user from the database
2239 public function extend_for_user($user) {
2240 $this->extendforuser[] = $user;
2244 * Returns all of the users the navigation is being extended for
2246 * @return array An array of extending users.
2248 public function get_extending_users() {
2249 return $this->extendforuser;
2252 * Adds the given course to the navigation structure.
2254 * @param stdClass $course
2255 * @param bool $forcegeneric (optional)
2256 * @param bool $ismycourse (optional)
2257 * @return navigation_node
2259 public function add_course(stdClass $course, $forcegeneric = false, $ismycourse = false) {
2260 global $CFG;
2262 // We found the course... we can return it now :)
2263 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2264 return $this->addedcourses[$course->id];
2267 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2269 if ($course->id != SITEID && !$course->visible) {
2270 if (is_role_switched($course->id)) {
2271 // user has to be able to access course in order to switch, let's skip the visibility test here
2272 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2273 return false;
2277 $issite = ($course->id == SITEID);
2278 $ismycourse = ($ismycourse && !$forcegeneric);
2279 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2281 if ($issite) {
2282 $parent = $this;
2283 $url = null;
2284 if (empty($CFG->usesitenameforsitepages)) {
2285 $shortname = get_string('sitepages');
2287 } else if ($ismycourse) {
2288 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_CATEGORY))) {
2289 // Nothing to do here the above statement set $parent to the category within mycourses.
2290 } else {
2291 $parent = $this->rootnodes['mycourses'];
2293 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2294 } else {
2295 $parent = $this->rootnodes['courses'];
2296 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2299 if (!$ismycourse && !$issite && !empty($course->category)) {
2300 if ($this->show_categories()) {
2301 // We need to load the category structure for this course
2302 $this->load_all_categories($course->category);
2304 if (array_key_exists($course->category, $this->addedcategories)) {
2305 $parent = $this->addedcategories[$course->category];
2306 // This could lead to the course being created so we should check whether it is the case again
2307 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2308 return $this->addedcourses[$course->id];
2313 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
2314 $coursenode->nodetype = self::NODETYPE_BRANCH;
2315 $coursenode->hidden = (!$course->visible);
2316 $coursenode->title(format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))));
2317 if (!$forcegeneric) {
2318 $this->addedcourses[$course->id] = &$coursenode;
2320 if ($ismycourse && !empty($CFG->navshowallcourses)) {
2321 // We need to add this course to the general courses node as well as the
2322 // my courses node, rerun the function with the kill param
2323 $genericcourse = $this->add_course($course, true);
2324 if ($genericcourse->isactive) {
2325 $genericcourse->make_inactive();
2326 $genericcourse->collapse = true;
2327 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
2328 $parent = $genericcourse->parent;
2329 while ($parent && $parent->type == self::TYPE_CATEGORY) {
2330 $parent->collapse = true;
2331 $parent = $parent->parent;
2337 return $coursenode;
2340 * Adds essential course nodes to the navigation for the given course.
2342 * This method adds nodes such as reports, blogs and participants
2344 * @param navigation_node $coursenode
2345 * @param stdClass $course
2346 * @return bool returns true on successful addition of a node.
2348 public function add_course_essentials($coursenode, stdClass $course) {
2349 global $CFG;
2351 if ($course->id == SITEID) {
2352 return $this->add_front_page_course_essentials($coursenode, $course);
2355 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2356 return true;
2359 //Participants
2360 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2361 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2362 $currentgroup = groups_get_course_group($course, true);
2363 if ($course->id == SITEID) {
2364 $filterselect = '';
2365 } else if ($course->id && !$currentgroup) {
2366 $filterselect = $course->id;
2367 } else {
2368 $filterselect = $currentgroup;
2370 $filterselect = clean_param($filterselect, PARAM_INT);
2371 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2372 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2373 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2374 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2376 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2377 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2379 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2380 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2383 // View course reports
2384 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2385 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2386 $coursereports = get_plugin_list('coursereport'); // deprecated
2387 foreach ($coursereports as $report=>$dir) {
2388 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2389 if (file_exists($libfile)) {
2390 require_once($libfile);
2391 $reportfunction = $report.'_report_extend_navigation';
2392 if (function_exists($report.'_report_extend_navigation')) {
2393 $reportfunction($reportnav, $course, $this->page->context);
2398 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2399 foreach ($reports as $reportfunction) {
2400 $reportfunction($reportnav, $course, $this->page->context);
2403 return true;
2406 * This generates the structure of the course that won't be generated when
2407 * the modules and sections are added.
2409 * Things such as the reports branch, the participants branch, blogs... get
2410 * added to the course node by this method.
2412 * @param navigation_node $coursenode
2413 * @param stdClass $course
2414 * @return bool True for successfull generation
2416 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2417 global $CFG;
2419 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2420 return true;
2423 // Hidden node that we use to determine if the front page navigation is loaded.
2424 // This required as there are not other guaranteed nodes that may be loaded.
2425 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2427 //Participants
2428 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2429 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2432 $filterselect = 0;
2434 // Blogs
2435 if (!empty($CFG->bloglevel)
2436 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2437 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2438 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2439 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2442 // Notes
2443 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2444 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2447 // Tags
2448 if (!empty($CFG->usetags) && isloggedin()) {
2449 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2452 if (isloggedin()) {
2453 // Calendar
2454 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2455 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2458 // View course reports
2459 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2460 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2461 $coursereports = get_plugin_list('coursereport'); // deprecated
2462 foreach ($coursereports as $report=>$dir) {
2463 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2464 if (file_exists($libfile)) {
2465 require_once($libfile);
2466 $reportfunction = $report.'_report_extend_navigation';
2467 if (function_exists($report.'_report_extend_navigation')) {
2468 $reportfunction($reportnav, $course, $this->page->context);
2473 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2474 foreach ($reports as $reportfunction) {
2475 $reportfunction($reportnav, $course, $this->page->context);
2478 return true;
2482 * Clears the navigation cache
2484 public function clear_cache() {
2485 $this->cache->clear();
2489 * Sets an expansion limit for the navigation
2491 * The expansion limit is used to prevent the display of content that has a type
2492 * greater than the provided $type.
2494 * Can be used to ensure things such as activities or activity content don't get
2495 * shown on the navigation.
2496 * They are still generated in order to ensure the navbar still makes sense.
2498 * @param int $type One of navigation_node::TYPE_*
2499 * @return bool true when complete.
2501 public function set_expansion_limit($type) {
2502 $nodes = $this->find_all_of_type($type);
2503 foreach ($nodes as &$node) {
2504 // We need to generate the full site node
2505 if ($type == self::TYPE_COURSE && $node->key == SITEID) {
2506 continue;
2508 foreach ($node->children as &$child) {
2509 // We still want to show course reports and participants containers
2510 // or there will be navigation missing.
2511 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2512 continue;
2514 $child->display = false;
2517 return true;
2520 * Attempts to get the navigation with the given key from this nodes children.
2522 * This function only looks at this nodes children, it does NOT look recursivily.
2523 * If the node can't be found then false is returned.
2525 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2527 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2528 * may be of more use to you.
2530 * @param string|int $key The key of the node you wish to receive.
2531 * @param int $type One of navigation_node::TYPE_*
2532 * @return navigation_node|false
2534 public function get($key, $type = null) {
2535 if (!$this->initialised) {
2536 $this->initialise();
2538 return parent::get($key, $type);
2542 * Searches this nodes children and their children to find a navigation node
2543 * with the matching key and type.
2545 * This method is recursive and searches children so until either a node is
2546 * found or there are no more nodes to search.
2548 * If you know that the node being searched for is a child of this node
2549 * then use the {@link global_navigation::get()} method instead.
2551 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2552 * may be of more use to you.
2554 * @param string|int $key The key of the node you wish to receive.
2555 * @param int $type One of navigation_node::TYPE_*
2556 * @return navigation_node|false
2558 public function find($key, $type) {
2559 if (!$this->initialised) {
2560 $this->initialise();
2562 return parent::find($key, $type);
2567 * The limited global navigation class used for the AJAX extension of the global
2568 * navigation class.
2570 * The primary methods that are used in the global navigation class have been overriden
2571 * to ensure that only the relevant branch is generated at the root of the tree.
2572 * This can be done because AJAX is only used when the backwards structure for the
2573 * requested branch exists.
2574 * This has been done only because it shortens the amounts of information that is generated
2575 * which of course will speed up the response time.. because no one likes laggy AJAX.
2577 * @package core
2578 * @category navigation
2579 * @copyright 2009 Sam Hemelryk
2580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2582 class global_navigation_for_ajax extends global_navigation {
2584 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2585 protected $branchtype;
2587 /** @var int the instance id */
2588 protected $instanceid;
2590 /** @var array Holds an array of expandable nodes */
2591 protected $expandable = array();
2594 * Constructs the navigation for use in an AJAX request
2596 * @param moodle_page $page moodle_page object
2597 * @param int $branchtype
2598 * @param int $id
2600 public function __construct($page, $branchtype, $id) {
2601 $this->page = $page;
2602 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2603 $this->children = new navigation_node_collection();
2604 $this->branchtype = $branchtype;
2605 $this->instanceid = $id;
2606 $this->initialise();
2609 * Initialise the navigation given the type and id for the branch to expand.
2611 * @return array An array of the expandable nodes
2613 public function initialise() {
2614 global $CFG, $DB, $SITE;
2616 if ($this->initialised || during_initial_install()) {
2617 return $this->expandable;
2619 $this->initialised = true;
2621 $this->rootnodes = array();
2622 $this->rootnodes['site'] = $this->add_course($SITE);
2623 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2625 // Branchtype will be one of navigation_node::TYPE_*
2626 switch ($this->branchtype) {
2627 case self::TYPE_CATEGORY :
2628 $this->load_all_categories($this->instanceid);
2629 $limit = 20;
2630 if (!empty($CFG->navcourselimit)) {
2631 $limit = (int)$CFG->navcourselimit;
2633 $courses = $DB->get_records('course', array('category' => $this->instanceid), 'sortorder','*', 0, $limit);
2634 foreach ($courses as $course) {
2635 $this->add_course($course);
2637 break;
2638 case self::TYPE_COURSE :
2639 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2640 require_course_login($course, true, null, false, true);
2641 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2642 $coursenode = $this->add_course($course);
2643 $this->add_course_essentials($coursenode, $course);
2644 if ($this->format_display_course_content($course->format)) {
2645 $this->load_course_sections($course, $coursenode);
2647 break;
2648 case self::TYPE_SECTION :
2649 $sql = 'SELECT c.*, cs.section AS sectionnumber
2650 FROM {course} c
2651 LEFT JOIN {course_sections} cs ON cs.course = c.id
2652 WHERE cs.id = ?';
2653 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2654 require_course_login($course, true, null, false, true);
2655 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2656 $coursenode = $this->add_course($course);
2657 $this->add_course_essentials($coursenode, $course);
2658 $sections = $this->load_course_sections($course, $coursenode);
2659 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2660 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, $activities);
2661 break;
2662 case self::TYPE_ACTIVITY :
2663 $sql = "SELECT c.*
2664 FROM {course} c
2665 JOIN {course_modules} cm ON cm.course = c.id
2666 WHERE cm.id = :cmid";
2667 $params = array('cmid' => $this->instanceid);
2668 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2669 $modinfo = get_fast_modinfo($course);
2670 $cm = $modinfo->get_cm($this->instanceid);
2671 require_course_login($course, true, $cm, false, true);
2672 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
2673 $coursenode = $this->load_course($course);
2674 if ($course->id == SITEID) {
2675 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2676 } else {
2677 $sections = $this->load_course_sections($course, $coursenode);
2678 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2679 $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, $activities);
2680 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2682 break;
2683 default:
2684 throw new Exception('Unknown type');
2685 return $this->expandable;
2688 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
2689 $this->load_for_user(null, true);
2692 $this->find_expandable($this->expandable);
2693 return $this->expandable;
2697 * Returns an array of expandable nodes
2698 * @return array
2700 public function get_expandable() {
2701 return $this->expandable;
2706 * Navbar class
2708 * This class is used to manage the navbar, which is initialised from the navigation
2709 * object held by PAGE
2711 * @package core
2712 * @category navigation
2713 * @copyright 2009 Sam Hemelryk
2714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2716 class navbar extends navigation_node {
2717 /** @var bool A switch for whether the navbar is initialised or not */
2718 protected $initialised = false;
2719 /** @var mixed keys used to reference the nodes on the navbar */
2720 protected $keys = array();
2721 /** @var null|string content of the navbar */
2722 protected $content = null;
2723 /** @var moodle_page object the moodle page that this navbar belongs to */
2724 protected $page;
2725 /** @var bool A switch for whether to ignore the active navigation information */
2726 protected $ignoreactive = false;
2727 /** @var bool A switch to let us know if we are in the middle of an install */
2728 protected $duringinstall = false;
2729 /** @var bool A switch for whether the navbar has items */
2730 protected $hasitems = false;
2731 /** @var array An array of navigation nodes for the navbar */
2732 protected $items;
2733 /** @var array An array of child node objects */
2734 public $children = array();
2735 /** @var bool A switch for whether we want to include the root node in the navbar */
2736 public $includesettingsbase = false;
2738 * The almighty constructor
2740 * @param moodle_page $page
2742 public function __construct(moodle_page $page) {
2743 global $CFG;
2744 if (during_initial_install()) {
2745 $this->duringinstall = true;
2746 return false;
2748 $this->page = $page;
2749 $this->text = get_string('home');
2750 $this->shorttext = get_string('home');
2751 $this->action = new moodle_url($CFG->wwwroot);
2752 $this->nodetype = self::NODETYPE_BRANCH;
2753 $this->type = self::TYPE_SYSTEM;
2757 * Quick check to see if the navbar will have items in.
2759 * @return bool Returns true if the navbar will have items, false otherwise
2761 public function has_items() {
2762 if ($this->duringinstall) {
2763 return false;
2764 } else if ($this->hasitems !== false) {
2765 return true;
2767 $this->page->navigation->initialise($this->page);
2769 $activenodefound = ($this->page->navigation->contains_active_node() ||
2770 $this->page->settingsnav->contains_active_node());
2772 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2773 $this->hasitems = $outcome;
2774 return $outcome;
2778 * Turn on/off ignore active
2780 * @param bool $setting
2782 public function ignore_active($setting=true) {
2783 $this->ignoreactive = ($setting);
2787 * Gets a navigation node
2789 * @param string|int $key for referencing the navbar nodes
2790 * @param int $type navigation_node::TYPE_*
2791 * @return navigation_node|bool
2793 public function get($key, $type = null) {
2794 foreach ($this->children as &$child) {
2795 if ($child->key === $key && ($type == null || $type == $child->type)) {
2796 return $child;
2799 return false;
2802 * Returns an array of navigation_node's that make up the navbar.
2804 * @return array
2806 public function get_items() {
2807 $items = array();
2808 // Make sure that navigation is initialised
2809 if (!$this->has_items()) {
2810 return $items;
2812 if ($this->items !== null) {
2813 return $this->items;
2816 if (count($this->children) > 0) {
2817 // Add the custom children
2818 $items = array_reverse($this->children);
2821 $navigationactivenode = $this->page->navigation->find_active_node();
2822 $settingsactivenode = $this->page->settingsnav->find_active_node();
2824 // Check if navigation contains the active node
2825 if (!$this->ignoreactive) {
2827 if ($navigationactivenode && $settingsactivenode) {
2828 // Parse a combined navigation tree
2829 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2830 if (!$settingsactivenode->mainnavonly) {
2831 $items[] = $settingsactivenode;
2833 $settingsactivenode = $settingsactivenode->parent;
2835 if (!$this->includesettingsbase) {
2836 // Removes the first node from the settings (root node) from the list
2837 array_pop($items);
2839 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2840 if (!$navigationactivenode->mainnavonly) {
2841 $items[] = $navigationactivenode;
2843 $navigationactivenode = $navigationactivenode->parent;
2845 } else if ($navigationactivenode) {
2846 // Parse the navigation tree to get the active node
2847 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2848 if (!$navigationactivenode->mainnavonly) {
2849 $items[] = $navigationactivenode;
2851 $navigationactivenode = $navigationactivenode->parent;
2853 } else if ($settingsactivenode) {
2854 // Parse the settings navigation to get the active node
2855 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2856 if (!$settingsactivenode->mainnavonly) {
2857 $items[] = $settingsactivenode;
2859 $settingsactivenode = $settingsactivenode->parent;
2864 $items[] = new navigation_node(array(
2865 'text'=>$this->page->navigation->text,
2866 'shorttext'=>$this->page->navigation->shorttext,
2867 'key'=>$this->page->navigation->key,
2868 'action'=>$this->page->navigation->action
2871 $this->items = array_reverse($items);
2872 return $this->items;
2876 * Add a new navigation_node to the navbar, overrides parent::add
2878 * This function overrides {@link navigation_node::add()} so that we can change
2879 * the way nodes get added to allow us to simply call add and have the node added to the
2880 * end of the navbar
2882 * @param string $text
2883 * @param string|moodle_url $action
2884 * @param int $type
2885 * @param string|int $key
2886 * @param string $shorttext
2887 * @param string $icon
2888 * @return navigation_node
2890 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
2891 if ($this->content !== null) {
2892 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2895 // Properties array used when creating the new navigation node
2896 $itemarray = array(
2897 'text' => $text,
2898 'type' => $type
2900 // Set the action if one was provided
2901 if ($action!==null) {
2902 $itemarray['action'] = $action;
2904 // Set the shorttext if one was provided
2905 if ($shorttext!==null) {
2906 $itemarray['shorttext'] = $shorttext;
2908 // Set the icon if one was provided
2909 if ($icon!==null) {
2910 $itemarray['icon'] = $icon;
2912 // Default the key to the number of children if not provided
2913 if ($key === null) {
2914 $key = count($this->children);
2916 // Set the key
2917 $itemarray['key'] = $key;
2918 // Set the parent to this node
2919 $itemarray['parent'] = $this;
2920 // Add the child using the navigation_node_collections add method
2921 $this->children[] = new navigation_node($itemarray);
2922 return $this;
2927 * Class used to manage the settings option for the current page
2929 * This class is used to manage the settings options in a tree format (recursively)
2930 * and was created initially for use with the settings blocks.
2932 * @package core
2933 * @category navigation
2934 * @copyright 2009 Sam Hemelryk
2935 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2937 class settings_navigation extends navigation_node {
2938 /** @var stdClass the current context */
2939 protected $context;
2940 /** @var moodle_page the moodle page that the navigation belongs to */
2941 protected $page;
2942 /** @var string contains administration section navigation_nodes */
2943 protected $adminsection;
2944 /** @var bool A switch to see if the navigation node is initialised */
2945 protected $initialised = false;
2946 /** @var array An array of users that the nodes can extend for. */
2947 protected $userstoextendfor = array();
2948 /** @var navigation_cache **/
2949 protected $cache;
2952 * Sets up the object with basic settings and preparse it for use
2954 * @param moodle_page $page
2956 public function __construct(moodle_page &$page) {
2957 if (during_initial_install()) {
2958 return false;
2960 $this->page = $page;
2961 // Initialise the main navigation. It is most important that this is done
2962 // before we try anything
2963 $this->page->navigation->initialise();
2964 // Initialise the navigation cache
2965 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2966 $this->children = new navigation_node_collection();
2969 * Initialise the settings navigation based on the current context
2971 * This function initialises the settings navigation tree for a given context
2972 * by calling supporting functions to generate major parts of the tree.
2975 public function initialise() {
2976 global $DB, $SESSION;
2978 if (during_initial_install()) {
2979 return false;
2980 } else if ($this->initialised) {
2981 return true;
2983 $this->id = 'settingsnav';
2984 $this->context = $this->page->context;
2986 $context = $this->context;
2987 if ($context->contextlevel == CONTEXT_BLOCK) {
2988 $this->load_block_settings();
2989 $context = $context->get_parent_context();
2992 switch ($context->contextlevel) {
2993 case CONTEXT_SYSTEM:
2994 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2995 $this->load_front_page_settings(($context->id == $this->context->id));
2997 break;
2998 case CONTEXT_COURSECAT:
2999 $this->load_category_settings();
3000 break;
3001 case CONTEXT_COURSE:
3002 if ($this->page->course->id != SITEID) {
3003 $this->load_course_settings(($context->id == $this->context->id));
3004 } else {
3005 $this->load_front_page_settings(($context->id == $this->context->id));
3007 break;
3008 case CONTEXT_MODULE:
3009 $this->load_module_settings();
3010 $this->load_course_settings();
3011 break;
3012 case CONTEXT_USER:
3013 if ($this->page->course->id != SITEID) {
3014 $this->load_course_settings();
3016 break;
3019 $settings = $this->load_user_settings($this->page->course->id);
3021 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
3022 $admin = $this->load_administration_settings();
3023 $SESSION->load_navigation_admin = ($admin->has_children());
3024 } else {
3025 $admin = false;
3028 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
3029 $admin->force_open();
3030 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
3031 $settings->force_open();
3034 // Check if the user is currently logged in as another user
3035 if (session_is_loggedinas()) {
3036 // Get the actual user, we need this so we can display an informative return link
3037 $realuser = session_get_realuser();
3038 // Add the informative return to original user link
3039 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3040 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3043 foreach ($this->children as $key=>$node) {
3044 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3045 $node->remove();
3048 $this->initialised = true;
3051 * Override the parent function so that we can add preceeding hr's and set a
3052 * root node class against all first level element
3054 * It does this by first calling the parent's add method {@link navigation_node::add()}
3055 * and then proceeds to use the key to set class and hr
3057 * @param string $text text to be used for the link.
3058 * @param string|moodle_url $url url for the new node
3059 * @param int $type the type of node navigation_node::TYPE_*
3060 * @param string $shorttext
3061 * @param string|int $key a key to access the node by.
3062 * @param pix_icon $icon An icon that appears next to the node.
3063 * @return navigation_node with the new node added to it.
3065 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3066 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3067 $node->add_class('root_node');
3068 return $node;
3072 * This function allows the user to add something to the start of the settings
3073 * navigation, which means it will be at the top of the settings navigation block
3075 * @param string $text text to be used for the link.
3076 * @param string|moodle_url $url url for the new node
3077 * @param int $type the type of node navigation_node::TYPE_*
3078 * @param string $shorttext
3079 * @param string|int $key a key to access the node by.
3080 * @param pix_icon $icon An icon that appears next to the node.
3081 * @return navigation_node $node with the new node added to it.
3083 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3084 $children = $this->children;
3085 $childrenclass = get_class($children);
3086 $this->children = new $childrenclass;
3087 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3088 foreach ($children as $child) {
3089 $this->children->add($child);
3091 return $node;
3094 * Load the site administration tree
3096 * This function loads the site administration tree by using the lib/adminlib library functions
3098 * @param navigation_node $referencebranch A reference to a branch in the settings
3099 * navigation tree
3100 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3101 * tree and start at the beginning
3102 * @return mixed A key to access the admin tree by
3104 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3105 global $CFG;
3107 // Check if we are just starting to generate this navigation.
3108 if ($referencebranch === null) {
3110 // Require the admin lib then get an admin structure
3111 if (!function_exists('admin_get_root')) {
3112 require_once($CFG->dirroot.'/lib/adminlib.php');
3114 $adminroot = admin_get_root(false, false);
3115 // This is the active section identifier
3116 $this->adminsection = $this->page->url->param('section');
3118 // Disable the navigation from automatically finding the active node
3119 navigation_node::$autofindactive = false;
3120 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
3121 foreach ($adminroot->children as $adminbranch) {
3122 $this->load_administration_settings($referencebranch, $adminbranch);
3124 navigation_node::$autofindactive = true;
3126 // Use the admin structure to locate the active page
3127 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3128 $currentnode = $this;
3129 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3130 $currentnode = $currentnode->get($pathkey);
3132 if ($currentnode) {
3133 $currentnode->make_active();
3135 } else {
3136 $this->scan_for_active_node($referencebranch);
3138 return $referencebranch;
3139 } else if ($adminbranch->check_access()) {
3140 // We have a reference branch that we can access and is not hidden `hurrah`
3141 // Now we need to display it and any children it may have
3142 $url = null;
3143 $icon = null;
3144 if ($adminbranch instanceof admin_settingpage) {
3145 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3146 } else if ($adminbranch instanceof admin_externalpage) {
3147 $url = $adminbranch->url;
3148 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3149 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3152 // Add the branch
3153 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3155 if ($adminbranch->is_hidden()) {
3156 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3157 $reference->add_class('hidden');
3158 } else {
3159 $reference->display = false;
3163 // Check if we are generating the admin notifications and whether notificiations exist
3164 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3165 $reference->add_class('criticalnotification');
3167 // Check if this branch has children
3168 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3169 foreach ($adminbranch->children as $branch) {
3170 // Generate the child branches as well now using this branch as the reference
3171 $this->load_administration_settings($reference, $branch);
3173 } else {
3174 $reference->icon = new pix_icon('i/settings', '');
3180 * This function recursivily scans nodes until it finds the active node or there
3181 * are no more nodes.
3182 * @param navigation_node $node
3184 protected function scan_for_active_node(navigation_node $node) {
3185 if (!$node->check_if_active() && $node->children->count()>0) {
3186 foreach ($node->children as &$child) {
3187 $this->scan_for_active_node($child);
3193 * Gets a navigation node given an array of keys that represent the path to
3194 * the desired node.
3196 * @param array $path
3197 * @return navigation_node|false
3199 protected function get_by_path(array $path) {
3200 $node = $this->get(array_shift($path));
3201 foreach ($path as $key) {
3202 $node->get($key);
3204 return $node;
3208 * Generate the list of modules for the given course.
3210 * @param stdClass $course The course to get modules for
3212 protected function get_course_modules($course) {
3213 global $CFG;
3214 $mods = $modnames = $modnamesplural = $modnamesused = array();
3215 // This function is included when we include course/lib.php at the top
3216 // of this file
3217 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
3218 $resources = array();
3219 $activities = array();
3220 foreach($modnames as $modname=>$modnamestr) {
3221 if (!course_allowed_module($course, $modname)) {
3222 continue;
3225 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3226 if (!file_exists($libfile)) {
3227 continue;
3229 include_once($libfile);
3230 $gettypesfunc = $modname.'_get_types';
3231 if (function_exists($gettypesfunc)) {
3232 $types = $gettypesfunc();
3233 foreach($types as $type) {
3234 if (!isset($type->modclass) || !isset($type->typestr)) {
3235 debugging('Incorrect activity type in '.$modname);
3236 continue;
3238 if ($type->modclass == MOD_CLASS_RESOURCE) {
3239 $resources[html_entity_decode($type->type)] = $type->typestr;
3240 } else {
3241 $activities[html_entity_decode($type->type)] = $type->typestr;
3244 } else {
3245 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3246 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
3247 $resources[$modname] = $modnamestr;
3248 } else {
3249 // all other archetypes are considered activity
3250 $activities[$modname] = $modnamestr;
3254 return array($resources, $activities);
3258 * This function loads the course settings that are available for the user
3260 * @param bool $forceopen If set to true the course node will be forced open
3261 * @return navigation_node|false
3263 protected function load_course_settings($forceopen = false) {
3264 global $CFG;
3266 $course = $this->page->course;
3267 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
3269 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3271 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3272 if ($forceopen) {
3273 $coursenode->force_open();
3276 if (has_capability('moodle/course:update', $coursecontext)) {
3277 // Add the turn on/off settings
3278 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
3279 if ($this->page->user_is_editing()) {
3280 $url->param('edit', 'off');
3281 $editstring = get_string('turneditingoff');
3282 } else {
3283 $url->param('edit', 'on');
3284 $editstring = get_string('turneditingon');
3286 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3288 if ($this->page->user_is_editing()) {
3289 // Removed as per MDL-22732
3290 // $this->add_course_editing_links($course);
3293 // Add the course settings link
3294 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3295 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3297 // Add the course completion settings link
3298 if ($CFG->enablecompletion && $course->enablecompletion) {
3299 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3300 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3304 // add enrol nodes
3305 enrol_add_course_navigation($coursenode, $course);
3307 // Manage filters
3308 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3309 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3310 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3313 // Add view grade report is permitted
3314 $reportavailable = false;
3315 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3316 $reportavailable = true;
3317 } else if (!empty($course->showgrades)) {
3318 $reports = get_plugin_list('gradereport');
3319 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3320 arsort($reports); // user is last, we want to test it first
3321 foreach ($reports as $plugin => $plugindir) {
3322 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3323 //stop when the first visible plugin is found
3324 $reportavailable = true;
3325 break;
3330 if ($reportavailable) {
3331 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3332 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3335 // Add outcome if permitted
3336 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3337 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3338 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3341 // Backup this course
3342 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3343 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3344 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3347 // Restore to this course
3348 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3349 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3350 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3353 // Import data from other courses
3354 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3355 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3356 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
3359 // Publish course on a hub
3360 if (has_capability('moodle/course:publish', $coursecontext)) {
3361 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3362 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3365 // Reset this course
3366 if (has_capability('moodle/course:reset', $coursecontext)) {
3367 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3368 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3371 // Questions
3372 require_once($CFG->libdir . '/questionlib.php');
3373 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3375 if (has_capability('moodle/course:update', $coursecontext)) {
3376 // Repository Instances
3377 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3378 require_once($CFG->dirroot . '/repository/lib.php');
3379 $editabletypes = repository::get_editable_types($coursecontext);
3380 $haseditabletypes = !empty($editabletypes);
3381 unset($editabletypes);
3382 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3383 } else {
3384 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3386 if ($haseditabletypes) {
3387 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3388 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3392 // Manage files
3393 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3394 // hidden in new courses and courses where legacy files were turned off
3395 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3396 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
3400 // Switch roles
3401 $roles = array();
3402 $assumedrole = $this->in_alternative_role();
3403 if ($assumedrole !== false) {
3404 $roles[0] = get_string('switchrolereturn');
3406 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3407 $availableroles = get_switchable_roles($coursecontext);
3408 if (is_array($availableroles)) {
3409 foreach ($availableroles as $key=>$role) {
3410 if ($assumedrole == (int)$key) {
3411 continue;
3413 $roles[$key] = $role;
3417 if (is_array($roles) && count($roles)>0) {
3418 $switchroles = $this->add(get_string('switchroleto'));
3419 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3420 $switchroles->force_open();
3422 $returnurl = $this->page->url;
3423 $returnurl->param('sesskey', sesskey());
3424 foreach ($roles as $key => $name) {
3425 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3426 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
3429 // Return we are done
3430 return $coursenode;
3434 * Adds branches and links to the settings navigation to add course activities
3435 * and resources.
3437 * @param stdClass $course
3439 protected function add_course_editing_links($course) {
3440 global $CFG;
3442 require_once($CFG->dirroot.'/course/lib.php');
3444 // Add `add` resources|activities branches
3445 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3446 if (file_exists($structurefile)) {
3447 require_once($structurefile);
3448 $requestkey = call_user_func('callback_'.$course->format.'_request_key');
3449 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3450 } else {
3451 $requestkey = get_string('section');
3452 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3455 $sections = get_all_sections($course->id);
3457 $addresource = $this->add(get_string('addresource'));
3458 $addactivity = $this->add(get_string('addactivity'));
3459 if ($formatidentifier!==0) {
3460 $addresource->force_open();
3461 $addactivity->force_open();
3464 $this->get_course_modules($course);
3466 foreach ($sections as $section) {
3467 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
3468 continue;
3470 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $requestkey=>$section->section));
3471 if ($section->section == 0) {
3472 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3473 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3474 } else {
3475 $sectionname = get_section_name($course, $section);
3476 $sectionresources = $addresource->add($sectionname, $sectionurl, self::TYPE_SETTING);
3477 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self::TYPE_SETTING);
3479 foreach ($resources as $value=>$resource) {
3480 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3481 $pos = strpos($value, '&type=');
3482 if ($pos!==false) {
3483 $url->param('add', textlib::substr($value, 0,$pos));
3484 $url->param('type', textlib::substr($value, $pos+6));
3485 } else {
3486 $url->param('add', $value);
3488 $sectionresources->add($resource, $url, self::TYPE_SETTING);
3490 $subbranch = false;
3491 foreach ($activities as $activityname=>$activity) {
3492 if ($activity==='--') {
3493 $subbranch = false;
3494 continue;
3496 if (strpos($activity, '--')===0) {
3497 $subbranch = $sectionactivities->add(trim($activity, '-'));
3498 continue;
3500 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3501 $pos = strpos($activityname, '&type=');
3502 if ($pos!==false) {
3503 $url->param('add', textlib::substr($activityname, 0,$pos));
3504 $url->param('type', textlib::substr($activityname, $pos+6));
3505 } else {
3506 $url->param('add', $activityname);
3508 if ($subbranch !== false) {
3509 $subbranch->add($activity, $url, self::TYPE_SETTING);
3510 } else {
3511 $sectionactivities->add($activity, $url, self::TYPE_SETTING);
3518 * This function calls the module function to inject module settings into the
3519 * settings navigation tree.
3521 * This only gets called if there is a corrosponding function in the modules
3522 * lib file.
3524 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3526 * @return navigation_node|false
3528 protected function load_module_settings() {
3529 global $CFG;
3531 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3532 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3533 $this->page->set_cm($cm, $this->page->course);
3536 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3537 if (file_exists($file)) {
3538 require_once($file);
3541 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3542 $modulenode->force_open();
3544 // Settings for the module
3545 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3546 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3547 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3549 // Assign local roles
3550 if (count(get_assignable_roles($this->page->cm->context))>0) {
3551 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3552 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3554 // Override roles
3555 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3556 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3557 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3559 // Check role permissions
3560 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3561 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3562 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3564 // Manage filters
3565 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3566 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3567 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3569 // Add reports
3570 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3571 foreach ($reports as $reportfunction) {
3572 $reportfunction($modulenode, $this->page->cm);
3574 // Add a backup link
3575 $featuresfunc = $this->page->activityname.'_supports';
3576 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3577 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3578 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3581 // Restore this activity
3582 $featuresfunc = $this->page->activityname.'_supports';
3583 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3584 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3585 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3588 // Allow the active advanced grading method plugin to append its settings
3589 $featuresfunc = $this->page->activityname.'_supports';
3590 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3591 require_once($CFG->dirroot.'/grade/grading/lib.php');
3592 $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
3593 $gradingman->extend_settings_navigation($this, $modulenode);
3596 $function = $this->page->activityname.'_extend_settings_navigation';
3597 if (!function_exists($function)) {
3598 return $modulenode;
3601 $function($this, $modulenode);
3603 // Remove the module node if there are no children
3604 if (empty($modulenode->children)) {
3605 $modulenode->remove();
3608 return $modulenode;
3612 * Loads the user settings block of the settings nav
3614 * This function is simply works out the userid and whether we need to load
3615 * just the current users profile settings, or the current user and the user the
3616 * current user is viewing.
3618 * This function has some very ugly code to work out the user, if anyone has
3619 * any bright ideas please feel free to intervene.
3621 * @param int $courseid The course id of the current course
3622 * @return navigation_node|false
3624 protected function load_user_settings($courseid=SITEID) {
3625 global $USER, $CFG;
3627 if (isguestuser() || !isloggedin()) {
3628 return false;
3631 $navusers = $this->page->navigation->get_extending_users();
3633 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3634 $usernode = null;
3635 foreach ($this->userstoextendfor as $userid) {
3636 if ($userid == $USER->id) {
3637 continue;
3639 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3640 if (is_null($usernode)) {
3641 $usernode = $node;
3644 foreach ($navusers as $user) {
3645 if ($user->id == $USER->id) {
3646 continue;
3648 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3649 if (is_null($usernode)) {
3650 $usernode = $node;
3653 $this->generate_user_settings($courseid, $USER->id);
3654 } else {
3655 $usernode = $this->generate_user_settings($courseid, $USER->id);
3657 return $usernode;
3661 * Extends the settings navigation for the given user.
3663 * Note: This method gets called automatically if you call
3664 * $PAGE->navigation->extend_for_user($userid)
3666 * @param int $userid
3668 public function extend_for_user($userid) {
3669 global $CFG;
3671 if (!in_array($userid, $this->userstoextendfor)) {
3672 $this->userstoextendfor[] = $userid;
3673 if ($this->initialised) {
3674 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3675 $children = array();
3676 foreach ($this->children as $child) {
3677 $children[] = $child;
3679 array_unshift($children, array_pop($children));
3680 $this->children = new navigation_node_collection();
3681 foreach ($children as $child) {
3682 $this->children->add($child);
3689 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3690 * what can be shown/done
3692 * @param int $courseid The current course' id
3693 * @param int $userid The user id to load for
3694 * @param string $gstitle The string to pass to get_string for the branch title
3695 * @return navigation_node|false
3697 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3698 global $DB, $CFG, $USER, $SITE;
3700 if ($courseid != SITEID) {
3701 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3702 $course = $this->page->course;
3703 } else {
3704 $select = context_helper::get_preload_record_columns_sql('ctx');
3705 $sql = "SELECT c.*, $select
3706 FROM {course} c
3707 JOIN {context} ctx ON c.id = ctx.instanceid
3708 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
3709 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
3710 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3711 context_helper::preload_from_record($course);
3713 } else {
3714 $course = $SITE;
3717 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3718 $systemcontext = get_system_context();
3719 $currentuser = ($USER->id == $userid);
3721 if ($currentuser) {
3722 $user = $USER;
3723 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3724 } else {
3725 $select = context_helper::get_preload_record_columns_sql('ctx');
3726 $sql = "SELECT u.*, $select
3727 FROM {user} u
3728 JOIN {context} ctx ON u.id = ctx.instanceid
3729 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
3730 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
3731 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
3732 if (!$user) {
3733 return false;
3735 context_helper::preload_from_record($user);
3737 // Check that the user can view the profile
3738 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3739 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3741 if ($course->id == SITEID) {
3742 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
3743 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3744 return false;
3746 } else {
3747 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
3748 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
3749 if ((!$canviewusercourse && !$canviewuser) || !can_access_course($course, $user->id)) {
3750 return false;
3752 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
3753 // If groups are in use, make sure we can see that group
3754 return false;
3759 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3761 $key = $gstitle;
3762 if ($gstitle != 'usercurrentsettings') {
3763 $key .= $userid;
3766 // Add a user setting branch
3767 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3768 $usersetting->id = 'usersettings';
3769 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3770 // Automatically start by making it active
3771 $usersetting->make_active();
3774 // Check if the user has been deleted
3775 if ($user->deleted) {
3776 if (!has_capability('moodle/user:update', $coursecontext)) {
3777 // We can't edit the user so just show the user deleted message
3778 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3779 } else {
3780 // We can edit the user so show the user deleted message and link it to the profile
3781 if ($course->id == SITEID) {
3782 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3783 } else {
3784 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3786 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3788 return true;
3791 $userauthplugin = false;
3792 if (!empty($user->auth)) {
3793 $userauthplugin = get_auth_plugin($user->auth);
3796 // Add the profile edit link
3797 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3798 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3799 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3800 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3801 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3802 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
3803 $url = $userauthplugin->edit_profile_url();
3804 if (empty($url)) {
3805 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3807 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3812 // Change password link
3813 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
3814 $passwordchangeurl = $userauthplugin->change_password_url();
3815 if (empty($passwordchangeurl)) {
3816 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3818 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3821 // View the roles settings
3822 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3823 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3825 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3826 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3828 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3830 if (!empty($assignableroles)) {
3831 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3832 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3835 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3836 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3837 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3840 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3841 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3844 // Portfolio
3845 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3846 require_once($CFG->libdir . '/portfoliolib.php');
3847 if (portfolio_instances(true, false)) {
3848 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3850 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3851 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
3853 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
3854 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
3858 $enablemanagetokens = false;
3859 if (!empty($CFG->enablerssfeeds)) {
3860 $enablemanagetokens = true;
3861 } else if (!is_siteadmin($USER->id)
3862 && !empty($CFG->enablewebservices)
3863 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3864 $enablemanagetokens = true;
3866 // Security keys
3867 if ($currentuser && $enablemanagetokens) {
3868 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3869 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
3872 // Repository
3873 if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
3874 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
3875 require_once($CFG->dirroot . '/repository/lib.php');
3876 $editabletypes = repository::get_editable_types($usercontext);
3877 $haseditabletypes = !empty($editabletypes);
3878 unset($editabletypes);
3879 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
3880 } else {
3881 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
3883 if ($haseditabletypes) {
3884 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
3885 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
3889 // Messaging
3890 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
3891 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3892 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
3895 // Blogs
3896 if ($currentuser && !empty($CFG->bloglevel)) {
3897 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
3898 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
3899 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
3900 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
3901 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
3905 // Login as ...
3906 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
3907 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
3908 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
3911 return $usersetting;
3915 * Loads block specific settings in the navigation
3917 * @return navigation_node
3919 protected function load_block_settings() {
3920 global $CFG;
3922 $blocknode = $this->add(print_context_name($this->context));
3923 $blocknode->force_open();
3925 // Assign local roles
3926 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3927 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
3929 // Override roles
3930 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3931 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3932 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3934 // Check role permissions
3935 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3936 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3937 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3940 return $blocknode;
3944 * Loads category specific settings in the navigation
3946 * @return navigation_node
3948 protected function load_category_settings() {
3949 global $CFG;
3951 $categorynode = $this->add(print_context_name($this->context));
3952 $categorynode->force_open();
3954 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context)) {
3955 $url = new moodle_url('/course/category.php', array('id'=>$this->context->instanceid, 'sesskey'=>sesskey()));
3956 if ($this->page->user_is_editing()) {
3957 $url->param('categoryedit', '0');
3958 $editstring = get_string('turneditingoff');
3959 } else {
3960 $url->param('categoryedit', '1');
3961 $editstring = get_string('turneditingon');
3963 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3966 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
3967 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
3968 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
3970 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
3971 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
3974 // Assign local roles
3975 if (has_capability('moodle/role:assign', $this->context)) {
3976 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3977 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
3980 // Override roles
3981 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3982 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3983 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
3985 // Check role permissions
3986 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3987 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3988 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
3991 // Cohorts
3992 if (has_capability('moodle/cohort:manage', $this->context) or has_capability('moodle/cohort:view', $this->context)) {
3993 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', array('contextid' => $this->context->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
3996 // Manage filters
3997 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
3998 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
3999 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4002 return $categorynode;
4006 * Determine whether the user is assuming another role
4008 * This function checks to see if the user is assuming another role by means of
4009 * role switching. In doing this we compare each RSW key (context path) against
4010 * the current context path. This ensures that we can provide the switching
4011 * options against both the course and any page shown under the course.
4013 * @return bool|int The role(int) if the user is in another role, false otherwise
4015 protected function in_alternative_role() {
4016 global $USER;
4017 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4018 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4019 return $USER->access['rsw'][$this->page->context->path];
4021 foreach ($USER->access['rsw'] as $key=>$role) {
4022 if (strpos($this->context->path,$key)===0) {
4023 return $role;
4027 return false;
4031 * This function loads all of the front page settings into the settings navigation.
4032 * This function is called when the user is on the front page, or $COURSE==$SITE
4033 * @param bool $forceopen (optional)
4034 * @return navigation_node
4036 protected function load_front_page_settings($forceopen = false) {
4037 global $SITE, $CFG;
4039 $course = clone($SITE);
4040 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
4042 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4043 if ($forceopen) {
4044 $frontpage->force_open();
4046 $frontpage->id = 'frontpagesettings';
4048 if (has_capability('moodle/course:update', $coursecontext)) {
4050 // Add the turn on/off settings
4051 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4052 if ($this->page->user_is_editing()) {
4053 $url->param('edit', 'off');
4054 $editstring = get_string('turneditingoff');
4055 } else {
4056 $url->param('edit', 'on');
4057 $editstring = get_string('turneditingon');
4059 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4061 // Add the course settings link
4062 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4063 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4066 // add enrol nodes
4067 enrol_add_course_navigation($frontpage, $course);
4069 // Manage filters
4070 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4071 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4072 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4075 // Backup this course
4076 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4077 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4078 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4081 // Restore to this course
4082 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4083 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4084 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4087 // Questions
4088 require_once($CFG->libdir . '/questionlib.php');
4089 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4091 // Manage files
4092 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4093 //hiden in new installs
4094 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
4095 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
4097 return $frontpage;
4101 * This function marks the cache as volatile so it is cleared during shutdown
4103 public function clear_cache() {
4104 $this->cache->volatile();
4109 * Simple class used to output a navigation branch in XML
4111 * @package core
4112 * @category navigation
4113 * @copyright 2009 Sam Hemelryk
4114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4116 class navigation_json {
4117 /** @var array An array of different node types */
4118 protected $nodetype = array('node','branch');
4119 /** @var array An array of node keys and types */
4120 protected $expandable = array();
4122 * Turns a branch and all of its children into XML
4124 * @param navigation_node $branch
4125 * @return string XML string
4127 public function convert($branch) {
4128 $xml = $this->convert_child($branch);
4129 return $xml;
4132 * Set the expandable items in the array so that we have enough information
4133 * to attach AJAX events
4134 * @param array $expandable
4136 public function set_expandable($expandable) {
4137 foreach ($expandable as $node) {
4138 $this->expandable[$node['key'].':'.$node['type']] = $node;
4142 * Recusively converts a child node and its children to XML for output
4144 * @param navigation_node $child The child to convert
4145 * @param int $depth Pointlessly used to track the depth of the XML structure
4146 * @return string JSON
4148 protected function convert_child($child, $depth=1) {
4149 if (!$child->display) {
4150 return '';
4152 $attributes = array();
4153 $attributes['id'] = $child->id;
4154 $attributes['name'] = $child->text;
4155 $attributes['type'] = $child->type;
4156 $attributes['key'] = $child->key;
4157 $attributes['class'] = $child->get_css_type();
4159 if ($child->icon instanceof pix_icon) {
4160 $attributes['icon'] = array(
4161 'component' => $child->icon->component,
4162 'pix' => $child->icon->pix,
4164 foreach ($child->icon->attributes as $key=>$value) {
4165 if ($key == 'class') {
4166 $attributes['icon']['classes'] = explode(' ', $value);
4167 } else if (!array_key_exists($key, $attributes['icon'])) {
4168 $attributes['icon'][$key] = $value;
4172 } else if (!empty($child->icon)) {
4173 $attributes['icon'] = (string)$child->icon;
4176 if ($child->forcetitle || $child->title !== $child->text) {
4177 $attributes['title'] = htmlentities($child->title);
4179 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4180 $attributes['expandable'] = $child->key;
4181 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4184 if (count($child->classes)>0) {
4185 $attributes['class'] .= ' '.join(' ',$child->classes);
4187 if (is_string($child->action)) {
4188 $attributes['link'] = $child->action;
4189 } else if ($child->action instanceof moodle_url) {
4190 $attributes['link'] = $child->action->out();
4191 } else if ($child->action instanceof action_link) {
4192 $attributes['link'] = $child->action->url->out();
4194 $attributes['hidden'] = ($child->hidden);
4195 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4197 if ($child->children->count() > 0) {
4198 $attributes['children'] = array();
4199 foreach ($child->children as $subchild) {
4200 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4204 if ($depth > 1) {
4205 return $attributes;
4206 } else {
4207 return json_encode($attributes);
4213 * The cache class used by global navigation and settings navigation to cache bits
4214 * and bobs that are used during their generation.
4216 * It is basically an easy access point to session with a bit of smarts to make
4217 * sure that the information that is cached is valid still.
4219 * Example use:
4220 * <code php>
4221 * if (!$cache->viewdiscussion()) {
4222 * // Code to do stuff and produce cachable content
4223 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4225 * $content = $cache->viewdiscussion;
4226 * </code>
4228 * @package core
4229 * @category navigation
4230 * @copyright 2009 Sam Hemelryk
4231 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4233 class navigation_cache {
4234 /** @var int represents the time created */
4235 protected $creation;
4236 /** @var array An array of session keys */
4237 protected $session;
4239 * The string to use to segregate this particular cache. It can either be
4240 * unique to start a fresh cache or if you want to share a cache then make
4241 * it the string used in the original cache.
4242 * @var string
4244 protected $area;
4245 /** @var int a time that the information will time out */
4246 protected $timeout;
4247 /** @var stdClass The current context */
4248 protected $currentcontext;
4249 /** @var int cache time information */
4250 const CACHETIME = 0;
4251 /** @var int cache user id */
4252 const CACHEUSERID = 1;
4253 /** @var int cache value */
4254 const CACHEVALUE = 2;
4255 /** @var null|array An array of navigation cache areas to expire on shutdown */
4256 public static $volatilecaches;
4259 * Contructor for the cache. Requires two arguments
4261 * @param string $area The string to use to segregate this particular cache
4262 * it can either be unique to start a fresh cache or if you want
4263 * to share a cache then make it the string used in the original
4264 * cache
4265 * @param int $timeout The number of seconds to time the information out after
4267 public function __construct($area, $timeout=1800) {
4268 $this->creation = time();
4269 $this->area = $area;
4270 $this->timeout = time() - $timeout;
4271 if (rand(0,100) === 0) {
4272 $this->garbage_collection();
4277 * Used to set up the cache within the SESSION.
4279 * This is called for each access and ensure that we don't put anything into the session before
4280 * it is required.
4282 protected function ensure_session_cache_initialised() {
4283 global $SESSION;
4284 if (empty($this->session)) {
4285 if (!isset($SESSION->navcache)) {
4286 $SESSION->navcache = new stdClass;
4288 if (!isset($SESSION->navcache->{$this->area})) {
4289 $SESSION->navcache->{$this->area} = array();
4291 $this->session = &$SESSION->navcache->{$this->area};
4296 * Magic Method to retrieve something by simply calling using = cache->key
4298 * @param mixed $key The identifier for the information you want out again
4299 * @return void|mixed Either void or what ever was put in
4301 public function __get($key) {
4302 if (!$this->cached($key)) {
4303 return;
4305 $information = $this->session[$key][self::CACHEVALUE];
4306 return unserialize($information);
4310 * Magic method that simply uses {@link set();} to store something in the cache
4312 * @param string|int $key
4313 * @param mixed $information
4315 public function __set($key, $information) {
4316 $this->set($key, $information);
4320 * Sets some information against the cache (session) for later retrieval
4322 * @param string|int $key
4323 * @param mixed $information
4325 public function set($key, $information) {
4326 global $USER;
4327 $this->ensure_session_cache_initialised();
4328 $information = serialize($information);
4329 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4332 * Check the existence of the identifier in the cache
4334 * @param string|int $key
4335 * @return bool
4337 public function cached($key) {
4338 global $USER;
4339 $this->ensure_session_cache_initialised();
4340 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) {
4341 return false;
4343 return true;
4346 * Compare something to it's equivilant in the cache
4348 * @param string $key
4349 * @param mixed $value
4350 * @param bool $serialise Whether to serialise the value before comparison
4351 * this should only be set to false if the value is already
4352 * serialised
4353 * @return bool If the value is the same false if it is not set or doesn't match
4355 public function compare($key, $value, $serialise = true) {
4356 if ($this->cached($key)) {
4357 if ($serialise) {
4358 $value = serialize($value);
4360 if ($this->session[$key][self::CACHEVALUE] === $value) {
4361 return true;
4364 return false;
4367 * Wipes the entire cache, good to force regeneration
4369 public function clear() {
4370 global $SESSION;
4371 unset($SESSION->navcache);
4372 $this->session = null;
4375 * Checks all cache entries and removes any that have expired, good ole cleanup
4377 protected function garbage_collection() {
4378 if (empty($this->session)) {
4379 return true;
4381 foreach ($this->session as $key=>$cachedinfo) {
4382 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4383 unset($this->session[$key]);
4389 * Marks the cache as being volatile (likely to change)
4391 * Any caches marked as volatile will be destroyed at the on shutdown by
4392 * {@link navigation_node::destroy_volatile_caches()} which is registered
4393 * as a shutdown function if any caches are marked as volatile.
4395 * @param bool $setting True to destroy the cache false not too
4397 public function volatile($setting = true) {
4398 if (self::$volatilecaches===null) {
4399 self::$volatilecaches = array();
4400 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4403 if ($setting) {
4404 self::$volatilecaches[$this->area] = $this->area;
4405 } else if (array_key_exists($this->area, self::$volatilecaches)) {
4406 unset(self::$volatilecaches[$this->area]);
4411 * Destroys all caches marked as volatile
4413 * This function is static and works in conjunction with the static volatilecaches
4414 * property of navigation cache.
4415 * Because this function is static it manually resets the cached areas back to an
4416 * empty array.
4418 public static function destroy_volatile_caches() {
4419 global $SESSION;
4420 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4421 foreach (self::$volatilecaches as $area) {
4422 $SESSION->navcache->{$area} = array();
4424 } else {
4425 $SESSION->navcache = new stdClass;