MDL-36805 Correct docs for workshop_grade_item_update in mod_workshop
[moodle.git] / lib / navigationlib.php
blob0fd249691c8b08bfedde7b23f1a37bef6e483a1f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
33 /**
34 * This class is used to represent a node in a navigation tree
36 * This class is used to represent a node in a navigation tree within Moodle,
37 * the tree could be one of global navigation, settings navigation, or the navbar.
38 * Each node can be one of two types either a Leaf (default) or a branch.
39 * When a node is first created it is created as a leaf, when/if children are added
40 * the node then becomes a branch.
42 * @package core
43 * @category navigation
44 * @copyright 2009 Sam Hemelryk
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class navigation_node implements renderable {
48 /** @var int Used to identify this node a leaf (default) 0 */
49 const NODETYPE_LEAF = 0;
50 /** @var int Used to identify this node a branch, happens with children 1 */
51 const NODETYPE_BRANCH = 1;
52 /** @var null Unknown node type null */
53 const TYPE_UNKNOWN = null;
54 /** @var int System node type 0 */
55 const TYPE_ROOTNODE = 0;
56 /** @var int System node type 1 */
57 const TYPE_SYSTEM = 1;
58 /** @var int Category node type 10 */
59 const TYPE_CATEGORY = 10;
60 /** @var int Course node type 20 */
61 const TYPE_COURSE = 20;
62 /** @var int Course Structure node type 30 */
63 const TYPE_SECTION = 30;
64 /** @var int Activity node type, e.g. Forum, Quiz 40 */
65 const TYPE_ACTIVITY = 40;
66 /** @var int Resource node type, e.g. Link to a file, or label 50 */
67 const TYPE_RESOURCE = 50;
68 /** @var int A custom node type, default when adding without specifing type 60 */
69 const TYPE_CUSTOM = 60;
70 /** @var int Setting node type, used only within settings nav 70 */
71 const TYPE_SETTING = 70;
72 /** @var int Setting node type, used only within settings nav 80 */
73 const TYPE_USER = 80;
74 /** @var int Setting node type, used for containers of no importance 90 */
75 const TYPE_CONTAINER = 90;
76 /** var int Course the current user is not enrolled in */
77 const COURSE_OTHER = 0;
78 /** var int Course the current user is enrolled in but not viewing */
79 const COURSE_MY = 1;
80 /** var int Course the current user is currently viewing */
81 const COURSE_CURRENT = 2;
83 /** @var int Parameter to aid the coder in tracking [optional] */
84 public $id = null;
85 /** @var string|int The identifier for the node, used to retrieve the node */
86 public $key = null;
87 /** @var string The text to use for the node */
88 public $text = null;
89 /** @var string Short text to use if requested [optional] */
90 public $shorttext = null;
91 /** @var string The title attribute for an action if one is defined */
92 public $title = null;
93 /** @var string A string that can be used to build a help button */
94 public $helpbutton = null;
95 /** @var moodle_url|action_link|null An action for the node (link) */
96 public $action = null;
97 /** @var pix_icon The path to an icon to use for this node */
98 public $icon = null;
99 /** @var int See TYPE_* constants defined for this class */
100 public $type = self::TYPE_UNKNOWN;
101 /** @var int See NODETYPE_* constants defined for this class */
102 public $nodetype = self::NODETYPE_LEAF;
103 /** @var bool If set to true the node will be collapsed by default */
104 public $collapse = false;
105 /** @var bool If set to true the node will be expanded by default */
106 public $forceopen = false;
107 /** @var array An array of CSS classes for the node */
108 public $classes = array();
109 /** @var navigation_node_collection An array of child nodes */
110 public $children = array();
111 /** @var bool If set to true the node will be recognised as active */
112 public $isactive = false;
113 /** @var bool If set to true the node will be dimmed */
114 public $hidden = false;
115 /** @var bool If set to false the node will not be displayed */
116 public $display = true;
117 /** @var bool If set to true then an HR will be printed before the node */
118 public $preceedwithhr = false;
119 /** @var bool If set to true the the navigation bar should ignore this node */
120 public $mainnavonly = false;
121 /** @var bool If set to true a title will be added to the action no matter what */
122 public $forcetitle = false;
123 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
124 public $parent = null;
125 /** @var bool Override to not display the icon even if one is provided **/
126 public $hideicon = false;
127 /** @var bool Set to true if we KNOW that this node can be expanded. */
128 public $isexpandable = false;
129 /** @var array */
130 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
131 /** @var moodle_url */
132 protected static $fullmeurl = null;
133 /** @var bool toogles auto matching of active node */
134 public static $autofindactive = true;
135 /** @var mixed If set to an int, that section will be included even if it has no activities */
136 public $includesectionnum = false;
139 * Constructs a new navigation_node
141 * @param array|string $properties Either an array of properties or a string to use
142 * as the text for the node
144 public function __construct($properties) {
145 if (is_array($properties)) {
146 // Check the array for each property that we allow to set at construction.
147 // text - The main content for the node
148 // shorttext - A short text if required for the node
149 // icon - The icon to display for the node
150 // type - The type of the node
151 // key - The key to use to identify the node
152 // parent - A reference to the nodes parent
153 // action - The action to attribute to this node, usually a URL to link to
154 if (array_key_exists('text', $properties)) {
155 $this->text = $properties['text'];
157 if (array_key_exists('shorttext', $properties)) {
158 $this->shorttext = $properties['shorttext'];
160 if (!array_key_exists('icon', $properties)) {
161 $properties['icon'] = new pix_icon('i/navigationitem', '');
163 $this->icon = $properties['icon'];
164 if ($this->icon instanceof pix_icon) {
165 if (empty($this->icon->attributes['class'])) {
166 $this->icon->attributes['class'] = 'navicon';
167 } else {
168 $this->icon->attributes['class'] .= ' navicon';
171 if (array_key_exists('type', $properties)) {
172 $this->type = $properties['type'];
173 } else {
174 $this->type = self::TYPE_CUSTOM;
176 if (array_key_exists('key', $properties)) {
177 $this->key = $properties['key'];
179 // This needs to happen last because of the check_if_active call that occurs
180 if (array_key_exists('action', $properties)) {
181 $this->action = $properties['action'];
182 if (is_string($this->action)) {
183 $this->action = new moodle_url($this->action);
185 if (self::$autofindactive) {
186 $this->check_if_active();
189 if (array_key_exists('parent', $properties)) {
190 $this->set_parent($properties['parent']);
192 } else if (is_string($properties)) {
193 $this->text = $properties;
195 if ($this->text === null) {
196 throw new coding_exception('You must set the text for the node when you create it.');
198 // Default the title to the text
199 $this->title = $this->text;
200 // Instantiate a new navigation node collection for this nodes children
201 $this->children = new navigation_node_collection();
205 * Checks if this node is the active node.
207 * This is determined by comparing the action for the node against the
208 * defined URL for the page. A match will see this node marked as active.
210 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
211 * @return bool
213 public function check_if_active($strength=URL_MATCH_EXACT) {
214 global $FULLME, $PAGE;
215 // Set fullmeurl if it hasn't already been set
216 if (self::$fullmeurl == null) {
217 if ($PAGE->has_set_url()) {
218 self::override_active_url(new moodle_url($PAGE->url));
219 } else {
220 self::override_active_url(new moodle_url($FULLME));
224 // Compare the action of this node against the fullmeurl
225 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
226 $this->make_active();
227 return true;
229 return false;
233 * This sets the URL that the URL of new nodes get compared to when locating
234 * the active node.
236 * The active node is the node that matches the URL set here. By default this
237 * is either $PAGE->url or if that hasn't been set $FULLME.
239 * @param moodle_url $url The url to use for the fullmeurl.
241 public static function override_active_url(moodle_url $url) {
242 // Clone the URL, in case the calling script changes their URL later.
243 self::$fullmeurl = new moodle_url($url);
247 * Creates a navigation node, ready to add it as a child using add_node
248 * function. (The created node needs to be added before you can use it.)
249 * @param string $text
250 * @param moodle_url|action_link $action
251 * @param int $type
252 * @param string $shorttext
253 * @param string|int $key
254 * @param pix_icon $icon
255 * @return navigation_node
257 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
258 $shorttext=null, $key=null, pix_icon $icon=null) {
259 // Properties array used when creating the new navigation node
260 $itemarray = array(
261 'text' => $text,
262 'type' => $type
264 // Set the action if one was provided
265 if ($action!==null) {
266 $itemarray['action'] = $action;
268 // Set the shorttext if one was provided
269 if ($shorttext!==null) {
270 $itemarray['shorttext'] = $shorttext;
272 // Set the icon if one was provided
273 if ($icon!==null) {
274 $itemarray['icon'] = $icon;
276 // Set the key
277 $itemarray['key'] = $key;
278 // Construct and return
279 return new navigation_node($itemarray);
283 * Adds a navigation node as a child of this node.
285 * @param string $text
286 * @param moodle_url|action_link $action
287 * @param int $type
288 * @param string $shorttext
289 * @param string|int $key
290 * @param pix_icon $icon
291 * @return navigation_node
293 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
294 // Create child node
295 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
297 // Add the child to end and return
298 return $this->add_node($childnode);
302 * Adds a navigation node as a child of this one, given a $node object
303 * created using the create function.
304 * @param navigation_node $childnode Node to add
305 * @param string $beforekey
306 * @return navigation_node The added node
308 public function add_node(navigation_node $childnode, $beforekey=null) {
309 // First convert the nodetype for this node to a branch as it will now have children
310 if ($this->nodetype !== self::NODETYPE_BRANCH) {
311 $this->nodetype = self::NODETYPE_BRANCH;
313 // Set the parent to this node
314 $childnode->set_parent($this);
316 // Default the key to the number of children if not provided
317 if ($childnode->key === null) {
318 $childnode->key = $this->children->count();
321 // Add the child using the navigation_node_collections add method
322 $node = $this->children->add($childnode, $beforekey);
324 // If added node is a category node or the user is logged in and it's a course
325 // then mark added node as a branch (makes it expandable by AJAX)
326 $type = $childnode->type;
327 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
328 $node->nodetype = self::NODETYPE_BRANCH;
330 // If this node is hidden mark it's children as hidden also
331 if ($this->hidden) {
332 $node->hidden = true;
334 // Return added node (reference returned by $this->children->add()
335 return $node;
339 * Return a list of all the keys of all the child nodes.
340 * @return array the keys.
342 public function get_children_key_list() {
343 return $this->children->get_key_list();
347 * Searches for a node of the given type with the given key.
349 * This searches this node plus all of its children, and their children....
350 * If you know the node you are looking for is a child of this node then please
351 * use the get method instead.
353 * @param int|string $key The key of the node we are looking for
354 * @param int $type One of navigation_node::TYPE_*
355 * @return navigation_node|false
357 public function find($key, $type) {
358 return $this->children->find($key, $type);
362 * Get the child of this node that has the given key + (optional) type.
364 * If you are looking for a node and want to search all children + thier children
365 * then please use the find method instead.
367 * @param int|string $key The key of the node we are looking for
368 * @param int $type One of navigation_node::TYPE_*
369 * @return navigation_node|false
371 public function get($key, $type=null) {
372 return $this->children->get($key, $type);
376 * Removes this node.
378 * @return bool
380 public function remove() {
381 return $this->parent->children->remove($this->key, $this->type);
385 * Checks if this node has or could have any children
387 * @return bool Returns true if it has children or could have (by AJAX expansion)
389 public function has_children() {
390 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
394 * Marks this node as active and forces it open.
396 * Important: If you are here because you need to mark a node active to get
397 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
398 * You can use it to specify a different URL to match the active navigation node on
399 * rather than having to locate and manually mark a node active.
401 public function make_active() {
402 $this->isactive = true;
403 $this->add_class('active_tree_node');
404 $this->force_open();
405 if ($this->parent !== null) {
406 $this->parent->make_inactive();
411 * Marks a node as inactive and recusised back to the base of the tree
412 * doing the same to all parents.
414 public function make_inactive() {
415 $this->isactive = false;
416 $this->remove_class('active_tree_node');
417 if ($this->parent !== null) {
418 $this->parent->make_inactive();
423 * Forces this node to be open and at the same time forces open all
424 * parents until the root node.
426 * Recursive.
428 public function force_open() {
429 $this->forceopen = true;
430 if ($this->parent !== null) {
431 $this->parent->force_open();
436 * Adds a CSS class to this node.
438 * @param string $class
439 * @return bool
441 public function add_class($class) {
442 if (!in_array($class, $this->classes)) {
443 $this->classes[] = $class;
445 return true;
449 * Removes a CSS class from this node.
451 * @param string $class
452 * @return bool True if the class was successfully removed.
454 public function remove_class($class) {
455 if (in_array($class, $this->classes)) {
456 $key = array_search($class,$this->classes);
457 if ($key!==false) {
458 unset($this->classes[$key]);
459 return true;
462 return false;
466 * Sets the title for this node and forces Moodle to utilise it.
467 * @param string $title
469 public function title($title) {
470 $this->title = $title;
471 $this->forcetitle = true;
475 * Resets the page specific information on this node if it is being unserialised.
477 public function __wakeup(){
478 $this->forceopen = false;
479 $this->isactive = false;
480 $this->remove_class('active_tree_node');
484 * Checks if this node or any of its children contain the active node.
486 * Recursive.
488 * @return bool
490 public function contains_active_node() {
491 if ($this->isactive) {
492 return true;
493 } else {
494 foreach ($this->children as $child) {
495 if ($child->isactive || $child->contains_active_node()) {
496 return true;
500 return false;
504 * Finds the active node.
506 * Searches this nodes children plus all of the children for the active node
507 * and returns it if found.
509 * Recursive.
511 * @return navigation_node|false
513 public function find_active_node() {
514 if ($this->isactive) {
515 return $this;
516 } else {
517 foreach ($this->children as &$child) {
518 $outcome = $child->find_active_node();
519 if ($outcome !== false) {
520 return $outcome;
524 return false;
528 * Searches all children for the best matching active node
529 * @return navigation_node|false
531 public function search_for_active_node() {
532 if ($this->check_if_active(URL_MATCH_BASE)) {
533 return $this;
534 } else {
535 foreach ($this->children as &$child) {
536 $outcome = $child->search_for_active_node();
537 if ($outcome !== false) {
538 return $outcome;
542 return false;
546 * Gets the content for this node.
548 * @param bool $shorttext If true shorttext is used rather than the normal text
549 * @return string
551 public function get_content($shorttext=false) {
552 if ($shorttext && $this->shorttext!==null) {
553 return format_string($this->shorttext);
554 } else {
555 return format_string($this->text);
560 * Gets the title to use for this node.
562 * @return string
564 public function get_title() {
565 if ($this->forcetitle || $this->action != null){
566 return $this->title;
567 } else {
568 return '';
573 * Gets the CSS class to add to this node to describe its type
575 * @return string
577 public function get_css_type() {
578 if (array_key_exists($this->type, $this->namedtypes)) {
579 return 'type_'.$this->namedtypes[$this->type];
581 return 'type_unknown';
585 * Finds all nodes that are expandable by AJAX
587 * @param array $expandable An array by reference to populate with expandable nodes.
589 public function find_expandable(array &$expandable) {
590 foreach ($this->children as &$child) {
591 if ($child->display && $child->has_children() && $child->children->count() == 0) {
592 $child->id = 'expandable_branch_'.(count($expandable)+1);
593 $this->add_class('canexpand');
594 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
596 $child->find_expandable($expandable);
601 * Finds all nodes of a given type (recursive)
603 * @param int $type One of navigation_node::TYPE_*
604 * @return array
606 public function find_all_of_type($type) {
607 $nodes = $this->children->type($type);
608 foreach ($this->children as &$node) {
609 $childnodes = $node->find_all_of_type($type);
610 $nodes = array_merge($nodes, $childnodes);
612 return $nodes;
616 * Removes this node if it is empty
618 public function trim_if_empty() {
619 if ($this->children->count() == 0) {
620 $this->remove();
625 * Creates a tab representation of this nodes children that can be used
626 * with print_tabs to produce the tabs on a page.
628 * call_user_func_array('print_tabs', $node->get_tabs_array());
630 * @param array $inactive
631 * @param bool $return
632 * @return array Array (tabs, selected, inactive, activated, return)
634 public function get_tabs_array(array $inactive=array(), $return=false) {
635 $tabs = array();
636 $rows = array();
637 $selected = null;
638 $activated = array();
639 foreach ($this->children as $node) {
640 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
641 if ($node->contains_active_node()) {
642 if ($node->children->count() > 0) {
643 $activated[] = $node->key;
644 foreach ($node->children as $child) {
645 if ($child->contains_active_node()) {
646 $selected = $child->key;
648 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
650 } else {
651 $selected = $node->key;
655 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
659 * Sets the parent for this node and if this node is active ensures that the tree is properly
660 * adjusted as well.
662 * @param navigation_node $parent
664 public function set_parent(navigation_node $parent) {
665 // Set the parent (thats the easy part)
666 $this->parent = $parent;
667 // Check if this node is active (this is checked during construction)
668 if ($this->isactive) {
669 // Force all of the parent nodes open so you can see this node
670 $this->parent->force_open();
671 // Make all parents inactive so that its clear where we are.
672 $this->parent->make_inactive();
678 * Navigation node collection
680 * This class is responsible for managing a collection of navigation nodes.
681 * It is required because a node's unique identifier is a combination of both its
682 * key and its type.
684 * Originally an array was used with a string key that was a combination of the two
685 * however it was decided that a better solution would be to use a class that
686 * implements the standard IteratorAggregate interface.
688 * @package core
689 * @category navigation
690 * @copyright 2010 Sam Hemelryk
691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 class navigation_node_collection implements IteratorAggregate {
695 * A multidimensional array to where the first key is the type and the second
696 * key is the nodes key.
697 * @var array
699 protected $collection = array();
701 * An array that contains references to nodes in the same order they were added.
702 * This is maintained as a progressive array.
703 * @var array
705 protected $orderedcollection = array();
707 * A reference to the last node that was added to the collection
708 * @var navigation_node
710 protected $last = null;
712 * The total number of items added to this array.
713 * @var int
715 protected $count = 0;
718 * Adds a navigation node to the collection
720 * @param navigation_node $node Node to add
721 * @param string $beforekey If specified, adds before a node with this key,
722 * otherwise adds at end
723 * @return navigation_node Added node
725 public function add(navigation_node $node, $beforekey=null) {
726 global $CFG;
727 $key = $node->key;
728 $type = $node->type;
730 // First check we have a 2nd dimension for this type
731 if (!array_key_exists($type, $this->orderedcollection)) {
732 $this->orderedcollection[$type] = array();
734 // Check for a collision and report if debugging is turned on
735 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
736 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
739 // Find the key to add before
740 $newindex = $this->count;
741 $last = true;
742 if ($beforekey !== null) {
743 foreach ($this->collection as $index => $othernode) {
744 if ($othernode->key === $beforekey) {
745 $newindex = $index;
746 $last = false;
747 break;
750 if ($newindex === $this->count) {
751 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
752 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
756 // Add the node to the appropriate place in the by-type structure (which
757 // is not ordered, despite the variable name)
758 $this->orderedcollection[$type][$key] = $node;
759 if (!$last) {
760 // Update existing references in the ordered collection (which is the
761 // one that isn't called 'ordered') to shuffle them along if required
762 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
763 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
766 // Add a reference to the node to the progressive collection.
767 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
768 // Update the last property to a reference to this new node.
769 $this->last = $this->orderedcollection[$type][$key];
771 // Reorder the array by index if needed
772 if (!$last) {
773 ksort($this->collection);
775 $this->count++;
776 // Return the reference to the now added node
777 return $node;
781 * Return a list of all the keys of all the nodes.
782 * @return array the keys.
784 public function get_key_list() {
785 $keys = array();
786 foreach ($this->collection as $node) {
787 $keys[] = $node->key;
789 return $keys;
793 * Fetches a node from this collection.
795 * @param string|int $key The key of the node we want to find.
796 * @param int $type One of navigation_node::TYPE_*.
797 * @return navigation_node|null
799 public function get($key, $type=null) {
800 if ($type !== null) {
801 // If the type is known then we can simply check and fetch
802 if (!empty($this->orderedcollection[$type][$key])) {
803 return $this->orderedcollection[$type][$key];
805 } else {
806 // Because we don't know the type we look in the progressive array
807 foreach ($this->collection as $node) {
808 if ($node->key === $key) {
809 return $node;
813 return false;
817 * Searches for a node with matching key and type.
819 * This function searches both the nodes in this collection and all of
820 * the nodes in each collection belonging to the nodes in this collection.
822 * Recursive.
824 * @param string|int $key The key of the node we want to find.
825 * @param int $type One of navigation_node::TYPE_*.
826 * @return navigation_node|null
828 public function find($key, $type=null) {
829 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
830 return $this->orderedcollection[$type][$key];
831 } else {
832 $nodes = $this->getIterator();
833 // Search immediate children first
834 foreach ($nodes as &$node) {
835 if ($node->key === $key && ($type === null || $type === $node->type)) {
836 return $node;
839 // Now search each childs children
840 foreach ($nodes as &$node) {
841 $result = $node->children->find($key, $type);
842 if ($result !== false) {
843 return $result;
847 return false;
851 * Fetches the last node that was added to this collection
853 * @return navigation_node
855 public function last() {
856 return $this->last;
860 * Fetches all nodes of a given type from this collection
862 * @param string|int $type node type being searched for.
863 * @return array ordered collection
865 public function type($type) {
866 if (!array_key_exists($type, $this->orderedcollection)) {
867 $this->orderedcollection[$type] = array();
869 return $this->orderedcollection[$type];
872 * Removes the node with the given key and type from the collection
874 * @param string|int $key The key of the node we want to find.
875 * @param int $type
876 * @return bool
878 public function remove($key, $type=null) {
879 $child = $this->get($key, $type);
880 if ($child !== false) {
881 foreach ($this->collection as $colkey => $node) {
882 if ($node->key == $key && $node->type == $type) {
883 unset($this->collection[$colkey]);
884 break;
887 unset($this->orderedcollection[$child->type][$child->key]);
888 $this->count--;
889 return true;
891 return false;
895 * Gets the number of nodes in this collection
897 * This option uses an internal count rather than counting the actual options to avoid
898 * a performance hit through the count function.
900 * @return int
902 public function count() {
903 return $this->count;
906 * Gets an array iterator for the collection.
908 * This is required by the IteratorAggregator interface and is used by routines
909 * such as the foreach loop.
911 * @return ArrayIterator
913 public function getIterator() {
914 return new ArrayIterator($this->collection);
919 * The global navigation class used for... the global navigation
921 * This class is used by PAGE to store the global navigation for the site
922 * and is then used by the settings nav and navbar to save on processing and DB calls
924 * See
925 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
926 * {@link lib/ajax/getnavbranch.php} Called by ajax
928 * @package core
929 * @category navigation
930 * @copyright 2009 Sam Hemelryk
931 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
933 class global_navigation extends navigation_node {
934 /** @var moodle_page The Moodle page this navigation object belongs to. */
935 protected $page;
936 /** @var bool switch to let us know if the navigation object is initialised*/
937 protected $initialised = false;
938 /** @var array An array of course information */
939 protected $mycourses = array();
940 /** @var array An array for containing root navigation nodes */
941 protected $rootnodes = array();
942 /** @var bool A switch for whether to show empty sections in the navigation */
943 protected $showemptysections = true;
944 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
945 protected $showcategories = null;
946 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
947 protected $showmycategories = null;
948 /** @var array An array of stdClasses for users that the navigation is extended for */
949 protected $extendforuser = array();
950 /** @var navigation_cache */
951 protected $cache;
952 /** @var array An array of course ids that are present in the navigation */
953 protected $addedcourses = array();
954 /** @var bool */
955 protected $allcategoriesloaded = false;
956 /** @var array An array of category ids that are included in the navigation */
957 protected $addedcategories = array();
958 /** @var int expansion limit */
959 protected $expansionlimit = 0;
960 /** @var int userid to allow parent to see child's profile page navigation */
961 protected $useridtouseforparentchecks = 0;
963 /** Used when loading categories to load all top level categories [parent = 0] **/
964 const LOAD_ROOT_CATEGORIES = 0;
965 /** Used when loading categories to load all categories **/
966 const LOAD_ALL_CATEGORIES = -1;
969 * Constructs a new global navigation
971 * @param moodle_page $page The page this navigation object belongs to
973 public function __construct(moodle_page $page) {
974 global $CFG, $SITE, $USER;
976 if (during_initial_install()) {
977 return;
980 if (get_home_page() == HOMEPAGE_SITE) {
981 // We are using the site home for the root element
982 $properties = array(
983 'key' => 'home',
984 'type' => navigation_node::TYPE_SYSTEM,
985 'text' => get_string('home'),
986 'action' => new moodle_url('/')
988 } else {
989 // We are using the users my moodle for the root element
990 $properties = array(
991 'key' => 'myhome',
992 'type' => navigation_node::TYPE_SYSTEM,
993 'text' => get_string('myhome'),
994 'action' => new moodle_url('/my/')
998 // Use the parents constructor.... good good reuse
999 parent::__construct($properties);
1001 // Initalise and set defaults
1002 $this->page = $page;
1003 $this->forceopen = true;
1004 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1008 * Mutator to set userid to allow parent to see child's profile
1009 * page navigation. See MDL-25805 for initial issue. Linked to it
1010 * is an issue explaining why this is a REALLY UGLY HACK thats not
1011 * for you to use!
1013 * @param int $userid userid of profile page that parent wants to navigate around.
1015 public function set_userid_for_parent_checks($userid) {
1016 $this->useridtouseforparentchecks = $userid;
1021 * Initialises the navigation object.
1023 * This causes the navigation object to look at the current state of the page
1024 * that it is associated with and then load the appropriate content.
1026 * This should only occur the first time that the navigation structure is utilised
1027 * which will normally be either when the navbar is called to be displayed or
1028 * when a block makes use of it.
1030 * @return bool
1032 public function initialise() {
1033 global $CFG, $SITE, $USER;
1034 // Check if it has already been initialised
1035 if ($this->initialised || during_initial_install()) {
1036 return true;
1038 $this->initialised = true;
1040 // Set up the five base root nodes. These are nodes where we will put our
1041 // content and are as follows:
1042 // site: Navigation for the front page.
1043 // myprofile: User profile information goes here.
1044 // currentcourse: The course being currently viewed.
1045 // mycourses: The users courses get added here.
1046 // courses: Additional courses are added here.
1047 // users: Other users information loaded here.
1048 $this->rootnodes = array();
1049 if (get_home_page() == HOMEPAGE_SITE) {
1050 // The home element should be my moodle because the root element is the site
1051 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1052 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1054 } else {
1055 // The home element should be the site because the root node is my moodle
1056 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1057 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1058 // We need to stop automatic redirection
1059 $this->rootnodes['home']->action->param('redirect', '0');
1062 $this->rootnodes['site'] = $this->add_course($SITE);
1063 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1064 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1065 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
1066 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1067 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1069 // We always load the frontpage course to ensure it is available without
1070 // JavaScript enabled.
1071 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1072 $this->load_course_sections($SITE, $this->rootnodes['site']);
1074 $course = $this->page->course;
1076 // $issite gets set to true if the current pages course is the sites frontpage course
1077 $issite = ($this->page->course->id == $SITE->id);
1078 // Determine if the user is enrolled in any course.
1079 $enrolledinanycourse = enrol_user_sees_own_courses();
1081 $this->rootnodes['currentcourse']->mainnavonly = true;
1082 if ($enrolledinanycourse) {
1083 $this->rootnodes['mycourses']->isexpandable = true;
1084 if ($CFG->navshowallcourses) {
1085 // When we show all courses we need to show both the my courses and the regular courses branch.
1086 $this->rootnodes['courses']->isexpandable = true;
1088 } else {
1089 $this->rootnodes['courses']->isexpandable = true;
1092 $canviewcourseprofile = true;
1094 // Next load context specific content into the navigation
1095 switch ($this->page->context->contextlevel) {
1096 case CONTEXT_SYSTEM :
1097 // Nothing left to do here I feel.
1098 break;
1099 case CONTEXT_COURSECAT :
1100 // This is essential, we must load categories.
1101 $this->load_all_categories($this->page->context->instanceid, true);
1102 break;
1103 case CONTEXT_BLOCK :
1104 case CONTEXT_COURSE :
1105 if ($issite) {
1106 // Nothing left to do here.
1107 break;
1110 // Load the course associated with the current page into the navigation.
1111 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1112 // If the course wasn't added then don't try going any further.
1113 if (!$coursenode) {
1114 $canviewcourseprofile = false;
1115 break;
1118 // If the user is not enrolled then we only want to show the
1119 // course node and not populate it.
1121 // Not enrolled, can't view, and hasn't switched roles
1122 if (!can_access_course($course)) {
1123 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1124 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1125 if (!$this->current_user_is_parent_role()) {
1126 $coursenode->make_active();
1127 $canviewcourseprofile = false;
1128 break;
1132 // Add the essentials such as reports etc...
1133 $this->add_course_essentials($coursenode, $course);
1134 // Extend course navigation with it's sections/activities
1135 $this->load_course_sections($course, $coursenode);
1136 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1137 $coursenode->make_active();
1140 break;
1141 case CONTEXT_MODULE :
1142 if ($issite) {
1143 // If this is the site course then most information will have
1144 // already been loaded.
1145 // However we need to check if there is more content that can
1146 // yet be loaded for the specific module instance.
1147 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1148 if ($activitynode) {
1149 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1151 break;
1154 $course = $this->page->course;
1155 $cm = $this->page->cm;
1157 // Load the course associated with the page into the navigation
1158 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1160 // If the course wasn't added then don't try going any further.
1161 if (!$coursenode) {
1162 $canviewcourseprofile = false;
1163 break;
1166 // If the user is not enrolled then we only want to show the
1167 // course node and not populate it.
1168 if (!can_access_course($course)) {
1169 $coursenode->make_active();
1170 $canviewcourseprofile = false;
1171 break;
1174 $this->add_course_essentials($coursenode, $course);
1176 // Load the course sections into the page
1177 $this->load_course_sections($course, $coursenode, null, $cm);
1178 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1179 // Finally load the cm specific navigaton information
1180 $this->load_activity($cm, $course, $activity);
1181 // Check if we have an active ndoe
1182 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1183 // And make the activity node active.
1184 $activity->make_active();
1186 break;
1187 case CONTEXT_USER :
1188 if ($issite) {
1189 // The users profile information etc is already loaded
1190 // for the front page.
1191 break;
1193 $course = $this->page->course;
1194 // Load the course associated with the user into the navigation
1195 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1197 // If the course wasn't added then don't try going any further.
1198 if (!$coursenode) {
1199 $canviewcourseprofile = false;
1200 break;
1203 // If the user is not enrolled then we only want to show the
1204 // course node and not populate it.
1205 if (!can_access_course($course)) {
1206 $coursenode->make_active();
1207 $canviewcourseprofile = false;
1208 break;
1210 $this->add_course_essentials($coursenode, $course);
1211 $this->load_course_sections($course, $coursenode);
1212 break;
1215 // Load for the current user
1216 $this->load_for_user();
1217 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1218 $this->load_for_user(null, true);
1220 // Load each extending user into the navigation.
1221 foreach ($this->extendforuser as $user) {
1222 if ($user->id != $USER->id) {
1223 $this->load_for_user($user);
1227 // Give the local plugins a chance to include some navigation if they want.
1228 foreach (get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1229 $function = "local_{$plugin}_extends_navigation";
1230 $oldfunction = "{$plugin}_extends_navigation";
1231 if (function_exists($function)) {
1232 // This is the preferred function name as there is less chance of conflicts
1233 $function($this);
1234 } else if (function_exists($oldfunction)) {
1235 // We continue to support the old function name to ensure backwards compatibility
1236 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. Support for the old callback will be dropped after the release of 2.4", DEBUG_DEVELOPER);
1237 $oldfunction($this);
1241 // Remove any empty root nodes
1242 foreach ($this->rootnodes as $node) {
1243 // Dont remove the home node
1244 if ($node->key !== 'home' && !$node->has_children()) {
1245 $node->remove();
1249 if (!$this->contains_active_node()) {
1250 $this->search_for_active_node();
1253 // If the user is not logged in modify the navigation structure as detailed
1254 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1255 if (!isloggedin()) {
1256 $activities = clone($this->rootnodes['site']->children);
1257 $this->rootnodes['site']->remove();
1258 $children = clone($this->children);
1259 $this->children = new navigation_node_collection();
1260 foreach ($activities as $child) {
1261 $this->children->add($child);
1263 foreach ($children as $child) {
1264 $this->children->add($child);
1267 return true;
1271 * Returns true if the current user is a parent of the user being currently viewed.
1273 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1274 * other user being viewed this function returns false.
1275 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1277 * @since 2.4
1278 * @return bool
1280 protected function current_user_is_parent_role() {
1281 global $USER, $DB;
1282 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1283 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1284 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1285 return false;
1287 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1288 return true;
1291 return false;
1295 * Returns true if courses should be shown within categories on the navigation.
1297 * @param bool $ismycourse Set to true if you are calculating this for a course.
1298 * @return bool
1300 protected function show_categories($ismycourse = false) {
1301 global $CFG, $DB;
1302 if ($ismycourse) {
1303 return $this->show_my_categories();
1305 if ($this->showcategories === null) {
1306 $show = false;
1307 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1308 $show = true;
1309 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1310 $show = true;
1312 $this->showcategories = $show;
1314 return $this->showcategories;
1318 * Returns true if we should show categories in the My Courses branch.
1319 * @return bool
1321 protected function show_my_categories() {
1322 global $CFG, $DB;
1323 if ($this->showmycategories === null) {
1324 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1326 return $this->showmycategories;
1330 * Loads the courses in Moodle into the navigation.
1332 * @global moodle_database $DB
1333 * @param string|array $categoryids An array containing categories to load courses
1334 * for, OR null to load courses for all categories.
1335 * @return array An array of navigation_nodes one for each course
1337 protected function load_all_courses($categoryids = null) {
1338 global $CFG, $DB, $SITE;
1340 // Work out the limit of courses.
1341 $limit = 20;
1342 if (!empty($CFG->navcourselimit)) {
1343 $limit = $CFG->navcourselimit;
1346 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1348 // If we are going to show all courses AND we are showing categories then
1349 // to save us repeated DB calls load all of the categories now
1350 if ($this->show_categories()) {
1351 $this->load_all_categories($toload);
1354 // Will be the return of our efforts
1355 $coursenodes = array();
1357 // Check if we need to show categories.
1358 if ($this->show_categories()) {
1359 // Hmmm we need to show categories... this is going to be painful.
1360 // We now need to fetch up to $limit courses for each category to
1361 // be displayed.
1362 if ($categoryids !== null) {
1363 if (!is_array($categoryids)) {
1364 $categoryids = array($categoryids);
1366 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1367 $categorywhere = 'WHERE cc.id '.$categorywhere;
1368 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1369 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1370 $categoryparams = array();
1371 } else {
1372 $categorywhere = '';
1373 $categoryparams = array();
1376 // First up we are going to get the categories that we are going to
1377 // need so that we can determine how best to load the courses from them.
1378 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1379 FROM {course_categories} cc
1380 LEFT JOIN {course} c ON c.category = cc.id
1381 {$categorywhere}
1382 GROUP BY cc.id";
1383 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1384 $fullfetch = array();
1385 $partfetch = array();
1386 foreach ($categories as $category) {
1387 if (!$this->can_add_more_courses_to_category($category->id)) {
1388 continue;
1390 if ($category->coursecount > $limit * 5) {
1391 $partfetch[] = $category->id;
1392 } else if ($category->coursecount > 0) {
1393 $fullfetch[] = $category->id;
1396 $categories->close();
1398 if (count($fullfetch)) {
1399 // First up fetch all of the courses in categories where we know that we are going to
1400 // need the majority of courses.
1401 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1402 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1403 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1404 FROM {course} c
1405 $ccjoin
1406 WHERE c.category {$categoryids}
1407 ORDER BY c.sortorder ASC";
1408 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1409 foreach ($coursesrs as $course) {
1410 if ($course->id == $SITE->id) {
1411 // This should not be necessary, frontpage is not in any category.
1412 continue;
1414 if (array_key_exists($course->id, $this->addedcourses)) {
1415 // It is probably better to not include the already loaded courses
1416 // directly in SQL because inequalities may confuse query optimisers
1417 // and may interfere with query caching.
1418 continue;
1420 if (!$this->can_add_more_courses_to_category($course->category)) {
1421 continue;
1423 context_instance_preload($course);
1424 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1425 continue;
1427 $coursenodes[$course->id] = $this->add_course($course);
1429 $coursesrs->close();
1432 if (count($partfetch)) {
1433 // Next we will work our way through the categories where we will likely only need a small
1434 // proportion of the courses.
1435 foreach ($partfetch as $categoryid) {
1436 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1437 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1438 FROM {course} c
1439 $ccjoin
1440 WHERE c.category = :categoryid
1441 ORDER BY c.sortorder ASC";
1442 $courseparams = array('categoryid' => $categoryid);
1443 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1444 foreach ($coursesrs as $course) {
1445 if ($course->id == $SITE->id) {
1446 // This should not be necessary, frontpage is not in any category.
1447 continue;
1449 if (array_key_exists($course->id, $this->addedcourses)) {
1450 // It is probably better to not include the already loaded courses
1451 // directly in SQL because inequalities may confuse query optimisers
1452 // and may interfere with query caching.
1453 // This also helps to respect expected $limit on repeated executions.
1454 continue;
1456 if (!$this->can_add_more_courses_to_category($course->category)) {
1457 break;
1459 context_instance_preload($course);
1460 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1461 continue;
1463 $coursenodes[$course->id] = $this->add_course($course);
1465 $coursesrs->close();
1468 } else {
1469 // Prepare the SQL to load the courses and their contexts
1470 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1471 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1472 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1473 FROM {course} c
1474 $ccjoin
1475 WHERE c.id {$courseids}
1476 ORDER BY c.sortorder ASC";
1477 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1478 foreach ($coursesrs as $course) {
1479 if ($course->id == $SITE->id) {
1480 // frotpage is not wanted here
1481 continue;
1483 if ($this->page->course && ($this->page->course->id == $course->id)) {
1484 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1485 continue;
1487 context_instance_preload($course);
1488 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1489 continue;
1491 $coursenodes[$course->id] = $this->add_course($course);
1492 if (count($coursenodes) >= $limit) {
1493 break;
1496 $coursesrs->close();
1499 return $coursenodes;
1503 * Returns true if more courses can be added to the provided category.
1505 * @param int|navigation_node|stdClass $category
1506 * @return bool
1508 protected function can_add_more_courses_to_category($category) {
1509 global $CFG;
1510 $limit = 20;
1511 if (!empty($CFG->navcourselimit)) {
1512 $limit = (int)$CFG->navcourselimit;
1514 if (is_numeric($category)) {
1515 if (!array_key_exists($category, $this->addedcategories)) {
1516 return true;
1518 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1519 } else if ($category instanceof navigation_node) {
1520 if ($category->type != self::TYPE_CATEGORY) {
1521 return false;
1523 $coursecount = count($category->children->type(self::TYPE_COURSE));
1524 } else if (is_object($category) && property_exists($category,'id')) {
1525 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1527 return ($coursecount <= $limit);
1531 * Loads all categories (top level or if an id is specified for that category)
1533 * @param int $categoryid The category id to load or null/0 to load all base level categories
1534 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1535 * as the requested category and any parent categories.
1536 * @return navigation_node|void returns a navigation node if a category has been loaded.
1538 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1539 global $CFG, $DB;
1541 // Check if this category has already been loaded
1542 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1543 return true;
1546 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1547 $sqlselect = "SELECT cc.*, $catcontextsql
1548 FROM {course_categories} cc
1549 JOIN {context} ctx ON cc.id = ctx.instanceid";
1550 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1551 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1552 $params = array();
1554 $categoriestoload = array();
1555 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1556 // We are going to load all categories regardless... prepare to fire
1557 // on the database server!
1558 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1559 // We are going to load all of the first level categories (categories without parents)
1560 $sqlwhere .= " AND cc.parent = 0";
1561 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1562 // The category itself has been loaded already so we just need to ensure its subcategories
1563 // have been loaded
1564 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1565 if ($showbasecategories) {
1566 // We need to include categories with parent = 0 as well
1567 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1568 } else {
1569 // All we need is categories that match the parent
1570 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1572 $params['categoryid'] = $categoryid;
1573 } else {
1574 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1575 // and load this category plus all its parents and subcategories
1576 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1577 $categoriestoload = explode('/', trim($category->path, '/'));
1578 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1579 // We are going to use select twice so double the params
1580 $params = array_merge($params, $params);
1581 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1582 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1585 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1586 $categories = array();
1587 foreach ($categoriesrs as $category) {
1588 // Preload the context.. we'll need it when adding the category in order
1589 // to format the category name.
1590 context_helper::preload_from_record($category);
1591 if (array_key_exists($category->id, $this->addedcategories)) {
1592 // Do nothing, its already been added.
1593 } else if ($category->parent == '0') {
1594 // This is a root category lets add it immediately
1595 $this->add_category($category, $this->rootnodes['courses']);
1596 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1597 // This categories parent has already been added we can add this immediately
1598 $this->add_category($category, $this->addedcategories[$category->parent]);
1599 } else {
1600 $categories[] = $category;
1603 $categoriesrs->close();
1605 // Now we have an array of categories we need to add them to the navigation.
1606 while (!empty($categories)) {
1607 $category = reset($categories);
1608 if (array_key_exists($category->id, $this->addedcategories)) {
1609 // Do nothing
1610 } else if ($category->parent == '0') {
1611 $this->add_category($category, $this->rootnodes['courses']);
1612 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1613 $this->add_category($category, $this->addedcategories[$category->parent]);
1614 } else {
1615 // This category isn't in the navigation and niether is it's parent (yet).
1616 // We need to go through the category path and add all of its components in order.
1617 $path = explode('/', trim($category->path, '/'));
1618 foreach ($path as $catid) {
1619 if (!array_key_exists($catid, $this->addedcategories)) {
1620 // This category isn't in the navigation yet so add it.
1621 $subcategory = $categories[$catid];
1622 if ($subcategory->parent == '0') {
1623 // Yay we have a root category - this likely means we will now be able
1624 // to add categories without problems.
1625 $this->add_category($subcategory, $this->rootnodes['courses']);
1626 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1627 // The parent is in the category (as we'd expect) so add it now.
1628 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1629 // Remove the category from the categories array.
1630 unset($categories[$catid]);
1631 } else {
1632 // We should never ever arrive here - if we have then there is a bigger
1633 // problem at hand.
1634 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1639 // Remove the category from the categories array now that we know it has been added.
1640 unset($categories[$category->id]);
1642 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1643 $this->allcategoriesloaded = true;
1645 // Check if there are any categories to load.
1646 if (count($categoriestoload) > 0) {
1647 $readytoloadcourses = array();
1648 foreach ($categoriestoload as $category) {
1649 if ($this->can_add_more_courses_to_category($category)) {
1650 $readytoloadcourses[] = $category;
1653 if (count($readytoloadcourses)) {
1654 $this->load_all_courses($readytoloadcourses);
1658 // Look for all categories which have been loaded
1659 if (!empty($this->addedcategories)) {
1660 $categoryids = array();
1661 foreach ($this->addedcategories as $category) {
1662 if ($this->can_add_more_courses_to_category($category)) {
1663 $categoryids[] = $category->key;
1666 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1667 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1668 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1669 FROM {course_categories} cc
1670 JOIN {course} c ON c.category = cc.id
1671 WHERE cc.id {$categoriessql}
1672 GROUP BY cc.id
1673 HAVING COUNT(c.id) > :limit";
1674 $excessivecategories = $DB->get_records_sql($sql, $params);
1675 foreach ($categories as &$category) {
1676 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1677 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1678 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1685 * Adds a structured category to the navigation in the correct order/place
1687 * @param stdClass $category
1688 * @param navigation_node $parent
1690 protected function add_category(stdClass $category, navigation_node $parent) {
1691 if (array_key_exists($category->id, $this->addedcategories)) {
1692 return;
1694 $url = new moodle_url('/course/category.php', array('id' => $category->id));
1695 $context = context_coursecat::instance($category->id);
1696 $categoryname = format_string($category->name, true, array('context' => $context));
1697 $categorynode = $parent->add($categoryname, $url, self::TYPE_CATEGORY, $categoryname, $category->id);
1698 if (empty($category->visible)) {
1699 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1700 $categorynode->hidden = true;
1701 } else {
1702 $categorynode->display = false;
1705 $this->addedcategories[$category->id] = $categorynode;
1709 * Loads the given course into the navigation
1711 * @param stdClass $course
1712 * @return navigation_node
1714 protected function load_course(stdClass $course) {
1715 global $SITE;
1716 if ($course->id == $SITE->id) {
1717 // This is always loaded during initialisation
1718 return $this->rootnodes['site'];
1719 } else if (array_key_exists($course->id, $this->addedcourses)) {
1720 // The course has already been loaded so return a reference
1721 return $this->addedcourses[$course->id];
1722 } else {
1723 // Add the course
1724 return $this->add_course($course);
1729 * Loads all of the courses section into the navigation.
1731 * This function calls method from current course format, see
1732 * {@link format_base::extend_course_navigation()}
1733 * If course module ($cm) is specified but course format failed to create the node,
1734 * the activity node is created anyway.
1736 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1738 * @param stdClass $course Database record for the course
1739 * @param navigation_node $coursenode The course node within the navigation
1740 * @param null|int $sectionnum If specified load the contents of section with this relative number
1741 * @param null|cm_info $cm If specified make sure that activity node is created (either
1742 * in containg section or by calling load_stealth_activity() )
1744 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1745 global $CFG, $SITE;
1746 require_once($CFG->dirroot.'/course/lib.php');
1747 if (isset($cm->sectionnum)) {
1748 $sectionnum = $cm->sectionnum;
1750 if ($sectionnum !== null) {
1751 $this->includesectionnum = $sectionnum;
1753 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1754 if (isset($cm->id)) {
1755 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1756 if (empty($activity)) {
1757 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1763 * Generates an array of sections and an array of activities for the given course.
1765 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1767 * @param stdClass $course
1768 * @return array Array($sections, $activities)
1770 protected function generate_sections_and_activities(stdClass $course) {
1771 global $CFG;
1772 require_once($CFG->dirroot.'/course/lib.php');
1774 $modinfo = get_fast_modinfo($course);
1775 $sections = $modinfo->get_section_info_all();
1777 // For course formats using 'numsections' trim the sections list
1778 $courseformatoptions = course_get_format($course)->get_format_options();
1779 if (isset($courseformatoptions['numsections'])) {
1780 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1783 $activities = array();
1785 foreach ($sections as $key => $section) {
1786 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1787 $sections[$key] = clone($section);
1788 unset($sections[$key]->summary);
1789 $sections[$key]->hasactivites = false;
1790 if (!array_key_exists($section->section, $modinfo->sections)) {
1791 continue;
1793 foreach ($modinfo->sections[$section->section] as $cmid) {
1794 $cm = $modinfo->cms[$cmid];
1795 if (!$cm->uservisible) {
1796 continue;
1798 $activity = new stdClass;
1799 $activity->id = $cm->id;
1800 $activity->course = $course->id;
1801 $activity->section = $section->section;
1802 $activity->name = $cm->name;
1803 $activity->icon = $cm->icon;
1804 $activity->iconcomponent = $cm->iconcomponent;
1805 $activity->hidden = (!$cm->visible);
1806 $activity->modname = $cm->modname;
1807 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1808 $activity->onclick = $cm->get_on_click();
1809 $url = $cm->get_url();
1810 if (!$url) {
1811 $activity->url = null;
1812 $activity->display = false;
1813 } else {
1814 $activity->url = $cm->get_url()->out();
1815 $activity->display = true;
1816 if (self::module_extends_navigation($cm->modname)) {
1817 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1820 $activities[$cmid] = $activity;
1821 if ($activity->display) {
1822 $sections[$key]->hasactivites = true;
1827 return array($sections, $activities);
1831 * Generically loads the course sections into the course's navigation.
1833 * @param stdClass $course
1834 * @param navigation_node $coursenode
1835 * @return array An array of course section nodes
1837 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1838 global $CFG, $DB, $USER, $SITE;
1839 require_once($CFG->dirroot.'/course/lib.php');
1841 list($sections, $activities) = $this->generate_sections_and_activities($course);
1843 $navigationsections = array();
1844 foreach ($sections as $sectionid => $section) {
1845 $section = clone($section);
1846 if ($course->id == $SITE->id) {
1847 $this->load_section_activities($coursenode, $section->section, $activities);
1848 } else {
1849 if (!$section->uservisible || (!$this->showemptysections &&
1850 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1851 continue;
1854 $sectionname = get_section_name($course, $section);
1855 $url = course_get_url($course, $section->section, array('navigation' => true));
1857 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1858 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1859 $sectionnode->hidden = (!$section->visible || !$section->available);
1860 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1861 $this->load_section_activities($sectionnode, $section->section, $activities);
1863 $section->sectionnode = $sectionnode;
1864 $navigationsections[$sectionid] = $section;
1867 return $navigationsections;
1871 * Loads all of the activities for a section into the navigation structure.
1873 * @param navigation_node $sectionnode
1874 * @param int $sectionnumber
1875 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1876 * @param stdClass $course The course object the section and activities relate to.
1877 * @return array Array of activity nodes
1879 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1880 global $CFG, $SITE;
1881 // A static counter for JS function naming
1882 static $legacyonclickcounter = 0;
1884 $activitynodes = array();
1885 if (empty($activities)) {
1886 return $activitynodes;
1889 if (!is_object($course)) {
1890 $activity = reset($activities);
1891 $courseid = $activity->course;
1892 } else {
1893 $courseid = $course->id;
1895 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1897 foreach ($activities as $activity) {
1898 if ($activity->section != $sectionnumber) {
1899 continue;
1901 if ($activity->icon) {
1902 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1903 } else {
1904 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1907 // Prepare the default name and url for the node
1908 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1909 $action = new moodle_url($activity->url);
1911 // Check if the onclick property is set (puke!)
1912 if (!empty($activity->onclick)) {
1913 // Increment the counter so that we have a unique number.
1914 $legacyonclickcounter++;
1915 // Generate the function name we will use
1916 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1917 $propogrationhandler = '';
1918 // Check if we need to cancel propogation. Remember inline onclick
1919 // events would return false if they wanted to prevent propogation and the
1920 // default action.
1921 if (strpos($activity->onclick, 'return false')) {
1922 $propogrationhandler = 'e.halt();';
1924 // Decode the onclick - it has already been encoded for display (puke)
1925 $onclick = htmlspecialchars_decode($activity->onclick);
1926 // Build the JS function the click event will call
1927 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1928 $this->page->requires->js_init_code($jscode);
1929 // Override the default url with the new action link
1930 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1933 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1934 $activitynode->title(get_string('modulename', $activity->modname));
1935 $activitynode->hidden = $activity->hidden;
1936 $activitynode->display = $showactivities && $activity->display;
1937 $activitynode->nodetype = $activity->nodetype;
1938 $activitynodes[$activity->id] = $activitynode;
1941 return $activitynodes;
1944 * Loads a stealth module from unavailable section
1945 * @param navigation_node $coursenode
1946 * @param stdClass $modinfo
1947 * @return navigation_node or null if not accessible
1949 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1950 if (empty($modinfo->cms[$this->page->cm->id])) {
1951 return null;
1953 $cm = $modinfo->cms[$this->page->cm->id];
1954 if (!$cm->uservisible) {
1955 return null;
1957 if ($cm->icon) {
1958 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1959 } else {
1960 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1962 $url = $cm->get_url();
1963 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1964 $activitynode->title(get_string('modulename', $cm->modname));
1965 $activitynode->hidden = (!$cm->visible);
1966 if (!$url) {
1967 // Don't show activities that don't have links!
1968 $activitynode->display = false;
1969 } else if (self::module_extends_navigation($cm->modname)) {
1970 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1972 return $activitynode;
1975 * Loads the navigation structure for the given activity into the activities node.
1977 * This method utilises a callback within the modules lib.php file to load the
1978 * content specific to activity given.
1980 * The callback is a method: {modulename}_extend_navigation()
1981 * Examples:
1982 * * {@link forum_extend_navigation()}
1983 * * {@link workshop_extend_navigation()}
1985 * @param cm_info|stdClass $cm
1986 * @param stdClass $course
1987 * @param navigation_node $activity
1988 * @return bool
1990 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
1991 global $CFG, $DB;
1993 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
1994 if (!($cm instanceof cm_info)) {
1995 $modinfo = get_fast_modinfo($course);
1996 $cm = $modinfo->get_cm($cm->id);
1998 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1999 $activity->make_active();
2000 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2001 $function = $cm->modname.'_extend_navigation';
2003 if (file_exists($file)) {
2004 require_once($file);
2005 if (function_exists($function)) {
2006 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2007 $function($activity, $course, $activtyrecord, $cm);
2011 // Allow the active advanced grading method plugin to append module navigation
2012 $featuresfunc = $cm->modname.'_supports';
2013 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2014 require_once($CFG->dirroot.'/grade/grading/lib.php');
2015 $gradingman = get_grading_manager($cm->context, $cm->modname);
2016 $gradingman->extend_navigation($this, $activity);
2019 return $activity->has_children();
2022 * Loads user specific information into the navigation in the appropriate place.
2024 * If no user is provided the current user is assumed.
2026 * @param stdClass $user
2027 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2028 * @return bool
2030 protected function load_for_user($user=null, $forceforcontext=false) {
2031 global $DB, $CFG, $USER, $SITE;
2033 if ($user === null) {
2034 // We can't require login here but if the user isn't logged in we don't
2035 // want to show anything
2036 if (!isloggedin() || isguestuser()) {
2037 return false;
2039 $user = $USER;
2040 } else if (!is_object($user)) {
2041 // If the user is not an object then get them from the database
2042 $select = context_helper::get_preload_record_columns_sql('ctx');
2043 $sql = "SELECT u.*, $select
2044 FROM {user} u
2045 JOIN {context} ctx ON u.id = ctx.instanceid
2046 WHERE u.id = :userid AND
2047 ctx.contextlevel = :contextlevel";
2048 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2049 context_helper::preload_from_record($user);
2052 $iscurrentuser = ($user->id == $USER->id);
2054 $usercontext = context_user::instance($user->id);
2056 // Get the course set against the page, by default this will be the site
2057 $course = $this->page->course;
2058 $baseargs = array('id'=>$user->id);
2059 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2060 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2061 $baseargs['course'] = $course->id;
2062 $coursecontext = context_course::instance($course->id);
2063 $issitecourse = false;
2064 } else {
2065 // Load all categories and get the context for the system
2066 $coursecontext = context_system::instance();
2067 $issitecourse = true;
2070 // Create a node to add user information under.
2071 if ($iscurrentuser && !$forceforcontext) {
2072 // If it's the current user the information will go under the profile root node
2073 $usernode = $this->rootnodes['myprofile'];
2074 $course = get_site();
2075 $coursecontext = context_course::instance($course->id);
2076 $issitecourse = true;
2077 } else {
2078 if (!$issitecourse) {
2079 // Not the current user so add it to the participants node for the current course
2080 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2081 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2082 } else {
2083 // This is the site so add a users node to the root branch
2084 $usersnode = $this->rootnodes['users'];
2085 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2086 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2088 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2090 if (!$usersnode) {
2091 // We should NEVER get here, if the course hasn't been populated
2092 // with a participants node then the navigaiton either wasn't generated
2093 // for it (you are missing a require_login or set_context call) or
2094 // you don't have access.... in the interests of no leaking informatin
2095 // we simply quit...
2096 return false;
2098 // Add a branch for the current user
2099 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2100 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2102 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2103 $usernode->make_active();
2107 // If the user is the current user or has permission to view the details of the requested
2108 // user than add a view profile link.
2109 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2110 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2111 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2112 } else {
2113 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2117 if (!empty($CFG->navadduserpostslinks)) {
2118 // Add nodes for forum posts and discussions if the user can view either or both
2119 // There are no capability checks here as the content of the page is based
2120 // purely on the forums the current user has access too.
2121 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2122 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2123 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2126 // Add blog nodes
2127 if (!empty($CFG->enableblogs)) {
2128 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2129 require_once($CFG->dirroot.'/blog/lib.php');
2130 // Get all options for the user
2131 $options = blog_get_options_for_user($user);
2132 $this->cache->set('userblogoptions'.$user->id, $options);
2133 } else {
2134 $options = $this->cache->{'userblogoptions'.$user->id};
2137 if (count($options) > 0) {
2138 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2139 foreach ($options as $type => $option) {
2140 if ($type == "rss") {
2141 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2142 } else {
2143 $blogs->add($option['string'], $option['link']);
2149 if (!empty($CFG->messaging)) {
2150 $messageargs = null;
2151 if ($USER->id!=$user->id) {
2152 $messageargs = array('id'=>$user->id);
2154 $url = new moodle_url('/message/index.php',$messageargs);
2155 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2158 $context = context_user::instance($USER->id);
2159 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
2160 $url = new moodle_url('/user/files.php');
2161 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2164 // Add a node to view the users notes if permitted
2165 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2166 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2167 if ($coursecontext->instanceid) {
2168 $url->param('course', $coursecontext->instanceid);
2170 $usernode->add(get_string('notes', 'notes'), $url);
2173 // Add reports node
2174 $reporttab = $usernode->add(get_string('activityreports'));
2175 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2176 foreach ($reports as $reportfunction) {
2177 $reportfunction($reporttab, $user, $course);
2179 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
2180 if ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext)) {
2181 // Add grade hardcoded grade report if necessary
2182 $gradeaccess = false;
2183 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2184 //ok - can view all course grades
2185 $gradeaccess = true;
2186 } else if ($course->showgrades) {
2187 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
2188 //ok - can view own grades
2189 $gradeaccess = true;
2190 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
2191 // ok - can view grades of this user - parent most probably
2192 $gradeaccess = true;
2193 } else if ($anyreport) {
2194 // ok - can view grades of this user - parent most probably
2195 $gradeaccess = true;
2198 if ($gradeaccess) {
2199 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id, 'user'=>$usercontext->instanceid)));
2202 // Check the number of nodes in the report node... if there are none remove the node
2203 $reporttab->trim_if_empty();
2205 // If the user is the current user add the repositories for the current user
2206 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2207 if ($iscurrentuser) {
2208 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2209 require_once($CFG->dirroot . '/repository/lib.php');
2210 $editabletypes = repository::get_editable_types($usercontext);
2211 $haseditabletypes = !empty($editabletypes);
2212 unset($editabletypes);
2213 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2214 } else {
2215 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2217 if ($haseditabletypes) {
2218 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2220 } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2222 // Add view grade report is permitted
2223 $reports = get_plugin_list('gradereport');
2224 arsort($reports); // user is last, we want to test it first
2226 $userscourses = enrol_get_users_courses($user->id);
2227 $userscoursesnode = $usernode->add(get_string('courses'));
2229 foreach ($userscourses as $usercourse) {
2230 $usercoursecontext = context_course::instance($usercourse->id);
2231 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2232 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2234 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2235 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2236 foreach ($reports as $plugin => $plugindir) {
2237 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2238 //stop when the first visible plugin is found
2239 $gradeavailable = true;
2240 break;
2245 if ($gradeavailable) {
2246 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2247 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2250 // Add a node to view the users notes if permitted
2251 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2252 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2253 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2256 if (can_access_course($usercourse, $user->id)) {
2257 $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', ''));
2260 $reporttab = $usercoursenode->add(get_string('activityreports'));
2262 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2263 foreach ($reports as $reportfunction) {
2264 $reportfunction($reporttab, $user, $usercourse);
2267 $reporttab->trim_if_empty();
2270 return true;
2274 * This method simply checks to see if a given module can extend the navigation.
2276 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2278 * @param string $modname
2279 * @return bool
2281 public static function module_extends_navigation($modname) {
2282 global $CFG;
2283 static $extendingmodules = array();
2284 if (!array_key_exists($modname, $extendingmodules)) {
2285 $extendingmodules[$modname] = false;
2286 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2287 if (file_exists($file)) {
2288 $function = $modname.'_extend_navigation';
2289 require_once($file);
2290 $extendingmodules[$modname] = (function_exists($function));
2293 return $extendingmodules[$modname];
2296 * Extends the navigation for the given user.
2298 * @param stdClass $user A user from the database
2300 public function extend_for_user($user) {
2301 $this->extendforuser[] = $user;
2305 * Returns all of the users the navigation is being extended for
2307 * @return array An array of extending users.
2309 public function get_extending_users() {
2310 return $this->extendforuser;
2313 * Adds the given course to the navigation structure.
2315 * @param stdClass $course
2316 * @param bool $forcegeneric
2317 * @param bool $ismycourse
2318 * @return navigation_node
2320 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2321 global $CFG, $SITE;
2323 // We found the course... we can return it now :)
2324 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2325 return $this->addedcourses[$course->id];
2328 $coursecontext = context_course::instance($course->id);
2330 if ($course->id != $SITE->id && !$course->visible) {
2331 if (is_role_switched($course->id)) {
2332 // user has to be able to access course in order to switch, let's skip the visibility test here
2333 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2334 return false;
2338 $issite = ($course->id == $SITE->id);
2339 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2341 if ($issite) {
2342 $parent = $this;
2343 $url = null;
2344 if (empty($CFG->usesitenameforsitepages)) {
2345 $shortname = get_string('sitepages');
2347 } else if ($coursetype == self::COURSE_CURRENT) {
2348 $parent = $this->rootnodes['currentcourse'];
2349 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2350 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2351 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_CATEGORY))) {
2352 // Nothing to do here the above statement set $parent to the category within mycourses.
2353 } else {
2354 $parent = $this->rootnodes['mycourses'];
2356 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2357 } else {
2358 $parent = $this->rootnodes['courses'];
2359 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2360 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2361 if (!$this->is_category_fully_loaded($course->category)) {
2362 // We need to load the category structure for this course
2363 $this->load_all_categories($course->category, false);
2365 if (array_key_exists($course->category, $this->addedcategories)) {
2366 $parent = $this->addedcategories[$course->category];
2367 // This could lead to the course being created so we should check whether it is the case again
2368 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2369 return $this->addedcourses[$course->id];
2375 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
2376 $coursenode->nodetype = self::NODETYPE_BRANCH;
2377 $coursenode->hidden = (!$course->visible);
2378 $coursenode->title(format_string($course->fullname, true, array('context' => context_course::instance($course->id))));
2379 if (!$forcegeneric) {
2380 $this->addedcourses[$course->id] = $coursenode;
2383 return $coursenode;
2387 * Returns true if the category has already been loaded as have any child categories
2389 * @param int $categoryid
2390 * @return bool
2392 protected function is_category_fully_loaded($categoryid) {
2393 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2397 * Adds essential course nodes to the navigation for the given course.
2399 * This method adds nodes such as reports, blogs and participants
2401 * @param navigation_node $coursenode
2402 * @param stdClass $course
2403 * @return bool returns true on successful addition of a node.
2405 public function add_course_essentials($coursenode, stdClass $course) {
2406 global $CFG, $SITE;
2408 if ($course->id == $SITE->id) {
2409 return $this->add_front_page_course_essentials($coursenode, $course);
2412 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2413 return true;
2416 //Participants
2417 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2418 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2419 $currentgroup = groups_get_course_group($course, true);
2420 if ($course->id == $SITE->id) {
2421 $filterselect = '';
2422 } else if ($course->id && !$currentgroup) {
2423 $filterselect = $course->id;
2424 } else {
2425 $filterselect = $currentgroup;
2427 $filterselect = clean_param($filterselect, PARAM_INT);
2428 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2429 and has_capability('moodle/blog:view', context_system::instance())) {
2430 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2431 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2433 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2434 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2436 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2437 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2440 // View course reports
2441 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2442 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2443 $coursereports = get_plugin_list('coursereport'); // deprecated
2444 foreach ($coursereports as $report=>$dir) {
2445 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2446 if (file_exists($libfile)) {
2447 require_once($libfile);
2448 $reportfunction = $report.'_report_extend_navigation';
2449 if (function_exists($report.'_report_extend_navigation')) {
2450 $reportfunction($reportnav, $course, $this->page->context);
2455 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2456 foreach ($reports as $reportfunction) {
2457 $reportfunction($reportnav, $course, $this->page->context);
2460 return true;
2463 * This generates the structure of the course that won't be generated when
2464 * the modules and sections are added.
2466 * Things such as the reports branch, the participants branch, blogs... get
2467 * added to the course node by this method.
2469 * @param navigation_node $coursenode
2470 * @param stdClass $course
2471 * @return bool True for successfull generation
2473 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2474 global $CFG;
2476 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2477 return true;
2480 // Hidden node that we use to determine if the front page navigation is loaded.
2481 // This required as there are not other guaranteed nodes that may be loaded.
2482 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2484 //Participants
2485 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2486 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2489 $filterselect = 0;
2491 // Blogs
2492 if (!empty($CFG->enableblogs)
2493 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2494 and has_capability('moodle/blog:view', context_system::instance())) {
2495 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2496 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2499 // Notes
2500 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2501 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2504 // Tags
2505 if (!empty($CFG->usetags) && isloggedin()) {
2506 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2509 if (isloggedin()) {
2510 // Calendar
2511 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2512 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2515 // View course reports
2516 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2517 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2518 $coursereports = get_plugin_list('coursereport'); // deprecated
2519 foreach ($coursereports as $report=>$dir) {
2520 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2521 if (file_exists($libfile)) {
2522 require_once($libfile);
2523 $reportfunction = $report.'_report_extend_navigation';
2524 if (function_exists($report.'_report_extend_navigation')) {
2525 $reportfunction($reportnav, $course, $this->page->context);
2530 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2531 foreach ($reports as $reportfunction) {
2532 $reportfunction($reportnav, $course, $this->page->context);
2535 return true;
2539 * Clears the navigation cache
2541 public function clear_cache() {
2542 $this->cache->clear();
2546 * Sets an expansion limit for the navigation
2548 * The expansion limit is used to prevent the display of content that has a type
2549 * greater than the provided $type.
2551 * Can be used to ensure things such as activities or activity content don't get
2552 * shown on the navigation.
2553 * They are still generated in order to ensure the navbar still makes sense.
2555 * @param int $type One of navigation_node::TYPE_*
2556 * @return bool true when complete.
2558 public function set_expansion_limit($type) {
2559 global $SITE;
2560 $nodes = $this->find_all_of_type($type);
2561 foreach ($nodes as &$node) {
2562 // We need to generate the full site node
2563 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2564 continue;
2566 foreach ($node->children as &$child) {
2567 // We still want to show course reports and participants containers
2568 // or there will be navigation missing.
2569 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2570 continue;
2572 $child->display = false;
2575 return true;
2578 * Attempts to get the navigation with the given key from this nodes children.
2580 * This function only looks at this nodes children, it does NOT look recursivily.
2581 * If the node can't be found then false is returned.
2583 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2585 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2586 * may be of more use to you.
2588 * @param string|int $key The key of the node you wish to receive.
2589 * @param int $type One of navigation_node::TYPE_*
2590 * @return navigation_node|false
2592 public function get($key, $type = null) {
2593 if (!$this->initialised) {
2594 $this->initialise();
2596 return parent::get($key, $type);
2600 * Searches this nodes children and their children to find a navigation node
2601 * with the matching key and type.
2603 * This method is recursive and searches children so until either a node is
2604 * found or there are no more nodes to search.
2606 * If you know that the node being searched for is a child of this node
2607 * then use the {@link global_navigation::get()} method instead.
2609 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2610 * may be of more use to you.
2612 * @param string|int $key The key of the node you wish to receive.
2613 * @param int $type One of navigation_node::TYPE_*
2614 * @return navigation_node|false
2616 public function find($key, $type) {
2617 if (!$this->initialised) {
2618 $this->initialise();
2620 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2621 return $this->rootnodes[$key];
2623 return parent::find($key, $type);
2628 * The global navigation class used especially for AJAX requests.
2630 * The primary methods that are used in the global navigation class have been overriden
2631 * to ensure that only the relevant branch is generated at the root of the tree.
2632 * This can be done because AJAX is only used when the backwards structure for the
2633 * requested branch exists.
2634 * This has been done only because it shortens the amounts of information that is generated
2635 * which of course will speed up the response time.. because no one likes laggy AJAX.
2637 * @package core
2638 * @category navigation
2639 * @copyright 2009 Sam Hemelryk
2640 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2642 class global_navigation_for_ajax extends global_navigation {
2644 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2645 protected $branchtype;
2647 /** @var int the instance id */
2648 protected $instanceid;
2650 /** @var array Holds an array of expandable nodes */
2651 protected $expandable = array();
2654 * Constructs the navigation for use in an AJAX request
2656 * @param moodle_page $page moodle_page object
2657 * @param int $branchtype
2658 * @param int $id
2660 public function __construct($page, $branchtype, $id) {
2661 $this->page = $page;
2662 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2663 $this->children = new navigation_node_collection();
2664 $this->branchtype = $branchtype;
2665 $this->instanceid = $id;
2666 $this->initialise();
2669 * Initialise the navigation given the type and id for the branch to expand.
2671 * @return array An array of the expandable nodes
2673 public function initialise() {
2674 global $DB, $SITE;
2676 if ($this->initialised || during_initial_install()) {
2677 return $this->expandable;
2679 $this->initialised = true;
2681 $this->rootnodes = array();
2682 $this->rootnodes['site'] = $this->add_course($SITE);
2683 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2684 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2686 // Branchtype will be one of navigation_node::TYPE_*
2687 switch ($this->branchtype) {
2688 case 0:
2689 if ($this->instanceid === 'mycourses') {
2690 $this->load_courses_enrolled();
2691 } else if ($this->instanceid === 'courses') {
2692 $this->load_courses_other();
2694 break;
2695 case self::TYPE_CATEGORY :
2696 $this->load_category($this->instanceid);
2697 break;
2698 case self::TYPE_COURSE :
2699 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2700 require_course_login($course, true, null, false, true);
2701 $this->page->set_context(context_course::instance($course->id));
2702 $coursenode = $this->add_course($course);
2703 $this->add_course_essentials($coursenode, $course);
2704 $this->load_course_sections($course, $coursenode);
2705 break;
2706 case self::TYPE_SECTION :
2707 $sql = 'SELECT c.*, cs.section AS sectionnumber
2708 FROM {course} c
2709 LEFT JOIN {course_sections} cs ON cs.course = c.id
2710 WHERE cs.id = ?';
2711 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2712 require_course_login($course, true, null, false, true);
2713 $this->page->set_context(context_course::instance($course->id));
2714 $coursenode = $this->add_course($course);
2715 $this->add_course_essentials($coursenode, $course);
2716 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2717 break;
2718 case self::TYPE_ACTIVITY :
2719 $sql = "SELECT c.*
2720 FROM {course} c
2721 JOIN {course_modules} cm ON cm.course = c.id
2722 WHERE cm.id = :cmid";
2723 $params = array('cmid' => $this->instanceid);
2724 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2725 $modinfo = get_fast_modinfo($course);
2726 $cm = $modinfo->get_cm($this->instanceid);
2727 require_course_login($course, true, $cm, false, true);
2728 $this->page->set_context(context_module::instance($cm->id));
2729 $coursenode = $this->load_course($course);
2730 if ($course->id != $SITE->id) {
2731 $this->load_course_sections($course, $coursenode, null, $cm);
2733 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2734 break;
2735 default:
2736 throw new Exception('Unknown type');
2737 return $this->expandable;
2740 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2741 $this->load_for_user(null, true);
2744 $this->find_expandable($this->expandable);
2745 return $this->expandable;
2749 * They've expanded the 'my courses' branch.
2751 protected function load_courses_enrolled() {
2752 global $DB;
2753 $courses = enrol_get_my_courses();
2754 if ($this->show_my_categories(true)) {
2755 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2756 // In order to make sure we load everything required we must first find the categories that are not
2757 // base categories and work out the bottom category in thier path.
2758 $categoryids = array();
2759 foreach ($courses as $course) {
2760 $categoryids[] = $course->category;
2762 $categoryids = array_unique($categoryids);
2763 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2764 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2765 foreach ($categories as $category) {
2766 $bits = explode('/', trim($category->path,'/'));
2767 $categoryids[] = array_shift($bits);
2769 $categoryids = array_unique($categoryids);
2770 $categories->close();
2772 // Now we load the base categories.
2773 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2774 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2775 foreach ($categories as $category) {
2776 $this->add_category($category, $this->rootnodes['mycourses']);
2778 $categories->close();
2779 } else {
2780 foreach ($courses as $course) {
2781 $this->add_course($course, false, self::COURSE_MY);
2787 * They've expanded the general 'courses' branch.
2789 protected function load_courses_other() {
2790 $this->load_all_courses();
2794 * Loads a single category into the AJAX navigation.
2796 * This function is special in that it doesn't concern itself with the parent of
2797 * the requested category or its siblings.
2798 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2799 * request that.
2801 * @global moodle_database $DB
2802 * @param int $categoryid
2804 protected function load_category($categoryid) {
2805 global $CFG, $DB;
2807 $limit = 20;
2808 if (!empty($CFG->navcourselimit)) {
2809 $limit = (int)$CFG->navcourselimit;
2812 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2813 $sql = "SELECT cc.*, $catcontextsql
2814 FROM {course_categories} cc
2815 JOIN {context} ctx ON cc.id = ctx.instanceid
2816 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2817 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2818 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2819 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2820 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2821 $subcategories = array();
2822 $basecategory = null;
2823 foreach ($categories as $category) {
2824 context_helper::preload_from_record($category);
2825 if ($category->id == $categoryid) {
2826 $this->add_category($category, $this);
2827 $basecategory = $this->addedcategories[$category->id];
2828 } else {
2829 $subcategories[] = $category;
2832 $categories->close();
2834 if (!is_null($basecategory)) {
2835 foreach ($subcategories as $category) {
2836 $this->add_category($category, $basecategory);
2840 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2841 foreach ($courses as $course) {
2842 $this->add_course($course);
2844 $courses->close();
2848 * Returns an array of expandable nodes
2849 * @return array
2851 public function get_expandable() {
2852 return $this->expandable;
2857 * Navbar class
2859 * This class is used to manage the navbar, which is initialised from the navigation
2860 * object held by PAGE
2862 * @package core
2863 * @category navigation
2864 * @copyright 2009 Sam Hemelryk
2865 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2867 class navbar extends navigation_node {
2868 /** @var bool A switch for whether the navbar is initialised or not */
2869 protected $initialised = false;
2870 /** @var mixed keys used to reference the nodes on the navbar */
2871 protected $keys = array();
2872 /** @var null|string content of the navbar */
2873 protected $content = null;
2874 /** @var moodle_page object the moodle page that this navbar belongs to */
2875 protected $page;
2876 /** @var bool A switch for whether to ignore the active navigation information */
2877 protected $ignoreactive = false;
2878 /** @var bool A switch to let us know if we are in the middle of an install */
2879 protected $duringinstall = false;
2880 /** @var bool A switch for whether the navbar has items */
2881 protected $hasitems = false;
2882 /** @var array An array of navigation nodes for the navbar */
2883 protected $items;
2884 /** @var array An array of child node objects */
2885 public $children = array();
2886 /** @var bool A switch for whether we want to include the root node in the navbar */
2887 public $includesettingsbase = false;
2889 * The almighty constructor
2891 * @param moodle_page $page
2893 public function __construct(moodle_page $page) {
2894 global $CFG;
2895 if (during_initial_install()) {
2896 $this->duringinstall = true;
2897 return false;
2899 $this->page = $page;
2900 $this->text = get_string('home');
2901 $this->shorttext = get_string('home');
2902 $this->action = new moodle_url($CFG->wwwroot);
2903 $this->nodetype = self::NODETYPE_BRANCH;
2904 $this->type = self::TYPE_SYSTEM;
2908 * Quick check to see if the navbar will have items in.
2910 * @return bool Returns true if the navbar will have items, false otherwise
2912 public function has_items() {
2913 if ($this->duringinstall) {
2914 return false;
2915 } else if ($this->hasitems !== false) {
2916 return true;
2918 $this->page->navigation->initialise($this->page);
2920 $activenodefound = ($this->page->navigation->contains_active_node() ||
2921 $this->page->settingsnav->contains_active_node());
2923 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2924 $this->hasitems = $outcome;
2925 return $outcome;
2929 * Turn on/off ignore active
2931 * @param bool $setting
2933 public function ignore_active($setting=true) {
2934 $this->ignoreactive = ($setting);
2938 * Gets a navigation node
2940 * @param string|int $key for referencing the navbar nodes
2941 * @param int $type navigation_node::TYPE_*
2942 * @return navigation_node|bool
2944 public function get($key, $type = null) {
2945 foreach ($this->children as &$child) {
2946 if ($child->key === $key && ($type == null || $type == $child->type)) {
2947 return $child;
2950 return false;
2953 * Returns an array of navigation_node's that make up the navbar.
2955 * @return array
2957 public function get_items() {
2958 $items = array();
2959 // Make sure that navigation is initialised
2960 if (!$this->has_items()) {
2961 return $items;
2963 if ($this->items !== null) {
2964 return $this->items;
2967 if (count($this->children) > 0) {
2968 // Add the custom children
2969 $items = array_reverse($this->children);
2972 $navigationactivenode = $this->page->navigation->find_active_node();
2973 $settingsactivenode = $this->page->settingsnav->find_active_node();
2975 // Check if navigation contains the active node
2976 if (!$this->ignoreactive) {
2978 if ($navigationactivenode && $settingsactivenode) {
2979 // Parse a combined navigation tree
2980 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2981 if (!$settingsactivenode->mainnavonly) {
2982 $items[] = $settingsactivenode;
2984 $settingsactivenode = $settingsactivenode->parent;
2986 if (!$this->includesettingsbase) {
2987 // Removes the first node from the settings (root node) from the list
2988 array_pop($items);
2990 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2991 if (!$navigationactivenode->mainnavonly) {
2992 $items[] = $navigationactivenode;
2994 $navigationactivenode = $navigationactivenode->parent;
2996 } else if ($navigationactivenode) {
2997 // Parse the navigation tree to get the active node
2998 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2999 if (!$navigationactivenode->mainnavonly) {
3000 $items[] = $navigationactivenode;
3002 $navigationactivenode = $navigationactivenode->parent;
3004 } else if ($settingsactivenode) {
3005 // Parse the settings navigation to get the active node
3006 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3007 if (!$settingsactivenode->mainnavonly) {
3008 $items[] = $settingsactivenode;
3010 $settingsactivenode = $settingsactivenode->parent;
3015 $items[] = new navigation_node(array(
3016 'text'=>$this->page->navigation->text,
3017 'shorttext'=>$this->page->navigation->shorttext,
3018 'key'=>$this->page->navigation->key,
3019 'action'=>$this->page->navigation->action
3022 $this->items = array_reverse($items);
3023 return $this->items;
3027 * Add a new navigation_node to the navbar, overrides parent::add
3029 * This function overrides {@link navigation_node::add()} so that we can change
3030 * the way nodes get added to allow us to simply call add and have the node added to the
3031 * end of the navbar
3033 * @param string $text
3034 * @param string|moodle_url|action_link $action An action to associate with this node.
3035 * @param int $type One of navigation_node::TYPE_*
3036 * @param string $shorttext
3037 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3038 * @param pix_icon $icon An optional icon to use for this node.
3039 * @return navigation_node
3041 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3042 if ($this->content !== null) {
3043 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3046 // Properties array used when creating the new navigation node
3047 $itemarray = array(
3048 'text' => $text,
3049 'type' => $type
3051 // Set the action if one was provided
3052 if ($action!==null) {
3053 $itemarray['action'] = $action;
3055 // Set the shorttext if one was provided
3056 if ($shorttext!==null) {
3057 $itemarray['shorttext'] = $shorttext;
3059 // Set the icon if one was provided
3060 if ($icon!==null) {
3061 $itemarray['icon'] = $icon;
3063 // Default the key to the number of children if not provided
3064 if ($key === null) {
3065 $key = count($this->children);
3067 // Set the key
3068 $itemarray['key'] = $key;
3069 // Set the parent to this node
3070 $itemarray['parent'] = $this;
3071 // Add the child using the navigation_node_collections add method
3072 $this->children[] = new navigation_node($itemarray);
3073 return $this;
3078 * Class used to manage the settings option for the current page
3080 * This class is used to manage the settings options in a tree format (recursively)
3081 * and was created initially for use with the settings blocks.
3083 * @package core
3084 * @category navigation
3085 * @copyright 2009 Sam Hemelryk
3086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3088 class settings_navigation extends navigation_node {
3089 /** @var stdClass the current context */
3090 protected $context;
3091 /** @var moodle_page the moodle page that the navigation belongs to */
3092 protected $page;
3093 /** @var string contains administration section navigation_nodes */
3094 protected $adminsection;
3095 /** @var bool A switch to see if the navigation node is initialised */
3096 protected $initialised = false;
3097 /** @var array An array of users that the nodes can extend for. */
3098 protected $userstoextendfor = array();
3099 /** @var navigation_cache **/
3100 protected $cache;
3103 * Sets up the object with basic settings and preparse it for use
3105 * @param moodle_page $page
3107 public function __construct(moodle_page &$page) {
3108 if (during_initial_install()) {
3109 return false;
3111 $this->page = $page;
3112 // Initialise the main navigation. It is most important that this is done
3113 // before we try anything
3114 $this->page->navigation->initialise();
3115 // Initialise the navigation cache
3116 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3117 $this->children = new navigation_node_collection();
3120 * Initialise the settings navigation based on the current context
3122 * This function initialises the settings navigation tree for a given context
3123 * by calling supporting functions to generate major parts of the tree.
3126 public function initialise() {
3127 global $DB, $SESSION, $SITE;
3129 if (during_initial_install()) {
3130 return false;
3131 } else if ($this->initialised) {
3132 return true;
3134 $this->id = 'settingsnav';
3135 $this->context = $this->page->context;
3137 $context = $this->context;
3138 if ($context->contextlevel == CONTEXT_BLOCK) {
3139 $this->load_block_settings();
3140 $context = $context->get_parent_context();
3143 switch ($context->contextlevel) {
3144 case CONTEXT_SYSTEM:
3145 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3146 $this->load_front_page_settings(($context->id == $this->context->id));
3148 break;
3149 case CONTEXT_COURSECAT:
3150 $this->load_category_settings();
3151 break;
3152 case CONTEXT_COURSE:
3153 if ($this->page->course->id != $SITE->id) {
3154 $this->load_course_settings(($context->id == $this->context->id));
3155 } else {
3156 $this->load_front_page_settings(($context->id == $this->context->id));
3158 break;
3159 case CONTEXT_MODULE:
3160 $this->load_module_settings();
3161 $this->load_course_settings();
3162 break;
3163 case CONTEXT_USER:
3164 if ($this->page->course->id != $SITE->id) {
3165 $this->load_course_settings();
3167 break;
3170 $settings = $this->load_user_settings($this->page->course->id);
3172 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
3173 $admin = $this->load_administration_settings();
3174 $SESSION->load_navigation_admin = ($admin->has_children());
3175 } else {
3176 $admin = false;
3179 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
3180 $admin->force_open();
3181 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
3182 $settings->force_open();
3185 // Check if the user is currently logged in as another user
3186 if (session_is_loggedinas()) {
3187 // Get the actual user, we need this so we can display an informative return link
3188 $realuser = session_get_realuser();
3189 // Add the informative return to original user link
3190 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3191 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3194 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3195 $this->load_local_plugin_settings();
3197 foreach ($this->children as $key=>$node) {
3198 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3199 $node->remove();
3202 $this->initialised = true;
3205 * Override the parent function so that we can add preceeding hr's and set a
3206 * root node class against all first level element
3208 * It does this by first calling the parent's add method {@link navigation_node::add()}
3209 * and then proceeds to use the key to set class and hr
3211 * @param string $text text to be used for the link.
3212 * @param string|moodle_url $url url for the new node
3213 * @param int $type the type of node navigation_node::TYPE_*
3214 * @param string $shorttext
3215 * @param string|int $key a key to access the node by.
3216 * @param pix_icon $icon An icon that appears next to the node.
3217 * @return navigation_node with the new node added to it.
3219 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3220 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3221 $node->add_class('root_node');
3222 return $node;
3226 * This function allows the user to add something to the start of the settings
3227 * navigation, which means it will be at the top of the settings navigation block
3229 * @param string $text text to be used for the link.
3230 * @param string|moodle_url $url url for the new node
3231 * @param int $type the type of node navigation_node::TYPE_*
3232 * @param string $shorttext
3233 * @param string|int $key a key to access the node by.
3234 * @param pix_icon $icon An icon that appears next to the node.
3235 * @return navigation_node $node with the new node added to it.
3237 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3238 $children = $this->children;
3239 $childrenclass = get_class($children);
3240 $this->children = new $childrenclass;
3241 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3242 foreach ($children as $child) {
3243 $this->children->add($child);
3245 return $node;
3248 * Load the site administration tree
3250 * This function loads the site administration tree by using the lib/adminlib library functions
3252 * @param navigation_node $referencebranch A reference to a branch in the settings
3253 * navigation tree
3254 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3255 * tree and start at the beginning
3256 * @return mixed A key to access the admin tree by
3258 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3259 global $CFG;
3261 // Check if we are just starting to generate this navigation.
3262 if ($referencebranch === null) {
3264 // Require the admin lib then get an admin structure
3265 if (!function_exists('admin_get_root')) {
3266 require_once($CFG->dirroot.'/lib/adminlib.php');
3268 $adminroot = admin_get_root(false, false);
3269 // This is the active section identifier
3270 $this->adminsection = $this->page->url->param('section');
3272 // Disable the navigation from automatically finding the active node
3273 navigation_node::$autofindactive = false;
3274 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
3275 foreach ($adminroot->children as $adminbranch) {
3276 $this->load_administration_settings($referencebranch, $adminbranch);
3278 navigation_node::$autofindactive = true;
3280 // Use the admin structure to locate the active page
3281 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3282 $currentnode = $this;
3283 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3284 $currentnode = $currentnode->get($pathkey);
3286 if ($currentnode) {
3287 $currentnode->make_active();
3289 } else {
3290 $this->scan_for_active_node($referencebranch);
3292 return $referencebranch;
3293 } else if ($adminbranch->check_access()) {
3294 // We have a reference branch that we can access and is not hidden `hurrah`
3295 // Now we need to display it and any children it may have
3296 $url = null;
3297 $icon = null;
3298 if ($adminbranch instanceof admin_settingpage) {
3299 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3300 } else if ($adminbranch instanceof admin_externalpage) {
3301 $url = $adminbranch->url;
3302 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3303 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3306 // Add the branch
3307 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3309 if ($adminbranch->is_hidden()) {
3310 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3311 $reference->add_class('hidden');
3312 } else {
3313 $reference->display = false;
3317 // Check if we are generating the admin notifications and whether notificiations exist
3318 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3319 $reference->add_class('criticalnotification');
3321 // Check if this branch has children
3322 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3323 foreach ($adminbranch->children as $branch) {
3324 // Generate the child branches as well now using this branch as the reference
3325 $this->load_administration_settings($reference, $branch);
3327 } else {
3328 $reference->icon = new pix_icon('i/settings', '');
3334 * This function recursivily scans nodes until it finds the active node or there
3335 * are no more nodes.
3336 * @param navigation_node $node
3338 protected function scan_for_active_node(navigation_node $node) {
3339 if (!$node->check_if_active() && $node->children->count()>0) {
3340 foreach ($node->children as &$child) {
3341 $this->scan_for_active_node($child);
3347 * Gets a navigation node given an array of keys that represent the path to
3348 * the desired node.
3350 * @param array $path
3351 * @return navigation_node|false
3353 protected function get_by_path(array $path) {
3354 $node = $this->get(array_shift($path));
3355 foreach ($path as $key) {
3356 $node->get($key);
3358 return $node;
3362 * Generate the list of modules for the given course.
3364 * @param stdClass $course The course to get modules for
3366 protected function get_course_modules($course) {
3367 global $CFG;
3368 // This function is included when we include course/lib.php at the top
3369 // of this file
3370 $modnames = get_module_types_names();
3371 $resources = array();
3372 $activities = array();
3373 foreach($modnames as $modname=>$modnamestr) {
3374 if (!course_allowed_module($course, $modname)) {
3375 continue;
3378 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3379 if (!file_exists($libfile)) {
3380 continue;
3382 include_once($libfile);
3383 $gettypesfunc = $modname.'_get_types';
3384 if (function_exists($gettypesfunc)) {
3385 $types = $gettypesfunc();
3386 foreach($types as $type) {
3387 if (!isset($type->modclass) || !isset($type->typestr)) {
3388 debugging('Incorrect activity type in '.$modname);
3389 continue;
3391 if ($type->modclass == MOD_CLASS_RESOURCE) {
3392 $resources[html_entity_decode($type->type)] = $type->typestr;
3393 } else {
3394 $activities[html_entity_decode($type->type)] = $type->typestr;
3397 } else {
3398 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3399 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
3400 $resources[$modname] = $modnamestr;
3401 } else {
3402 // all other archetypes are considered activity
3403 $activities[$modname] = $modnamestr;
3407 return array($resources, $activities);
3411 * This function loads the course settings that are available for the user
3413 * @param bool $forceopen If set to true the course node will be forced open
3414 * @return navigation_node|false
3416 protected function load_course_settings($forceopen = false) {
3417 global $CFG;
3419 $course = $this->page->course;
3420 $coursecontext = context_course::instance($course->id);
3422 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3424 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3425 if ($forceopen) {
3426 $coursenode->force_open();
3429 if (has_capability('moodle/course:update', $coursecontext)) {
3430 // Add the turn on/off settings
3432 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3433 // We are on the course page, retain the current page params e.g. section.
3434 $baseurl = clone($this->page->url);
3435 $baseurl->param('sesskey', sesskey());
3436 } else {
3437 // Edit on the main course page.
3438 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3441 $editurl = clone($baseurl);
3442 if ($this->page->user_is_editing()) {
3443 $editurl->param('edit', 'off');
3444 $editstring = get_string('turneditingoff');
3445 } else {
3446 $editurl->param('edit', 'on');
3447 $editstring = get_string('turneditingon');
3449 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3451 // Add the module chooser toggle
3452 $modchoosertoggleurl = clone($baseurl);
3453 if ($this->page->user_is_editing() && course_ajax_enabled($course)) {
3454 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
3455 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
3456 $modchoosertoggleurl->param('modchooser', 'off');
3457 } else {
3458 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
3459 $modchoosertoggleurl->param('modchooser', 'on');
3461 $modchoosertoggle = $coursenode->add($modchoosertogglestring, $modchoosertoggleurl, self::TYPE_SETTING);
3462 $modchoosertoggle->add_class('modchoosertoggle');
3463 $modchoosertoggle->add_class('visibleifjs');
3464 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
3467 // Add the course settings link
3468 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3469 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3471 // Add the course completion settings link
3472 if ($CFG->enablecompletion && $course->enablecompletion) {
3473 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3474 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3478 // add enrol nodes
3479 enrol_add_course_navigation($coursenode, $course);
3481 // Manage filters
3482 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3483 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3484 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3487 // Add view grade report is permitted
3488 $reportavailable = false;
3489 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3490 $reportavailable = true;
3491 } else if (!empty($course->showgrades)) {
3492 $reports = get_plugin_list('gradereport');
3493 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3494 arsort($reports); // user is last, we want to test it first
3495 foreach ($reports as $plugin => $plugindir) {
3496 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3497 //stop when the first visible plugin is found
3498 $reportavailable = true;
3499 break;
3504 if ($reportavailable) {
3505 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3506 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3509 // Add outcome if permitted
3510 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3511 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3512 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3515 // Backup this course
3516 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3517 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3518 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3521 // Restore to this course
3522 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3523 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3524 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3527 // Import data from other courses
3528 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3529 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3530 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
3533 // Publish course on a hub
3534 if (has_capability('moodle/course:publish', $coursecontext)) {
3535 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3536 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3539 // Reset this course
3540 if (has_capability('moodle/course:reset', $coursecontext)) {
3541 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3542 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3545 // Questions
3546 require_once($CFG->libdir . '/questionlib.php');
3547 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3549 if (has_capability('moodle/course:update', $coursecontext)) {
3550 // Repository Instances
3551 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3552 require_once($CFG->dirroot . '/repository/lib.php');
3553 $editabletypes = repository::get_editable_types($coursecontext);
3554 $haseditabletypes = !empty($editabletypes);
3555 unset($editabletypes);
3556 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3557 } else {
3558 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3560 if ($haseditabletypes) {
3561 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3562 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3566 // Manage files
3567 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3568 // hidden in new courses and courses where legacy files were turned off
3569 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3570 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
3574 // Switch roles
3575 $roles = array();
3576 $assumedrole = $this->in_alternative_role();
3577 if ($assumedrole !== false) {
3578 $roles[0] = get_string('switchrolereturn');
3580 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3581 $availableroles = get_switchable_roles($coursecontext);
3582 if (is_array($availableroles)) {
3583 foreach ($availableroles as $key=>$role) {
3584 if ($assumedrole == (int)$key) {
3585 continue;
3587 $roles[$key] = $role;
3591 if (is_array($roles) && count($roles)>0) {
3592 $switchroles = $this->add(get_string('switchroleto'));
3593 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3594 $switchroles->force_open();
3596 $returnurl = $this->page->url;
3597 $returnurl->param('sesskey', sesskey());
3598 foreach ($roles as $key => $name) {
3599 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3600 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
3603 // Return we are done
3604 return $coursenode;
3608 * This function calls the module function to inject module settings into the
3609 * settings navigation tree.
3611 * This only gets called if there is a corrosponding function in the modules
3612 * lib file.
3614 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3616 * @return navigation_node|false
3618 protected function load_module_settings() {
3619 global $CFG;
3621 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3622 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3623 $this->page->set_cm($cm, $this->page->course);
3626 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3627 if (file_exists($file)) {
3628 require_once($file);
3631 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3632 $modulenode->force_open();
3634 // Settings for the module
3635 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3636 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3637 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3639 // Assign local roles
3640 if (count(get_assignable_roles($this->page->cm->context))>0) {
3641 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3642 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3644 // Override roles
3645 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3646 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3647 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3649 // Check role permissions
3650 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3651 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3652 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3654 // Manage filters
3655 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3656 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3657 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3659 // Add reports
3660 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3661 foreach ($reports as $reportfunction) {
3662 $reportfunction($modulenode, $this->page->cm);
3664 // Add a backup link
3665 $featuresfunc = $this->page->activityname.'_supports';
3666 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3667 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3668 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3671 // Restore this activity
3672 $featuresfunc = $this->page->activityname.'_supports';
3673 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3674 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3675 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3678 // Allow the active advanced grading method plugin to append its settings
3679 $featuresfunc = $this->page->activityname.'_supports';
3680 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3681 require_once($CFG->dirroot.'/grade/grading/lib.php');
3682 $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
3683 $gradingman->extend_settings_navigation($this, $modulenode);
3686 $function = $this->page->activityname.'_extend_settings_navigation';
3687 if (!function_exists($function)) {
3688 return $modulenode;
3691 $function($this, $modulenode);
3693 // Remove the module node if there are no children
3694 if (empty($modulenode->children)) {
3695 $modulenode->remove();
3698 return $modulenode;
3702 * Loads the user settings block of the settings nav
3704 * This function is simply works out the userid and whether we need to load
3705 * just the current users profile settings, or the current user and the user the
3706 * current user is viewing.
3708 * This function has some very ugly code to work out the user, if anyone has
3709 * any bright ideas please feel free to intervene.
3711 * @param int $courseid The course id of the current course
3712 * @return navigation_node|false
3714 protected function load_user_settings($courseid = SITEID) {
3715 global $USER, $CFG;
3717 if (isguestuser() || !isloggedin()) {
3718 return false;
3721 $navusers = $this->page->navigation->get_extending_users();
3723 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3724 $usernode = null;
3725 foreach ($this->userstoextendfor as $userid) {
3726 if ($userid == $USER->id) {
3727 continue;
3729 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3730 if (is_null($usernode)) {
3731 $usernode = $node;
3734 foreach ($navusers as $user) {
3735 if ($user->id == $USER->id) {
3736 continue;
3738 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3739 if (is_null($usernode)) {
3740 $usernode = $node;
3743 $this->generate_user_settings($courseid, $USER->id);
3744 } else {
3745 $usernode = $this->generate_user_settings($courseid, $USER->id);
3747 return $usernode;
3751 * Extends the settings navigation for the given user.
3753 * Note: This method gets called automatically if you call
3754 * $PAGE->navigation->extend_for_user($userid)
3756 * @param int $userid
3758 public function extend_for_user($userid) {
3759 global $CFG;
3761 if (!in_array($userid, $this->userstoextendfor)) {
3762 $this->userstoextendfor[] = $userid;
3763 if ($this->initialised) {
3764 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3765 $children = array();
3766 foreach ($this->children as $child) {
3767 $children[] = $child;
3769 array_unshift($children, array_pop($children));
3770 $this->children = new navigation_node_collection();
3771 foreach ($children as $child) {
3772 $this->children->add($child);
3779 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3780 * what can be shown/done
3782 * @param int $courseid The current course' id
3783 * @param int $userid The user id to load for
3784 * @param string $gstitle The string to pass to get_string for the branch title
3785 * @return navigation_node|false
3787 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3788 global $DB, $CFG, $USER, $SITE;
3790 if ($courseid != $SITE->id) {
3791 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3792 $course = $this->page->course;
3793 } else {
3794 $select = context_helper::get_preload_record_columns_sql('ctx');
3795 $sql = "SELECT c.*, $select
3796 FROM {course} c
3797 JOIN {context} ctx ON c.id = ctx.instanceid
3798 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
3799 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
3800 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3801 context_helper::preload_from_record($course);
3803 } else {
3804 $course = $SITE;
3807 $coursecontext = context_course::instance($course->id); // Course context
3808 $systemcontext = get_system_context();
3809 $currentuser = ($USER->id == $userid);
3811 if ($currentuser) {
3812 $user = $USER;
3813 $usercontext = context_user::instance($user->id); // User context
3814 } else {
3815 $select = context_helper::get_preload_record_columns_sql('ctx');
3816 $sql = "SELECT u.*, $select
3817 FROM {user} u
3818 JOIN {context} ctx ON u.id = ctx.instanceid
3819 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
3820 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
3821 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
3822 if (!$user) {
3823 return false;
3825 context_helper::preload_from_record($user);
3827 // Check that the user can view the profile
3828 $usercontext = context_user::instance($user->id); // User context
3829 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3831 if ($course->id == $SITE->id) {
3832 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
3833 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3834 return false;
3836 } else {
3837 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
3838 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
3839 if ((!$canviewusercourse && !$canviewuser) || !can_access_course($course, $user->id)) {
3840 return false;
3842 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
3843 // If groups are in use, make sure we can see that group
3844 return false;
3849 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3851 $key = $gstitle;
3852 if ($gstitle != 'usercurrentsettings') {
3853 $key .= $userid;
3856 // Add a user setting branch
3857 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3858 $usersetting->id = 'usersettings';
3859 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3860 // Automatically start by making it active
3861 $usersetting->make_active();
3864 // Check if the user has been deleted
3865 if ($user->deleted) {
3866 if (!has_capability('moodle/user:update', $coursecontext)) {
3867 // We can't edit the user so just show the user deleted message
3868 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3869 } else {
3870 // We can edit the user so show the user deleted message and link it to the profile
3871 if ($course->id == $SITE->id) {
3872 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3873 } else {
3874 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3876 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3878 return true;
3881 $userauthplugin = false;
3882 if (!empty($user->auth)) {
3883 $userauthplugin = get_auth_plugin($user->auth);
3886 // Add the profile edit link
3887 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3888 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3889 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3890 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3891 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3892 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
3893 $url = $userauthplugin->edit_profile_url();
3894 if (empty($url)) {
3895 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3897 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3902 // Change password link
3903 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
3904 $passwordchangeurl = $userauthplugin->change_password_url();
3905 if (empty($passwordchangeurl)) {
3906 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3908 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3911 // View the roles settings
3912 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3913 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3915 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3916 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3918 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3920 if (!empty($assignableroles)) {
3921 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3922 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3925 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3926 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3927 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3930 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3931 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3934 // Portfolio
3935 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3936 require_once($CFG->libdir . '/portfoliolib.php');
3937 if (portfolio_instances(true, false)) {
3938 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3940 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3941 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
3943 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
3944 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
3948 $enablemanagetokens = false;
3949 if (!empty($CFG->enablerssfeeds)) {
3950 $enablemanagetokens = true;
3951 } else if (!is_siteadmin($USER->id)
3952 && !empty($CFG->enablewebservices)
3953 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3954 $enablemanagetokens = true;
3956 // Security keys
3957 if ($currentuser && $enablemanagetokens) {
3958 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3959 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
3962 // Repository
3963 if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
3964 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
3965 require_once($CFG->dirroot . '/repository/lib.php');
3966 $editabletypes = repository::get_editable_types($usercontext);
3967 $haseditabletypes = !empty($editabletypes);
3968 unset($editabletypes);
3969 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
3970 } else {
3971 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
3973 if ($haseditabletypes) {
3974 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
3975 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
3979 // Messaging
3980 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
3981 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3982 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
3985 // Blogs
3986 if ($currentuser && !empty($CFG->enableblogs)) {
3987 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
3988 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
3989 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
3990 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
3991 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
3995 // Login as ...
3996 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
3997 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
3998 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
4001 return $usersetting;
4005 * Loads block specific settings in the navigation
4007 * @return navigation_node
4009 protected function load_block_settings() {
4010 global $CFG;
4012 $blocknode = $this->add(print_context_name($this->context));
4013 $blocknode->force_open();
4015 // Assign local roles
4016 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4017 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4019 // Override roles
4020 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4021 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4022 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4024 // Check role permissions
4025 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4026 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4027 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4030 return $blocknode;
4034 * Loads category specific settings in the navigation
4036 * @return navigation_node
4038 protected function load_category_settings() {
4039 global $CFG;
4041 $categorynode = $this->add(print_context_name($this->context));
4042 $categorynode->force_open();
4044 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context)) {
4045 $url = new moodle_url('/course/category.php', array('id'=>$this->context->instanceid, 'sesskey'=>sesskey()));
4046 if ($this->page->user_is_editing()) {
4047 $url->param('categoryedit', '0');
4048 $editstring = get_string('turneditingoff');
4049 } else {
4050 $url->param('categoryedit', '1');
4051 $editstring = get_string('turneditingon');
4053 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4056 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
4057 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
4058 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4060 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
4061 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4064 // Assign local roles
4065 if (has_capability('moodle/role:assign', $this->context)) {
4066 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4067 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4070 // Override roles
4071 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4072 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4073 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4075 // Check role permissions
4076 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4077 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4078 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4081 // Cohorts
4082 if (has_capability('moodle/cohort:manage', $this->context) or has_capability('moodle/cohort:view', $this->context)) {
4083 $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', ''));
4086 // Manage filters
4087 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
4088 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
4089 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4092 return $categorynode;
4096 * Determine whether the user is assuming another role
4098 * This function checks to see if the user is assuming another role by means of
4099 * role switching. In doing this we compare each RSW key (context path) against
4100 * the current context path. This ensures that we can provide the switching
4101 * options against both the course and any page shown under the course.
4103 * @return bool|int The role(int) if the user is in another role, false otherwise
4105 protected function in_alternative_role() {
4106 global $USER;
4107 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4108 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4109 return $USER->access['rsw'][$this->page->context->path];
4111 foreach ($USER->access['rsw'] as $key=>$role) {
4112 if (strpos($this->context->path,$key)===0) {
4113 return $role;
4117 return false;
4121 * This function loads all of the front page settings into the settings navigation.
4122 * This function is called when the user is on the front page, or $COURSE==$SITE
4123 * @param bool $forceopen (optional)
4124 * @return navigation_node
4126 protected function load_front_page_settings($forceopen = false) {
4127 global $SITE, $CFG;
4129 $course = clone($SITE);
4130 $coursecontext = context_course::instance($course->id); // Course context
4132 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4133 if ($forceopen) {
4134 $frontpage->force_open();
4136 $frontpage->id = 'frontpagesettings';
4138 if (has_capability('moodle/course:update', $coursecontext)) {
4140 // Add the turn on/off settings
4141 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4142 if ($this->page->user_is_editing()) {
4143 $url->param('edit', 'off');
4144 $editstring = get_string('turneditingoff');
4145 } else {
4146 $url->param('edit', 'on');
4147 $editstring = get_string('turneditingon');
4149 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4151 // Add the course settings link
4152 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4153 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4156 // add enrol nodes
4157 enrol_add_course_navigation($frontpage, $course);
4159 // Manage filters
4160 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4161 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4162 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4165 // Backup this course
4166 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4167 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4168 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4171 // Restore to this course
4172 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4173 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4174 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4177 // Questions
4178 require_once($CFG->libdir . '/questionlib.php');
4179 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4181 // Manage files
4182 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4183 //hiden in new installs
4184 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
4185 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
4187 return $frontpage;
4191 * This function gives local plugins an opportunity to modify the settings navigation.
4193 protected function load_local_plugin_settings() {
4194 // Get all local plugins with an extend_settings_navigation function in their lib.php file
4195 foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
4196 // Call each function providing this (the settings navigation) and the current context.
4197 $function($this, $this->context);
4202 * This function marks the cache as volatile so it is cleared during shutdown
4204 public function clear_cache() {
4205 $this->cache->volatile();
4210 * Simple class used to output a navigation branch in XML
4212 * @package core
4213 * @category navigation
4214 * @copyright 2009 Sam Hemelryk
4215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4217 class navigation_json {
4218 /** @var array An array of different node types */
4219 protected $nodetype = array('node','branch');
4220 /** @var array An array of node keys and types */
4221 protected $expandable = array();
4223 * Turns a branch and all of its children into XML
4225 * @param navigation_node $branch
4226 * @return string XML string
4228 public function convert($branch) {
4229 $xml = $this->convert_child($branch);
4230 return $xml;
4233 * Set the expandable items in the array so that we have enough information
4234 * to attach AJAX events
4235 * @param array $expandable
4237 public function set_expandable($expandable) {
4238 foreach ($expandable as $node) {
4239 $this->expandable[$node['key'].':'.$node['type']] = $node;
4243 * Recusively converts a child node and its children to XML for output
4245 * @param navigation_node $child The child to convert
4246 * @param int $depth Pointlessly used to track the depth of the XML structure
4247 * @return string JSON
4249 protected function convert_child($child, $depth=1) {
4250 if (!$child->display) {
4251 return '';
4253 $attributes = array();
4254 $attributes['id'] = $child->id;
4255 $attributes['name'] = $child->text;
4256 $attributes['type'] = $child->type;
4257 $attributes['key'] = $child->key;
4258 $attributes['class'] = $child->get_css_type();
4260 if ($child->icon instanceof pix_icon) {
4261 $attributes['icon'] = array(
4262 'component' => $child->icon->component,
4263 'pix' => $child->icon->pix,
4265 foreach ($child->icon->attributes as $key=>$value) {
4266 if ($key == 'class') {
4267 $attributes['icon']['classes'] = explode(' ', $value);
4268 } else if (!array_key_exists($key, $attributes['icon'])) {
4269 $attributes['icon'][$key] = $value;
4273 } else if (!empty($child->icon)) {
4274 $attributes['icon'] = (string)$child->icon;
4277 if ($child->forcetitle || $child->title !== $child->text) {
4278 $attributes['title'] = htmlentities($child->title);
4280 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4281 $attributes['expandable'] = $child->key;
4282 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4285 if (count($child->classes)>0) {
4286 $attributes['class'] .= ' '.join(' ',$child->classes);
4288 if (is_string($child->action)) {
4289 $attributes['link'] = $child->action;
4290 } else if ($child->action instanceof moodle_url) {
4291 $attributes['link'] = $child->action->out();
4292 } else if ($child->action instanceof action_link) {
4293 $attributes['link'] = $child->action->url->out();
4295 $attributes['hidden'] = ($child->hidden);
4296 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4298 if ($child->children->count() > 0) {
4299 $attributes['children'] = array();
4300 foreach ($child->children as $subchild) {
4301 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4305 if ($depth > 1) {
4306 return $attributes;
4307 } else {
4308 return json_encode($attributes);
4314 * The cache class used by global navigation and settings navigation.
4316 * It is basically an easy access point to session with a bit of smarts to make
4317 * sure that the information that is cached is valid still.
4319 * Example use:
4320 * <code php>
4321 * if (!$cache->viewdiscussion()) {
4322 * // Code to do stuff and produce cachable content
4323 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4325 * $content = $cache->viewdiscussion;
4326 * </code>
4328 * @package core
4329 * @category navigation
4330 * @copyright 2009 Sam Hemelryk
4331 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4333 class navigation_cache {
4334 /** @var int represents the time created */
4335 protected $creation;
4336 /** @var array An array of session keys */
4337 protected $session;
4339 * The string to use to segregate this particular cache. It can either be
4340 * unique to start a fresh cache or if you want to share a cache then make
4341 * it the string used in the original cache.
4342 * @var string
4344 protected $area;
4345 /** @var int a time that the information will time out */
4346 protected $timeout;
4347 /** @var stdClass The current context */
4348 protected $currentcontext;
4349 /** @var int cache time information */
4350 const CACHETIME = 0;
4351 /** @var int cache user id */
4352 const CACHEUSERID = 1;
4353 /** @var int cache value */
4354 const CACHEVALUE = 2;
4355 /** @var null|array An array of navigation cache areas to expire on shutdown */
4356 public static $volatilecaches;
4359 * Contructor for the cache. Requires two arguments
4361 * @param string $area The string to use to segregate this particular cache
4362 * it can either be unique to start a fresh cache or if you want
4363 * to share a cache then make it the string used in the original
4364 * cache
4365 * @param int $timeout The number of seconds to time the information out after
4367 public function __construct($area, $timeout=1800) {
4368 $this->creation = time();
4369 $this->area = $area;
4370 $this->timeout = time() - $timeout;
4371 if (rand(0,100) === 0) {
4372 $this->garbage_collection();
4377 * Used to set up the cache within the SESSION.
4379 * This is called for each access and ensure that we don't put anything into the session before
4380 * it is required.
4382 protected function ensure_session_cache_initialised() {
4383 global $SESSION;
4384 if (empty($this->session)) {
4385 if (!isset($SESSION->navcache)) {
4386 $SESSION->navcache = new stdClass;
4388 if (!isset($SESSION->navcache->{$this->area})) {
4389 $SESSION->navcache->{$this->area} = array();
4391 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
4396 * Magic Method to retrieve something by simply calling using = cache->key
4398 * @param mixed $key The identifier for the information you want out again
4399 * @return void|mixed Either void or what ever was put in
4401 public function __get($key) {
4402 if (!$this->cached($key)) {
4403 return;
4405 $information = $this->session[$key][self::CACHEVALUE];
4406 return unserialize($information);
4410 * Magic method that simply uses {@link set();} to store something in the cache
4412 * @param string|int $key
4413 * @param mixed $information
4415 public function __set($key, $information) {
4416 $this->set($key, $information);
4420 * Sets some information against the cache (session) for later retrieval
4422 * @param string|int $key
4423 * @param mixed $information
4425 public function set($key, $information) {
4426 global $USER;
4427 $this->ensure_session_cache_initialised();
4428 $information = serialize($information);
4429 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4432 * Check the existence of the identifier in the cache
4434 * @param string|int $key
4435 * @return bool
4437 public function cached($key) {
4438 global $USER;
4439 $this->ensure_session_cache_initialised();
4440 if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) {
4441 return false;
4443 return true;
4446 * Compare something to it's equivilant in the cache
4448 * @param string $key
4449 * @param mixed $value
4450 * @param bool $serialise Whether to serialise the value before comparison
4451 * this should only be set to false if the value is already
4452 * serialised
4453 * @return bool If the value is the same false if it is not set or doesn't match
4455 public function compare($key, $value, $serialise = true) {
4456 if ($this->cached($key)) {
4457 if ($serialise) {
4458 $value = serialize($value);
4460 if ($this->session[$key][self::CACHEVALUE] === $value) {
4461 return true;
4464 return false;
4467 * Wipes the entire cache, good to force regeneration
4469 public function clear() {
4470 global $SESSION;
4471 unset($SESSION->navcache);
4472 $this->session = null;
4475 * Checks all cache entries and removes any that have expired, good ole cleanup
4477 protected function garbage_collection() {
4478 if (empty($this->session)) {
4479 return true;
4481 foreach ($this->session as $key=>$cachedinfo) {
4482 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4483 unset($this->session[$key]);
4489 * Marks the cache as being volatile (likely to change)
4491 * Any caches marked as volatile will be destroyed at the on shutdown by
4492 * {@link navigation_node::destroy_volatile_caches()} which is registered
4493 * as a shutdown function if any caches are marked as volatile.
4495 * @param bool $setting True to destroy the cache false not too
4497 public function volatile($setting = true) {
4498 if (self::$volatilecaches===null) {
4499 self::$volatilecaches = array();
4500 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4503 if ($setting) {
4504 self::$volatilecaches[$this->area] = $this->area;
4505 } else if (array_key_exists($this->area, self::$volatilecaches)) {
4506 unset(self::$volatilecaches[$this->area]);
4511 * Destroys all caches marked as volatile
4513 * This function is static and works in conjunction with the static volatilecaches
4514 * property of navigation cache.
4515 * Because this function is static it manually resets the cached areas back to an
4516 * empty array.
4518 public static function destroy_volatile_caches() {
4519 global $SESSION;
4520 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4521 foreach (self::$volatilecaches as $area) {
4522 $SESSION->navcache->{$area} = array();
4524 } else {
4525 $SESSION->navcache = new stdClass;