3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains classes used to manage the navigation structures in Moodle
20 * and was introduced as part of the changes occuring in Moodle 2.0
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 * The name that will be used to separate the navigation cache within SESSION
34 define('NAVIGATION_CACHE_NAME', 'navigation');
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
46 * @subpackage navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node implements renderable {
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF = 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH = 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN = null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE = 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM = 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY = 10;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int Setting node type, used only within settings nav 80 */
77 /** @var int Setting node type, used for containers of no importance 90 */
78 const TYPE_CONTAINER = 90;
80 /** @var int Parameter to aid the coder in tracking [optional] */
82 /** @var string|int The identifier for the node, used to retrieve the node */
84 /** @var string The text to use for the node */
86 /** @var string Short text to use if requested [optional] */
87 public $shorttext = null;
88 /** @var string The title attribute for an action if one is defined */
90 /** @var string A string that can be used to build a help button */
91 public $helpbutton = null;
92 /** @var moodle_url|action_link|null An action for the node (link) */
93 public $action = null;
94 /** @var pix_icon The path to an icon to use for this node */
96 /** @var int See TYPE_* constants defined for this class */
97 public $type = self::TYPE_UNKNOWN;
98 /** @var int See NODETYPE_* constants defined for this class */
99 public $nodetype = self::NODETYPE_LEAF;
100 /** @var bool If set to true the node will be collapsed by default */
101 public $collapse = false;
102 /** @var bool If set to true the node will be expanded by default */
103 public $forceopen = false;
104 /** @var array An array of CSS classes for the node */
105 public $classes = array();
106 /** @var navigation_node_collection An array of child nodes */
107 public $children = array();
108 /** @var bool If set to true the node will be recognised as active */
109 public $isactive = false;
110 /** @var bool If set to true the node will be dimmed */
111 public $hidden = false;
112 /** @var bool If set to false the node will not be displayed */
113 public $display = true;
114 /** @var bool If set to true then an HR will be printed before the node */
115 public $preceedwithhr = false;
116 /** @var bool If set to true the the navigation bar should ignore this node */
117 public $mainnavonly = false;
118 /** @var bool If set to true a title will be added to the action no matter what */
119 public $forcetitle = false;
120 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
121 public $parent = null;
122 /** @var bool Override to not display the icon even if one is provided **/
123 public $hideicon = false;
125 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
126 /** @var moodle_url */
127 protected static $fullmeurl = null;
128 /** @var bool toogles auto matching of active node */
129 public static $autofindactive = true;
132 * Constructs a new navigation_node
134 * @param array|string $properties Either an array of properties or a string to use
135 * as the text for the node
137 public function __construct($properties) {
138 if (is_array($properties)) {
139 // Check the array for each property that we allow to set at construction.
140 // text - The main content for the node
141 // shorttext - A short text if required for the node
142 // icon - The icon to display for the node
143 // type - The type of the node
144 // key - The key to use to identify the node
145 // parent - A reference to the nodes parent
146 // action - The action to attribute to this node, usually a URL to link to
147 if (array_key_exists('text', $properties)) {
148 $this->text = $properties['text'];
150 if (array_key_exists('shorttext', $properties)) {
151 $this->shorttext = $properties['shorttext'];
153 if (!array_key_exists('icon', $properties)) {
154 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
156 $this->icon = $properties['icon'];
157 if ($this->icon instanceof pix_icon) {
158 if (empty($this->icon->attributes['class'])) {
159 $this->icon->attributes['class'] = 'navicon';
161 $this->icon->attributes['class'] .= ' navicon';
164 if (array_key_exists('type', $properties)) {
165 $this->type = $properties['type'];
167 $this->type = self::TYPE_CUSTOM;
169 if (array_key_exists('key', $properties)) {
170 $this->key = $properties['key'];
172 // This needs to happen last because of the check_if_active call that occurs
173 if (array_key_exists('action', $properties)) {
174 $this->action = $properties['action'];
175 if (is_string($this->action)) {
176 $this->action = new moodle_url($this->action);
178 if (self::$autofindactive) {
179 $this->check_if_active();
182 if (array_key_exists('parent', $properties)) {
183 $this->set_parent($properties['parent']);
185 } else if (is_string($properties)) {
186 $this->text = $properties;
188 if ($this->text === null) {
189 throw new coding_exception('You must set the text for the node when you create it.');
191 // Default the title to the text
192 $this->title = $this->text;
193 // Instantiate a new navigation node collection for this nodes children
194 $this->children = new navigation_node_collection();
198 * Checks if this node is the active node.
200 * This is determined by comparing the action for the node against the
201 * defined URL for the page. A match will see this node marked as active.
203 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
206 public function check_if_active($strength=URL_MATCH_EXACT) {
207 global $FULLME, $PAGE;
208 // Set fullmeurl if it hasn't already been set
209 if (self::$fullmeurl == null) {
210 if ($PAGE->has_set_url()) {
211 self::override_active_url(new moodle_url($PAGE->url));
213 self::override_active_url(new moodle_url($FULLME));
217 // Compare the action of this node against the fullmeurl
218 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
219 $this->make_active();
226 * This sets the URL that the URL of new nodes get compared to when locating
229 * The active node is the node that matches the URL set here. By default this
230 * is either $PAGE->url or if that hasn't been set $FULLME.
232 * @param moodle_url $url The url to use for the fullmeurl.
234 public static function override_active_url(moodle_url $url) {
235 // Clone the URL, in case the calling script changes their URL later.
236 self::$fullmeurl = new moodle_url($url);
240 * Creates a navigation node, ready to add it as a child using add_node
241 * function. (The created node needs to be added before you can use it.)
242 * @param string $text
243 * @param moodle_url|action_link $action
245 * @param string $shorttext
246 * @param string|int $key
247 * @param pix_icon $icon
248 * @return navigation_node
250 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
251 $shorttext=null, $key=null, pix_icon $icon=null) {
252 // Properties array used when creating the new navigation node
257 // Set the action if one was provided
258 if ($action!==null) {
259 $itemarray['action'] = $action;
261 // Set the shorttext if one was provided
262 if ($shorttext!==null) {
263 $itemarray['shorttext'] = $shorttext;
265 // Set the icon if one was provided
267 $itemarray['icon'] = $icon;
270 $itemarray['key'] = $key;
271 // Construct and return
272 return new navigation_node($itemarray);
276 * Adds a navigation node as a child of this node.
278 * @param string $text
279 * @param moodle_url|action_link $action
281 * @param string $shorttext
282 * @param string|int $key
283 * @param pix_icon $icon
284 * @return navigation_node
286 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
288 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
290 // Add the child to end and return
291 return $this->add_node($childnode);
295 * Adds a navigation node as a child of this one, given a $node object
296 * created using the create function.
297 * @param navigation_node $childnode Node to add
298 * @param int|string $key The key of a node to add this before. If not
299 * specified, adds at end of list
300 * @return navigation_node The added node
302 public function add_node(navigation_node $childnode, $beforekey=null) {
303 // First convert the nodetype for this node to a branch as it will now have children
304 if ($this->nodetype !== self::NODETYPE_BRANCH) {
305 $this->nodetype = self::NODETYPE_BRANCH;
307 // Set the parent to this node
308 $childnode->set_parent($this);
310 // Default the key to the number of children if not provided
311 if ($childnode->key === null) {
312 $childnode->key = $this->children->count();
315 // Add the child using the navigation_node_collections add method
316 $node = $this->children->add($childnode, $beforekey);
318 // If added node is a category node or the user is logged in and it's a course
319 // then mark added node as a branch (makes it expandable by AJAX)
320 $type = $childnode->type;
321 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
322 $node->nodetype = self::NODETYPE_BRANCH;
324 // If this node is hidden mark it's children as hidden also
326 $node->hidden = true;
328 // Return added node (reference returned by $this->children->add()
333 * Return a list of all the keys of all the child nodes.
334 * @return array the keys.
336 public function get_children_key_list() {
337 return $this->children->get_key_list();
341 * Searches for a node of the given type with the given key.
343 * This searches this node plus all of its children, and their children....
344 * If you know the node you are looking for is a child of this node then please
345 * use the get method instead.
347 * @param int|string $key The key of the node we are looking for
348 * @param int $type One of navigation_node::TYPE_*
349 * @return navigation_node|false
351 public function find($key, $type) {
352 return $this->children->find($key, $type);
356 * Get ths child of this node that has the given key + (optional) type.
358 * If you are looking for a node and want to search all children + thier children
359 * then please use the find method instead.
361 * @param int|string $key The key of the node we are looking for
362 * @param int $type One of navigation_node::TYPE_*
363 * @return navigation_node|false
365 public function get($key, $type=null) {
366 return $this->children->get($key, $type);
374 public function remove() {
375 return $this->parent->children->remove($this->key, $this->type);
379 * Checks if this node has or could have any children
381 * @return bool Returns true if it has children or could have (by AJAX expansion)
383 public function has_children() {
384 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
388 * Marks this node as active and forces it open.
390 * Important: If you are here because you need to mark a node active to get
391 * the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
392 * You can use it to specify a different URL to match the active navigation node on
393 * rather than having to locate and manually mark a node active.
395 public function make_active() {
396 $this->isactive = true;
397 $this->add_class('active_tree_node');
399 if ($this->parent !== null) {
400 $this->parent->make_inactive();
405 * Marks a node as inactive and recusised back to the base of the tree
406 * doing the same to all parents.
408 public function make_inactive() {
409 $this->isactive = false;
410 $this->remove_class('active_tree_node');
411 if ($this->parent !== null) {
412 $this->parent->make_inactive();
417 * Forces this node to be open and at the same time forces open all
418 * parents until the root node.
422 public function force_open() {
423 $this->forceopen = true;
424 if ($this->parent !== null) {
425 $this->parent->force_open();
430 * Adds a CSS class to this node.
432 * @param string $class
435 public function add_class($class) {
436 if (!in_array($class, $this->classes)) {
437 $this->classes[] = $class;
443 * Removes a CSS class from this node.
445 * @param string $class
446 * @return bool True if the class was successfully removed.
448 public function remove_class($class) {
449 if (in_array($class, $this->classes)) {
450 $key = array_search($class,$this->classes);
452 unset($this->classes[$key]);
460 * Sets the title for this node and forces Moodle to utilise it.
461 * @param string $title
463 public function title($title) {
464 $this->title = $title;
465 $this->forcetitle = true;
469 * Resets the page specific information on this node if it is being unserialised.
471 public function __wakeup(){
472 $this->forceopen = false;
473 $this->isactive = false;
474 $this->remove_class('active_tree_node');
478 * Checks if this node or any of its children contain the active node.
484 public function contains_active_node() {
485 if ($this->isactive) {
488 foreach ($this->children as $child) {
489 if ($child->isactive || $child->contains_active_node()) {
498 * Finds the active node.
500 * Searches this nodes children plus all of the children for the active node
501 * and returns it if found.
505 * @return navigation_node|false
507 public function find_active_node() {
508 if ($this->isactive) {
511 foreach ($this->children as &$child) {
512 $outcome = $child->find_active_node();
513 if ($outcome !== false) {
522 * Searches all children for the best matching active node
523 * @return navigation_node|false
525 public function search_for_active_node() {
526 if ($this->check_if_active(URL_MATCH_BASE)) {
529 foreach ($this->children as &$child) {
530 $outcome = $child->search_for_active_node();
531 if ($outcome !== false) {
540 * Gets the content for this node.
542 * @param bool $shorttext If true shorttext is used rather than the normal text
545 public function get_content($shorttext=false) {
546 if ($shorttext && $this->shorttext!==null) {
547 return format_string($this->shorttext);
549 return format_string($this->text);
554 * Gets the title to use for this node.
558 public function get_title() {
559 if ($this->forcetitle || $this->action != null){
567 * Gets the CSS class to add to this node to describe its type
571 public function get_css_type() {
572 if (array_key_exists($this->type, $this->namedtypes)) {
573 return 'type_'.$this->namedtypes[$this->type];
575 return 'type_unknown';
579 * Finds all nodes that are expandable by AJAX
581 * @param array $expandable An array by reference to populate with expandable nodes.
583 public function find_expandable(array &$expandable) {
584 foreach ($this->children as &$child) {
585 if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count() == 0 && $child->display) {
586 $child->id = 'expandable_branch_'.(count($expandable)+1);
587 $this->add_class('canexpand');
588 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
590 $child->find_expandable($expandable);
595 * Finds all nodes of a given type (recursive)
597 * @param int $type On of navigation_node::TYPE_*
600 public function find_all_of_type($type) {
601 $nodes = $this->children->type($type);
602 foreach ($this->children as &$node) {
603 $childnodes = $node->find_all_of_type($type);
604 $nodes = array_merge($nodes, $childnodes);
610 * Removes this node if it is empty
612 public function trim_if_empty() {
613 if ($this->children->count() == 0) {
619 * Creates a tab representation of this nodes children that can be used
620 * with print_tabs to produce the tabs on a page.
622 * call_user_func_array('print_tabs', $node->get_tabs_array());
624 * @param array $inactive
625 * @param bool $return
626 * @return array Array (tabs, selected, inactive, activated, return)
628 public function get_tabs_array(array $inactive=array(), $return=false) {
632 $activated = array();
633 foreach ($this->children as $node) {
634 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
635 if ($node->contains_active_node()) {
636 if ($node->children->count() > 0) {
637 $activated[] = $node->key;
638 foreach ($node->children as $child) {
639 if ($child->contains_active_node()) {
640 $selected = $child->key;
642 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
645 $selected = $node->key;
649 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
653 * Sets the parent for this node and if this node is active ensures that the tree is properly
656 * @param navigation_node $parent
658 public function set_parent(navigation_node $parent) {
659 // Set the parent (thats the easy part)
660 $this->parent = $parent;
661 // Check if this node is active (this is checked during construction)
662 if ($this->isactive) {
663 // Force all of the parent nodes open so you can see this node
664 $this->parent->force_open();
665 // Make all parents inactive so that its clear where we are.
666 $this->parent->make_inactive();
672 * Navigation node collection
674 * This class is responsible for managing a collection of navigation nodes.
675 * It is required because a node's unique identifier is a combination of both its
678 * Originally an array was used with a string key that was a combination of the two
679 * however it was decided that a better solution would be to use a class that
680 * implements the standard IteratorAggregate interface.
682 * @package moodlecore
683 * @subpackage navigation
684 * @copyright 2010 Sam Hemelryk
685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
687 class navigation_node_collection implements IteratorAggregate {
689 * A multidimensional array to where the first key is the type and the second
690 * key is the nodes key.
693 protected $collection = array();
695 * An array that contains references to nodes in the same order they were added.
696 * This is maintained as a progressive array.
699 protected $orderedcollection = array();
701 * A reference to the last node that was added to the collection
702 * @var navigation_node
704 protected $last = null;
706 * The total number of items added to this array.
709 protected $count = 0;
712 * Adds a navigation node to the collection
714 * @param navigation_node $node Node to add
715 * @param string $beforekey If specified, adds before a node with this key,
716 * otherwise adds at end
717 * @return navigation_node Added node
719 public function add(navigation_node $node, $beforekey=null) {
724 // First check we have a 2nd dimension for this type
725 if (!array_key_exists($type, $this->orderedcollection)) {
726 $this->orderedcollection[$type] = array();
728 // Check for a collision and report if debugging is turned on
729 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
730 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
733 // Find the key to add before
734 $newindex = $this->count;
736 if ($beforekey !== null) {
737 foreach ($this->collection as $index => $othernode) {
738 if ($othernode->key === $beforekey) {
744 if ($newindex === $this->count) {
745 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
746 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
750 // Add the node to the appropriate place in the by-type structure (which
751 // is not ordered, despite the variable name)
752 $this->orderedcollection[$type][$key] = $node;
754 // Update existing references in the ordered collection (which is the
755 // one that isn't called 'ordered') to shuffle them along if required
756 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
757 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
760 // Add a reference to the node to the progressive collection.
761 $this->collection[$newindex] = &$this->orderedcollection[$type][$key];
762 // Update the last property to a reference to this new node.
763 $this->last = &$this->orderedcollection[$type][$key];
765 // Reorder the array by index if needed
767 ksort($this->collection);
770 // Return the reference to the now added node
775 * Return a list of all the keys of all the nodes.
776 * @return array the keys.
778 public function get_key_list() {
780 foreach ($this->collection as $node) {
781 $keys[] = $node->key;
787 * Fetches a node from this collection.
789 * @param string|int $key The key of the node we want to find.
790 * @param int $type One of navigation_node::TYPE_*.
791 * @return navigation_node|null
793 public function get($key, $type=null) {
794 if ($type !== null) {
795 // If the type is known then we can simply check and fetch
796 if (!empty($this->orderedcollection[$type][$key])) {
797 return $this->orderedcollection[$type][$key];
800 // Because we don't know the type we look in the progressive array
801 foreach ($this->collection as $node) {
802 if ($node->key === $key) {
811 * Searches for a node with matching key and type.
813 * This function searches both the nodes in this collection and all of
814 * the nodes in each collection belonging to the nodes in this collection.
818 * @param string|int $key The key of the node we want to find.
819 * @param int $type One of navigation_node::TYPE_*.
820 * @return navigation_node|null
822 public function find($key, $type=null) {
823 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
824 return $this->orderedcollection[$type][$key];
826 $nodes = $this->getIterator();
827 // Search immediate children first
828 foreach ($nodes as &$node) {
829 if ($node->key === $key && ($type === null || $type === $node->type)) {
833 // Now search each childs children
834 foreach ($nodes as &$node) {
835 $result = $node->children->find($key, $type);
836 if ($result !== false) {
845 * Fetches the last node that was added to this collection
847 * @return navigation_node
849 public function last() {
854 * Fetches all nodes of a given type from this collection
856 public function type($type) {
857 if (!array_key_exists($type, $this->orderedcollection)) {
858 $this->orderedcollection[$type] = array();
860 return $this->orderedcollection[$type];
863 * Removes the node with the given key and type from the collection
865 * @param string|int $key
869 public function remove($key, $type=null) {
870 $child = $this->get($key, $type);
871 if ($child !== false) {
872 foreach ($this->collection as $colkey => $node) {
873 if ($node->key == $key && $node->type == $type) {
874 unset($this->collection[$colkey]);
878 unset($this->orderedcollection[$child->type][$child->key]);
886 * Gets the number of nodes in this collection
888 * This option uses an internal count rather than counting the actual options to avoid
889 * a performance hit through the count function.
893 public function count() {
897 * Gets an array iterator for the collection.
899 * This is required by the IteratorAggregator interface and is used by routines
900 * such as the foreach loop.
902 * @return ArrayIterator
904 public function getIterator() {
905 return new ArrayIterator($this->collection);
910 * The global navigation class used for... the global navigation
912 * This class is used by PAGE to store the global navigation for the site
913 * and is then used by the settings nav and navbar to save on processing and DB calls
917 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
918 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
921 * @package moodlecore
922 * @subpackage navigation
923 * @copyright 2009 Sam Hemelryk
924 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
926 class global_navigation extends navigation_node {
928 * The Moodle page this navigation object belongs to.
933 protected $initialised = false;
935 protected $mycourses = array();
937 protected $rootnodes = array();
939 protected $showemptysections = false;
941 protected $extendforuser = array();
942 /** @var navigation_cache */
945 protected $addedcourses = array();
947 protected $addedcategories = array();
949 protected $expansionlimit = 0;
951 protected $useridtouseforparentchecks = 0;
954 * Constructs a new global navigation
956 * @param moodle_page $page The page this navigation object belongs to
958 public function __construct(moodle_page $page) {
959 global $CFG, $SITE, $USER;
961 if (during_initial_install()) {
965 if (get_home_page() == HOMEPAGE_SITE) {
966 // We are using the site home for the root element
969 'type' => navigation_node::TYPE_SYSTEM,
970 'text' => get_string('home'),
971 'action' => new moodle_url('/')
974 // We are using the users my moodle for the root element
977 'type' => navigation_node::TYPE_SYSTEM,
978 'text' => get_string('myhome'),
979 'action' => new moodle_url('/my/')
983 // Use the parents consturctor.... good good reuse
984 parent::__construct($properties);
986 // Initalise and set defaults
988 $this->forceopen = true;
989 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
993 * Mutator to set userid to allow parent to see child's profile
994 * page navigation. See MDL-25805 for initial issue. Linked to it
995 * is an issue explaining why this is a REALLY UGLY HACK thats not
998 * @param int $userid userid of profile page that parent wants to navigate around.
1000 public function set_userid_for_parent_checks($userid) {
1001 $this->useridtouseforparentchecks = $userid;
1006 * Initialises the navigation object.
1008 * This causes the navigation object to look at the current state of the page
1009 * that it is associated with and then load the appropriate content.
1011 * This should only occur the first time that the navigation structure is utilised
1012 * which will normally be either when the navbar is called to be displayed or
1013 * when a block makes use of it.
1017 public function initialise() {
1018 global $CFG, $SITE, $USER, $DB;
1019 // Check if it has alread been initialised
1020 if ($this->initialised || during_initial_install()) {
1023 $this->initialised = true;
1025 // Set up the five base root nodes. These are nodes where we will put our
1026 // content and are as follows:
1027 // site: Navigation for the front page.
1028 // myprofile: User profile information goes here.
1029 // mycourses: The users courses get added here.
1030 // courses: Additional courses are added here.
1031 // users: Other users information loaded here.
1032 $this->rootnodes = array();
1033 if (get_home_page() == HOMEPAGE_SITE) {
1034 // The home element should be my moodle because the root element is the site
1035 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1036 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1039 // The home element should be the site because the root node is my moodle
1040 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1041 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
1042 // We need to stop automatic redirection
1043 $this->rootnodes['home']->action->param('redirect', '0');
1046 $this->rootnodes['site'] = $this->add_course($SITE);
1047 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1048 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
1049 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
1050 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1052 // Fetch all of the users courses.
1054 if (!empty($CFG->navcourselimit)) {
1055 $limit = $CFG->navcourselimit;
1058 if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') == 1) {
1059 // There is only one category so we don't want to show categories
1060 $CFG->navshowcategories = false;
1063 $mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit);
1064 $showallcourses = (count($mycourses) == 0 || !empty($CFG->navshowallcourses));
1065 $showcategories = ($showallcourses && !empty($CFG->navshowcategories));
1066 $issite = ($this->page->course->id != SITEID);
1067 $ismycourse = (array_key_exists($this->page->course->id, $mycourses));
1069 // Check if any courses were returned.
1070 if (count($mycourses) > 0) {
1071 // Add all of the users courses to the navigation
1072 foreach ($mycourses as $course) {
1073 $course->coursenode = $this->add_course($course, false, true);
1077 if ($showallcourses) {
1079 $this->load_all_courses();
1082 // We always load the frontpage course to ensure it is available without
1083 // JavaScript enabled.
1084 $frontpagecourse = $this->load_course($SITE);
1085 $this->add_front_page_course_essentials($frontpagecourse, $SITE);
1087 $canviewcourseprofile = true;
1089 // Next load context specific content into the navigation
1090 switch ($this->page->context->contextlevel) {
1091 case CONTEXT_SYSTEM :
1092 // This has already been loaded we just need to map the variable
1093 $coursenode = $frontpagecourse;
1094 $this->load_all_categories(null, $showcategories);
1096 case CONTEXT_COURSECAT :
1097 // This has already been loaded we just need to map the variable
1098 $coursenode = $frontpagecourse;
1099 $this->load_all_categories($this->page->context->instanceid, $showcategories);
1101 case CONTEXT_BLOCK :
1102 case CONTEXT_COURSE :
1103 // Load the course associated with the page into the navigation
1104 $course = $this->page->course;
1105 if ($showcategories && !$issite && !$ismycourse) {
1106 $this->load_all_categories($course->category, $showcategories);
1108 $coursenode = $this->load_course($course);
1110 // If the course wasn't added then don't try going any further.
1112 $canviewcourseprofile = false;
1116 // If the user is not enrolled then we only want to show the
1117 // course node and not populate it.
1118 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1120 // Not enrolled, can't view, and hasn't switched roles
1121 if (!can_access_course($coursecontext)) {
1122 // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1123 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1125 if ($this->useridtouseforparentchecks) {
1126 if ($this->useridtouseforparentchecks != $USER->id) {
1127 $usercontext = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST);
1128 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))
1129 and has_capability('moodle/user:viewdetails', $usercontext)) {
1136 $coursenode->make_active();
1137 $canviewcourseprofile = false;
1141 // Add the essentials such as reports etc...
1142 $this->add_course_essentials($coursenode, $course);
1143 if ($this->format_display_course_content($course->format)) {
1144 // Load the course sections
1145 $sections = $this->load_course_sections($course, $coursenode);
1147 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1148 $coursenode->make_active();
1151 case CONTEXT_MODULE :
1152 $course = $this->page->course;
1153 $cm = $this->page->cm;
1155 if ($showcategories && !$issite && !$ismycourse) {
1156 $this->load_all_categories($course->category, $showcategories);
1159 // Load the course associated with the page into the navigation
1160 $coursenode = $this->load_course($course);
1162 // If the course wasn't added then don't try going any further.
1164 $canviewcourseprofile = false;
1168 // If the user is not enrolled then we only want to show the
1169 // course node and not populate it.
1170 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1171 if (!can_access_course($coursecontext)) {
1172 $coursenode->make_active();
1173 $canviewcourseprofile = false;
1177 $this->add_course_essentials($coursenode, $course);
1178 // Load the course sections into the page
1179 $sections = $this->load_course_sections($course, $coursenode);
1180 if ($course->id != SITEID) {
1181 // Find the section for the $CM associated with the page and collect
1182 // its section number.
1183 if (isset($cm->sectionnum)) {
1184 $cm->sectionnumber = $cm->sectionnum;
1186 foreach ($sections as $section) {
1187 if ($section->id == $cm->section) {
1188 $cm->sectionnumber = $section->section;
1194 // Load all of the section activities for the section the cm belongs to.
1195 if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) {
1196 list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
1197 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, $activityarray);
1199 $activities = array();
1200 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1201 // "stealth" activity from unavailable section
1202 $activities[$cm->id] = $activity;
1206 $activities = array();
1207 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1209 if (!empty($activities[$cm->id])) {
1210 // Finally load the cm specific navigaton information
1211 $this->load_activity($cm, $course, $activities[$cm->id]);
1212 // Check if we have an active ndoe
1213 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1214 // And make the activity node active.
1215 $activities[$cm->id]->make_active();
1218 //TODO: something is wrong, what to do? (Skodak)
1222 $course = $this->page->course;
1223 if ($course->id != SITEID) {
1224 if ($showcategories && !$issite && !$ismycourse) {
1225 $this->load_all_categories($course->category, $showcategories);
1227 // Load the course associated with the user into the navigation
1228 $coursenode = $this->load_course($course);
1230 // If the course wasn't added then don't try going any further.
1232 $canviewcourseprofile = false;
1236 // If the user is not enrolled then we only want to show the
1237 // course node and not populate it.
1238 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1239 if (!can_access_course($coursecontext)) {
1240 $coursenode->make_active();
1241 $canviewcourseprofile = false;
1244 $this->add_course_essentials($coursenode, $course);
1245 $sections = $this->load_course_sections($course, $coursenode);
1251 if (!empty($CFG->navcourselimit)) {
1252 $limit = $CFG->navcourselimit;
1254 if ($showcategories) {
1255 $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1256 foreach ($categories as &$category) {
1257 if ($category->children->count() >= $limit) {
1258 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1259 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1262 } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1263 $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1266 // Load for the current user
1267 $this->load_for_user();
1268 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) {
1269 $this->load_for_user(null, true);
1271 // Load each extending user into the navigation.
1272 foreach ($this->extendforuser as $user) {
1273 if ($user->id != $USER->id) {
1274 $this->load_for_user($user);
1278 // Give the local plugins a chance to include some navigation if they want.
1279 foreach (get_list_of_plugins('local') as $plugin) {
1280 if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1283 require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1284 $function = $plugin.'_extends_navigation';
1285 if (function_exists($function)) {
1290 // Remove any empty root nodes
1291 foreach ($this->rootnodes as $node) {
1292 // Dont remove the home node
1293 if ($node->key !== 'home' && !$node->has_children()) {
1298 if (!$this->contains_active_node()) {
1299 $this->search_for_active_node();
1302 // If the user is not logged in modify the navigation structure as detailed
1303 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1304 if (!isloggedin()) {
1305 $activities = clone($this->rootnodes['site']->children);
1306 $this->rootnodes['site']->remove();
1307 $children = clone($this->children);
1308 $this->children = new navigation_node_collection();
1309 foreach ($activities as $child) {
1310 $this->children->add($child);
1312 foreach ($children as $child) {
1313 $this->children->add($child);
1319 * Checks the course format to see whether it wants the navigation to load
1320 * additional information for the course.
1322 * This function utilises a callback that can exist within the course format lib.php file
1323 * The callback should be a function called:
1324 * callback_{formatname}_display_content()
1325 * It doesn't get any arguments and should return true if additional content is
1326 * desired. If the callback doesn't exist we assume additional content is wanted.
1328 * @param string $format The course format
1331 protected function format_display_course_content($format) {
1333 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1334 if (file_exists($formatlib)) {
1335 require_once($formatlib);
1336 $displayfunc = 'callback_'.$format.'_display_content';
1337 if (function_exists($displayfunc) && !$displayfunc()) {
1338 return $displayfunc();
1345 * Loads of the the courses in Moodle into the navigation.
1347 * @global moodle_database $DB
1348 * @param string|array $categoryids Either a string or array of category ids to load courses for
1349 * @return array An array of navigation_node
1351 protected function load_all_courses($categoryids=null) {
1352 global $CFG, $DB, $USER;
1354 if ($categoryids !== null) {
1355 if (is_array($categoryids)) {
1356 list ($categoryselect, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'catid');
1358 $categoryselect = '= :categoryid';
1359 $params = array('categoryid', $categoryids);
1361 $params['siteid'] = SITEID;
1362 $categoryselect = ' AND c.category '.$categoryselect;
1364 $params = array('siteid' => SITEID);
1365 $categoryselect = '';
1368 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1369 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses) + array(SITEID), SQL_PARAMS_NAMED, 'lcourse', false);
1370 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category, cat.path AS categorypath $ccselect
1373 LEFT JOIN {course_categories} cat ON cat.id=c.category
1374 WHERE c.id {$courseids} {$categoryselect}
1375 ORDER BY c.sortorder ASC";
1377 if (!empty($CFG->navcourselimit)) {
1378 $limit = $CFG->navcourselimit;
1380 $courses = $DB->get_records_sql($sql, $params + $courseparams, 0, $limit);
1382 $coursenodes = array();
1383 foreach ($courses as $course) {
1384 context_instance_preload($course);
1385 $coursenodes[$course->id] = $this->add_course($course);
1387 return $coursenodes;
1391 * Loads all categories (top level or if an id is specified for that category)
1393 * @param int $categoryid The category id to load or null/0 to load all base level categories
1394 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1395 * as the requested category and any parent categories.
1398 protected function load_all_categories($categoryid = null, $showbasecategories = false) {
1401 // Check if this category has already been loaded
1402 if ($categoryid !== null && array_key_exists($categoryid, $this->addedcategories) && $this->addedcategories[$categoryid]->children->count() > 0) {
1403 return $this->addedcategories[$categoryid];
1406 $coursestoload = array();
1407 if (empty($categoryid)) { // can be 0
1408 // We are going to load all of the first level categories (categories without parents)
1409 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder ASC, id ASC');
1410 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1411 // The category itself has been loaded already so we just need to ensure its subcategories
1413 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1414 if ($showbasecategories) {
1415 // We need to include categories with parent = 0 as well
1417 FROM {course_categories} cc
1418 WHERE (parent = :categoryid OR parent = 0) AND
1420 ORDER BY depth DESC, sortorder ASC, id ASC";
1423 FROM {course_categories} cc
1424 WHERE parent = :categoryid AND
1426 ORDER BY depth DESC, sortorder ASC, id ASC";
1428 $params['categoryid'] = $categoryid;
1429 $categories = $DB->get_records_sql($sql, $params);
1430 if (count($categories) == 0) {
1431 // There are no further categories that require loading.
1435 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1436 // and load this category plus all its parents and subcategories
1437 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1438 $coursestoload = explode('/', trim($category->path, '/'));
1439 list($select, $params) = $DB->get_in_or_equal($coursestoload);
1440 $select = 'id '.$select.' OR parent '.$select;
1441 if ($showbasecategories) {
1442 $select .= ' OR parent = 0';
1444 $params = array_merge($params, $params);
1445 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1448 // Now we have an array of categories we need to add them to the navigation.
1449 while (!empty($categories)) {
1450 $category = reset($categories);
1451 if (array_key_exists($category->id, $this->addedcategories)) {
1453 } else if ($category->parent == '0') {
1454 $this->add_category($category, $this->rootnodes['courses']);
1455 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1456 $this->add_category($category, $this->addedcategories[$category->parent]);
1458 // This category isn't in the navigation and niether is it's parent (yet).
1459 // We need to go through the category path and add all of its components in order.
1460 $path = explode('/', trim($category->path, '/'));
1461 foreach ($path as $catid) {
1462 if (!array_key_exists($catid, $this->addedcategories)) {
1463 // This category isn't in the navigation yet so add it.
1464 $subcategory = $categories[$catid];
1465 if ($subcategory->parent == '0') {
1466 // Yay we have a root category - this likely means we will now be able
1467 // to add categories without problems.
1468 $this->add_category($subcategory, $this->rootnodes['courses']);
1469 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1470 // The parent is in the category (as we'd expect) so add it now.
1471 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1472 // Remove the category from the categories array.
1473 unset($categories[$catid]);
1475 // We should never ever arrive here - if we have then there is a bigger
1477 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1482 // Remove the category from the categories array now that we know it has been added.
1483 unset($categories[$category->id]);
1485 // Check if there are any categories to load.
1486 if (count($coursestoload) > 0) {
1487 $this->load_all_courses($coursestoload);
1492 * Adds a structured category to the navigation in the correct order/place
1494 * @param stdClass $category
1495 * @param navigation_node $parent
1497 protected function add_category(stdClass $category, navigation_node $parent) {
1498 if (array_key_exists($category->id, $this->addedcategories)) {
1501 $url = new moodle_url('/course/category.php', array('id' => $category->id));
1502 $categorynode = $parent->add($category->name, $url, self::TYPE_CATEGORY, $category->name, $category->id);
1503 if (empty($category->visible)) {
1504 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1505 $categorynode->hidden = true;
1507 $categorynode->display = false;
1510 $this->addedcategories[$category->id] = &$categorynode;
1514 * Loads the given course into the navigation
1516 * @param stdClass $course
1517 * @return navigation_node
1519 protected function load_course(stdClass $course) {
1520 if ($course->id == SITEID) {
1521 return $this->rootnodes['site'];
1522 } else if (array_key_exists($course->id, $this->addedcourses)) {
1523 return $this->addedcourses[$course->id];
1525 return $this->add_course($course);
1530 * Loads all of the courses section into the navigation.
1532 * This function utilisies a callback that can be implemented within the course
1533 * formats lib.php file to customise the navigation that is generated at this
1534 * point for the course.
1536 * By default (if not defined) the method {@see load_generic_course_sections} is
1539 * @param stdClass $course Database record for the course
1540 * @param navigation_node $coursenode The course node within the navigation
1541 * @return array Array of navigation nodes for the section with key = section id
1543 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1545 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1546 $structurefunc = 'callback_'.$course->format.'_load_content';
1547 if (function_exists($structurefunc)) {
1548 return $structurefunc($this, $course, $coursenode);
1549 } else if (file_exists($structurefile)) {
1550 require_once $structurefile;
1551 if (function_exists($structurefunc)) {
1552 return $structurefunc($this, $course, $coursenode);
1554 return $this->load_generic_course_sections($course, $coursenode);
1557 return $this->load_generic_course_sections($course, $coursenode);
1562 * Generates an array of sections and an array of activities for the given course.
1564 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1566 * @param stdClass $course
1567 * @return array Array($sections, $activities)
1569 protected function generate_sections_and_activities(stdClass $course) {
1571 require_once($CFG->dirroot.'/course/lib.php');
1573 if (!$this->cache->cached('course_sections_'.$course->id) || !$this->cache->cached('course_activites_'.$course->id)) {
1574 $modinfo = get_fast_modinfo($course);
1575 $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1577 $activities = array();
1579 foreach ($sections as $key => $section) {
1580 $sections[$key]->hasactivites = false;
1581 if (!array_key_exists($section->section, $modinfo->sections)) {
1584 foreach ($modinfo->sections[$section->section] as $cmid) {
1585 $cm = $modinfo->cms[$cmid];
1586 if (!$cm->uservisible) {
1589 $activity = new stdClass;
1590 $activity->section = $section->section;
1591 $activity->name = $cm->name;
1592 $activity->icon = $cm->icon;
1593 $activity->iconcomponent = $cm->iconcomponent;
1594 $activity->id = $cm->id;
1595 $activity->hidden = (!$cm->visible);
1596 $activity->modname = $cm->modname;
1597 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1598 $url = $cm->get_url();
1600 $activity->url = null;
1601 $activity->display = false;
1603 $activity->url = $cm->get_url()->out();
1604 $activity->display = true;
1605 if (self::module_extends_navigation($cm->modname)) {
1606 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1609 $activities[$cmid] = $activity;
1610 $sections[$key]->hasactivites = true;
1613 $this->cache->set('course_sections_'.$course->id, $sections);
1614 $this->cache->set('course_activites_'.$course->id, $activities);
1616 $sections = $this->cache->{'course_sections_'.$course->id};
1617 $activities = $this->cache->{'course_activites_'.$course->id};
1619 return array($sections, $activities);
1623 * Generically loads the course sections into the course's navigation.
1625 * @param stdClass $course
1626 * @param navigation_node $coursenode
1627 * @param string $courseformat The course format
1628 * @return array An array of course section nodes
1630 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1631 global $CFG, $DB, $USER;
1632 require_once($CFG->dirroot.'/course/lib.php');
1634 list($sections, $activities) = $this->generate_sections_and_activities($course);
1636 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1637 $namingfunctionexists = (function_exists($namingfunction));
1638 $activesection = course_get_display($course->id);
1639 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1641 $navigationsections = array();
1642 foreach ($sections as $sectionid => $section) {
1643 $section = clone($section);
1644 if ($course->id == SITEID) {
1645 $this->load_section_activities($coursenode, $section->section, $activities);
1647 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !$section->hasactivites)) {
1650 if ($namingfunctionexists) {
1651 $sectionname = $namingfunction($course, $section, $sections);
1653 $sectionname = get_string('section').' '.$section->section;
1655 //$url = new moodle_url('/course/view.php', array('id'=>$course->id));
1657 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1658 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1659 $sectionnode->hidden = (!$section->visible);
1660 if ($this->page->context->contextlevel != CONTEXT_MODULE && $section->hasactivites && ($sectionnode->isactive || ($activesection && $section->section == $activesection))) {
1661 $sectionnode->force_open();
1662 $this->load_section_activities($sectionnode, $section->section, $activities);
1664 $section->sectionnode = $sectionnode;
1665 $navigationsections[$sectionid] = $section;
1668 return $navigationsections;
1671 * Loads all of the activities for a section into the navigation structure.
1673 * @todo 2.2 - $activities should always be an array and we should no longer check for it being a
1674 * course_modinfo object
1676 * @param navigation_node $sectionnode
1677 * @param int $sectionnumber
1678 * @param course_modinfo $modinfo Object returned from {@see get_fast_modinfo()}
1679 * @return array Array of activity nodes
1681 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $activities) {
1683 if ($activities instanceof course_modinfo) {
1684 debugging('global_navigation::load_section_activities argument 3 should now recieve an array of activites. See that method for an example.', DEBUG_DEVELOPER);
1685 list($sections, $activities) = $this->generate_sections_and_activities($activities->course);
1688 $activitynodes = array();
1689 foreach ($activities as $activity) {
1690 if ($activity->section != $sectionnumber) {
1693 if ($activity->icon) {
1694 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1696 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1698 $activitynode = $sectionnode->add(format_string($activity->name), $activity->url, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1699 $activitynode->title(get_string('modulename', $activity->modname));
1700 $activitynode->hidden = $activity->hidden;
1701 $activitynode->display = $activity->display;
1702 $activitynode->nodetype = $activity->nodetype;
1703 $activitynodes[$activity->id] = $activitynode;
1706 return $activitynodes;
1709 * Loads a stealth module from unavailable section
1710 * @param navigation_node $coursenode
1711 * @param stdClass $modinfo
1712 * @return navigation_node or null if not accessible
1714 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1715 if (empty($modinfo->cms[$this->page->cm->id])) {
1718 $cm = $modinfo->cms[$this->page->cm->id];
1719 if (!$cm->uservisible) {
1723 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1725 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1727 $url = $cm->get_url();
1728 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1729 $activitynode->title(get_string('modulename', $cm->modname));
1730 $activitynode->hidden = (!$cm->visible);
1732 // Don't show activities that don't have links!
1733 $activitynode->display = false;
1734 } else if (self::module_extends_navigation($cm->modname)) {
1735 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1737 return $activitynode;
1740 * Loads the navigation structure for the given activity into the activities node.
1742 * This method utilises a callback within the modules lib.php file to load the
1743 * content specific to activity given.
1745 * The callback is a method: {modulename}_extend_navigation()
1747 * * {@see forum_extend_navigation()}
1748 * * {@see workshop_extend_navigation()}
1750 * @param cm_info|stdClass $cm
1751 * @param stdClass $course
1752 * @param navigation_node $activity
1755 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
1758 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
1759 if (!($cm instanceof cm_info)) {
1760 $modinfo = get_fast_modinfo($course);
1761 $cm = $modinfo->get_cm($cm->id);
1764 $activity->make_active();
1765 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1766 $function = $cm->modname.'_extend_navigation';
1768 if (file_exists($file)) {
1769 require_once($file);
1770 if (function_exists($function)) {
1771 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1772 $function($activity, $course, $activtyrecord, $cm);
1776 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1780 * Loads user specific information into the navigation in the appopriate place.
1782 * If no user is provided the current user is assumed.
1784 * @param stdClass $user
1787 protected function load_for_user($user=null, $forceforcontext=false) {
1788 global $DB, $CFG, $USER;
1790 if ($user === null) {
1791 // We can't require login here but if the user isn't logged in we don't
1792 // want to show anything
1793 if (!isloggedin() || isguestuser()) {
1797 } else if (!is_object($user)) {
1798 // If the user is not an object then get them from the database
1799 list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
1800 $sql = "SELECT u.* $select FROM {user} u $join WHERE u.id = :userid";
1801 $user = $DB->get_record_sql($sql, array('userid' => (int)$user), MUST_EXIST);
1802 context_instance_preload($user);
1805 $iscurrentuser = ($user->id == $USER->id);
1807 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1809 // Get the course set against the page, by default this will be the site
1810 $course = $this->page->course;
1811 $baseargs = array('id'=>$user->id);
1812 if ($course->id != SITEID && (!$iscurrentuser || $forceforcontext)) {
1813 $coursenode = $this->load_course($course);
1814 $baseargs['course'] = $course->id;
1815 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1816 $issitecourse = false;
1818 // Load all categories and get the context for the system
1819 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1820 $issitecourse = true;
1823 // Create a node to add user information under.
1824 if ($iscurrentuser && !$forceforcontext) {
1825 // If it's the current user the information will go under the profile root node
1826 $usernode = $this->rootnodes['myprofile'];
1828 if (!$issitecourse) {
1829 // Not the current user so add it to the participants node for the current course
1830 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1831 $userviewurl = new moodle_url('/user/view.php', $baseargs);
1833 // This is the site so add a users node to the root branch
1834 $usersnode = $this->rootnodes['users'];
1835 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
1836 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1838 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
1841 // We should NEVER get here, if the course hasn't been populated
1842 // with a participants node then the navigaiton either wasn't generated
1843 // for it (you are missing a require_login or set_context call) or
1844 // you don't have access.... in the interests of no leaking informatin
1845 // we simply quit...
1848 // Add a branch for the current user
1849 $usernode = $usersnode->add(fullname($user, true), $userviewurl, self::TYPE_USER, null, $user->id);
1851 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1852 $usernode->make_active();
1856 // If the user is the current user or has permission to view the details of the requested
1857 // user than add a view profile link.
1858 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1859 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
1860 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1862 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1866 // Add nodes for forum posts and discussions if the user can view either or both
1867 // There are no capability checks here as the content of the page is based
1868 // purely on the forums the current user has access too.
1869 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1870 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1871 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
1874 if (!empty($CFG->bloglevel)) {
1875 if (!$this->cache->cached('userblogoptions'.$user->id)) {
1876 require_once($CFG->dirroot.'/blog/lib.php');
1877 // Get all options for the user
1878 $options = blog_get_options_for_user($user);
1879 $this->cache->set('userblogoptions'.$user->id, $options);
1881 $options = $this->cache->{'userblogoptions'.$user->id};
1884 if (count($options) > 0) {
1885 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1886 foreach ($options as $option) {
1887 $blogs->add($option['string'], $option['link']);
1892 if (!empty($CFG->messaging)) {
1893 $messageargs = null;
1894 if ($USER->id!=$user->id) {
1895 $messageargs = array('id'=>$user->id);
1897 $url = new moodle_url('/message/index.php',$messageargs);
1898 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
1901 $context = get_context_instance(CONTEXT_USER, $USER->id);
1902 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
1903 $url = new moodle_url('/user/files.php');
1904 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
1907 // Add a node to view the users notes if permitted
1908 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1909 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1910 if ($coursecontext->instanceid) {
1911 $url->param('course', $coursecontext->instanceid);
1913 $usernode->add(get_string('notes', 'notes'), $url);
1916 // Add a reports tab and then add reports the the user has permission to see.
1917 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1919 $outlinetreport = ($anyreport || has_capability('coursereport/outline:view', $coursecontext));
1920 $logtodayreport = ($anyreport || has_capability('coursereport/log:viewtoday', $coursecontext));
1921 $logreport = ($anyreport || has_capability('coursereport/log:view', $coursecontext));
1922 $statsreport = ($anyreport || has_capability('coursereport/stats:view', $coursecontext));
1924 $somereport = $outlinetreport || $logtodayreport || $logreport || $statsreport;
1926 $viewreports = ($anyreport || $somereport || ($course->showreports && $iscurrentuser && $forceforcontext));
1928 $reporttab = $usernode->add(get_string('activityreports'));
1929 $reportargs = array('user'=>$user->id);
1930 if (!empty($course->id)) {
1931 $reportargs['id'] = $course->id;
1933 $reportargs['id'] = SITEID;
1935 if ($viewreports || $outlinetreport) {
1936 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1937 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1940 if ($viewreports || $logtodayreport) {
1941 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1944 if ($viewreports || $logreport ) {
1945 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1948 if (!empty($CFG->enablestats)) {
1949 if ($viewreports || $statsreport) {
1950 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1954 $gradeaccess = false;
1955 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1956 //ok - can view all course grades
1957 $gradeaccess = true;
1958 } else if ($course->showgrades) {
1959 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1960 //ok - can view own grades
1961 $gradeaccess = true;
1962 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1963 // ok - can view grades of this user - parent most probably
1964 $gradeaccess = true;
1965 } else if ($anyreport) {
1966 // ok - can view grades of this user - parent most probably
1967 $gradeaccess = true;
1971 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1974 // Check the number of nodes in the report node... if there are none remove
1976 $reporttab->trim_if_empty();
1979 // If the user is the current user add the repositories for the current user
1980 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
1981 if ($iscurrentuser) {
1982 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
1983 require_once($CFG->dirroot . '/repository/lib.php');
1984 $editabletypes = repository::get_editable_types($usercontext);
1985 $haseditabletypes = !empty($editabletypes);
1986 unset($editabletypes);
1987 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
1989 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
1991 if ($haseditabletypes) {
1992 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
1994 } else if ($course->id == SITEID && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
1996 // Add view grade report is permitted
1997 $reports = get_plugin_list('gradereport');
1998 arsort($reports); // user is last, we want to test it first
2000 $userscourses = enrol_get_users_courses($user->id);
2001 $userscoursesnode = $usernode->add(get_string('courses'));
2003 foreach ($userscourses as $usercourse) {
2004 $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id);
2005 $usercoursenode = $userscoursesnode->add($usercourse->shortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2007 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2008 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2009 foreach ($reports as $plugin => $plugindir) {
2010 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2011 //stop when the first visible plugin is found
2012 $gradeavailable = true;
2018 if ($gradeavailable) {
2019 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2020 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2023 // Add a node to view the users notes if permitted
2024 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2025 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2026 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2029 if (can_access_course(get_context_instance(CONTEXT_COURSE, $usercourse->id), $user->id)) {
2030 $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', ''));
2033 $outlinetreport = ($anyreport || has_capability('coursereport/outline:view', $usercoursecontext));
2034 $logtodayreport = ($anyreport || has_capability('coursereport/log:viewtoday', $usercoursecontext));
2035 $logreport = ($anyreport || has_capability('coursereport/log:view', $usercoursecontext));
2036 $statsreport = ($anyreport || has_capability('coursereport/stats:view', $usercoursecontext));
2037 if ($outlinetreport || $logtodayreport || $logreport || $statsreport) {
2038 $reporttab = $usercoursenode->add(get_string('activityreports'));
2039 $reportargs = array('user'=>$user->id, 'id'=>$usercourse->id);
2040 if ($outlinetreport) {
2041 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
2042 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
2045 if ($logtodayreport) {
2046 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
2050 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
2053 if (!empty($CFG->enablestats) && $statsreport) {
2054 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
2063 * This method simply checks to see if a given module can extend the navigation.
2065 * TODO: A shared caching solution should be used to save details on what extends navigation
2067 * @param string $modname
2070 protected static function module_extends_navigation($modname) {
2072 static $extendingmodules = array();
2073 if (!array_key_exists($modname, $extendingmodules)) {
2074 $extendingmodules[$modname] = false;
2075 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2076 if (file_exists($file)) {
2077 $function = $modname.'_extend_navigation';
2078 require_once($file);
2079 $extendingmodules[$modname] = (function_exists($function));
2082 return $extendingmodules[$modname];
2085 * Extends the navigation for the given user.
2087 * @param stdClass $user A user from the database
2089 public function extend_for_user($user) {
2090 $this->extendforuser[] = $user;
2094 * Returns all of the users the navigation is being extended for
2098 public function get_extending_users() {
2099 return $this->extendforuser;
2102 * Adds the given course to the navigation structure.
2104 * @param stdClass $course
2105 * @return navigation_node
2107 public function add_course(stdClass $course, $forcegeneric = false, $ismycourse = false) {
2110 // We found the course... we can return it now :)
2111 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2112 return $this->addedcourses[$course->id];
2115 if ($course->id != SITEID && !$course->visible) {
2116 if (is_role_switched($course->id)) {
2117 // user has to be able to access course in order to switch, let's skip the visibility test here
2118 } else if (!has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2123 $issite = ($course->id == SITEID);
2124 $ismycourse = ($ismycourse && !$forcegeneric);
2125 $shortname = $course->shortname;
2130 $shortname = get_string('sitepages');
2131 } else if ($ismycourse) {
2132 $parent = $this->rootnodes['mycourses'];
2133 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2135 $parent = $this->rootnodes['courses'];
2136 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2139 if (!$ismycourse && !$issite && !empty($course->category)) {
2140 if (!empty($CFG->navshowcategories)) {
2141 // We need to load the category structure for this course
2142 $this->load_all_categories($course->category);
2144 if (array_key_exists($course->category, $this->addedcategories)) {
2145 $parent = $this->addedcategories[$course->category];
2146 // This could lead to the course being created so we should check whether it is the case again
2147 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2148 return $this->addedcourses[$course->id];
2153 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
2154 $coursenode->nodetype = self::NODETYPE_BRANCH;
2155 $coursenode->hidden = (!$course->visible);
2156 $coursenode->title($course->fullname);
2157 if (!$forcegeneric) {
2158 $this->addedcourses[$course->id] = &$coursenode;
2160 if ($ismycourse && !empty($CFG->navshowallcourses)) {
2161 // We need to add this course to the general courses node as well as the
2162 // my courses node, rerun the function with the kill param
2163 $genericcourse = $this->add_course($course, true);
2164 if ($genericcourse->isactive) {
2165 $genericcourse->make_inactive();
2166 $genericcourse->collapse = true;
2167 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
2168 $parent = $genericcourse->parent;
2169 while ($parent && $parent->type == self::TYPE_CATEGORY) {
2170 $parent->collapse = true;
2171 $parent = $parent->parent;
2180 * Adds essential course nodes to the navigation for the given course.
2182 * This method adds nodes such as reports, blogs and participants
2184 * @param navigation_node $coursenode
2185 * @param stdClass $course
2188 public function add_course_essentials($coursenode, stdClass $course) {
2191 if ($course->id == SITEID) {
2192 return $this->add_front_page_course_essentials($coursenode, $course);
2195 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2200 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2201 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2202 $currentgroup = groups_get_course_group($course, true);
2203 if ($course->id == SITEID) {
2205 } else if ($course->id && !$currentgroup) {
2206 $filterselect = $course->id;
2208 $filterselect = $currentgroup;
2210 $filterselect = clean_param($filterselect, PARAM_INT);
2211 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2212 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2213 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2214 $participants->add(get_string('blogs','blog'), $blogsurls->out());
2216 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2217 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2219 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2220 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2223 // View course reports
2224 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2225 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2226 $coursereports = get_plugin_list('coursereport');
2227 foreach ($coursereports as $report=>$dir) {
2228 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2229 if (file_exists($libfile)) {
2230 require_once($libfile);
2231 $reportfunction = $report.'_report_extend_navigation';
2232 if (function_exists($report.'_report_extend_navigation')) {
2233 $reportfunction($reportnav, $course, $this->page->context);
2241 * This generates the the structure of the course that won't be generated when
2242 * the modules and sections are added.
2244 * Things such as the reports branch, the participants branch, blogs... get
2245 * added to the course node by this method.
2247 * @param navigation_node $coursenode
2248 * @param stdClass $course
2249 * @return bool True for successfull generation
2251 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2254 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2258 // Hidden node that we use to determine if the front page navigation is loaded.
2259 // This required as there are not other guaranteed nodes that may be loaded.
2260 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2263 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2264 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2270 if (!empty($CFG->bloglevel)
2271 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2272 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2273 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2274 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
2278 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2279 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2283 if (!empty($CFG->usetags) && isloggedin()) {
2284 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2288 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2289 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2291 // View course reports
2292 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2293 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2294 $coursereports = get_plugin_list('coursereport');
2295 foreach ($coursereports as $report=>$dir) {
2296 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2297 if (file_exists($libfile)) {
2298 require_once($libfile);
2299 $reportfunction = $report.'_report_extend_navigation';
2300 if (function_exists($report.'_report_extend_navigation')) {
2301 $reportfunction($reportnav, $course, $this->page->context);
2310 * Clears the navigation cache
2312 public function clear_cache() {
2313 $this->cache->clear();
2317 * Sets an expansion limit for the navigation
2319 * The expansion limit is used to prevent the display of content that has a type
2320 * greater than the provided $type.
2322 * Can be used to ensure things such as activities or activity content don't get
2323 * shown on the navigation.
2324 * They are still generated in order to ensure the navbar still makes sense.
2326 * @param int $type One of navigation_node::TYPE_*
2329 public function set_expansion_limit($type) {
2330 $nodes = $this->find_all_of_type($type);
2331 foreach ($nodes as &$node) {
2332 // We need to generate the full site node
2333 if ($type == self::TYPE_COURSE && $node->key == SITEID) {
2336 foreach ($node->children as &$child) {
2337 // We still want to show course reports and participants containers
2338 // or there will be navigation missing.
2339 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2342 $child->display = false;
2348 * Attempts to get the navigation with the given key from this nodes children.
2350 * This function only looks at this nodes children, it does NOT look recursivily.
2351 * If the node can't be found then false is returned.
2353 * If you need to search recursivily then use the {@see find()} method.
2355 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2356 * may be of more use to you.
2358 * @param string|int $key The key of the node you wish to receive.
2359 * @param int $type One of navigation_node::TYPE_*
2360 * @return navigation_node|false
2362 public function get($key, $type = null) {
2363 if (!$this->initialised) {
2364 $this->initialise();
2366 return parent::get($key, $type);
2370 * Searches this nodes children and thier children to find a navigation node
2371 * with the matching key and type.
2373 * This method is recursive and searches children so until either a node is
2374 * found of there are no more nodes to search.
2376 * If you know that the node being searched for is a child of this node
2377 * then use the {@see get()} method instead.
2379 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2380 * may be of more use to you.
2382 * @param string|int $key The key of the node you wish to receive.
2383 * @param int $type One of navigation_node::TYPE_*
2384 * @return navigation_node|false
2386 public function find($key, $type) {
2387 if (!$this->initialised) {
2388 $this->initialise();
2390 return parent::find($key, $type);
2395 * The limited global navigation class used for the AJAX extension of the global
2398 * The primary methods that are used in the global navigation class have been overriden
2399 * to ensure that only the relevant branch is generated at the root of the tree.
2400 * This can be done because AJAX is only used when the backwards structure for the
2401 * requested branch exists.
2402 * This has been done only because it shortens the amounts of information that is generated
2403 * which of course will speed up the response time.. because no one likes laggy AJAX.
2405 * @package moodlecore
2406 * @subpackage navigation
2407 * @copyright 2009 Sam Hemelryk
2408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2410 class global_navigation_for_ajax extends global_navigation {
2412 protected $branchtype;
2413 protected $instanceid;
2416 protected $expandable = array();
2419 * Constructs the navigation for use in AJAX request
2421 public function __construct($page, $branchtype, $id) {
2422 $this->page = $page;
2423 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2424 $this->children = new navigation_node_collection();
2425 $this->branchtype = $branchtype;
2426 $this->instanceid = $id;
2427 $this->initialise();
2430 * Initialise the navigation given the type and id for the branch to expand.
2432 * @return array The expandable nodes
2434 public function initialise() {
2435 global $CFG, $DB, $SITE;
2437 if ($this->initialised || during_initial_install()) {
2438 return $this->expandable;
2440 $this->initialised = true;
2442 $this->rootnodes = array();
2443 $this->rootnodes['site'] = $this->add_course($SITE);
2444 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2446 // Branchtype will be one of navigation_node::TYPE_*
2447 switch ($this->branchtype) {
2448 case self::TYPE_CATEGORY :
2449 $this->load_all_categories($this->instanceid);
2451 if (!empty($CFG->navcourselimit)) {
2452 $limit = (int)$CFG->navcourselimit;
2454 $courses = $DB->get_records('course', array('category' => $this->instanceid), 'sortorder','*', 0, $limit);
2455 foreach ($courses as $course) {
2456 $this->add_course($course);
2459 case self::TYPE_COURSE :
2460 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2461 require_course_login($course);
2462 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2463 $coursenode = $this->add_course($course);
2464 $this->add_course_essentials($coursenode, $course);
2465 if ($this->format_display_course_content($course->format)) {
2466 $this->load_course_sections($course, $coursenode);
2469 case self::TYPE_SECTION :
2470 $sql = 'SELECT c.*, cs.section AS sectionnumber
2472 LEFT JOIN {course_sections} cs ON cs.course = c.id
2474 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2475 require_course_login($course);
2476 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2477 $coursenode = $this->add_course($course);
2478 $this->add_course_essentials($coursenode, $course);
2479 $sections = $this->load_course_sections($course, $coursenode);
2480 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2481 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, $activities);
2483 case self::TYPE_ACTIVITY :
2486 JOIN {course_modules} cm ON cm.course = c.id
2487 WHERE cm.id = :cmid";
2488 $params = array('cmid' => $this->instanceid);
2489 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2490 $modinfo = get_fast_modinfo($course);
2491 $cm = $modinfo->get_cm($this->instanceid);
2492 require_course_login($course, true, $cm);
2493 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
2494 $coursenode = $this->load_course($course);
2495 if ($course->id == SITEID) {
2496 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2498 $sections = $this->load_course_sections($course, $coursenode);
2499 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2500 $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, $activities);
2501 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2505 throw new Exception('Unknown type');
2506 return $this->expandable;
2509 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
2510 $this->load_for_user(null, true);
2513 $this->find_expandable($this->expandable);
2514 return $this->expandable;
2518 * Returns an array of expandable nodes
2521 public function get_expandable() {
2522 return $this->expandable;
2529 * This class is used to manage the navbar, which is initialised from the navigation
2530 * object held by PAGE
2532 * @package moodlecore
2533 * @subpackage navigation
2534 * @copyright 2009 Sam Hemelryk
2535 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2537 class navbar extends navigation_node {
2539 protected $initialised = false;
2541 protected $keys = array();
2542 /** @var null|string */
2543 protected $content = null;
2544 /** @var moodle_page object */
2547 protected $ignoreactive = false;
2549 protected $duringinstall = false;
2551 protected $hasitems = false;
2555 public $children = array();
2557 public $includesettingsbase = false;
2559 * The almighty constructor
2561 * @param moodle_page $page
2563 public function __construct(moodle_page $page) {
2565 if (during_initial_install()) {
2566 $this->duringinstall = true;
2569 $this->page = $page;
2570 $this->text = get_string('home');
2571 $this->shorttext = get_string('home');
2572 $this->action = new moodle_url($CFG->wwwroot);
2573 $this->nodetype = self::NODETYPE_BRANCH;
2574 $this->type = self::TYPE_SYSTEM;
2578 * Quick check to see if the navbar will have items in.
2580 * @return bool Returns true if the navbar will have items, false otherwise
2582 public function has_items() {
2583 if ($this->duringinstall) {
2585 } else if ($this->hasitems !== false) {
2588 $this->page->navigation->initialise($this->page);
2590 $activenodefound = ($this->page->navigation->contains_active_node() ||
2591 $this->page->settingsnav->contains_active_node());
2593 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2594 $this->hasitems = $outcome;
2599 * Turn on/off ignore active
2601 * @param bool $setting
2603 public function ignore_active($setting=true) {
2604 $this->ignoreactive = ($setting);
2606 public function get($key, $type = null) {
2607 foreach ($this->children as &$child) {
2608 if ($child->key === $key && ($type == null || $type == $child->type)) {
2615 * Returns an array of navigation_node's that make up the navbar.
2619 public function get_items() {
2621 // Make sure that navigation is initialised
2622 if (!$this->has_items()) {
2625 if ($this->items !== null) {
2626 return $this->items;
2629 if (count($this->children) > 0) {
2630 // Add the custom children
2631 $items = array_reverse($this->children);
2634 $navigationactivenode = $this->page->navigation->find_active_node();
2635 $settingsactivenode = $this->page->settingsnav->find_active_node();
2637 // Check if navigation contains the active node
2638 if (!$this->ignoreactive) {
2640 if ($navigationactivenode && $settingsactivenode) {
2641 // Parse a combined navigation tree
2642 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2643 if (!$settingsactivenode->mainnavonly) {
2644 $items[] = $settingsactivenode;
2646 $settingsactivenode = $settingsactivenode->parent;
2648 if (!$this->includesettingsbase) {
2649 // Removes the first node from the settings (root node) from the list
2652 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2653 if (!$navigationactivenode->mainnavonly) {
2654 $items[] = $navigationactivenode;
2656 $navigationactivenode = $navigationactivenode->parent;
2658 } else if ($navigationactivenode) {
2659 // Parse the navigation tree to get the active node
2660 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2661 if (!$navigationactivenode->mainnavonly) {
2662 $items[] = $navigationactivenode;
2664 $navigationactivenode = $navigationactivenode->parent;
2666 } else if ($settingsactivenode) {
2667 // Parse the settings navigation to get the active node
2668 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2669 if (!$settingsactivenode->mainnavonly) {
2670 $items[] = $settingsactivenode;
2672 $settingsactivenode = $settingsactivenode->parent;
2677 $items[] = new navigation_node(array(
2678 'text'=>$this->page->navigation->text,
2679 'shorttext'=>$this->page->navigation->shorttext,
2680 'key'=>$this->page->navigation->key,
2681 'action'=>$this->page->navigation->action
2684 $this->items = array_reverse($items);
2685 return $this->items;
2689 * Add a new navigation_node to the navbar, overrides parent::add
2691 * This function overrides {@link navigation_node::add()} so that we can change
2692 * the way nodes get added to allow us to simply call add and have the node added to the
2695 * @param string $text
2696 * @param string|moodle_url $action
2698 * @param string|int $key
2699 * @param string $shorttext
2700 * @param string $icon
2701 * @return navigation_node
2703 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
2704 if ($this->content !== null) {
2705 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2708 // Properties array used when creating the new navigation node
2713 // Set the action if one was provided
2714 if ($action!==null) {
2715 $itemarray['action'] = $action;
2717 // Set the shorttext if one was provided
2718 if ($shorttext!==null) {
2719 $itemarray['shorttext'] = $shorttext;
2721 // Set the icon if one was provided
2723 $itemarray['icon'] = $icon;
2725 // Default the key to the number of children if not provided
2726 if ($key === null) {
2727 $key = count($this->children);
2730 $itemarray['key'] = $key;
2731 // Set the parent to this node
2732 $itemarray['parent'] = $this;
2733 // Add the child using the navigation_node_collections add method
2734 $this->children[] = new navigation_node($itemarray);
2740 * Class used to manage the settings option for the current page
2742 * This class is used to manage the settings options in a tree format (recursively)
2743 * and was created initially for use with the settings blocks.
2745 * @package moodlecore
2746 * @subpackage navigation
2747 * @copyright 2009 Sam Hemelryk
2748 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2750 class settings_navigation extends navigation_node {
2751 /** @var stdClass */
2753 /** @var moodle_page */
2756 protected $adminsection;
2758 protected $initialised = false;
2760 protected $userstoextendfor = array();
2761 /** @var navigation_cache **/
2765 * Sets up the object with basic settings and preparse it for use
2767 * @param moodle_page $page
2769 public function __construct(moodle_page &$page) {
2770 if (during_initial_install()) {
2773 $this->page = $page;
2774 // Initialise the main navigation. It is most important that this is done
2775 // before we try anything
2776 $this->page->navigation->initialise();
2777 // Initialise the navigation cache
2778 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2779 $this->children = new navigation_node_collection();
2782 * Initialise the settings navigation based on the current context
2784 * This function initialises the settings navigation tree for a given context
2785 * by calling supporting functions to generate major parts of the tree.
2788 public function initialise() {
2789 global $DB, $SESSION;
2791 if (during_initial_install()) {
2793 } else if ($this->initialised) {
2796 $this->id = 'settingsnav';
2797 $this->context = $this->page->context;
2799 $context = $this->context;
2800 if ($context->contextlevel == CONTEXT_BLOCK) {
2801 $this->load_block_settings();
2802 $context = $DB->get_record_sql('SELECT ctx.* FROM {block_instances} bi LEFT JOIN {context} ctx ON ctx.id=bi.parentcontextid WHERE bi.id=?', array($context->instanceid));
2805 switch ($context->contextlevel) {
2806 case CONTEXT_SYSTEM:
2807 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2808 $this->load_front_page_settings(($context->id == $this->context->id));
2811 case CONTEXT_COURSECAT:
2812 $this->load_category_settings();
2814 case CONTEXT_COURSE:
2815 if ($this->page->course->id != SITEID) {
2816 $this->load_course_settings(($context->id == $this->context->id));
2818 $this->load_front_page_settings(($context->id == $this->context->id));
2821 case CONTEXT_MODULE:
2822 $this->load_module_settings();
2823 $this->load_course_settings();
2826 if ($this->page->course->id != SITEID) {
2827 $this->load_course_settings();
2832 $settings = $this->load_user_settings($this->page->course->id);
2834 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
2835 $admin = $this->load_administration_settings();
2836 $SESSION->load_navigation_admin = ($admin->has_children());
2841 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
2842 $admin->force_open();
2843 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
2844 $settings->force_open();
2847 // Check if the user is currently logged in as another user
2848 if (session_is_loggedinas()) {
2849 // Get the actual user, we need this so we can display an informative return link
2850 $realuser = session_get_realuser();
2851 // Add the informative return to original user link
2852 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
2853 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
2856 foreach ($this->children as $key=>$node) {
2857 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
2861 $this->initialised = true;
2864 * Override the parent function so that we can add preceeding hr's and set a
2865 * root node class against all first level element
2867 * It does this by first calling the parent's add method {@link navigation_node::add()}
2868 * and then proceeds to use the key to set class and hr
2870 * @param string $text
2871 * @param sting|moodle_url $url
2872 * @param string $shorttext
2873 * @param string|int $key
2875 * @param string $icon
2876 * @return navigation_node
2878 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2879 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
2880 $node->add_class('root_node');
2885 * This function allows the user to add something to the start of the settings
2886 * navigation, which means it will be at the top of the settings navigation block
2888 * @param string $text
2889 * @param sting|moodle_url $url
2890 * @param string $shorttext
2891 * @param string|int $key
2893 * @param string $icon
2894 * @return navigation_node
2896 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2897 $children = $this->children;
2898 $childrenclass = get_class($children);
2899 $this->children = new $childrenclass;
2900 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2901 foreach ($children as $child) {
2902 $this->children->add($child);
2907 * Load the site administration tree
2909 * This function loads the site administration tree by using the lib/adminlib library functions
2911 * @param navigation_node $referencebranch A reference to a branch in the settings
2913 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
2914 * tree and start at the beginning
2915 * @return mixed A key to access the admin tree by
2917 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
2920 // Check if we are just starting to generate this navigation.
2921 if ($referencebranch === null) {
2923 // Require the admin lib then get an admin structure
2924 if (!function_exists('admin_get_root')) {
2925 require_once($CFG->dirroot.'/lib/adminlib.php');
2927 $adminroot = admin_get_root(false, false);
2928 // This is the active section identifier
2929 $this->adminsection = $this->page->url->param('section');
2931 // Disable the navigation from automatically finding the active node
2932 navigation_node::$autofindactive = false;
2933 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
2934 foreach ($adminroot->children as $adminbranch) {
2935 $this->load_administration_settings($referencebranch, $adminbranch);
2937 navigation_node::$autofindactive = true;
2939 // Use the admin structure to locate the active page
2940 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2941 $currentnode = $this;
2942 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2943 $currentnode = $currentnode->get($pathkey);
2946 $currentnode->make_active();
2949 $this->scan_for_active_node($referencebranch);
2951 return $referencebranch;
2952 } else if ($adminbranch->check_access()) {
2953 // We have a reference branch that we can access and is not hidden `hurrah`
2954 // Now we need to display it and any children it may have
2957 if ($adminbranch instanceof admin_settingpage) {
2958 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2959 } else if ($adminbranch instanceof admin_externalpage) {
2960 $url = $adminbranch->url;
2964 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
2966 if ($adminbranch->is_hidden()) {
2967 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2968 $reference->add_class('hidden');
2970 $reference->display = false;
2974 // Check if we are generating the admin notifications and whether notificiations exist
2975 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2976 $reference->add_class('criticalnotification');
2978 // Check if this branch has children
2979 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2980 foreach ($adminbranch->children as $branch) {
2981 // Generate the child branches as well now using this branch as the reference
2982 $this->load_administration_settings($reference, $branch);
2985 $reference->icon = new pix_icon('i/settings', '');
2991 * This function recursivily scans nodes until it finds the active node or there
2992 * are no more nodes.
2993 * @param navigation_node $node
2995 protected function scan_for_active_node(navigation_node $node) {
2996 if (!$node->check_if_active() && $node->children->count()>0) {
2997 foreach ($node->children as &$child) {
2998 $this->scan_for_active_node($child);
3004 * Gets a navigation node given an array of keys that represent the path to
3007 * @param array $path
3008 * @return navigation_node|false
3010 protected function get_by_path(array $path) {
3011 $node = $this->get(array_shift($path));
3012 foreach ($path as $key) {
3019 * Generate the list of modules for the given course.
3021 * @param stdClass $course The course to get modules for
3023 protected function get_course_modules($course) {
3025 $mods = $modnames = $modnamesplural = $modnamesused = array();
3026 // This function is included when we include course/lib.php at the top
3028 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
3029 $resources = array();
3030 $activities = array();
3031 foreach($modnames as $modname=>$modnamestr) {
3032 if (!course_allowed_module($course, $modname)) {
3036 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3037 if (!file_exists($libfile)) {
3040 include_once($libfile);
3041 $gettypesfunc = $modname.'_get_types';
3042 if (function_exists($gettypesfunc)) {
3043 $types = $gettypesfunc();
3044 foreach($types as $type) {
3045 if (!isset($type->modclass) || !isset($type->typestr)) {
3046 debugging('Incorrect activity type in '.$modname);
3049 if ($type->modclass == MOD_CLASS_RESOURCE) {
3050 $resources[html_entity_decode($type->type)] = $type->typestr;
3052 $activities[html_entity_decode($type->type)] = $type->typestr;
3056 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3057 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
3058 $resources[$modname] = $modnamestr;
3060 // all other archetypes are considered activity
3061 $activities[$modname] = $modnamestr;
3065 return array($resources, $activities);
3069 * This function loads the course settings that are available for the user
3071 * @param bool $forceopen If set to true the course node will be forced open
3072 * @return navigation_node|false
3074 protected function load_course_settings($forceopen = false) {
3077 $course = $this->page->course;
3078 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
3080 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3082 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3084 $coursenode->force_open();
3087 if (has_capability('moodle/course:update', $coursecontext)) {
3088 // Add the turn on/off settings
3089 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
3090 if ($this->page->user_is_editing()) {
3091 $url->param('edit', 'off');
3092 $editstring = get_string('turneditingoff');
3094 $url->param('edit', 'on');
3095 $editstring = get_string('turneditingon');
3097 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3099 if ($this->page->user_is_editing()) {
3100 // Removed as per MDL-22732
3101 // $this->add_course_editing_links($course);
3104 // Add the course settings link
3105 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3106 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3108 // Add the course completion settings link
3109 if ($CFG->enablecompletion && $course->enablecompletion) {
3110 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3111 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3116 enrol_add_course_navigation($coursenode, $course);
3119 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3120 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3121 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3124 // Add view grade report is permitted
3125 $reportavailable = false;
3126 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3127 $reportavailable = true;
3128 } else if (!empty($course->showgrades)) {
3129 $reports = get_plugin_list('gradereport');
3130 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3131 arsort($reports); // user is last, we want to test it first
3132 foreach ($reports as $plugin => $plugindir) {
3133 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3134 //stop when the first visible plugin is found
3135 $reportavailable = true;
3141 if ($reportavailable) {
3142 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3143 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3146 // Add outcome if permitted
3147 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3148 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3149 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3152 // Backup this course
3153 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3154 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3155 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3158 // Restore to this course
3159 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3160 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3161 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3164 // Import data from other courses
3165 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3166 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3167 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
3170 // Publish course on a hub
3171 if (has_capability('moodle/course:publish', $coursecontext)) {
3172 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3173 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3176 // Reset this course
3177 if (has_capability('moodle/course:reset', $coursecontext)) {
3178 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3179 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3183 require_once($CFG->dirroot.'/question/editlib.php');
3184 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3186 if (has_capability('moodle/course:update', $coursecontext)) {
3187 // Repository Instances
3188 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3189 require_once($CFG->dirroot . '/repository/lib.php');
3190 $editabletypes = repository::get_editable_types($coursecontext);
3191 $haseditabletypes = !empty($editabletypes);
3192 unset($editabletypes);
3193 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3195 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3197 if ($haseditabletypes) {
3198 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3199 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3204 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3205 // hidden in new courses and courses where legacy files were turned off
3206 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3207 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
3212 $assumedrole = $this->in_alternative_role();
3213 if ($assumedrole !== false) {
3214 $roles[0] = get_string('switchrolereturn');
3216 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3217 $availableroles = get_switchable_roles($coursecontext);
3218 if (is_array($availableroles)) {
3219 foreach ($availableroles as $key=>$role) {
3220 if ($assumedrole == (int)$key) {
3223 $roles[$key] = $role;
3227 if (is_array($roles) && count($roles)>0) {
3228 $switchroles = $this->add(get_string('switchroleto'));
3229 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3230 $switchroles->force_open();
3232 $returnurl = $this->page->url;
3233 $returnurl->param('sesskey', sesskey());
3234 foreach ($roles as $key => $name) {
3235 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3236 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
3239 // Return we are done
3244 * Adds branches and links to the settings navigation to add course activities
3247 * @param stdClass $course
3249 protected function add_course_editing_links($course) {
3252 require_once($CFG->dirroot.'/course/lib.php');
3254 // Add `add` resources|activities branches
3255 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3256 if (file_exists($structurefile)) {
3257 require_once($structurefile);
3258 $requestkey = call_user_func('callback_'.$course->format.'_request_key');
3259 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3261 $requestkey = get_string('section');
3262 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3265 $sections = get_all_sections($course->id);
3267 $addresource = $this->add(get_string('addresource'));
3268 $addactivity = $this->add(get_string('addactivity'));
3269 if ($formatidentifier!==0) {
3270 $addresource->force_open();
3271 $addactivity->force_open();
3274 $this->get_course_modules($course);
3276 $textlib = textlib_get_instance();
3278 foreach ($sections as $section) {
3279 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
3282 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $requestkey=>$section->section));
3283 if ($section->section == 0) {
3284 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3285 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3287 $sectionname = get_section_name($course, $section);
3288 $sectionresources = $addresource->add($sectionname, $sectionurl, self::TYPE_SETTING);
3289 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self::TYPE_SETTING);
3291 foreach ($resources as $value=>$resource) {
3292 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3293 $pos = strpos($value, '&type=');
3295 $url->param('add', $textlib->substr($value, 0,$pos));
3296 $url->param('type', $textlib->substr($value, $pos+6));
3298 $url->param('add', $value);
3300 $sectionresources->add($resource, $url, self::TYPE_SETTING);
3303 foreach ($activities as $activityname=>$activity) {
3304 if ($activity==='--') {
3308 if (strpos($activity, '--')===0) {
3309 $subbranch = $sectionactivities->add(trim($activity, '-'));
3312 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3313 $pos = strpos($activityname, '&type=');
3315 $url->param('add', $textlib->substr($activityname, 0,$pos));
3316 $url->param('type', $textlib->substr($activityname, $pos+6));
3318 $url->param('add', $activityname);
3320 if ($subbranch !== false) {
3321 $subbranch->add($activity, $url, self::TYPE_SETTING);
3323 $sectionactivities->add($activity, $url, self::TYPE_SETTING);
3330 * This function calls the module function to inject module settings into the
3331 * settings navigation tree.
3333 * This only gets called if there is a corrosponding function in the modules
3336 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
3338 * @return navigation_node|false
3340 protected function load_module_settings() {
3343 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3344 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3345 $this->page->set_cm($cm, $this->page->course);
3348 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3349 if (file_exists($file)) {
3350 require_once($file);
3353 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3354 $modulenode->force_open();
3356 // Settings for the module
3357 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3358 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3359 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3361 // Assign local roles
3362 if (count(get_assignable_roles($this->page->cm->context))>0) {
3363 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3364 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3367 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3368 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3369 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3371 // Check role permissions
3372 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3373 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3374 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3377 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3378 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3379 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3382 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $this->page->cm->course))) {
3383 $url = new moodle_url('/course/report/log/index.php', array('chooselog'=>'1','id'=>$this->page->cm->course,'modid'=>$this->page->cm->id));
3384 $modulenode->add(get_string('logs'), $url, self::TYPE_SETTING, null, 'logreport');
3387 // Add a backup link
3388 $featuresfunc = $this->page->activityname.'_supports';
3389 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3390 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3391 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3394 // Restore this activity
3395 $featuresfunc = $this->page->activityname.'_supports';
3396 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3397 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3398 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3401 $function = $this->page->activityname.'_extend_settings_navigation';
3402 if (!function_exists($function)) {
3406 $function($this, $modulenode);
3408 // Remove the module node if there are no children
3409 if (empty($modulenode->children)) {
3410 $modulenode->remove();
3417 * Loads the user settings block of the settings nav
3419 * This function is simply works out the userid and whether we need to load
3420 * just the current users profile settings, or the current user and the user the
3421 * current user is viewing.
3423 * This function has some very ugly code to work out the user, if anyone has
3424 * any bright ideas please feel free to intervene.
3426 * @param int $courseid The course id of the current course
3427 * @return navigation_node|false
3429 protected function load_user_settings($courseid=SITEID) {
3430 global $USER, $FULLME, $CFG;
3432 if (isguestuser() || !isloggedin()) {
3436 $navusers = $this->page->navigation->get_extending_users();
3438 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3440 foreach ($this->userstoextendfor as $userid) {
3441 if ($userid == $USER->id) {
3444 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3445 if (is_null($usernode)) {
3449 foreach ($navusers as $user) {
3450 if ($user->id == $USER->id) {
3453 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3454 if (is_null($usernode)) {
3458 $this->generate_user_settings($courseid, $USER->id);
3460 $usernode = $this->generate_user_settings($courseid, $USER->id);
3466 * Extends the settings navigation for the given user.
3468 * Note: This method gets called automatically if you call
3469 * $PAGE->navigation->extend_for_user($userid)
3471 * @param int $userid
3473 public function extend_for_user($userid) {
3476 if (!in_array($userid, $this->userstoextendfor)) {
3477 $this->userstoextendfor[] = $userid;
3478 if ($this->initialised) {
3479 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3480 $children = array();
3481 foreach ($this->children as $child) {
3482 $children[] = $child;
3484 array_unshift($children, array_pop($children));
3485 $this->children = new navigation_node_collection();
3486 foreach ($children as $child) {
3487 $this->children->add($child);
3494 * This function gets called by {@link load_user_settings()} and actually works out
3495 * what can be shown/done
3497 * @global moodle_database $DB
3498 * @param int $courseid The current course' id
3499 * @param int $userid The user id to load for
3500 * @param string $gstitle The string to pass to get_string for the branch title
3501 * @return navigation_node|false
3503 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3504 global $DB, $CFG, $USER, $SITE;
3506 if ($courseid != SITEID) {
3507 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3508 $course = $this->page->course;
3510 list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
3511 $sql = "SELECT c.* $select FROM {course} c $join WHERE c.id = :courseid";
3512 $course = $DB->get_record_sql($sql, array('courseid' => $courseid), MUST_EXIST);
3513 context_instance_preload($course);
3519 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3520 $systemcontext = get_system_context();
3521 $currentuser = ($USER->id == $userid);
3525 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3528 list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
3529 $sql = "SELECT u.* $select FROM {user} u $join WHERE u.id = :userid";
3530 $user = $DB->get_record_sql($sql, array('userid' => $userid), IGNORE_MISSING);
3534 context_instance_preload($user);
3536 // Check that the user can view the profile
3537 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3538 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3540 if ($course->id == SITEID) {
3541 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
3542 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3546 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
3547 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
3548 if ((!$canviewusercourse && !$canviewuser) || !can_access_course($coursecontext, $user->id)) {
3551 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
3552 // If groups are in use, make sure we can see that group
3558 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3561 if ($gstitle != 'usercurrentsettings') {
3565 // Add a user setting branch
3566 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3567 $usersetting->id = 'usersettings';
3568 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3569 // Automatically start by making it active
3570 $usersetting->make_active();
3573 // Check if the user has been deleted
3574 if ($user->deleted) {
3575 if (!has_capability('moodle/user:update', $coursecontext)) {
3576 // We can't edit the user so just show the user deleted message
3577 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3579 // We can edit the user so show the user deleted message and link it to the profile
3580 if ($course->id == SITEID) {
3581 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3583 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3585 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3590 $userauthplugin = false;
3591 if (!empty($user->auth)) {
3592 $userauthplugin = get_auth_plugin($user->auth);
3595 // Add the profile edit link
3596 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3597 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3598 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3599 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3600 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3601 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
3602 $url = $userauthplugin->edit_profile_url();
3604 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3606 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3611 // Change password link
3612 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
3613 $passwordchangeurl = $userauthplugin->change_password_url();
3614 if (empty($passwordchangeurl)) {
3615 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3617 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3620 // View the roles settings
3621 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3622 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3624 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3625 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3627 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3629 if (!empty($assignableroles)) {
3630 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3631 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3634 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3635 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3636 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3639 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3640 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3644 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3645 require_once($CFG->libdir . '/portfoliolib.php');
3646 if (portfolio_instances(true, false)) {
3647 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3649 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3650 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
3652 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
3653 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
3657 $enablemanagetokens = false;
3658 if (!empty($CFG->enablerssfeeds)) {
3659 $enablemanagetokens = true;
3660 } else if (!is_siteadmin($USER->id)
3661 && !empty($CFG->enablewebservices)
3662 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3663 $enablemanagetokens = true;
3666 if ($currentuser && $enablemanagetokens) {
3667 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3668 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
3672 if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
3673 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
3674 require_once($CFG->dirroot . '/repository/lib.php');
3675 $editabletypes = repository::get_editable_types($usercontext);
3676 $haseditabletypes = !empty($editabletypes);
3677 unset($editabletypes);
3678 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
3680 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
3682 if ($haseditabletypes) {
3683 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
3684 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
3689 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
3690 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3691 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
3695 if ($currentuser && !empty($CFG->bloglevel)) {
3696 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
3697 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
3698 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
3699 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
3700 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
3705 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
3706 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
3707 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
3710 return $usersetting;
3714 * Loads block specific settings in the navigation
3716 * @return navigation_node
3718 protected function load_block_settings() {
3721 $blocknode = $this->add(print_context_name($this->context));
3722 $blocknode->force_open();
3724 // Assign local roles
3725 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3726 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
3729 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3730 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3731 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3733 // Check role permissions
3734 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3735 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3736 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3743 * Loads category specific settings in the navigation
3745 * @return navigation_node
3747 protected function load_category_settings() {
3750 $categorynode = $this->add(print_context_name($this->context));
3751 $categorynode->force_open();
3753 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context)) {
3754 $url = new moodle_url('/course/category.php', array('id'=>$this->context->instanceid, 'sesskey'=>sesskey()));
3755 if ($this->page->user_is_editing()) {
3756 $url->param('categoryedit', '0');
3757 $editstring = get_string('turneditingoff');
3759 $url->param('categoryedit', '1');
3760 $editstring = get_string('turneditingon');
3762 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3765 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
3766 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
3767 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
3769 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
3770 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
3773 // Assign local roles
3774 if (has_capability('moodle/role:assign', $this->context)) {
3775 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3776 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
3780 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3781 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3782 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
3784 // Check role permissions
3785 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3786 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3787 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
3791 if (has_capability('moodle/cohort:manage', $this->context) or has_capability('moodle/cohort:view', $this->context)) {
3792 $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', ''));
3796 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
3797 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
3798 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
3801 return $categorynode;
3805 * Determine whether the user is assuming another role
3807 * This function checks to see if the user is assuming another role by means of
3808 * role switching. In doing this we compare each RSW key (context path) against
3809 * the current context path. This ensures that we can provide the switching
3810 * options against both the course and any page shown under the course.
3812 * @return bool|int The role(int) if the user is in another role, false otherwise
3814 protected function in_alternative_role() {
3816 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
3817 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
3818 return $USER->access['rsw'][$this->page->context->path];
3820 foreach ($USER->access['rsw'] as $key=>$role) {
3821 if (strpos($this->context->path,$key)===0) {