Merge branch 'wip-MDL-33017-m24-r2' of git://github.com/samhemelryk/moodle
[moodle.git] / lib / navigationlib.php
blobe124c920e6aa4f90959b613e20407165803f49eb
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
33 /**
34 * This class is used to represent a node in a navigation tree
36 * This class is used to represent a node in a navigation tree within Moodle,
37 * the tree could be one of global navigation, settings navigation, or the navbar.
38 * Each node can be one of two types either a Leaf (default) or a branch.
39 * When a node is first created it is created as a leaf, when/if children are added
40 * the node then becomes a branch.
42 * @package core
43 * @category navigation
44 * @copyright 2009 Sam Hemelryk
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class navigation_node implements renderable {
48 /** @var int Used to identify this node a leaf (default) 0 */
49 const NODETYPE_LEAF = 0;
50 /** @var int Used to identify this node a branch, happens with children 1 */
51 const NODETYPE_BRANCH = 1;
52 /** @var null Unknown node type null */
53 const TYPE_UNKNOWN = null;
54 /** @var int System node type 0 */
55 const TYPE_ROOTNODE = 0;
56 /** @var int System node type 1 */
57 const TYPE_SYSTEM = 1;
58 /** @var int Category node type 10 */
59 const TYPE_CATEGORY = 10;
60 /** @var int Course node type 20 */
61 const TYPE_COURSE = 20;
62 /** @var int Course Structure node type 30 */
63 const TYPE_SECTION = 30;
64 /** @var int Activity node type, e.g. Forum, Quiz 40 */
65 const TYPE_ACTIVITY = 40;
66 /** @var int Resource node type, e.g. Link to a file, or label 50 */
67 const TYPE_RESOURCE = 50;
68 /** @var int A custom node type, default when adding without specifing type 60 */
69 const TYPE_CUSTOM = 60;
70 /** @var int Setting node type, used only within settings nav 70 */
71 const TYPE_SETTING = 70;
72 /** @var int Setting node type, used only within settings nav 80 */
73 const TYPE_USER = 80;
74 /** @var int Setting node type, used for containers of no importance 90 */
75 const TYPE_CONTAINER = 90;
76 /** var int Course the current user is not enrolled in */
77 const COURSE_OTHER = 0;
78 /** var int Course the current user is enrolled in but not viewing */
79 const COURSE_MY = 1;
80 /** var int Course the current user is currently viewing */
81 const COURSE_CURRENT = 2;
83 /** @var int Parameter to aid the coder in tracking [optional] */
84 public $id = null;
85 /** @var string|int The identifier for the node, used to retrieve the node */
86 public $key = null;
87 /** @var string The text to use for the node */
88 public $text = null;
89 /** @var string Short text to use if requested [optional] */
90 public $shorttext = null;
91 /** @var string The title attribute for an action if one is defined */
92 public $title = null;
93 /** @var string A string that can be used to build a help button */
94 public $helpbutton = null;
95 /** @var moodle_url|action_link|null An action for the node (link) */
96 public $action = null;
97 /** @var pix_icon The path to an icon to use for this node */
98 public $icon = null;
99 /** @var int See TYPE_* constants defined for this class */
100 public $type = self::TYPE_UNKNOWN;
101 /** @var int See NODETYPE_* constants defined for this class */
102 public $nodetype = self::NODETYPE_LEAF;
103 /** @var bool If set to true the node will be collapsed by default */
104 public $collapse = false;
105 /** @var bool If set to true the node will be expanded by default */
106 public $forceopen = false;
107 /** @var array An array of CSS classes for the node */
108 public $classes = array();
109 /** @var navigation_node_collection An array of child nodes */
110 public $children = array();
111 /** @var bool If set to true the node will be recognised as active */
112 public $isactive = false;
113 /** @var bool If set to true the node will be dimmed */
114 public $hidden = false;
115 /** @var bool If set to false the node will not be displayed */
116 public $display = true;
117 /** @var bool If set to true then an HR will be printed before the node */
118 public $preceedwithhr = false;
119 /** @var bool If set to true the the navigation bar should ignore this node */
120 public $mainnavonly = false;
121 /** @var bool If set to true a title will be added to the action no matter what */
122 public $forcetitle = false;
123 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
124 public $parent = null;
125 /** @var bool Override to not display the icon even if one is provided **/
126 public $hideicon = false;
127 /** @var bool Set to true if we KNOW that this node can be expanded. */
128 public $isexpandable = false;
129 /** @var array */
130 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
131 /** @var moodle_url */
132 protected static $fullmeurl = null;
133 /** @var bool toogles auto matching of active node */
134 public static $autofindactive = true;
135 /** @var mixed If set to an int, that section will be included even if it has no activities */
136 public $includesectionnum = false;
139 * Constructs a new navigation_node
141 * @param array|string $properties Either an array of properties or a string to use
142 * as the text for the node
144 public function __construct($properties) {
145 if (is_array($properties)) {
146 // Check the array for each property that we allow to set at construction.
147 // text - The main content for the node
148 // shorttext - A short text if required for the node
149 // icon - The icon to display for the node
150 // type - The type of the node
151 // key - The key to use to identify the node
152 // parent - A reference to the nodes parent
153 // action - The action to attribute to this node, usually a URL to link to
154 if (array_key_exists('text', $properties)) {
155 $this->text = $properties['text'];
157 if (array_key_exists('shorttext', $properties)) {
158 $this->shorttext = $properties['shorttext'];
160 if (!array_key_exists('icon', $properties)) {
161 $properties['icon'] = new pix_icon('i/navigationitem', '');
163 $this->icon = $properties['icon'];
164 if ($this->icon instanceof pix_icon) {
165 if (empty($this->icon->attributes['class'])) {
166 $this->icon->attributes['class'] = 'navicon';
167 } else {
168 $this->icon->attributes['class'] .= ' navicon';
171 if (array_key_exists('type', $properties)) {
172 $this->type = $properties['type'];
173 } else {
174 $this->type = self::TYPE_CUSTOM;
176 if (array_key_exists('key', $properties)) {
177 $this->key = $properties['key'];
179 // This needs to happen last because of the check_if_active call that occurs
180 if (array_key_exists('action', $properties)) {
181 $this->action = $properties['action'];
182 if (is_string($this->action)) {
183 $this->action = new moodle_url($this->action);
185 if (self::$autofindactive) {
186 $this->check_if_active();
189 if (array_key_exists('parent', $properties)) {
190 $this->set_parent($properties['parent']);
192 } else if (is_string($properties)) {
193 $this->text = $properties;
195 if ($this->text === null) {
196 throw new coding_exception('You must set the text for the node when you create it.');
198 // Default the title to the text
199 $this->title = $this->text;
200 // Instantiate a new navigation node collection for this nodes children
201 $this->children = new navigation_node_collection();
205 * Checks if this node is the active node.
207 * This is determined by comparing the action for the node against the
208 * defined URL for the page. A match will see this node marked as active.
210 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
211 * @return bool
213 public function check_if_active($strength=URL_MATCH_EXACT) {
214 global $FULLME, $PAGE;
215 // Set fullmeurl if it hasn't already been set
216 if (self::$fullmeurl == null) {
217 if ($PAGE->has_set_url()) {
218 self::override_active_url(new moodle_url($PAGE->url));
219 } else {
220 self::override_active_url(new moodle_url($FULLME));
224 // Compare the action of this node against the fullmeurl
225 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
226 $this->make_active();
227 return true;
229 return false;
233 * This sets the URL that the URL of new nodes get compared to when locating
234 * the active node.
236 * The active node is the node that matches the URL set here. By default this
237 * is either $PAGE->url or if that hasn't been set $FULLME.
239 * @param moodle_url $url The url to use for the fullmeurl.
241 public static function override_active_url(moodle_url $url) {
242 // Clone the URL, in case the calling script changes their URL later.
243 self::$fullmeurl = new moodle_url($url);
247 * Creates a navigation node, ready to add it as a child using add_node
248 * function. (The created node needs to be added before you can use it.)
249 * @param string $text
250 * @param moodle_url|action_link $action
251 * @param int $type
252 * @param string $shorttext
253 * @param string|int $key
254 * @param pix_icon $icon
255 * @return navigation_node
257 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
258 $shorttext=null, $key=null, pix_icon $icon=null) {
259 // Properties array used when creating the new navigation node
260 $itemarray = array(
261 'text' => $text,
262 'type' => $type
264 // Set the action if one was provided
265 if ($action!==null) {
266 $itemarray['action'] = $action;
268 // Set the shorttext if one was provided
269 if ($shorttext!==null) {
270 $itemarray['shorttext'] = $shorttext;
272 // Set the icon if one was provided
273 if ($icon!==null) {
274 $itemarray['icon'] = $icon;
276 // Set the key
277 $itemarray['key'] = $key;
278 // Construct and return
279 return new navigation_node($itemarray);
283 * Adds a navigation node as a child of this node.
285 * @param string $text
286 * @param moodle_url|action_link $action
287 * @param int $type
288 * @param string $shorttext
289 * @param string|int $key
290 * @param pix_icon $icon
291 * @return navigation_node
293 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
294 // Create child node
295 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
297 // Add the child to end and return
298 return $this->add_node($childnode);
302 * Adds a navigation node as a child of this one, given a $node object
303 * created using the create function.
304 * @param navigation_node $childnode Node to add
305 * @param string $beforekey
306 * @return navigation_node The added node
308 public function add_node(navigation_node $childnode, $beforekey=null) {
309 // First convert the nodetype for this node to a branch as it will now have children
310 if ($this->nodetype !== self::NODETYPE_BRANCH) {
311 $this->nodetype = self::NODETYPE_BRANCH;
313 // Set the parent to this node
314 $childnode->set_parent($this);
316 // Default the key to the number of children if not provided
317 if ($childnode->key === null) {
318 $childnode->key = $this->children->count();
321 // Add the child using the navigation_node_collections add method
322 $node = $this->children->add($childnode, $beforekey);
324 // If added node is a category node or the user is logged in and it's a course
325 // then mark added node as a branch (makes it expandable by AJAX)
326 $type = $childnode->type;
327 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
328 $node->nodetype = self::NODETYPE_BRANCH;
330 // If this node is hidden mark it's children as hidden also
331 if ($this->hidden) {
332 $node->hidden = true;
334 // Return added node (reference returned by $this->children->add()
335 return $node;
339 * Return a list of all the keys of all the child nodes.
340 * @return array the keys.
342 public function get_children_key_list() {
343 return $this->children->get_key_list();
347 * Searches for a node of the given type with the given key.
349 * This searches this node plus all of its children, and their children....
350 * If you know the node you are looking for is a child of this node then please
351 * use the get method instead.
353 * @param int|string $key The key of the node we are looking for
354 * @param int $type One of navigation_node::TYPE_*
355 * @return navigation_node|false
357 public function find($key, $type) {
358 return $this->children->find($key, $type);
362 * Get the child of this node that has the given key + (optional) type.
364 * If you are looking for a node and want to search all children + thier children
365 * then please use the find method instead.
367 * @param int|string $key The key of the node we are looking for
368 * @param int $type One of navigation_node::TYPE_*
369 * @return navigation_node|false
371 public function get($key, $type=null) {
372 return $this->children->get($key, $type);
376 * Removes this node.
378 * @return bool
380 public function remove() {
381 return $this->parent->children->remove($this->key, $this->type);
385 * Checks if this node has or could have any children
387 * @return bool Returns true if it has children or could have (by AJAX expansion)
389 public function has_children() {
390 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
394 * Marks this node as active and forces it open.
396 * Important: If you are here because you need to mark a node active to get
397 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
398 * You can use it to specify a different URL to match the active navigation node on
399 * rather than having to locate and manually mark a node active.
401 public function make_active() {
402 $this->isactive = true;
403 $this->add_class('active_tree_node');
404 $this->force_open();
405 if ($this->parent !== null) {
406 $this->parent->make_inactive();
411 * Marks a node as inactive and recusised back to the base of the tree
412 * doing the same to all parents.
414 public function make_inactive() {
415 $this->isactive = false;
416 $this->remove_class('active_tree_node');
417 if ($this->parent !== null) {
418 $this->parent->make_inactive();
423 * Forces this node to be open and at the same time forces open all
424 * parents until the root node.
426 * Recursive.
428 public function force_open() {
429 $this->forceopen = true;
430 if ($this->parent !== null) {
431 $this->parent->force_open();
436 * Adds a CSS class to this node.
438 * @param string $class
439 * @return bool
441 public function add_class($class) {
442 if (!in_array($class, $this->classes)) {
443 $this->classes[] = $class;
445 return true;
449 * Removes a CSS class from this node.
451 * @param string $class
452 * @return bool True if the class was successfully removed.
454 public function remove_class($class) {
455 if (in_array($class, $this->classes)) {
456 $key = array_search($class,$this->classes);
457 if ($key!==false) {
458 unset($this->classes[$key]);
459 return true;
462 return false;
466 * Sets the title for this node and forces Moodle to utilise it.
467 * @param string $title
469 public function title($title) {
470 $this->title = $title;
471 $this->forcetitle = true;
475 * Resets the page specific information on this node if it is being unserialised.
477 public function __wakeup(){
478 $this->forceopen = false;
479 $this->isactive = false;
480 $this->remove_class('active_tree_node');
484 * Checks if this node or any of its children contain the active node.
486 * Recursive.
488 * @return bool
490 public function contains_active_node() {
491 if ($this->isactive) {
492 return true;
493 } else {
494 foreach ($this->children as $child) {
495 if ($child->isactive || $child->contains_active_node()) {
496 return true;
500 return false;
504 * Finds the active node.
506 * Searches this nodes children plus all of the children for the active node
507 * and returns it if found.
509 * Recursive.
511 * @return navigation_node|false
513 public function find_active_node() {
514 if ($this->isactive) {
515 return $this;
516 } else {
517 foreach ($this->children as &$child) {
518 $outcome = $child->find_active_node();
519 if ($outcome !== false) {
520 return $outcome;
524 return false;
528 * Searches all children for the best matching active node
529 * @return navigation_node|false
531 public function search_for_active_node() {
532 if ($this->check_if_active(URL_MATCH_BASE)) {
533 return $this;
534 } else {
535 foreach ($this->children as &$child) {
536 $outcome = $child->search_for_active_node();
537 if ($outcome !== false) {
538 return $outcome;
542 return false;
546 * Gets the content for this node.
548 * @param bool $shorttext If true shorttext is used rather than the normal text
549 * @return string
551 public function get_content($shorttext=false) {
552 if ($shorttext && $this->shorttext!==null) {
553 return format_string($this->shorttext);
554 } else {
555 return format_string($this->text);
560 * Gets the title to use for this node.
562 * @return string
564 public function get_title() {
565 if ($this->forcetitle || $this->action != null){
566 return $this->title;
567 } else {
568 return '';
573 * Gets the CSS class to add to this node to describe its type
575 * @return string
577 public function get_css_type() {
578 if (array_key_exists($this->type, $this->namedtypes)) {
579 return 'type_'.$this->namedtypes[$this->type];
581 return 'type_unknown';
585 * Finds all nodes that are expandable by AJAX
587 * @param array $expandable An array by reference to populate with expandable nodes.
589 public function find_expandable(array &$expandable) {
590 foreach ($this->children as &$child) {
591 if ($child->display && $child->has_children() && $child->children->count() == 0) {
592 $child->id = 'expandable_branch_'.(count($expandable)+1);
593 $this->add_class('canexpand');
594 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
596 $child->find_expandable($expandable);
601 * Finds all nodes of a given type (recursive)
603 * @param int $type One of navigation_node::TYPE_*
604 * @return array
606 public function find_all_of_type($type) {
607 $nodes = $this->children->type($type);
608 foreach ($this->children as &$node) {
609 $childnodes = $node->find_all_of_type($type);
610 $nodes = array_merge($nodes, $childnodes);
612 return $nodes;
616 * Removes this node if it is empty
618 public function trim_if_empty() {
619 if ($this->children->count() == 0) {
620 $this->remove();
625 * Creates a tab representation of this nodes children that can be used
626 * with print_tabs to produce the tabs on a page.
628 * call_user_func_array('print_tabs', $node->get_tabs_array());
630 * @param array $inactive
631 * @param bool $return
632 * @return array Array (tabs, selected, inactive, activated, return)
634 public function get_tabs_array(array $inactive=array(), $return=false) {
635 $tabs = array();
636 $rows = array();
637 $selected = null;
638 $activated = array();
639 foreach ($this->children as $node) {
640 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
641 if ($node->contains_active_node()) {
642 if ($node->children->count() > 0) {
643 $activated[] = $node->key;
644 foreach ($node->children as $child) {
645 if ($child->contains_active_node()) {
646 $selected = $child->key;
648 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
650 } else {
651 $selected = $node->key;
655 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
659 * Sets the parent for this node and if this node is active ensures that the tree is properly
660 * adjusted as well.
662 * @param navigation_node $parent
664 public function set_parent(navigation_node $parent) {
665 // Set the parent (thats the easy part)
666 $this->parent = $parent;
667 // Check if this node is active (this is checked during construction)
668 if ($this->isactive) {
669 // Force all of the parent nodes open so you can see this node
670 $this->parent->force_open();
671 // Make all parents inactive so that its clear where we are.
672 $this->parent->make_inactive();
678 * Navigation node collection
680 * This class is responsible for managing a collection of navigation nodes.
681 * It is required because a node's unique identifier is a combination of both its
682 * key and its type.
684 * Originally an array was used with a string key that was a combination of the two
685 * however it was decided that a better solution would be to use a class that
686 * implements the standard IteratorAggregate interface.
688 * @package core
689 * @category navigation
690 * @copyright 2010 Sam Hemelryk
691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 class navigation_node_collection implements IteratorAggregate {
695 * A multidimensional array to where the first key is the type and the second
696 * key is the nodes key.
697 * @var array
699 protected $collection = array();
701 * An array that contains references to nodes in the same order they were added.
702 * This is maintained as a progressive array.
703 * @var array
705 protected $orderedcollection = array();
707 * A reference to the last node that was added to the collection
708 * @var navigation_node
710 protected $last = null;
712 * The total number of items added to this array.
713 * @var int
715 protected $count = 0;
718 * Adds a navigation node to the collection
720 * @param navigation_node $node Node to add
721 * @param string $beforekey If specified, adds before a node with this key,
722 * otherwise adds at end
723 * @return navigation_node Added node
725 public function add(navigation_node $node, $beforekey=null) {
726 global $CFG;
727 $key = $node->key;
728 $type = $node->type;
730 // First check we have a 2nd dimension for this type
731 if (!array_key_exists($type, $this->orderedcollection)) {
732 $this->orderedcollection[$type] = array();
734 // Check for a collision and report if debugging is turned on
735 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
736 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
739 // Find the key to add before
740 $newindex = $this->count;
741 $last = true;
742 if ($beforekey !== null) {
743 foreach ($this->collection as $index => $othernode) {
744 if ($othernode->key === $beforekey) {
745 $newindex = $index;
746 $last = false;
747 break;
750 if ($newindex === $this->count) {
751 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
752 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
756 // Add the node to the appropriate place in the by-type structure (which
757 // is not ordered, despite the variable name)
758 $this->orderedcollection[$type][$key] = $node;
759 if (!$last) {
760 // Update existing references in the ordered collection (which is the
761 // one that isn't called 'ordered') to shuffle them along if required
762 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
763 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
766 // Add a reference to the node to the progressive collection.
767 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
768 // Update the last property to a reference to this new node.
769 $this->last = $this->orderedcollection[$type][$key];
771 // Reorder the array by index if needed
772 if (!$last) {
773 ksort($this->collection);
775 $this->count++;
776 // Return the reference to the now added node
777 return $node;
781 * Return a list of all the keys of all the nodes.
782 * @return array the keys.
784 public function get_key_list() {
785 $keys = array();
786 foreach ($this->collection as $node) {
787 $keys[] = $node->key;
789 return $keys;
793 * Fetches a node from this collection.
795 * @param string|int $key The key of the node we want to find.
796 * @param int $type One of navigation_node::TYPE_*.
797 * @return navigation_node|null
799 public function get($key, $type=null) {
800 if ($type !== null) {
801 // If the type is known then we can simply check and fetch
802 if (!empty($this->orderedcollection[$type][$key])) {
803 return $this->orderedcollection[$type][$key];
805 } else {
806 // Because we don't know the type we look in the progressive array
807 foreach ($this->collection as $node) {
808 if ($node->key === $key) {
809 return $node;
813 return false;
817 * Searches for a node with matching key and type.
819 * This function searches both the nodes in this collection and all of
820 * the nodes in each collection belonging to the nodes in this collection.
822 * Recursive.
824 * @param string|int $key The key of the node we want to find.
825 * @param int $type One of navigation_node::TYPE_*.
826 * @return navigation_node|null
828 public function find($key, $type=null) {
829 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
830 return $this->orderedcollection[$type][$key];
831 } else {
832 $nodes = $this->getIterator();
833 // Search immediate children first
834 foreach ($nodes as &$node) {
835 if ($node->key === $key && ($type === null || $type === $node->type)) {
836 return $node;
839 // Now search each childs children
840 foreach ($nodes as &$node) {
841 $result = $node->children->find($key, $type);
842 if ($result !== false) {
843 return $result;
847 return false;
851 * Fetches the last node that was added to this collection
853 * @return navigation_node
855 public function last() {
856 return $this->last;
860 * Fetches all nodes of a given type from this collection
862 * @param string|int $type node type being searched for.
863 * @return array ordered collection
865 public function type($type) {
866 if (!array_key_exists($type, $this->orderedcollection)) {
867 $this->orderedcollection[$type] = array();
869 return $this->orderedcollection[$type];
872 * Removes the node with the given key and type from the collection
874 * @param string|int $key The key of the node we want to find.
875 * @param int $type
876 * @return bool
878 public function remove($key, $type=null) {
879 $child = $this->get($key, $type);
880 if ($child !== false) {
881 foreach ($this->collection as $colkey => $node) {
882 if ($node->key == $key && $node->type == $type) {
883 unset($this->collection[$colkey]);
884 break;
887 unset($this->orderedcollection[$child->type][$child->key]);
888 $this->count--;
889 return true;
891 return false;
895 * Gets the number of nodes in this collection
897 * This option uses an internal count rather than counting the actual options to avoid
898 * a performance hit through the count function.
900 * @return int
902 public function count() {
903 return $this->count;
906 * Gets an array iterator for the collection.
908 * This is required by the IteratorAggregator interface and is used by routines
909 * such as the foreach loop.
911 * @return ArrayIterator
913 public function getIterator() {
914 return new ArrayIterator($this->collection);
919 * The global navigation class used for... the global navigation
921 * This class is used by PAGE to store the global navigation for the site
922 * and is then used by the settings nav and navbar to save on processing and DB calls
924 * See
925 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
926 * {@link lib/ajax/getnavbranch.php} Called by ajax
928 * @package core
929 * @category navigation
930 * @copyright 2009 Sam Hemelryk
931 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
933 class global_navigation extends navigation_node {
934 /** @var moodle_page The Moodle page this navigation object belongs to. */
935 protected $page;
936 /** @var bool switch to let us know if the navigation object is initialised*/
937 protected $initialised = false;
938 /** @var array An array of course information */
939 protected $mycourses = array();
940 /** @var array An array for containing root navigation nodes */
941 protected $rootnodes = array();
942 /** @var bool A switch for whether to show empty sections in the navigation */
943 protected $showemptysections = true;
944 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
945 protected $showcategories = null;
946 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
947 protected $showmycategories = null;
948 /** @var array An array of stdClasses for users that the navigation is extended for */
949 protected $extendforuser = array();
950 /** @var navigation_cache */
951 protected $cache;
952 /** @var array An array of course ids that are present in the navigation */
953 protected $addedcourses = array();
954 /** @var bool */
955 protected $allcategoriesloaded = false;
956 /** @var array An array of category ids that are included in the navigation */
957 protected $addedcategories = array();
958 /** @var int expansion limit */
959 protected $expansionlimit = 0;
960 /** @var int userid to allow parent to see child's profile page navigation */
961 protected $useridtouseforparentchecks = 0;
963 /** Used when loading categories to load all top level categories [parent = 0] **/
964 const LOAD_ROOT_CATEGORIES = 0;
965 /** Used when loading categories to load all categories **/
966 const LOAD_ALL_CATEGORIES = -1;
969 * Constructs a new global navigation
971 * @param moodle_page $page The page this navigation object belongs to
973 public function __construct(moodle_page $page) {
974 global $CFG, $SITE, $USER;
976 if (during_initial_install()) {
977 return;
980 if (get_home_page() == HOMEPAGE_SITE) {
981 // We are using the site home for the root element
982 $properties = array(
983 'key' => 'home',
984 'type' => navigation_node::TYPE_SYSTEM,
985 'text' => get_string('home'),
986 'action' => new moodle_url('/')
988 } else {
989 // We are using the users my moodle for the root element
990 $properties = array(
991 'key' => 'myhome',
992 'type' => navigation_node::TYPE_SYSTEM,
993 'text' => get_string('myhome'),
994 'action' => new moodle_url('/my/')
998 // Use the parents constructor.... good good reuse
999 parent::__construct($properties);
1001 // Initalise and set defaults
1002 $this->page = $page;
1003 $this->forceopen = true;
1004 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1008 * Mutator to set userid to allow parent to see child's profile
1009 * page navigation. See MDL-25805 for initial issue. Linked to it
1010 * is an issue explaining why this is a REALLY UGLY HACK thats not
1011 * for you to use!
1013 * @param int $userid userid of profile page that parent wants to navigate around.
1015 public function set_userid_for_parent_checks($userid) {
1016 $this->useridtouseforparentchecks = $userid;
1021 * Initialises the navigation object.
1023 * This causes the navigation object to look at the current state of the page
1024 * that it is associated with and then load the appropriate content.
1026 * This should only occur the first time that the navigation structure is utilised
1027 * which will normally be either when the navbar is called to be displayed or
1028 * when a block makes use of it.
1030 * @return bool
1032 public function initialise() {
1033 global $CFG, $SITE, $USER;
1034 // Check if it has already been initialised
1035 if ($this->initialised || during_initial_install()) {
1036 return true;
1038 $this->initialised = true;
1040 // Set up the five base root nodes. These are nodes where we will put our
1041 // content and are as follows:
1042 // site: Navigation for the front page.
1043 // myprofile: User profile information goes here.
1044 // currentcourse: The course being currently viewed.
1045 // mycourses: The users courses get added here.
1046 // courses: Additional courses are added here.
1047 // users: Other users information loaded here.
1048 $this->rootnodes = array();
1049 if (get_home_page() == HOMEPAGE_SITE) {
1050 // The home element should be my moodle because the root element is the site
1051 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1052 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1054 } else {
1055 // The home element should be the site because the root node is my moodle
1056 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1057 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1058 // We need to stop automatic redirection
1059 $this->rootnodes['home']->action->param('redirect', '0');
1062 $this->rootnodes['site'] = $this->add_course($SITE);
1063 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1064 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1065 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
1066 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1067 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1069 // We always load the frontpage course to ensure it is available without
1070 // JavaScript enabled.
1071 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1072 $this->load_course_sections($SITE, $this->rootnodes['site']);
1074 $course = $this->page->course;
1076 // $issite gets set to true if the current pages course is the sites frontpage course
1077 $issite = ($this->page->course->id == $SITE->id);
1078 // Determine if the user is enrolled in any course.
1079 $enrolledinanycourse = enrol_user_sees_own_courses();
1081 $this->rootnodes['currentcourse']->mainnavonly = true;
1082 if ($enrolledinanycourse) {
1083 $this->rootnodes['mycourses']->isexpandable = true;
1084 if ($CFG->navshowallcourses) {
1085 // When we show all courses we need to show both the my courses and the regular courses branch.
1086 $this->rootnodes['courses']->isexpandable = true;
1088 } else {
1089 $this->rootnodes['courses']->isexpandable = true;
1092 $canviewcourseprofile = true;
1094 // Next load context specific content into the navigation
1095 switch ($this->page->context->contextlevel) {
1096 case CONTEXT_SYSTEM :
1097 // Nothing left to do here I feel.
1098 break;
1099 case CONTEXT_COURSECAT :
1100 // This is essential, we must load categories.
1101 $this->load_all_categories($this->page->context->instanceid, true);
1102 break;
1103 case CONTEXT_BLOCK :
1104 case CONTEXT_COURSE :
1105 if ($issite) {
1106 // Nothing left to do here.
1107 break;
1110 // Load the course associated with the current page into the navigation.
1111 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1112 // If the course wasn't added then don't try going any further.
1113 if (!$coursenode) {
1114 $canviewcourseprofile = false;
1115 break;
1118 // If the user is not enrolled then we only want to show the
1119 // course node and not populate it.
1121 // Not enrolled, can't view, and hasn't switched roles
1122 if (!can_access_course($course)) {
1123 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1124 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1125 if (!$this->current_user_is_parent_role()) {
1126 $coursenode->make_active();
1127 $canviewcourseprofile = false;
1128 break;
1132 // Add the essentials such as reports etc...
1133 $this->add_course_essentials($coursenode, $course);
1134 // Extend course navigation with it's sections/activities
1135 $this->load_course_sections($course, $coursenode);
1136 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1137 $coursenode->make_active();
1140 break;
1141 case CONTEXT_MODULE :
1142 if ($issite) {
1143 // If this is the site course then most information will have
1144 // already been loaded.
1145 // However we need to check if there is more content that can
1146 // yet be loaded for the specific module instance.
1147 $activitynode = $this->rootnodes['site']->get($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1148 if ($activitynode) {
1149 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1151 break;
1154 $course = $this->page->course;
1155 $cm = $this->page->cm;
1157 // Load the course associated with the page into the navigation
1158 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1160 // If the course wasn't added then don't try going any further.
1161 if (!$coursenode) {
1162 $canviewcourseprofile = false;
1163 break;
1166 // If the user is not enrolled then we only want to show the
1167 // course node and not populate it.
1168 if (!can_access_course($course)) {
1169 $coursenode->make_active();
1170 $canviewcourseprofile = false;
1171 break;
1174 $this->add_course_essentials($coursenode, $course);
1176 // Get section number from $cm (if provided) - we need this
1177 // before loading sections in order to tell it to load this section
1178 // even if it would not normally display (=> it contains only
1179 // a label, which we are now editing)
1180 $sectionnum = isset($cm->sectionnum) ? $cm->sectionnum : 0;
1181 if ($sectionnum) {
1182 // This value has to be stored in a member variable because
1183 // otherwise we would have to pass it through a public API
1184 // to course formats and they would need to change their
1185 // functions to pass it along again...
1186 $this->includesectionnum = $sectionnum;
1187 } else {
1188 $this->includesectionnum = false;
1191 // Load the course sections into the page
1192 $sections = $this->load_course_sections($course, $coursenode);
1193 if ($course->id != $SITE->id) {
1194 // Find the section for the $CM associated with the page and collect
1195 // its section number.
1196 if ($sectionnum) {
1197 $cm->sectionnumber = $sectionnum;
1198 } else {
1199 foreach ($sections as $section) {
1200 if ($section->id == $cm->section) {
1201 $cm->sectionnumber = $section->section;
1202 break;
1207 // Load all of the section activities for the section the cm belongs to.
1208 if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) {
1209 list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
1210 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, $activityarray);
1211 } else {
1212 $activities = array();
1213 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1214 // "stealth" activity from unavailable section
1215 $activities[$cm->id] = $activity;
1218 } else {
1219 $activities = array();
1220 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1222 if (!empty($activities[$cm->id])) {
1223 // Finally load the cm specific navigaton information
1224 $this->load_activity($cm, $course, $activities[$cm->id]);
1225 // Check if we have an active ndoe
1226 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1227 // And make the activity node active.
1228 $activities[$cm->id]->make_active();
1230 } else {
1231 //TODO: something is wrong, what to do? (Skodak)
1233 break;
1234 case CONTEXT_USER :
1235 if ($issite) {
1236 // The users profile information etc is already loaded
1237 // for the front page.
1238 break;
1240 $course = $this->page->course;
1241 // Load the course associated with the user into the navigation
1242 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1244 // If the course wasn't added then don't try going any further.
1245 if (!$coursenode) {
1246 $canviewcourseprofile = false;
1247 break;
1250 // If the user is not enrolled then we only want to show the
1251 // course node and not populate it.
1252 if (!can_access_course($course)) {
1253 $coursenode->make_active();
1254 $canviewcourseprofile = false;
1255 break;
1257 $this->add_course_essentials($coursenode, $course);
1258 $this->load_course_sections($course, $coursenode);
1259 break;
1262 // Load for the current user
1263 $this->load_for_user();
1264 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1265 $this->load_for_user(null, true);
1267 // Load each extending user into the navigation.
1268 foreach ($this->extendforuser as $user) {
1269 if ($user->id != $USER->id) {
1270 $this->load_for_user($user);
1274 // Give the local plugins a chance to include some navigation if they want.
1275 foreach (get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1276 $function = "local_{$plugin}_extends_navigation";
1277 $oldfunction = "{$plugin}_extends_navigation";
1278 if (function_exists($function)) {
1279 // This is the preferred function name as there is less chance of conflicts
1280 $function($this);
1281 } else if (function_exists($oldfunction)) {
1282 // We continue to support the old function name to ensure backwards compatibility
1283 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. Support for the old callback will be dropped after the release of 2.4", DEBUG_DEVELOPER);
1284 $oldfunction($this);
1288 // Remove any empty root nodes
1289 foreach ($this->rootnodes as $node) {
1290 // Dont remove the home node
1291 if ($node->key !== 'home' && !$node->has_children()) {
1292 $node->remove();
1296 if (!$this->contains_active_node()) {
1297 $this->search_for_active_node();
1300 // If the user is not logged in modify the navigation structure as detailed
1301 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1302 if (!isloggedin()) {
1303 $activities = clone($this->rootnodes['site']->children);
1304 $this->rootnodes['site']->remove();
1305 $children = clone($this->children);
1306 $this->children = new navigation_node_collection();
1307 foreach ($activities as $child) {
1308 $this->children->add($child);
1310 foreach ($children as $child) {
1311 $this->children->add($child);
1314 return true;
1318 * Returns true if the current user is a parent of the user being currently viewed.
1320 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1321 * other user being viewed this function returns false.
1322 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1324 * @since 2.4
1325 * @return bool
1327 protected function current_user_is_parent_role() {
1328 global $USER, $DB;
1329 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1330 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1331 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1332 return false;
1334 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1335 return true;
1338 return false;
1342 * Returns true if courses should be shown within categories on the navigation.
1344 * @param bool $ismycourse Set to true if you are calculating this for a course.
1345 * @return bool
1347 protected function show_categories($ismycourse = false) {
1348 global $CFG, $DB;
1349 if ($ismycourse) {
1350 return $this->show_my_categories();
1352 if ($this->showcategories === null) {
1353 $show = false;
1354 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1355 $show = true;
1356 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1357 $show = true;
1359 $this->showcategories = $show;
1361 return $this->showcategories;
1365 * Returns true if we should show categories in the My Courses branch.
1366 * @return bool
1368 protected function show_my_categories() {
1369 global $CFG, $DB;
1370 if ($this->showmycategories === null) {
1371 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1373 return $this->showmycategories;
1377 * Loads the courses in Moodle into the navigation.
1379 * @global moodle_database $DB
1380 * @param string|array $categoryids An array containing categories to load courses
1381 * for, OR null to load courses for all categories.
1382 * @return array An array of navigation_nodes one for each course
1384 protected function load_all_courses($categoryids = null) {
1385 global $CFG, $DB, $SITE;
1387 // Work out the limit of courses.
1388 $limit = 20;
1389 if (!empty($CFG->navcourselimit)) {
1390 $limit = $CFG->navcourselimit;
1393 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1395 // If we are going to show all courses AND we are showing categories then
1396 // to save us repeated DB calls load all of the categories now
1397 if ($this->show_categories()) {
1398 $this->load_all_categories($toload);
1401 // Will be the return of our efforts
1402 $coursenodes = array();
1404 // Check if we need to show categories.
1405 if ($this->show_categories()) {
1406 // Hmmm we need to show categories... this is going to be painful.
1407 // We now need to fetch up to $limit courses for each category to
1408 // be displayed.
1409 if ($categoryids !== null) {
1410 if (!is_array($categoryids)) {
1411 $categoryids = array($categoryids);
1413 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1414 $categorywhere = 'WHERE cc.id '.$categorywhere;
1415 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1416 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1417 $categoryparams = array();
1418 } else {
1419 $categorywhere = '';
1420 $categoryparams = array();
1423 // First up we are going to get the categories that we are going to
1424 // need so that we can determine how best to load the courses from them.
1425 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1426 FROM {course_categories} cc
1427 LEFT JOIN {course} c ON c.category = cc.id
1428 {$categorywhere}
1429 GROUP BY cc.id";
1430 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1431 $fullfetch = array();
1432 $partfetch = array();
1433 foreach ($categories as $category) {
1434 if (!$this->can_add_more_courses_to_category($category->id)) {
1435 continue;
1437 if ($category->coursecount > $limit * 5) {
1438 $partfetch[] = $category->id;
1439 } else if ($category->coursecount > 0) {
1440 $fullfetch[] = $category->id;
1443 $categories->close();
1445 if (count($fullfetch)) {
1446 // First up fetch all of the courses in categories where we know that we are going to
1447 // need the majority of courses.
1448 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1449 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1450 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1451 FROM {course} c
1452 $ccjoin
1453 WHERE c.category {$categoryids}
1454 ORDER BY c.sortorder ASC";
1455 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1456 foreach ($coursesrs as $course) {
1457 if ($course->id == $SITE->id) {
1458 // This should not be necessary, frontpage is not in any category.
1459 continue;
1461 if (array_key_exists($course->id, $this->addedcourses)) {
1462 // It is probably better to not include the already loaded courses
1463 // directly in SQL because inequalities may confuse query optimisers
1464 // and may interfere with query caching.
1465 continue;
1467 if (!$this->can_add_more_courses_to_category($course->category)) {
1468 continue;
1470 context_instance_preload($course);
1471 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1472 continue;
1474 $coursenodes[$course->id] = $this->add_course($course);
1476 $coursesrs->close();
1479 if (count($partfetch)) {
1480 // Next we will work our way through the categories where we will likely only need a small
1481 // proportion of the courses.
1482 foreach ($partfetch as $categoryid) {
1483 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1484 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1485 FROM {course} c
1486 $ccjoin
1487 WHERE c.category = :categoryid
1488 ORDER BY c.sortorder ASC";
1489 $courseparams = array('categoryid' => $categoryid);
1490 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1491 foreach ($coursesrs as $course) {
1492 if ($course->id == $SITE->id) {
1493 // This should not be necessary, frontpage is not in any category.
1494 continue;
1496 if (array_key_exists($course->id, $this->addedcourses)) {
1497 // It is probably better to not include the already loaded courses
1498 // directly in SQL because inequalities may confuse query optimisers
1499 // and may interfere with query caching.
1500 // This also helps to respect expected $limit on repeated executions.
1501 continue;
1503 if (!$this->can_add_more_courses_to_category($course->category)) {
1504 break;
1506 context_instance_preload($course);
1507 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1508 continue;
1510 $coursenodes[$course->id] = $this->add_course($course);
1512 $coursesrs->close();
1515 } else {
1516 // Prepare the SQL to load the courses and their contexts
1517 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1518 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1519 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1520 FROM {course} c
1521 $ccjoin
1522 WHERE c.id {$courseids}
1523 ORDER BY c.sortorder ASC";
1524 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1525 foreach ($coursesrs as $course) {
1526 if ($course->id == $SITE->id) {
1527 // frotpage is not wanted here
1528 continue;
1530 if ($this->page->course && ($this->page->course->id == $course->id)) {
1531 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1532 continue;
1534 context_instance_preload($course);
1535 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1536 continue;
1538 $coursenodes[$course->id] = $this->add_course($course);
1539 if (count($coursenodes) >= $limit) {
1540 break;
1543 $coursesrs->close();
1546 return $coursenodes;
1550 * Returns true if more courses can be added to the provided category.
1552 * @param int|navigation_node|stdClass $category
1553 * @return bool
1555 protected function can_add_more_courses_to_category($category) {
1556 global $CFG;
1557 $limit = 20;
1558 if (!empty($CFG->navcourselimit)) {
1559 $limit = (int)$CFG->navcourselimit;
1561 if (is_numeric($category)) {
1562 if (!array_key_exists($category, $this->addedcategories)) {
1563 return true;
1565 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1566 } else if ($category instanceof navigation_node) {
1567 if ($category->type != self::TYPE_CATEGORY) {
1568 return false;
1570 $coursecount = count($category->children->type(self::TYPE_COURSE));
1571 } else if (is_object($category) && property_exists($category,'id')) {
1572 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1574 return ($coursecount <= $limit);
1578 * Loads all categories (top level or if an id is specified for that category)
1580 * @param int $categoryid The category id to load or null/0 to load all base level categories
1581 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1582 * as the requested category and any parent categories.
1583 * @return navigation_node|void returns a navigation node if a category has been loaded.
1585 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1586 global $CFG, $DB;
1588 // Check if this category has already been loaded
1589 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1590 return true;
1593 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1594 $sqlselect = "SELECT cc.*, $catcontextsql
1595 FROM {course_categories} cc
1596 JOIN {context} ctx ON cc.id = ctx.instanceid";
1597 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1598 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1599 $params = array();
1601 $categoriestoload = array();
1602 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1603 // We are going to load all categories regardless... prepare to fire
1604 // on the database server!
1605 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1606 // We are going to load all of the first level categories (categories without parents)
1607 $sqlwhere .= " AND cc.parent = 0";
1608 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1609 // The category itself has been loaded already so we just need to ensure its subcategories
1610 // have been loaded
1611 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1612 if ($showbasecategories) {
1613 // We need to include categories with parent = 0 as well
1614 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1615 } else {
1616 // All we need is categories that match the parent
1617 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1619 $params['categoryid'] = $categoryid;
1620 } else {
1621 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1622 // and load this category plus all its parents and subcategories
1623 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1624 $categoriestoload = explode('/', trim($category->path, '/'));
1625 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1626 // We are going to use select twice so double the params
1627 $params = array_merge($params, $params);
1628 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1629 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1632 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1633 $categories = array();
1634 foreach ($categoriesrs as $category) {
1635 // Preload the context.. we'll need it when adding the category in order
1636 // to format the category name.
1637 context_helper::preload_from_record($category);
1638 if (array_key_exists($category->id, $this->addedcategories)) {
1639 // Do nothing, its already been added.
1640 } else if ($category->parent == '0') {
1641 // This is a root category lets add it immediately
1642 $this->add_category($category, $this->rootnodes['courses']);
1643 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1644 // This categories parent has already been added we can add this immediately
1645 $this->add_category($category, $this->addedcategories[$category->parent]);
1646 } else {
1647 $categories[] = $category;
1650 $categoriesrs->close();
1652 // Now we have an array of categories we need to add them to the navigation.
1653 while (!empty($categories)) {
1654 $category = reset($categories);
1655 if (array_key_exists($category->id, $this->addedcategories)) {
1656 // Do nothing
1657 } else if ($category->parent == '0') {
1658 $this->add_category($category, $this->rootnodes['courses']);
1659 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1660 $this->add_category($category, $this->addedcategories[$category->parent]);
1661 } else {
1662 // This category isn't in the navigation and niether is it's parent (yet).
1663 // We need to go through the category path and add all of its components in order.
1664 $path = explode('/', trim($category->path, '/'));
1665 foreach ($path as $catid) {
1666 if (!array_key_exists($catid, $this->addedcategories)) {
1667 // This category isn't in the navigation yet so add it.
1668 $subcategory = $categories[$catid];
1669 if ($subcategory->parent == '0') {
1670 // Yay we have a root category - this likely means we will now be able
1671 // to add categories without problems.
1672 $this->add_category($subcategory, $this->rootnodes['courses']);
1673 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1674 // The parent is in the category (as we'd expect) so add it now.
1675 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1676 // Remove the category from the categories array.
1677 unset($categories[$catid]);
1678 } else {
1679 // We should never ever arrive here - if we have then there is a bigger
1680 // problem at hand.
1681 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1686 // Remove the category from the categories array now that we know it has been added.
1687 unset($categories[$category->id]);
1689 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1690 $this->allcategoriesloaded = true;
1692 // Check if there are any categories to load.
1693 if (count($categoriestoload) > 0) {
1694 $readytoloadcourses = array();
1695 foreach ($categoriestoload as $category) {
1696 if ($this->can_add_more_courses_to_category($category)) {
1697 $readytoloadcourses[] = $category;
1700 if (count($readytoloadcourses)) {
1701 $this->load_all_courses($readytoloadcourses);
1705 // Look for all categories which have been loaded
1706 if (!empty($this->addedcategories)) {
1707 $categoryids = array();
1708 foreach ($this->addedcategories as $category) {
1709 if ($this->can_add_more_courses_to_category($category)) {
1710 $categoryids[] = $category->key;
1713 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1714 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1715 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1716 FROM {course_categories} cc
1717 JOIN {course} c ON c.category = cc.id
1718 WHERE cc.id {$categoriessql}
1719 GROUP BY cc.id
1720 HAVING COUNT(c.id) > :limit";
1721 $excessivecategories = $DB->get_records_sql($sql, $params);
1722 foreach ($categories as &$category) {
1723 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1724 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1725 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1732 * Adds a structured category to the navigation in the correct order/place
1734 * @param stdClass $category
1735 * @param navigation_node $parent
1737 protected function add_category(stdClass $category, navigation_node $parent) {
1738 if (array_key_exists($category->id, $this->addedcategories)) {
1739 return;
1741 $url = new moodle_url('/course/category.php', array('id' => $category->id));
1742 $context = context_coursecat::instance($category->id);
1743 $categoryname = format_string($category->name, true, array('context' => $context));
1744 $categorynode = $parent->add($categoryname, $url, self::TYPE_CATEGORY, $categoryname, $category->id);
1745 if (empty($category->visible)) {
1746 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1747 $categorynode->hidden = true;
1748 } else {
1749 $categorynode->display = false;
1752 $this->addedcategories[$category->id] = $categorynode;
1756 * Loads the given course into the navigation
1758 * @param stdClass $course
1759 * @return navigation_node
1761 protected function load_course(stdClass $course) {
1762 global $SITE;
1763 if ($course->id == $SITE->id) {
1764 // This is always loaded during initialisation
1765 return $this->rootnodes['site'];
1766 } else if (array_key_exists($course->id, $this->addedcourses)) {
1767 // The course has already been loaded so return a reference
1768 return $this->addedcourses[$course->id];
1769 } else {
1770 // Add the course
1771 return $this->add_course($course);
1776 * Loads all of the courses section into the navigation.
1778 * This function utilisies a callback that can be implemented within the course
1779 * formats lib.php file to customise the navigation that is generated at this
1780 * point for the course.
1782 * By default (if not defined) the method {@link global_navigation::load_generic_course_sections()} is
1783 * called instead.
1785 * @param stdClass $course Database record for the course
1786 * @param navigation_node $coursenode The course node within the navigation
1787 * @return array Array of navigation nodes for the section with key = section id
1789 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1790 global $CFG;
1791 require_once($CFG->dirroot.'/course/lib.php');
1792 return course_get_format($course)->extend_course_navigation($this, $coursenode);
1796 * Generates an array of sections and an array of activities for the given course.
1798 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1800 * @param stdClass $course
1801 * @return array Array($sections, $activities)
1803 protected function generate_sections_and_activities(stdClass $course) {
1804 global $CFG;
1805 require_once($CFG->dirroot.'/course/lib.php');
1807 $modinfo = get_fast_modinfo($course);
1808 $sections = $modinfo->get_section_info_all();
1810 // For course formats using 'numsections' trim the sections list
1811 $courseformatoptions = course_get_format($course)->get_format_options();
1812 if (isset($courseformatoptions['numsections'])) {
1813 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1816 $activities = array();
1818 foreach ($sections as $key => $section) {
1819 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1820 $sections[$key] = clone($section);
1821 unset($sections[$key]->summary);
1822 $sections[$key]->hasactivites = false;
1823 if (!array_key_exists($section->section, $modinfo->sections)) {
1824 continue;
1826 foreach ($modinfo->sections[$section->section] as $cmid) {
1827 $cm = $modinfo->cms[$cmid];
1828 if (!$cm->uservisible) {
1829 continue;
1831 $activity = new stdClass;
1832 $activity->id = $cm->id;
1833 $activity->course = $course->id;
1834 $activity->section = $section->section;
1835 $activity->name = $cm->name;
1836 $activity->icon = $cm->icon;
1837 $activity->iconcomponent = $cm->iconcomponent;
1838 $activity->hidden = (!$cm->visible);
1839 $activity->modname = $cm->modname;
1840 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1841 $activity->onclick = $cm->get_on_click();
1842 $url = $cm->get_url();
1843 if (!$url) {
1844 $activity->url = null;
1845 $activity->display = false;
1846 } else {
1847 $activity->url = $cm->get_url()->out();
1848 $activity->display = true;
1849 if (self::module_extends_navigation($cm->modname)) {
1850 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1853 $activities[$cmid] = $activity;
1854 if ($activity->display) {
1855 $sections[$key]->hasactivites = true;
1860 return array($sections, $activities);
1864 * Generically loads the course sections into the course's navigation.
1866 * @param stdClass $course
1867 * @param navigation_node $coursenode
1868 * @return array An array of course section nodes
1870 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1871 global $CFG, $DB, $USER, $SITE;
1872 require_once($CFG->dirroot.'/course/lib.php');
1874 list($sections, $activities) = $this->generate_sections_and_activities($course);
1876 $key = 0;
1877 if (defined('AJAX_SCRIPT') && AJAX_SCRIPT == '0' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1878 $key = optional_param('section', $key, PARAM_INT);
1881 $navigationsections = array();
1882 foreach ($sections as $sectionid => $section) {
1883 $section = clone($section);
1884 if ($course->id == $SITE->id) {
1885 $this->load_section_activities($coursenode, $section->section, $activities);
1886 } else {
1887 if (!$section->uservisible || (!$this->showemptysections &&
1888 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1889 continue;
1892 $sectionname = get_section_name($course, $section);
1893 $url = course_get_url($course, $section->section, array('navigation' => true));
1895 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1896 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1897 $sectionnode->hidden = (!$section->visible || !$section->available);
1898 if ($key != '0' && $section->section != '0' && $section->section == $key && $this->page->context->contextlevel != CONTEXT_MODULE && $section->hasactivites) {
1899 $sectionnode->make_active();
1900 $this->load_section_activities($sectionnode, $section->section, $activities);
1902 $section->sectionnode = $sectionnode;
1903 $navigationsections[$sectionid] = $section;
1906 return $navigationsections;
1909 * Loads all of the activities for a section into the navigation structure.
1911 * @param navigation_node $sectionnode
1912 * @param int $sectionnumber
1913 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1914 * @param stdClass $course The course object the section and activities relate to.
1915 * @return array Array of activity nodes
1917 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1918 global $CFG, $SITE;
1919 // A static counter for JS function naming
1920 static $legacyonclickcounter = 0;
1922 $activitynodes = array();
1923 if (empty($activities)) {
1924 return $activitynodes;
1927 if (!is_object($course)) {
1928 $activity = reset($activities);
1929 $courseid = $activity->course;
1930 } else {
1931 $courseid = $course->id;
1933 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1935 foreach ($activities as $activity) {
1936 if ($activity->section != $sectionnumber) {
1937 continue;
1939 if ($activity->icon) {
1940 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1941 } else {
1942 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1945 // Prepare the default name and url for the node
1946 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1947 $action = new moodle_url($activity->url);
1949 // Check if the onclick property is set (puke!)
1950 if (!empty($activity->onclick)) {
1951 // Increment the counter so that we have a unique number.
1952 $legacyonclickcounter++;
1953 // Generate the function name we will use
1954 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1955 $propogrationhandler = '';
1956 // Check if we need to cancel propogation. Remember inline onclick
1957 // events would return false if they wanted to prevent propogation and the
1958 // default action.
1959 if (strpos($activity->onclick, 'return false')) {
1960 $propogrationhandler = 'e.halt();';
1962 // Decode the onclick - it has already been encoded for display (puke)
1963 $onclick = htmlspecialchars_decode($activity->onclick);
1964 // Build the JS function the click event will call
1965 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1966 $this->page->requires->js_init_code($jscode);
1967 // Override the default url with the new action link
1968 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1971 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1972 $activitynode->title(get_string('modulename', $activity->modname));
1973 $activitynode->hidden = $activity->hidden;
1974 $activitynode->display = $showactivities && $activity->display;
1975 $activitynode->nodetype = $activity->nodetype;
1976 $activitynodes[$activity->id] = $activitynode;
1979 return $activitynodes;
1982 * Loads a stealth module from unavailable section
1983 * @param navigation_node $coursenode
1984 * @param stdClass $modinfo
1985 * @return navigation_node or null if not accessible
1987 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1988 if (empty($modinfo->cms[$this->page->cm->id])) {
1989 return null;
1991 $cm = $modinfo->cms[$this->page->cm->id];
1992 if (!$cm->uservisible) {
1993 return null;
1995 if ($cm->icon) {
1996 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1997 } else {
1998 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2000 $url = $cm->get_url();
2001 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2002 $activitynode->title(get_string('modulename', $cm->modname));
2003 $activitynode->hidden = (!$cm->visible);
2004 if (!$url) {
2005 // Don't show activities that don't have links!
2006 $activitynode->display = false;
2007 } else if (self::module_extends_navigation($cm->modname)) {
2008 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2010 return $activitynode;
2013 * Loads the navigation structure for the given activity into the activities node.
2015 * This method utilises a callback within the modules lib.php file to load the
2016 * content specific to activity given.
2018 * The callback is a method: {modulename}_extend_navigation()
2019 * Examples:
2020 * * {@link forum_extend_navigation()}
2021 * * {@link workshop_extend_navigation()}
2023 * @param cm_info|stdClass $cm
2024 * @param stdClass $course
2025 * @param navigation_node $activity
2026 * @return bool
2028 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2029 global $CFG, $DB;
2031 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2032 if (!($cm instanceof cm_info)) {
2033 $modinfo = get_fast_modinfo($course);
2034 $cm = $modinfo->get_cm($cm->id);
2037 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2038 $activity->make_active();
2039 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2040 $function = $cm->modname.'_extend_navigation';
2042 if (file_exists($file)) {
2043 require_once($file);
2044 if (function_exists($function)) {
2045 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2046 $function($activity, $course, $activtyrecord, $cm);
2050 // Allow the active advanced grading method plugin to append module navigation
2051 $featuresfunc = $cm->modname.'_supports';
2052 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2053 require_once($CFG->dirroot.'/grade/grading/lib.php');
2054 $gradingman = get_grading_manager($cm->context, $cm->modname);
2055 $gradingman->extend_navigation($this, $activity);
2058 return $activity->has_children();
2061 * Loads user specific information into the navigation in the appropriate place.
2063 * If no user is provided the current user is assumed.
2065 * @param stdClass $user
2066 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2067 * @return bool
2069 protected function load_for_user($user=null, $forceforcontext=false) {
2070 global $DB, $CFG, $USER, $SITE;
2072 if ($user === null) {
2073 // We can't require login here but if the user isn't logged in we don't
2074 // want to show anything
2075 if (!isloggedin() || isguestuser()) {
2076 return false;
2078 $user = $USER;
2079 } else if (!is_object($user)) {
2080 // If the user is not an object then get them from the database
2081 $select = context_helper::get_preload_record_columns_sql('ctx');
2082 $sql = "SELECT u.*, $select
2083 FROM {user} u
2084 JOIN {context} ctx ON u.id = ctx.instanceid
2085 WHERE u.id = :userid AND
2086 ctx.contextlevel = :contextlevel";
2087 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2088 context_helper::preload_from_record($user);
2091 $iscurrentuser = ($user->id == $USER->id);
2093 $usercontext = context_user::instance($user->id);
2095 // Get the course set against the page, by default this will be the site
2096 $course = $this->page->course;
2097 $baseargs = array('id'=>$user->id);
2098 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2099 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2100 $baseargs['course'] = $course->id;
2101 $coursecontext = context_course::instance($course->id);
2102 $issitecourse = false;
2103 } else {
2104 // Load all categories and get the context for the system
2105 $coursecontext = context_system::instance();
2106 $issitecourse = true;
2109 // Create a node to add user information under.
2110 if ($iscurrentuser && !$forceforcontext) {
2111 // If it's the current user the information will go under the profile root node
2112 $usernode = $this->rootnodes['myprofile'];
2113 $course = get_site();
2114 $coursecontext = context_course::instance($course->id);
2115 $issitecourse = true;
2116 } else {
2117 if (!$issitecourse) {
2118 // Not the current user so add it to the participants node for the current course
2119 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2120 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2121 } else {
2122 // This is the site so add a users node to the root branch
2123 $usersnode = $this->rootnodes['users'];
2124 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2125 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2127 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2129 if (!$usersnode) {
2130 // We should NEVER get here, if the course hasn't been populated
2131 // with a participants node then the navigaiton either wasn't generated
2132 // for it (you are missing a require_login or set_context call) or
2133 // you don't have access.... in the interests of no leaking informatin
2134 // we simply quit...
2135 return false;
2137 // Add a branch for the current user
2138 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2139 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2141 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2142 $usernode->make_active();
2146 // If the user is the current user or has permission to view the details of the requested
2147 // user than add a view profile link.
2148 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2149 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2150 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2151 } else {
2152 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2156 if (!empty($CFG->navadduserpostslinks)) {
2157 // Add nodes for forum posts and discussions if the user can view either or both
2158 // There are no capability checks here as the content of the page is based
2159 // purely on the forums the current user has access too.
2160 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2161 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2162 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2165 // Add blog nodes
2166 if (!empty($CFG->enableblogs)) {
2167 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2168 require_once($CFG->dirroot.'/blog/lib.php');
2169 // Get all options for the user
2170 $options = blog_get_options_for_user($user);
2171 $this->cache->set('userblogoptions'.$user->id, $options);
2172 } else {
2173 $options = $this->cache->{'userblogoptions'.$user->id};
2176 if (count($options) > 0) {
2177 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2178 foreach ($options as $type => $option) {
2179 if ($type == "rss") {
2180 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2181 } else {
2182 $blogs->add($option['string'], $option['link']);
2188 if (!empty($CFG->messaging)) {
2189 $messageargs = null;
2190 if ($USER->id!=$user->id) {
2191 $messageargs = array('id'=>$user->id);
2193 $url = new moodle_url('/message/index.php',$messageargs);
2194 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2197 $context = context_user::instance($USER->id);
2198 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
2199 $url = new moodle_url('/user/files.php');
2200 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2203 // Add a node to view the users notes if permitted
2204 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2205 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2206 if ($coursecontext->instanceid) {
2207 $url->param('course', $coursecontext->instanceid);
2209 $usernode->add(get_string('notes', 'notes'), $url);
2212 // Add reports node
2213 $reporttab = $usernode->add(get_string('activityreports'));
2214 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2215 foreach ($reports as $reportfunction) {
2216 $reportfunction($reporttab, $user, $course);
2218 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
2219 if ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext)) {
2220 // Add grade hardcoded grade report if necessary
2221 $gradeaccess = false;
2222 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2223 //ok - can view all course grades
2224 $gradeaccess = true;
2225 } else if ($course->showgrades) {
2226 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
2227 //ok - can view own grades
2228 $gradeaccess = true;
2229 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
2230 // ok - can view grades of this user - parent most probably
2231 $gradeaccess = true;
2232 } else if ($anyreport) {
2233 // ok - can view grades of this user - parent most probably
2234 $gradeaccess = true;
2237 if ($gradeaccess) {
2238 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id, 'user'=>$usercontext->instanceid)));
2241 // Check the number of nodes in the report node... if there are none remove the node
2242 $reporttab->trim_if_empty();
2244 // If the user is the current user add the repositories for the current user
2245 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2246 if ($iscurrentuser) {
2247 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2248 require_once($CFG->dirroot . '/repository/lib.php');
2249 $editabletypes = repository::get_editable_types($usercontext);
2250 $haseditabletypes = !empty($editabletypes);
2251 unset($editabletypes);
2252 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2253 } else {
2254 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2256 if ($haseditabletypes) {
2257 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2259 } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2261 // Add view grade report is permitted
2262 $reports = get_plugin_list('gradereport');
2263 arsort($reports); // user is last, we want to test it first
2265 $userscourses = enrol_get_users_courses($user->id);
2266 $userscoursesnode = $usernode->add(get_string('courses'));
2268 foreach ($userscourses as $usercourse) {
2269 $usercoursecontext = context_course::instance($usercourse->id);
2270 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2271 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2273 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2274 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2275 foreach ($reports as $plugin => $plugindir) {
2276 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2277 //stop when the first visible plugin is found
2278 $gradeavailable = true;
2279 break;
2284 if ($gradeavailable) {
2285 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2286 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2289 // Add a node to view the users notes if permitted
2290 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2291 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2292 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2295 if (can_access_course($usercourse, $user->id)) {
2296 $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', ''));
2299 $reporttab = $usercoursenode->add(get_string('activityreports'));
2301 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2302 foreach ($reports as $reportfunction) {
2303 $reportfunction($reporttab, $user, $usercourse);
2306 $reporttab->trim_if_empty();
2309 return true;
2313 * This method simply checks to see if a given module can extend the navigation.
2315 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2317 * @param string $modname
2318 * @return bool
2320 protected static function module_extends_navigation($modname) {
2321 global $CFG;
2322 static $extendingmodules = array();
2323 if (!array_key_exists($modname, $extendingmodules)) {
2324 $extendingmodules[$modname] = false;
2325 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2326 if (file_exists($file)) {
2327 $function = $modname.'_extend_navigation';
2328 require_once($file);
2329 $extendingmodules[$modname] = (function_exists($function));
2332 return $extendingmodules[$modname];
2335 * Extends the navigation for the given user.
2337 * @param stdClass $user A user from the database
2339 public function extend_for_user($user) {
2340 $this->extendforuser[] = $user;
2344 * Returns all of the users the navigation is being extended for
2346 * @return array An array of extending users.
2348 public function get_extending_users() {
2349 return $this->extendforuser;
2352 * Adds the given course to the navigation structure.
2354 * @param stdClass $course
2355 * @param bool $forcegeneric
2356 * @param bool $ismycourse
2357 * @return navigation_node
2359 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2360 global $CFG, $SITE;
2362 // We found the course... we can return it now :)
2363 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2364 return $this->addedcourses[$course->id];
2367 $coursecontext = context_course::instance($course->id);
2369 if ($course->id != $SITE->id && !$course->visible) {
2370 if (is_role_switched($course->id)) {
2371 // user has to be able to access course in order to switch, let's skip the visibility test here
2372 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2373 return false;
2377 $issite = ($course->id == $SITE->id);
2378 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2380 if ($issite) {
2381 $parent = $this;
2382 $url = null;
2383 if (empty($CFG->usesitenameforsitepages)) {
2384 $shortname = get_string('sitepages');
2386 } else if ($coursetype == self::COURSE_CURRENT) {
2387 $parent = $this->rootnodes['currentcourse'];
2388 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2389 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2390 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_CATEGORY))) {
2391 // Nothing to do here the above statement set $parent to the category within mycourses.
2392 } else {
2393 $parent = $this->rootnodes['mycourses'];
2395 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2396 } else {
2397 $parent = $this->rootnodes['courses'];
2398 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2399 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2400 if (!$this->is_category_fully_loaded($course->category)) {
2401 // We need to load the category structure for this course
2402 $this->load_all_categories($course->category, false);
2404 if (array_key_exists($course->category, $this->addedcategories)) {
2405 $parent = $this->addedcategories[$course->category];
2406 // This could lead to the course being created so we should check whether it is the case again
2407 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2408 return $this->addedcourses[$course->id];
2414 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
2415 $coursenode->nodetype = self::NODETYPE_BRANCH;
2416 $coursenode->hidden = (!$course->visible);
2417 $coursenode->title(format_string($course->fullname, true, array('context' => context_course::instance($course->id))));
2418 if (!$forcegeneric) {
2419 $this->addedcourses[$course->id] = $coursenode;
2422 return $coursenode;
2426 * Returns true if the category has already been loaded as have any child categories
2428 * @param int $categoryid
2429 * @return bool
2431 protected function is_category_fully_loaded($categoryid) {
2432 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2436 * Adds essential course nodes to the navigation for the given course.
2438 * This method adds nodes such as reports, blogs and participants
2440 * @param navigation_node $coursenode
2441 * @param stdClass $course
2442 * @return bool returns true on successful addition of a node.
2444 public function add_course_essentials($coursenode, stdClass $course) {
2445 global $CFG, $SITE;
2447 if ($course->id == $SITE->id) {
2448 return $this->add_front_page_course_essentials($coursenode, $course);
2451 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2452 return true;
2455 //Participants
2456 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2457 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2458 $currentgroup = groups_get_course_group($course, true);
2459 if ($course->id == $SITE->id) {
2460 $filterselect = '';
2461 } else if ($course->id && !$currentgroup) {
2462 $filterselect = $course->id;
2463 } else {
2464 $filterselect = $currentgroup;
2466 $filterselect = clean_param($filterselect, PARAM_INT);
2467 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2468 and has_capability('moodle/blog:view', context_system::instance())) {
2469 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2470 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2472 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2473 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2475 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2476 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2479 // View course reports
2480 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2481 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2482 $coursereports = get_plugin_list('coursereport'); // deprecated
2483 foreach ($coursereports as $report=>$dir) {
2484 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2485 if (file_exists($libfile)) {
2486 require_once($libfile);
2487 $reportfunction = $report.'_report_extend_navigation';
2488 if (function_exists($report.'_report_extend_navigation')) {
2489 $reportfunction($reportnav, $course, $this->page->context);
2494 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2495 foreach ($reports as $reportfunction) {
2496 $reportfunction($reportnav, $course, $this->page->context);
2499 return true;
2502 * This generates the structure of the course that won't be generated when
2503 * the modules and sections are added.
2505 * Things such as the reports branch, the participants branch, blogs... get
2506 * added to the course node by this method.
2508 * @param navigation_node $coursenode
2509 * @param stdClass $course
2510 * @return bool True for successfull generation
2512 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2513 global $CFG;
2515 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2516 return true;
2519 // Hidden node that we use to determine if the front page navigation is loaded.
2520 // This required as there are not other guaranteed nodes that may be loaded.
2521 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2523 //Participants
2524 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2525 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2528 $filterselect = 0;
2530 // Blogs
2531 if (!empty($CFG->enableblogs)
2532 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2533 and has_capability('moodle/blog:view', context_system::instance())) {
2534 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2535 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2538 // Notes
2539 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2540 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2543 // Tags
2544 if (!empty($CFG->usetags) && isloggedin()) {
2545 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2548 if (isloggedin()) {
2549 // Calendar
2550 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2551 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2554 // View course reports
2555 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2556 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2557 $coursereports = get_plugin_list('coursereport'); // deprecated
2558 foreach ($coursereports as $report=>$dir) {
2559 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2560 if (file_exists($libfile)) {
2561 require_once($libfile);
2562 $reportfunction = $report.'_report_extend_navigation';
2563 if (function_exists($report.'_report_extend_navigation')) {
2564 $reportfunction($reportnav, $course, $this->page->context);
2569 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2570 foreach ($reports as $reportfunction) {
2571 $reportfunction($reportnav, $course, $this->page->context);
2574 return true;
2578 * Clears the navigation cache
2580 public function clear_cache() {
2581 $this->cache->clear();
2585 * Sets an expansion limit for the navigation
2587 * The expansion limit is used to prevent the display of content that has a type
2588 * greater than the provided $type.
2590 * Can be used to ensure things such as activities or activity content don't get
2591 * shown on the navigation.
2592 * They are still generated in order to ensure the navbar still makes sense.
2594 * @param int $type One of navigation_node::TYPE_*
2595 * @return bool true when complete.
2597 public function set_expansion_limit($type) {
2598 global $SITE;
2599 $nodes = $this->find_all_of_type($type);
2600 foreach ($nodes as &$node) {
2601 // We need to generate the full site node
2602 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2603 continue;
2605 foreach ($node->children as &$child) {
2606 // We still want to show course reports and participants containers
2607 // or there will be navigation missing.
2608 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2609 continue;
2611 $child->display = false;
2614 return true;
2617 * Attempts to get the navigation with the given key from this nodes children.
2619 * This function only looks at this nodes children, it does NOT look recursivily.
2620 * If the node can't be found then false is returned.
2622 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2624 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2625 * may be of more use to you.
2627 * @param string|int $key The key of the node you wish to receive.
2628 * @param int $type One of navigation_node::TYPE_*
2629 * @return navigation_node|false
2631 public function get($key, $type = null) {
2632 if (!$this->initialised) {
2633 $this->initialise();
2635 return parent::get($key, $type);
2639 * Searches this nodes children and their children to find a navigation node
2640 * with the matching key and type.
2642 * This method is recursive and searches children so until either a node is
2643 * found or there are no more nodes to search.
2645 * If you know that the node being searched for is a child of this node
2646 * then use the {@link global_navigation::get()} method instead.
2648 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2649 * may be of more use to you.
2651 * @param string|int $key The key of the node you wish to receive.
2652 * @param int $type One of navigation_node::TYPE_*
2653 * @return navigation_node|false
2655 public function find($key, $type) {
2656 if (!$this->initialised) {
2657 $this->initialise();
2659 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2660 return $this->rootnodes[$key];
2662 return parent::find($key, $type);
2667 * The global navigation class used especially for AJAX requests.
2669 * The primary methods that are used in the global navigation class have been overriden
2670 * to ensure that only the relevant branch is generated at the root of the tree.
2671 * This can be done because AJAX is only used when the backwards structure for the
2672 * requested branch exists.
2673 * This has been done only because it shortens the amounts of information that is generated
2674 * which of course will speed up the response time.. because no one likes laggy AJAX.
2676 * @package core
2677 * @category navigation
2678 * @copyright 2009 Sam Hemelryk
2679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2681 class global_navigation_for_ajax extends global_navigation {
2683 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2684 protected $branchtype;
2686 /** @var int the instance id */
2687 protected $instanceid;
2689 /** @var array Holds an array of expandable nodes */
2690 protected $expandable = array();
2693 * Constructs the navigation for use in an AJAX request
2695 * @param moodle_page $page moodle_page object
2696 * @param int $branchtype
2697 * @param int $id
2699 public function __construct($page, $branchtype, $id) {
2700 $this->page = $page;
2701 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2702 $this->children = new navigation_node_collection();
2703 $this->branchtype = $branchtype;
2704 $this->instanceid = $id;
2705 $this->initialise();
2708 * Initialise the navigation given the type and id for the branch to expand.
2710 * @return array An array of the expandable nodes
2712 public function initialise() {
2713 global $DB, $SITE;
2715 if ($this->initialised || during_initial_install()) {
2716 return $this->expandable;
2718 $this->initialised = true;
2720 $this->rootnodes = array();
2721 $this->rootnodes['site'] = $this->add_course($SITE);
2722 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2723 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2725 // Branchtype will be one of navigation_node::TYPE_*
2726 switch ($this->branchtype) {
2727 case 0:
2728 if ($this->instanceid === 'mycourses') {
2729 $this->load_courses_enrolled();
2730 } else if ($this->instanceid === 'courses') {
2731 $this->load_courses_other();
2733 break;
2734 case self::TYPE_CATEGORY :
2735 $this->load_category($this->instanceid);
2736 break;
2737 case self::TYPE_COURSE :
2738 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2739 require_course_login($course, true, null, false, true);
2740 $this->page->set_context(context_course::instance($course->id));
2741 $coursenode = $this->add_course($course);
2742 $this->add_course_essentials($coursenode, $course);
2743 $this->load_course_sections($course, $coursenode);
2744 break;
2745 case self::TYPE_SECTION :
2746 $sql = 'SELECT c.*, cs.section AS sectionnumber
2747 FROM {course} c
2748 LEFT JOIN {course_sections} cs ON cs.course = c.id
2749 WHERE cs.id = ?';
2750 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2751 require_course_login($course, true, null, false, true);
2752 $this->page->set_context(context_course::instance($course->id));
2753 $coursenode = $this->add_course($course);
2754 $this->add_course_essentials($coursenode, $course);
2755 $sections = $this->load_course_sections($course, $coursenode);
2756 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2757 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, $activities);
2758 break;
2759 case self::TYPE_ACTIVITY :
2760 $sql = "SELECT c.*
2761 FROM {course} c
2762 JOIN {course_modules} cm ON cm.course = c.id
2763 WHERE cm.id = :cmid";
2764 $params = array('cmid' => $this->instanceid);
2765 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2766 $modinfo = get_fast_modinfo($course);
2767 $cm = $modinfo->get_cm($this->instanceid);
2768 require_course_login($course, true, $cm, false, true);
2769 $this->page->set_context(context_module::instance($cm->id));
2770 $coursenode = $this->load_course($course);
2771 if ($course->id == $SITE->id) {
2772 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2773 } else {
2774 $sections = $this->load_course_sections($course, $coursenode);
2775 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2776 $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, $activities);
2777 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2779 break;
2780 default:
2781 throw new Exception('Unknown type');
2782 return $this->expandable;
2785 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2786 $this->load_for_user(null, true);
2789 $this->find_expandable($this->expandable);
2790 return $this->expandable;
2794 * They've expanded the 'my courses' branch.
2796 protected function load_courses_enrolled() {
2797 global $DB;
2798 $courses = enrol_get_my_courses();
2799 if ($this->show_my_categories(true)) {
2800 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2801 // In order to make sure we load everything required we must first find the categories that are not
2802 // base categories and work out the bottom category in thier path.
2803 $categoryids = array();
2804 foreach ($courses as $course) {
2805 $categoryids[] = $course->category;
2807 $categoryids = array_unique($categoryids);
2808 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2809 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2810 foreach ($categories as $category) {
2811 $bits = explode('/', trim($category->path,'/'));
2812 $categoryids[] = array_shift($bits);
2814 $categoryids = array_unique($categoryids);
2815 $categories->close();
2817 // Now we load the base categories.
2818 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2819 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2820 foreach ($categories as $category) {
2821 $this->add_category($category, $this->rootnodes['mycourses']);
2823 $categories->close();
2824 } else {
2825 foreach ($courses as $course) {
2826 $this->add_course($course, false, self::COURSE_MY);
2832 * They've expanded the general 'courses' branch.
2834 protected function load_courses_other() {
2835 $this->load_all_courses();
2839 * Loads a single category into the AJAX navigation.
2841 * This function is special in that it doesn't concern itself with the parent of
2842 * the requested category or its siblings.
2843 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2844 * request that.
2846 * @global moodle_database $DB
2847 * @param int $categoryid
2849 protected function load_category($categoryid) {
2850 global $CFG, $DB;
2852 $limit = 20;
2853 if (!empty($CFG->navcourselimit)) {
2854 $limit = (int)$CFG->navcourselimit;
2857 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2858 $sql = "SELECT cc.*, $catcontextsql
2859 FROM {course_categories} cc
2860 JOIN {context} ctx ON cc.id = ctx.instanceid
2861 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2862 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2863 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2864 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2865 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2866 $subcategories = array();
2867 $basecategory = null;
2868 foreach ($categories as $category) {
2869 context_helper::preload_from_record($category);
2870 if ($category->id == $categoryid) {
2871 $this->add_category($category, $this);
2872 $basecategory = $this->addedcategories[$category->id];
2873 } else {
2874 $subcategories[] = $category;
2877 $categories->close();
2879 if (!is_null($basecategory)) {
2880 foreach ($subcategories as $category) {
2881 $this->add_category($category, $basecategory);
2885 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2886 foreach ($courses as $course) {
2887 $this->add_course($course);
2889 $courses->close();
2893 * Returns an array of expandable nodes
2894 * @return array
2896 public function get_expandable() {
2897 return $this->expandable;
2902 * Navbar class
2904 * This class is used to manage the navbar, which is initialised from the navigation
2905 * object held by PAGE
2907 * @package core
2908 * @category navigation
2909 * @copyright 2009 Sam Hemelryk
2910 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2912 class navbar extends navigation_node {
2913 /** @var bool A switch for whether the navbar is initialised or not */
2914 protected $initialised = false;
2915 /** @var mixed keys used to reference the nodes on the navbar */
2916 protected $keys = array();
2917 /** @var null|string content of the navbar */
2918 protected $content = null;
2919 /** @var moodle_page object the moodle page that this navbar belongs to */
2920 protected $page;
2921 /** @var bool A switch for whether to ignore the active navigation information */
2922 protected $ignoreactive = false;
2923 /** @var bool A switch to let us know if we are in the middle of an install */
2924 protected $duringinstall = false;
2925 /** @var bool A switch for whether the navbar has items */
2926 protected $hasitems = false;
2927 /** @var array An array of navigation nodes for the navbar */
2928 protected $items;
2929 /** @var array An array of child node objects */
2930 public $children = array();
2931 /** @var bool A switch for whether we want to include the root node in the navbar */
2932 public $includesettingsbase = false;
2934 * The almighty constructor
2936 * @param moodle_page $page
2938 public function __construct(moodle_page $page) {
2939 global $CFG;
2940 if (during_initial_install()) {
2941 $this->duringinstall = true;
2942 return false;
2944 $this->page = $page;
2945 $this->text = get_string('home');
2946 $this->shorttext = get_string('home');
2947 $this->action = new moodle_url($CFG->wwwroot);
2948 $this->nodetype = self::NODETYPE_BRANCH;
2949 $this->type = self::TYPE_SYSTEM;
2953 * Quick check to see if the navbar will have items in.
2955 * @return bool Returns true if the navbar will have items, false otherwise
2957 public function has_items() {
2958 if ($this->duringinstall) {
2959 return false;
2960 } else if ($this->hasitems !== false) {
2961 return true;
2963 $this->page->navigation->initialise($this->page);
2965 $activenodefound = ($this->page->navigation->contains_active_node() ||
2966 $this->page->settingsnav->contains_active_node());
2968 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2969 $this->hasitems = $outcome;
2970 return $outcome;
2974 * Turn on/off ignore active
2976 * @param bool $setting
2978 public function ignore_active($setting=true) {
2979 $this->ignoreactive = ($setting);
2983 * Gets a navigation node
2985 * @param string|int $key for referencing the navbar nodes
2986 * @param int $type navigation_node::TYPE_*
2987 * @return navigation_node|bool
2989 public function get($key, $type = null) {
2990 foreach ($this->children as &$child) {
2991 if ($child->key === $key && ($type == null || $type == $child->type)) {
2992 return $child;
2995 return false;
2998 * Returns an array of navigation_node's that make up the navbar.
3000 * @return array
3002 public function get_items() {
3003 $items = array();
3004 // Make sure that navigation is initialised
3005 if (!$this->has_items()) {
3006 return $items;
3008 if ($this->items !== null) {
3009 return $this->items;
3012 if (count($this->children) > 0) {
3013 // Add the custom children
3014 $items = array_reverse($this->children);
3017 $navigationactivenode = $this->page->navigation->find_active_node();
3018 $settingsactivenode = $this->page->settingsnav->find_active_node();
3020 // Check if navigation contains the active node
3021 if (!$this->ignoreactive) {
3023 if ($navigationactivenode && $settingsactivenode) {
3024 // Parse a combined navigation tree
3025 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3026 if (!$settingsactivenode->mainnavonly) {
3027 $items[] = $settingsactivenode;
3029 $settingsactivenode = $settingsactivenode->parent;
3031 if (!$this->includesettingsbase) {
3032 // Removes the first node from the settings (root node) from the list
3033 array_pop($items);
3035 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3036 if (!$navigationactivenode->mainnavonly) {
3037 $items[] = $navigationactivenode;
3039 $navigationactivenode = $navigationactivenode->parent;
3041 } else if ($navigationactivenode) {
3042 // Parse the navigation tree to get the active node
3043 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3044 if (!$navigationactivenode->mainnavonly) {
3045 $items[] = $navigationactivenode;
3047 $navigationactivenode = $navigationactivenode->parent;
3049 } else if ($settingsactivenode) {
3050 // Parse the settings navigation to get the active node
3051 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3052 if (!$settingsactivenode->mainnavonly) {
3053 $items[] = $settingsactivenode;
3055 $settingsactivenode = $settingsactivenode->parent;
3060 $items[] = new navigation_node(array(
3061 'text'=>$this->page->navigation->text,
3062 'shorttext'=>$this->page->navigation->shorttext,
3063 'key'=>$this->page->navigation->key,
3064 'action'=>$this->page->navigation->action
3067 $this->items = array_reverse($items);
3068 return $this->items;
3072 * Add a new navigation_node to the navbar, overrides parent::add
3074 * This function overrides {@link navigation_node::add()} so that we can change
3075 * the way nodes get added to allow us to simply call add and have the node added to the
3076 * end of the navbar
3078 * @param string $text
3079 * @param string|moodle_url|action_link $action An action to associate with this node.
3080 * @param int $type One of navigation_node::TYPE_*
3081 * @param string $shorttext
3082 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3083 * @param pix_icon $icon An optional icon to use for this node.
3084 * @return navigation_node
3086 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3087 if ($this->content !== null) {
3088 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3091 // Properties array used when creating the new navigation node
3092 $itemarray = array(
3093 'text' => $text,
3094 'type' => $type
3096 // Set the action if one was provided
3097 if ($action!==null) {
3098 $itemarray['action'] = $action;
3100 // Set the shorttext if one was provided
3101 if ($shorttext!==null) {
3102 $itemarray['shorttext'] = $shorttext;
3104 // Set the icon if one was provided
3105 if ($icon!==null) {
3106 $itemarray['icon'] = $icon;
3108 // Default the key to the number of children if not provided
3109 if ($key === null) {
3110 $key = count($this->children);
3112 // Set the key
3113 $itemarray['key'] = $key;
3114 // Set the parent to this node
3115 $itemarray['parent'] = $this;
3116 // Add the child using the navigation_node_collections add method
3117 $this->children[] = new navigation_node($itemarray);
3118 return $this;
3123 * Class used to manage the settings option for the current page
3125 * This class is used to manage the settings options in a tree format (recursively)
3126 * and was created initially for use with the settings blocks.
3128 * @package core
3129 * @category navigation
3130 * @copyright 2009 Sam Hemelryk
3131 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3133 class settings_navigation extends navigation_node {
3134 /** @var stdClass the current context */
3135 protected $context;
3136 /** @var moodle_page the moodle page that the navigation belongs to */
3137 protected $page;
3138 /** @var string contains administration section navigation_nodes */
3139 protected $adminsection;
3140 /** @var bool A switch to see if the navigation node is initialised */
3141 protected $initialised = false;
3142 /** @var array An array of users that the nodes can extend for. */
3143 protected $userstoextendfor = array();
3144 /** @var navigation_cache **/
3145 protected $cache;
3148 * Sets up the object with basic settings and preparse it for use
3150 * @param moodle_page $page
3152 public function __construct(moodle_page &$page) {
3153 if (during_initial_install()) {
3154 return false;
3156 $this->page = $page;
3157 // Initialise the main navigation. It is most important that this is done
3158 // before we try anything
3159 $this->page->navigation->initialise();
3160 // Initialise the navigation cache
3161 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3162 $this->children = new navigation_node_collection();
3165 * Initialise the settings navigation based on the current context
3167 * This function initialises the settings navigation tree for a given context
3168 * by calling supporting functions to generate major parts of the tree.
3171 public function initialise() {
3172 global $DB, $SESSION, $SITE;
3174 if (during_initial_install()) {
3175 return false;
3176 } else if ($this->initialised) {
3177 return true;
3179 $this->id = 'settingsnav';
3180 $this->context = $this->page->context;
3182 $context = $this->context;
3183 if ($context->contextlevel == CONTEXT_BLOCK) {
3184 $this->load_block_settings();
3185 $context = $context->get_parent_context();
3188 switch ($context->contextlevel) {
3189 case CONTEXT_SYSTEM:
3190 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3191 $this->load_front_page_settings(($context->id == $this->context->id));
3193 break;
3194 case CONTEXT_COURSECAT:
3195 $this->load_category_settings();
3196 break;
3197 case CONTEXT_COURSE:
3198 if ($this->page->course->id != $SITE->id) {
3199 $this->load_course_settings(($context->id == $this->context->id));
3200 } else {
3201 $this->load_front_page_settings(($context->id == $this->context->id));
3203 break;
3204 case CONTEXT_MODULE:
3205 $this->load_module_settings();
3206 $this->load_course_settings();
3207 break;
3208 case CONTEXT_USER:
3209 if ($this->page->course->id != $SITE->id) {
3210 $this->load_course_settings();
3212 break;
3215 $settings = $this->load_user_settings($this->page->course->id);
3217 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
3218 $admin = $this->load_administration_settings();
3219 $SESSION->load_navigation_admin = ($admin->has_children());
3220 } else {
3221 $admin = false;
3224 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
3225 $admin->force_open();
3226 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
3227 $settings->force_open();
3230 // Check if the user is currently logged in as another user
3231 if (session_is_loggedinas()) {
3232 // Get the actual user, we need this so we can display an informative return link
3233 $realuser = session_get_realuser();
3234 // Add the informative return to original user link
3235 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3236 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3239 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3240 $this->load_local_plugin_settings();
3242 foreach ($this->children as $key=>$node) {
3243 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3244 $node->remove();
3247 $this->initialised = true;
3250 * Override the parent function so that we can add preceeding hr's and set a
3251 * root node class against all first level element
3253 * It does this by first calling the parent's add method {@link navigation_node::add()}
3254 * and then proceeds to use the key to set class and hr
3256 * @param string $text text to be used for the link.
3257 * @param string|moodle_url $url url for the new node
3258 * @param int $type the type of node navigation_node::TYPE_*
3259 * @param string $shorttext
3260 * @param string|int $key a key to access the node by.
3261 * @param pix_icon $icon An icon that appears next to the node.
3262 * @return navigation_node with the new node added to it.
3264 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3265 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3266 $node->add_class('root_node');
3267 return $node;
3271 * This function allows the user to add something to the start of the settings
3272 * navigation, which means it will be at the top of the settings navigation block
3274 * @param string $text text to be used for the link.
3275 * @param string|moodle_url $url url for the new node
3276 * @param int $type the type of node navigation_node::TYPE_*
3277 * @param string $shorttext
3278 * @param string|int $key a key to access the node by.
3279 * @param pix_icon $icon An icon that appears next to the node.
3280 * @return navigation_node $node with the new node added to it.
3282 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3283 $children = $this->children;
3284 $childrenclass = get_class($children);
3285 $this->children = new $childrenclass;
3286 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3287 foreach ($children as $child) {
3288 $this->children->add($child);
3290 return $node;
3293 * Load the site administration tree
3295 * This function loads the site administration tree by using the lib/adminlib library functions
3297 * @param navigation_node $referencebranch A reference to a branch in the settings
3298 * navigation tree
3299 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3300 * tree and start at the beginning
3301 * @return mixed A key to access the admin tree by
3303 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3304 global $CFG;
3306 // Check if we are just starting to generate this navigation.
3307 if ($referencebranch === null) {
3309 // Require the admin lib then get an admin structure
3310 if (!function_exists('admin_get_root')) {
3311 require_once($CFG->dirroot.'/lib/adminlib.php');
3313 $adminroot = admin_get_root(false, false);
3314 // This is the active section identifier
3315 $this->adminsection = $this->page->url->param('section');
3317 // Disable the navigation from automatically finding the active node
3318 navigation_node::$autofindactive = false;
3319 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
3320 foreach ($adminroot->children as $adminbranch) {
3321 $this->load_administration_settings($referencebranch, $adminbranch);
3323 navigation_node::$autofindactive = true;
3325 // Use the admin structure to locate the active page
3326 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3327 $currentnode = $this;
3328 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3329 $currentnode = $currentnode->get($pathkey);
3331 if ($currentnode) {
3332 $currentnode->make_active();
3334 } else {
3335 $this->scan_for_active_node($referencebranch);
3337 return $referencebranch;
3338 } else if ($adminbranch->check_access()) {
3339 // We have a reference branch that we can access and is not hidden `hurrah`
3340 // Now we need to display it and any children it may have
3341 $url = null;
3342 $icon = null;
3343 if ($adminbranch instanceof admin_settingpage) {
3344 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3345 } else if ($adminbranch instanceof admin_externalpage) {
3346 $url = $adminbranch->url;
3347 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3348 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3351 // Add the branch
3352 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3354 if ($adminbranch->is_hidden()) {
3355 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3356 $reference->add_class('hidden');
3357 } else {
3358 $reference->display = false;
3362 // Check if we are generating the admin notifications and whether notificiations exist
3363 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3364 $reference->add_class('criticalnotification');
3366 // Check if this branch has children
3367 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3368 foreach ($adminbranch->children as $branch) {
3369 // Generate the child branches as well now using this branch as the reference
3370 $this->load_administration_settings($reference, $branch);
3372 } else {
3373 $reference->icon = new pix_icon('i/settings', '');
3379 * This function recursivily scans nodes until it finds the active node or there
3380 * are no more nodes.
3381 * @param navigation_node $node
3383 protected function scan_for_active_node(navigation_node $node) {
3384 if (!$node->check_if_active() && $node->children->count()>0) {
3385 foreach ($node->children as &$child) {
3386 $this->scan_for_active_node($child);
3392 * Gets a navigation node given an array of keys that represent the path to
3393 * the desired node.
3395 * @param array $path
3396 * @return navigation_node|false
3398 protected function get_by_path(array $path) {
3399 $node = $this->get(array_shift($path));
3400 foreach ($path as $key) {
3401 $node->get($key);
3403 return $node;
3407 * Generate the list of modules for the given course.
3409 * @param stdClass $course The course to get modules for
3411 protected function get_course_modules($course) {
3412 global $CFG;
3413 // This function is included when we include course/lib.php at the top
3414 // of this file
3415 $modnames = get_module_types_names();
3416 $resources = array();
3417 $activities = array();
3418 foreach($modnames as $modname=>$modnamestr) {
3419 if (!course_allowed_module($course, $modname)) {
3420 continue;
3423 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3424 if (!file_exists($libfile)) {
3425 continue;
3427 include_once($libfile);
3428 $gettypesfunc = $modname.'_get_types';
3429 if (function_exists($gettypesfunc)) {
3430 $types = $gettypesfunc();
3431 foreach($types as $type) {
3432 if (!isset($type->modclass) || !isset($type->typestr)) {
3433 debugging('Incorrect activity type in '.$modname);
3434 continue;
3436 if ($type->modclass == MOD_CLASS_RESOURCE) {
3437 $resources[html_entity_decode($type->type)] = $type->typestr;
3438 } else {
3439 $activities[html_entity_decode($type->type)] = $type->typestr;
3442 } else {
3443 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3444 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
3445 $resources[$modname] = $modnamestr;
3446 } else {
3447 // all other archetypes are considered activity
3448 $activities[$modname] = $modnamestr;
3452 return array($resources, $activities);
3456 * This function loads the course settings that are available for the user
3458 * @param bool $forceopen If set to true the course node will be forced open
3459 * @return navigation_node|false
3461 protected function load_course_settings($forceopen = false) {
3462 global $CFG;
3464 $course = $this->page->course;
3465 $coursecontext = context_course::instance($course->id);
3467 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3469 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3470 if ($forceopen) {
3471 $coursenode->force_open();
3474 if (has_capability('moodle/course:update', $coursecontext)) {
3475 // Add the turn on/off settings
3477 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3478 // We are on the course page, retain the current page params e.g. section.
3479 $baseurl = clone($this->page->url);
3480 $baseurl->param('sesskey', sesskey());
3481 } else {
3482 // Edit on the main course page.
3483 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3486 $editurl = clone($baseurl);
3487 if ($this->page->user_is_editing()) {
3488 $editurl->param('edit', 'off');
3489 $editstring = get_string('turneditingoff');
3490 } else {
3491 $editurl->param('edit', 'on');
3492 $editstring = get_string('turneditingon');
3494 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3496 // Add the module chooser toggle
3497 $modchoosertoggleurl = clone($baseurl);
3498 if ($this->page->user_is_editing() && course_ajax_enabled($course)) {
3499 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
3500 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
3501 $modchoosertoggleurl->param('modchooser', 'off');
3502 } else {
3503 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
3504 $modchoosertoggleurl->param('modchooser', 'on');
3506 $modchoosertoggle = $coursenode->add($modchoosertogglestring, $modchoosertoggleurl, self::TYPE_SETTING);
3507 $modchoosertoggle->add_class('modchoosertoggle');
3508 $modchoosertoggle->add_class('visibleifjs');
3509 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
3512 // Add the course settings link
3513 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3514 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3516 // Add the course completion settings link
3517 if ($CFG->enablecompletion && $course->enablecompletion) {
3518 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3519 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3523 // add enrol nodes
3524 enrol_add_course_navigation($coursenode, $course);
3526 // Manage filters
3527 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3528 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3529 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3532 // Add view grade report is permitted
3533 $reportavailable = false;
3534 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3535 $reportavailable = true;
3536 } else if (!empty($course->showgrades)) {
3537 $reports = get_plugin_list('gradereport');
3538 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3539 arsort($reports); // user is last, we want to test it first
3540 foreach ($reports as $plugin => $plugindir) {
3541 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3542 //stop when the first visible plugin is found
3543 $reportavailable = true;
3544 break;
3549 if ($reportavailable) {
3550 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3551 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3554 // Add outcome if permitted
3555 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3556 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3557 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3560 // Backup this course
3561 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3562 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3563 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3566 // Restore to this course
3567 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3568 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3569 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3572 // Import data from other courses
3573 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3574 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3575 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
3578 // Publish course on a hub
3579 if (has_capability('moodle/course:publish', $coursecontext)) {
3580 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3581 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3584 // Reset this course
3585 if (has_capability('moodle/course:reset', $coursecontext)) {
3586 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3587 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3590 // Questions
3591 require_once($CFG->libdir . '/questionlib.php');
3592 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3594 if (has_capability('moodle/course:update', $coursecontext)) {
3595 // Repository Instances
3596 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3597 require_once($CFG->dirroot . '/repository/lib.php');
3598 $editabletypes = repository::get_editable_types($coursecontext);
3599 $haseditabletypes = !empty($editabletypes);
3600 unset($editabletypes);
3601 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3602 } else {
3603 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3605 if ($haseditabletypes) {
3606 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3607 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3611 // Manage files
3612 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3613 // hidden in new courses and courses where legacy files were turned off
3614 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3615 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
3619 // Switch roles
3620 $roles = array();
3621 $assumedrole = $this->in_alternative_role();
3622 if ($assumedrole !== false) {
3623 $roles[0] = get_string('switchrolereturn');
3625 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3626 $availableroles = get_switchable_roles($coursecontext);
3627 if (is_array($availableroles)) {
3628 foreach ($availableroles as $key=>$role) {
3629 if ($assumedrole == (int)$key) {
3630 continue;
3632 $roles[$key] = $role;
3636 if (is_array($roles) && count($roles)>0) {
3637 $switchroles = $this->add(get_string('switchroleto'));
3638 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3639 $switchroles->force_open();
3641 $returnurl = $this->page->url;
3642 $returnurl->param('sesskey', sesskey());
3643 foreach ($roles as $key => $name) {
3644 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3645 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
3648 // Return we are done
3649 return $coursenode;
3653 * This function calls the module function to inject module settings into the
3654 * settings navigation tree.
3656 * This only gets called if there is a corrosponding function in the modules
3657 * lib file.
3659 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3661 * @return navigation_node|false
3663 protected function load_module_settings() {
3664 global $CFG;
3666 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3667 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3668 $this->page->set_cm($cm, $this->page->course);
3671 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3672 if (file_exists($file)) {
3673 require_once($file);
3676 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3677 $modulenode->force_open();
3679 // Settings for the module
3680 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3681 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3682 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3684 // Assign local roles
3685 if (count(get_assignable_roles($this->page->cm->context))>0) {
3686 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3687 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3689 // Override roles
3690 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3691 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3692 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3694 // Check role permissions
3695 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3696 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3697 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3699 // Manage filters
3700 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3701 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3702 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3704 // Add reports
3705 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3706 foreach ($reports as $reportfunction) {
3707 $reportfunction($modulenode, $this->page->cm);
3709 // Add a backup link
3710 $featuresfunc = $this->page->activityname.'_supports';
3711 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3712 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3713 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3716 // Restore this activity
3717 $featuresfunc = $this->page->activityname.'_supports';
3718 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3719 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3720 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3723 // Allow the active advanced grading method plugin to append its settings
3724 $featuresfunc = $this->page->activityname.'_supports';
3725 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3726 require_once($CFG->dirroot.'/grade/grading/lib.php');
3727 $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
3728 $gradingman->extend_settings_navigation($this, $modulenode);
3731 $function = $this->page->activityname.'_extend_settings_navigation';
3732 if (!function_exists($function)) {
3733 return $modulenode;
3736 $function($this, $modulenode);
3738 // Remove the module node if there are no children
3739 if (empty($modulenode->children)) {
3740 $modulenode->remove();
3743 return $modulenode;
3747 * Loads the user settings block of the settings nav
3749 * This function is simply works out the userid and whether we need to load
3750 * just the current users profile settings, or the current user and the user the
3751 * current user is viewing.
3753 * This function has some very ugly code to work out the user, if anyone has
3754 * any bright ideas please feel free to intervene.
3756 * @param int $courseid The course id of the current course
3757 * @return navigation_node|false
3759 protected function load_user_settings($courseid = SITEID) {
3760 global $USER, $CFG;
3762 if (isguestuser() || !isloggedin()) {
3763 return false;
3766 $navusers = $this->page->navigation->get_extending_users();
3768 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3769 $usernode = null;
3770 foreach ($this->userstoextendfor as $userid) {
3771 if ($userid == $USER->id) {
3772 continue;
3774 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3775 if (is_null($usernode)) {
3776 $usernode = $node;
3779 foreach ($navusers as $user) {
3780 if ($user->id == $USER->id) {
3781 continue;
3783 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3784 if (is_null($usernode)) {
3785 $usernode = $node;
3788 $this->generate_user_settings($courseid, $USER->id);
3789 } else {
3790 $usernode = $this->generate_user_settings($courseid, $USER->id);
3792 return $usernode;
3796 * Extends the settings navigation for the given user.
3798 * Note: This method gets called automatically if you call
3799 * $PAGE->navigation->extend_for_user($userid)
3801 * @param int $userid
3803 public function extend_for_user($userid) {
3804 global $CFG;
3806 if (!in_array($userid, $this->userstoextendfor)) {
3807 $this->userstoextendfor[] = $userid;
3808 if ($this->initialised) {
3809 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3810 $children = array();
3811 foreach ($this->children as $child) {
3812 $children[] = $child;
3814 array_unshift($children, array_pop($children));
3815 $this->children = new navigation_node_collection();
3816 foreach ($children as $child) {
3817 $this->children->add($child);
3824 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3825 * what can be shown/done
3827 * @param int $courseid The current course' id
3828 * @param int $userid The user id to load for
3829 * @param string $gstitle The string to pass to get_string for the branch title
3830 * @return navigation_node|false
3832 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3833 global $DB, $CFG, $USER, $SITE;
3835 if ($courseid != $SITE->id) {
3836 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3837 $course = $this->page->course;
3838 } else {
3839 $select = context_helper::get_preload_record_columns_sql('ctx');
3840 $sql = "SELECT c.*, $select
3841 FROM {course} c
3842 JOIN {context} ctx ON c.id = ctx.instanceid
3843 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
3844 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
3845 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3846 context_helper::preload_from_record($course);
3848 } else {
3849 $course = $SITE;
3852 $coursecontext = context_course::instance($course->id); // Course context
3853 $systemcontext = get_system_context();
3854 $currentuser = ($USER->id == $userid);
3856 if ($currentuser) {
3857 $user = $USER;
3858 $usercontext = context_user::instance($user->id); // User context
3859 } else {
3860 $select = context_helper::get_preload_record_columns_sql('ctx');
3861 $sql = "SELECT u.*, $select
3862 FROM {user} u
3863 JOIN {context} ctx ON u.id = ctx.instanceid
3864 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
3865 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
3866 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
3867 if (!$user) {
3868 return false;
3870 context_helper::preload_from_record($user);
3872 // Check that the user can view the profile
3873 $usercontext = context_user::instance($user->id); // User context
3874 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3876 if ($course->id == $SITE->id) {
3877 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
3878 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3879 return false;
3881 } else {
3882 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
3883 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
3884 if ((!$canviewusercourse && !$canviewuser) || !can_access_course($course, $user->id)) {
3885 return false;
3887 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
3888 // If groups are in use, make sure we can see that group
3889 return false;
3894 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3896 $key = $gstitle;
3897 if ($gstitle != 'usercurrentsettings') {
3898 $key .= $userid;
3901 // Add a user setting branch
3902 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3903 $usersetting->id = 'usersettings';
3904 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3905 // Automatically start by making it active
3906 $usersetting->make_active();
3909 // Check if the user has been deleted
3910 if ($user->deleted) {
3911 if (!has_capability('moodle/user:update', $coursecontext)) {
3912 // We can't edit the user so just show the user deleted message
3913 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3914 } else {
3915 // We can edit the user so show the user deleted message and link it to the profile
3916 if ($course->id == $SITE->id) {
3917 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3918 } else {
3919 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3921 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3923 return true;
3926 $userauthplugin = false;
3927 if (!empty($user->auth)) {
3928 $userauthplugin = get_auth_plugin($user->auth);
3931 // Add the profile edit link
3932 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3933 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3934 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3935 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3936 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3937 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
3938 $url = $userauthplugin->edit_profile_url();
3939 if (empty($url)) {
3940 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3942 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3947 // Change password link
3948 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
3949 $passwordchangeurl = $userauthplugin->change_password_url();
3950 if (empty($passwordchangeurl)) {
3951 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3953 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3956 // View the roles settings
3957 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3958 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3960 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3961 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3963 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3965 if (!empty($assignableroles)) {
3966 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3967 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3970 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3971 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3972 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3975 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3976 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3979 // Portfolio
3980 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3981 require_once($CFG->libdir . '/portfoliolib.php');
3982 if (portfolio_instances(true, false)) {
3983 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3985 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3986 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
3988 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
3989 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
3993 $enablemanagetokens = false;
3994 if (!empty($CFG->enablerssfeeds)) {
3995 $enablemanagetokens = true;
3996 } else if (!is_siteadmin($USER->id)
3997 && !empty($CFG->enablewebservices)
3998 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3999 $enablemanagetokens = true;
4001 // Security keys
4002 if ($currentuser && $enablemanagetokens) {
4003 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4004 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4007 // Repository
4008 if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
4009 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
4010 require_once($CFG->dirroot . '/repository/lib.php');
4011 $editabletypes = repository::get_editable_types($usercontext);
4012 $haseditabletypes = !empty($editabletypes);
4013 unset($editabletypes);
4014 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
4015 } else {
4016 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
4018 if ($haseditabletypes) {
4019 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
4020 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
4024 // Messaging
4025 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4026 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4027 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
4030 // Blogs
4031 if ($currentuser && !empty($CFG->enableblogs)) {
4032 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4033 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
4034 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
4035 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
4036 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
4040 // Login as ...
4041 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
4042 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
4043 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
4046 return $usersetting;
4050 * Loads block specific settings in the navigation
4052 * @return navigation_node
4054 protected function load_block_settings() {
4055 global $CFG;
4057 $blocknode = $this->add(print_context_name($this->context));
4058 $blocknode->force_open();
4060 // Assign local roles
4061 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4062 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4064 // Override roles
4065 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4066 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4067 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4069 // Check role permissions
4070 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4071 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4072 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4075 return $blocknode;
4079 * Loads category specific settings in the navigation
4081 * @return navigation_node
4083 protected function load_category_settings() {
4084 global $CFG;
4086 $categorynode = $this->add(print_context_name($this->context));
4087 $categorynode->force_open();
4089 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context)) {
4090 $url = new moodle_url('/course/category.php', array('id'=>$this->context->instanceid, 'sesskey'=>sesskey()));
4091 if ($this->page->user_is_editing()) {
4092 $url->param('categoryedit', '0');
4093 $editstring = get_string('turneditingoff');
4094 } else {
4095 $url->param('categoryedit', '1');
4096 $editstring = get_string('turneditingon');
4098 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4101 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
4102 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
4103 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4105 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
4106 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4109 // Assign local roles
4110 if (has_capability('moodle/role:assign', $this->context)) {
4111 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4112 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
4115 // Override roles
4116 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4117 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4118 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4120 // Check role permissions
4121 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4122 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4123 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4126 // Cohorts
4127 if (has_capability('moodle/cohort:manage', $this->context) or has_capability('moodle/cohort:view', $this->context)) {
4128 $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', ''));
4131 // Manage filters
4132 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
4133 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
4134 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4137 return $categorynode;
4141 * Determine whether the user is assuming another role
4143 * This function checks to see if the user is assuming another role by means of
4144 * role switching. In doing this we compare each RSW key (context path) against
4145 * the current context path. This ensures that we can provide the switching
4146 * options against both the course and any page shown under the course.
4148 * @return bool|int The role(int) if the user is in another role, false otherwise
4150 protected function in_alternative_role() {
4151 global $USER;
4152 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4153 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4154 return $USER->access['rsw'][$this->page->context->path];
4156 foreach ($USER->access['rsw'] as $key=>$role) {
4157 if (strpos($this->context->path,$key)===0) {
4158 return $role;
4162 return false;
4166 * This function loads all of the front page settings into the settings navigation.
4167 * This function is called when the user is on the front page, or $COURSE==$SITE
4168 * @param bool $forceopen (optional)
4169 * @return navigation_node
4171 protected function load_front_page_settings($forceopen = false) {
4172 global $SITE, $CFG;
4174 $course = clone($SITE);
4175 $coursecontext = context_course::instance($course->id); // Course context
4177 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4178 if ($forceopen) {
4179 $frontpage->force_open();
4181 $frontpage->id = 'frontpagesettings';
4183 if (has_capability('moodle/course:update', $coursecontext)) {
4185 // Add the turn on/off settings
4186 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4187 if ($this->page->user_is_editing()) {
4188 $url->param('edit', 'off');
4189 $editstring = get_string('turneditingoff');
4190 } else {
4191 $url->param('edit', 'on');
4192 $editstring = get_string('turneditingon');
4194 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4196 // Add the course settings link
4197 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4198 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4201 // add enrol nodes
4202 enrol_add_course_navigation($frontpage, $course);
4204 // Manage filters
4205 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4206 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4207 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4210 // Backup this course
4211 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4212 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4213 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4216 // Restore to this course
4217 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4218 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4219 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4222 // Questions
4223 require_once($CFG->libdir . '/questionlib.php');
4224 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4226 // Manage files
4227 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4228 //hiden in new installs
4229 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
4230 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
4232 return $frontpage;
4236 * This function gives local plugins an opportunity to modify the settings navigation.
4238 protected function load_local_plugin_settings() {
4239 // Get all local plugins with an extend_settings_navigation function in their lib.php file
4240 foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
4241 // Call each function providing this (the settings navigation) and the current context.
4242 $function($this, $this->context);
4247 * This function marks the cache as volatile so it is cleared during shutdown
4249 public function clear_cache() {
4250 $this->cache->volatile();
4255 * Simple class used to output a navigation branch in XML
4257 * @package core
4258 * @category navigation
4259 * @copyright 2009 Sam Hemelryk
4260 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4262 class navigation_json {
4263 /** @var array An array of different node types */
4264 protected $nodetype = array('node','branch');
4265 /** @var array An array of node keys and types */
4266 protected $expandable = array();
4268 * Turns a branch and all of its children into XML
4270 * @param navigation_node $branch
4271 * @return string XML string
4273 public function convert($branch) {
4274 $xml = $this->convert_child($branch);
4275 return $xml;
4278 * Set the expandable items in the array so that we have enough information
4279 * to attach AJAX events
4280 * @param array $expandable
4282 public function set_expandable($expandable) {
4283 foreach ($expandable as $node) {
4284 $this->expandable[$node['key'].':'.$node['type']] = $node;
4288 * Recusively converts a child node and its children to XML for output
4290 * @param navigation_node $child The child to convert
4291 * @param int $depth Pointlessly used to track the depth of the XML structure
4292 * @return string JSON
4294 protected function convert_child($child, $depth=1) {
4295 if (!$child->display) {
4296 return '';
4298 $attributes = array();
4299 $attributes['id'] = $child->id;
4300 $attributes['name'] = $child->text;
4301 $attributes['type'] = $child->type;
4302 $attributes['key'] = $child->key;
4303 $attributes['class'] = $child->get_css_type();
4305 if ($child->icon instanceof pix_icon) {
4306 $attributes['icon'] = array(
4307 'component' => $child->icon->component,
4308 'pix' => $child->icon->pix,
4310 foreach ($child->icon->attributes as $key=>$value) {
4311 if ($key == 'class') {
4312 $attributes['icon']['classes'] = explode(' ', $value);
4313 } else if (!array_key_exists($key, $attributes['icon'])) {
4314 $attributes['icon'][$key] = $value;
4318 } else if (!empty($child->icon)) {
4319 $attributes['icon'] = (string)$child->icon;
4322 if ($child->forcetitle || $child->title !== $child->text) {
4323 $attributes['title'] = htmlentities($child->title);
4325 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4326 $attributes['expandable'] = $child->key;
4327 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4330 if (count($child->classes)>0) {
4331 $attributes['class'] .= ' '.join(' ',$child->classes);
4333 if (is_string($child->action)) {
4334 $attributes['link'] = $child->action;
4335 } else if ($child->action instanceof moodle_url) {
4336 $attributes['link'] = $child->action->out();
4337 } else if ($child->action instanceof action_link) {
4338 $attributes['link'] = $child->action->url->out();
4340 $attributes['hidden'] = ($child->hidden);
4341 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4343 if ($child->children->count() > 0) {
4344 $attributes['children'] = array();
4345 foreach ($child->children as $subchild) {
4346 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4350 if ($depth > 1) {
4351 return $attributes;
4352 } else {
4353 return json_encode($attributes);
4359 * The cache class used by global navigation and settings navigation.
4361 * It is basically an easy access point to session with a bit of smarts to make
4362 * sure that the information that is cached is valid still.
4364 * Example use:
4365 * <code php>
4366 * if (!$cache->viewdiscussion()) {
4367 * // Code to do stuff and produce cachable content
4368 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4370 * $content = $cache->viewdiscussion;
4371 * </code>
4373 * @package core
4374 * @category navigation
4375 * @copyright 2009 Sam Hemelryk
4376 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4378 class navigation_cache {
4379 /** @var int represents the time created */
4380 protected $creation;
4381 /** @var array An array of session keys */
4382 protected $session;
4384 * The string to use to segregate this particular cache. It can either be
4385 * unique to start a fresh cache or if you want to share a cache then make
4386 * it the string used in the original cache.
4387 * @var string
4389 protected $area;
4390 /** @var int a time that the information will time out */
4391 protected $timeout;
4392 /** @var stdClass The current context */
4393 protected $currentcontext;
4394 /** @var int cache time information */
4395 const CACHETIME = 0;
4396 /** @var int cache user id */
4397 const CACHEUSERID = 1;
4398 /** @var int cache value */
4399 const CACHEVALUE = 2;
4400 /** @var null|array An array of navigation cache areas to expire on shutdown */
4401 public static $volatilecaches;
4404 * Contructor for the cache. Requires two arguments
4406 * @param string $area The string to use to segregate this particular cache
4407 * it can either be unique to start a fresh cache or if you want
4408 * to share a cache then make it the string used in the original
4409 * cache
4410 * @param int $timeout The number of seconds to time the information out after
4412 public function __construct($area, $timeout=1800) {
4413 $this->creation = time();
4414 $this->area = $area;
4415 $this->timeout = time() - $timeout;
4416 if (rand(0,100) === 0) {
4417 $this->garbage_collection();
4422 * Used to set up the cache within the SESSION.
4424 * This is called for each access and ensure that we don't put anything into the session before
4425 * it is required.
4427 protected function ensure_session_cache_initialised() {
4428 global $SESSION;
4429 if (empty($this->session)) {
4430 if (!isset($SESSION->navcache)) {
4431 $SESSION->navcache = new stdClass;
4433 if (!isset($SESSION->navcache->{$this->area})) {
4434 $SESSION->navcache->{$this->area} = array();
4436 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
4441 * Magic Method to retrieve something by simply calling using = cache->key
4443 * @param mixed $key The identifier for the information you want out again
4444 * @return void|mixed Either void or what ever was put in
4446 public function __get($key) {
4447 if (!$this->cached($key)) {
4448 return;
4450 $information = $this->session[$key][self::CACHEVALUE];
4451 return unserialize($information);
4455 * Magic method that simply uses {@link set();} to store something in the cache
4457 * @param string|int $key
4458 * @param mixed $information
4460 public function __set($key, $information) {
4461 $this->set($key, $information);
4465 * Sets some information against the cache (session) for later retrieval
4467 * @param string|int $key
4468 * @param mixed $information
4470 public function set($key, $information) {
4471 global $USER;
4472 $this->ensure_session_cache_initialised();
4473 $information = serialize($information);
4474 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4477 * Check the existence of the identifier in the cache
4479 * @param string|int $key
4480 * @return bool
4482 public function cached($key) {
4483 global $USER;
4484 $this->ensure_session_cache_initialised();
4485 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) {
4486 return false;
4488 return true;
4491 * Compare something to it's equivilant in the cache
4493 * @param string $key
4494 * @param mixed $value
4495 * @param bool $serialise Whether to serialise the value before comparison
4496 * this should only be set to false if the value is already
4497 * serialised
4498 * @return bool If the value is the same false if it is not set or doesn't match
4500 public function compare($key, $value, $serialise = true) {
4501 if ($this->cached($key)) {
4502 if ($serialise) {
4503 $value = serialize($value);
4505 if ($this->session[$key][self::CACHEVALUE] === $value) {
4506 return true;
4509 return false;
4512 * Wipes the entire cache, good to force regeneration
4514 public function clear() {
4515 global $SESSION;
4516 unset($SESSION->navcache);
4517 $this->session = null;
4520 * Checks all cache entries and removes any that have expired, good ole cleanup
4522 protected function garbage_collection() {
4523 if (empty($this->session)) {
4524 return true;
4526 foreach ($this->session as $key=>$cachedinfo) {
4527 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4528 unset($this->session[$key]);
4534 * Marks the cache as being volatile (likely to change)
4536 * Any caches marked as volatile will be destroyed at the on shutdown by
4537 * {@link navigation_node::destroy_volatile_caches()} which is registered
4538 * as a shutdown function if any caches are marked as volatile.
4540 * @param bool $setting True to destroy the cache false not too
4542 public function volatile($setting = true) {
4543 if (self::$volatilecaches===null) {
4544 self::$volatilecaches = array();
4545 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4548 if ($setting) {
4549 self::$volatilecaches[$this->area] = $this->area;
4550 } else if (array_key_exists($this->area, self::$volatilecaches)) {
4551 unset(self::$volatilecaches[$this->area]);
4556 * Destroys all caches marked as volatile
4558 * This function is static and works in conjunction with the static volatilecaches
4559 * property of navigation cache.
4560 * Because this function is static it manually resets the cached areas back to an
4561 * empty array.
4563 public static function destroy_volatile_caches() {
4564 global $SESSION;
4565 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4566 foreach (self::$volatilecaches as $area) {
4567 $SESSION->navcache->{$area} = array();
4569 } else {
4570 $SESSION->navcache = new stdClass;