Merge branch 'MDL-41565-master' of git://github.com/FMCorz/moodle
[moodle.git] / lib / navigationlib.php
blobbf958a61dcce380c0662c3221559550ca7255187
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 Category displayed in MyHome navigation node */
61 const TYPE_MY_CATEGORY = 11;
62 /** @var int Course node type 20 */
63 const TYPE_COURSE = 20;
64 /** @var int Course Structure node type 30 */
65 const TYPE_SECTION = 30;
66 /** @var int Activity node type, e.g. Forum, Quiz 40 */
67 const TYPE_ACTIVITY = 40;
68 /** @var int Resource node type, e.g. Link to a file, or label 50 */
69 const TYPE_RESOURCE = 50;
70 /** @var int A custom node type, default when adding without specifing type 60 */
71 const TYPE_CUSTOM = 60;
72 /** @var int Setting node type, used only within settings nav 70 */
73 const TYPE_SETTING = 70;
74 /** @var int Setting node type, used only within settings nav 80 */
75 const TYPE_USER = 80;
76 /** @var int Setting node type, used for containers of no importance 90 */
77 const TYPE_CONTAINER = 90;
78 /** var int Course the current user is not enrolled in */
79 const COURSE_OTHER = 0;
80 /** var int Course the current user is enrolled in but not viewing */
81 const COURSE_MY = 1;
82 /** var int Course the current user is currently viewing */
83 const COURSE_CURRENT = 2;
85 /** @var int Parameter to aid the coder in tracking [optional] */
86 public $id = null;
87 /** @var string|int The identifier for the node, used to retrieve the node */
88 public $key = null;
89 /** @var string The text to use for the node */
90 public $text = null;
91 /** @var string Short text to use if requested [optional] */
92 public $shorttext = null;
93 /** @var string The title attribute for an action if one is defined */
94 public $title = null;
95 /** @var string A string that can be used to build a help button */
96 public $helpbutton = null;
97 /** @var moodle_url|action_link|null An action for the node (link) */
98 public $action = null;
99 /** @var pix_icon The path to an icon to use for this node */
100 public $icon = null;
101 /** @var int See TYPE_* constants defined for this class */
102 public $type = self::TYPE_UNKNOWN;
103 /** @var int See NODETYPE_* constants defined for this class */
104 public $nodetype = self::NODETYPE_LEAF;
105 /** @var bool If set to true the node will be collapsed by default */
106 public $collapse = false;
107 /** @var bool If set to true the node will be expanded by default */
108 public $forceopen = false;
109 /** @var array An array of CSS classes for the node */
110 public $classes = array();
111 /** @var navigation_node_collection An array of child nodes */
112 public $children = array();
113 /** @var bool If set to true the node will be recognised as active */
114 public $isactive = false;
115 /** @var bool If set to true the node will be dimmed */
116 public $hidden = false;
117 /** @var bool If set to false the node will not be displayed */
118 public $display = true;
119 /** @var bool If set to true then an HR will be printed before the node */
120 public $preceedwithhr = false;
121 /** @var bool If set to true the the navigation bar should ignore this node */
122 public $mainnavonly = false;
123 /** @var bool If set to true a title will be added to the action no matter what */
124 public $forcetitle = false;
125 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
126 public $parent = null;
127 /** @var bool Override to not display the icon even if one is provided **/
128 public $hideicon = false;
129 /** @var bool Set to true if we KNOW that this node can be expanded. */
130 public $isexpandable = false;
131 /** @var array */
132 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
133 /** @var moodle_url */
134 protected static $fullmeurl = null;
135 /** @var bool toogles auto matching of active node */
136 public static $autofindactive = true;
137 /** @var mixed If set to an int, that section will be included even if it has no activities */
138 public $includesectionnum = false;
141 * Constructs a new navigation_node
143 * @param array|string $properties Either an array of properties or a string to use
144 * as the text for the node
146 public function __construct($properties) {
147 if (is_array($properties)) {
148 // Check the array for each property that we allow to set at construction.
149 // text - The main content for the node
150 // shorttext - A short text if required for the node
151 // icon - The icon to display for the node
152 // type - The type of the node
153 // key - The key to use to identify the node
154 // parent - A reference to the nodes parent
155 // action - The action to attribute to this node, usually a URL to link to
156 if (array_key_exists('text', $properties)) {
157 $this->text = $properties['text'];
159 if (array_key_exists('shorttext', $properties)) {
160 $this->shorttext = $properties['shorttext'];
162 if (!array_key_exists('icon', $properties)) {
163 $properties['icon'] = new pix_icon('i/navigationitem', '');
165 $this->icon = $properties['icon'];
166 if ($this->icon instanceof pix_icon) {
167 if (empty($this->icon->attributes['class'])) {
168 $this->icon->attributes['class'] = 'navicon';
169 } else {
170 $this->icon->attributes['class'] .= ' navicon';
173 if (array_key_exists('type', $properties)) {
174 $this->type = $properties['type'];
175 } else {
176 $this->type = self::TYPE_CUSTOM;
178 if (array_key_exists('key', $properties)) {
179 $this->key = $properties['key'];
181 // This needs to happen last because of the check_if_active call that occurs
182 if (array_key_exists('action', $properties)) {
183 $this->action = $properties['action'];
184 if (is_string($this->action)) {
185 $this->action = new moodle_url($this->action);
187 if (self::$autofindactive) {
188 $this->check_if_active();
191 if (array_key_exists('parent', $properties)) {
192 $this->set_parent($properties['parent']);
194 } else if (is_string($properties)) {
195 $this->text = $properties;
197 if ($this->text === null) {
198 throw new coding_exception('You must set the text for the node when you create it.');
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)) || ($type == self::TYPE_MY_CATEGORY)) {
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_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
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();
677 * Hides the node and any children it has.
679 * @since 2.5
680 * @param array $typestohide Optional. An array of node types that should be hidden.
681 * If null all nodes will be hidden.
682 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
683 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
685 public function hide(array $typestohide = null) {
686 if ($typestohide === null || in_array($this->type, $typestohide)) {
687 $this->display = false;
688 if ($this->has_children()) {
689 foreach ($this->children as $child) {
690 $child->hide($typestohide);
698 * Navigation node collection
700 * This class is responsible for managing a collection of navigation nodes.
701 * It is required because a node's unique identifier is a combination of both its
702 * key and its type.
704 * Originally an array was used with a string key that was a combination of the two
705 * however it was decided that a better solution would be to use a class that
706 * implements the standard IteratorAggregate interface.
708 * @package core
709 * @category navigation
710 * @copyright 2010 Sam Hemelryk
711 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
713 class navigation_node_collection implements IteratorAggregate {
715 * A multidimensional array to where the first key is the type and the second
716 * key is the nodes key.
717 * @var array
719 protected $collection = array();
721 * An array that contains references to nodes in the same order they were added.
722 * This is maintained as a progressive array.
723 * @var array
725 protected $orderedcollection = array();
727 * A reference to the last node that was added to the collection
728 * @var navigation_node
730 protected $last = null;
732 * The total number of items added to this array.
733 * @var int
735 protected $count = 0;
738 * Adds a navigation node to the collection
740 * @param navigation_node $node Node to add
741 * @param string $beforekey If specified, adds before a node with this key,
742 * otherwise adds at end
743 * @return navigation_node Added node
745 public function add(navigation_node $node, $beforekey=null) {
746 global $CFG;
747 $key = $node->key;
748 $type = $node->type;
750 // First check we have a 2nd dimension for this type
751 if (!array_key_exists($type, $this->orderedcollection)) {
752 $this->orderedcollection[$type] = array();
754 // Check for a collision and report if debugging is turned on
755 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
756 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
759 // Find the key to add before
760 $newindex = $this->count;
761 $last = true;
762 if ($beforekey !== null) {
763 foreach ($this->collection as $index => $othernode) {
764 if ($othernode->key === $beforekey) {
765 $newindex = $index;
766 $last = false;
767 break;
770 if ($newindex === $this->count) {
771 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
772 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
776 // Add the node to the appropriate place in the by-type structure (which
777 // is not ordered, despite the variable name)
778 $this->orderedcollection[$type][$key] = $node;
779 if (!$last) {
780 // Update existing references in the ordered collection (which is the
781 // one that isn't called 'ordered') to shuffle them along if required
782 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
783 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
786 // Add a reference to the node to the progressive collection.
787 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
788 // Update the last property to a reference to this new node.
789 $this->last = $this->orderedcollection[$type][$key];
791 // Reorder the array by index if needed
792 if (!$last) {
793 ksort($this->collection);
795 $this->count++;
796 // Return the reference to the now added node
797 return $node;
801 * Return a list of all the keys of all the nodes.
802 * @return array the keys.
804 public function get_key_list() {
805 $keys = array();
806 foreach ($this->collection as $node) {
807 $keys[] = $node->key;
809 return $keys;
813 * Fetches a node from this collection.
815 * @param string|int $key The key of the node we want to find.
816 * @param int $type One of navigation_node::TYPE_*.
817 * @return navigation_node|null
819 public function get($key, $type=null) {
820 if ($type !== null) {
821 // If the type is known then we can simply check and fetch
822 if (!empty($this->orderedcollection[$type][$key])) {
823 return $this->orderedcollection[$type][$key];
825 } else {
826 // Because we don't know the type we look in the progressive array
827 foreach ($this->collection as $node) {
828 if ($node->key === $key) {
829 return $node;
833 return false;
837 * Searches for a node with matching key and type.
839 * This function searches both the nodes in this collection and all of
840 * the nodes in each collection belonging to the nodes in this collection.
842 * Recursive.
844 * @param string|int $key The key of the node we want to find.
845 * @param int $type One of navigation_node::TYPE_*.
846 * @return navigation_node|null
848 public function find($key, $type=null) {
849 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
850 return $this->orderedcollection[$type][$key];
851 } else {
852 $nodes = $this->getIterator();
853 // Search immediate children first
854 foreach ($nodes as &$node) {
855 if ($node->key === $key && ($type === null || $type === $node->type)) {
856 return $node;
859 // Now search each childs children
860 foreach ($nodes as &$node) {
861 $result = $node->children->find($key, $type);
862 if ($result !== false) {
863 return $result;
867 return false;
871 * Fetches the last node that was added to this collection
873 * @return navigation_node
875 public function last() {
876 return $this->last;
880 * Fetches all nodes of a given type from this collection
882 * @param string|int $type node type being searched for.
883 * @return array ordered collection
885 public function type($type) {
886 if (!array_key_exists($type, $this->orderedcollection)) {
887 $this->orderedcollection[$type] = array();
889 return $this->orderedcollection[$type];
892 * Removes the node with the given key and type from the collection
894 * @param string|int $key The key of the node we want to find.
895 * @param int $type
896 * @return bool
898 public function remove($key, $type=null) {
899 $child = $this->get($key, $type);
900 if ($child !== false) {
901 foreach ($this->collection as $colkey => $node) {
902 if ($node->key === $key && $node->type == $type) {
903 unset($this->collection[$colkey]);
904 $this->collection = array_values($this->collection);
905 break;
908 unset($this->orderedcollection[$child->type][$child->key]);
909 $this->count--;
910 return true;
912 return false;
916 * Gets the number of nodes in this collection
918 * This option uses an internal count rather than counting the actual options to avoid
919 * a performance hit through the count function.
921 * @return int
923 public function count() {
924 return $this->count;
927 * Gets an array iterator for the collection.
929 * This is required by the IteratorAggregator interface and is used by routines
930 * such as the foreach loop.
932 * @return ArrayIterator
934 public function getIterator() {
935 return new ArrayIterator($this->collection);
940 * The global navigation class used for... the global navigation
942 * This class is used by PAGE to store the global navigation for the site
943 * and is then used by the settings nav and navbar to save on processing and DB calls
945 * See
946 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
947 * {@link lib/ajax/getnavbranch.php} Called by ajax
949 * @package core
950 * @category navigation
951 * @copyright 2009 Sam Hemelryk
952 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
954 class global_navigation extends navigation_node {
955 /** @var moodle_page The Moodle page this navigation object belongs to. */
956 protected $page;
957 /** @var bool switch to let us know if the navigation object is initialised*/
958 protected $initialised = false;
959 /** @var array An array of course information */
960 protected $mycourses = array();
961 /** @var array An array for containing root navigation nodes */
962 protected $rootnodes = array();
963 /** @var bool A switch for whether to show empty sections in the navigation */
964 protected $showemptysections = true;
965 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
966 protected $showcategories = null;
967 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
968 protected $showmycategories = null;
969 /** @var array An array of stdClasses for users that the navigation is extended for */
970 protected $extendforuser = array();
971 /** @var navigation_cache */
972 protected $cache;
973 /** @var array An array of course ids that are present in the navigation */
974 protected $addedcourses = array();
975 /** @var bool */
976 protected $allcategoriesloaded = false;
977 /** @var array An array of category ids that are included in the navigation */
978 protected $addedcategories = array();
979 /** @var int expansion limit */
980 protected $expansionlimit = 0;
981 /** @var int userid to allow parent to see child's profile page navigation */
982 protected $useridtouseforparentchecks = 0;
984 /** Used when loading categories to load all top level categories [parent = 0] **/
985 const LOAD_ROOT_CATEGORIES = 0;
986 /** Used when loading categories to load all categories **/
987 const LOAD_ALL_CATEGORIES = -1;
990 * Constructs a new global navigation
992 * @param moodle_page $page The page this navigation object belongs to
994 public function __construct(moodle_page $page) {
995 global $CFG, $SITE, $USER;
997 if (during_initial_install()) {
998 return;
1001 if (get_home_page() == HOMEPAGE_SITE) {
1002 // We are using the site home for the root element
1003 $properties = array(
1004 'key' => 'home',
1005 'type' => navigation_node::TYPE_SYSTEM,
1006 'text' => get_string('home'),
1007 'action' => new moodle_url('/')
1009 } else {
1010 // We are using the users my moodle for the root element
1011 $properties = array(
1012 'key' => 'myhome',
1013 'type' => navigation_node::TYPE_SYSTEM,
1014 'text' => get_string('myhome'),
1015 'action' => new moodle_url('/my/')
1019 // Use the parents constructor.... good good reuse
1020 parent::__construct($properties);
1022 // Initalise and set defaults
1023 $this->page = $page;
1024 $this->forceopen = true;
1025 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1029 * Mutator to set userid to allow parent to see child's profile
1030 * page navigation. See MDL-25805 for initial issue. Linked to it
1031 * is an issue explaining why this is a REALLY UGLY HACK thats not
1032 * for you to use!
1034 * @param int $userid userid of profile page that parent wants to navigate around.
1036 public function set_userid_for_parent_checks($userid) {
1037 $this->useridtouseforparentchecks = $userid;
1042 * Initialises the navigation object.
1044 * This causes the navigation object to look at the current state of the page
1045 * that it is associated with and then load the appropriate content.
1047 * This should only occur the first time that the navigation structure is utilised
1048 * which will normally be either when the navbar is called to be displayed or
1049 * when a block makes use of it.
1051 * @return bool
1053 public function initialise() {
1054 global $CFG, $SITE, $USER;
1055 // Check if it has already been initialised
1056 if ($this->initialised || during_initial_install()) {
1057 return true;
1059 $this->initialised = true;
1061 // Set up the five base root nodes. These are nodes where we will put our
1062 // content and are as follows:
1063 // site: Navigation for the front page.
1064 // myprofile: User profile information goes here.
1065 // currentcourse: The course being currently viewed.
1066 // mycourses: The users courses get added here.
1067 // courses: Additional courses are added here.
1068 // users: Other users information loaded here.
1069 $this->rootnodes = array();
1070 if (get_home_page() == HOMEPAGE_SITE) {
1071 // The home element should be my moodle because the root element is the site
1072 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1073 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1075 } else {
1076 // The home element should be the site because the root node is my moodle
1077 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1078 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1079 // We need to stop automatic redirection
1080 $this->rootnodes['home']->action->param('redirect', '0');
1083 $this->rootnodes['site'] = $this->add_course($SITE);
1084 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1085 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1086 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
1087 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1088 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1090 // We always load the frontpage course to ensure it is available without
1091 // JavaScript enabled.
1092 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1093 $this->load_course_sections($SITE, $this->rootnodes['site']);
1095 $course = $this->page->course;
1097 // $issite gets set to true if the current pages course is the sites frontpage course
1098 $issite = ($this->page->course->id == $SITE->id);
1099 // Determine if the user is enrolled in any course.
1100 $enrolledinanycourse = enrol_user_sees_own_courses();
1102 $this->rootnodes['currentcourse']->mainnavonly = true;
1103 if ($enrolledinanycourse) {
1104 $this->rootnodes['mycourses']->isexpandable = true;
1105 if ($CFG->navshowallcourses) {
1106 // When we show all courses we need to show both the my courses and the regular courses branch.
1107 $this->rootnodes['courses']->isexpandable = true;
1109 } else {
1110 $this->rootnodes['courses']->isexpandable = true;
1113 if ($this->rootnodes['mycourses']->isactive) {
1114 $this->load_courses_enrolled();
1117 $canviewcourseprofile = true;
1119 // Next load context specific content into the navigation
1120 switch ($this->page->context->contextlevel) {
1121 case CONTEXT_SYSTEM :
1122 // Nothing left to do here I feel.
1123 break;
1124 case CONTEXT_COURSECAT :
1125 // This is essential, we must load categories.
1126 $this->load_all_categories($this->page->context->instanceid, true);
1127 break;
1128 case CONTEXT_BLOCK :
1129 case CONTEXT_COURSE :
1130 if ($issite) {
1131 // Nothing left to do here.
1132 break;
1135 // Load the course associated with the current page into the navigation.
1136 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1137 // If the course wasn't added then don't try going any further.
1138 if (!$coursenode) {
1139 $canviewcourseprofile = false;
1140 break;
1143 // If the user is not enrolled then we only want to show the
1144 // course node and not populate it.
1146 // Not enrolled, can't view, and hasn't switched roles
1147 if (!can_access_course($course)) {
1148 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1149 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1150 if (!$this->current_user_is_parent_role()) {
1151 $coursenode->make_active();
1152 $canviewcourseprofile = false;
1153 break;
1157 // Add the essentials such as reports etc...
1158 $this->add_course_essentials($coursenode, $course);
1159 // Extend course navigation with it's sections/activities
1160 $this->load_course_sections($course, $coursenode);
1161 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1162 $coursenode->make_active();
1165 break;
1166 case CONTEXT_MODULE :
1167 if ($issite) {
1168 // If this is the site course then most information will have
1169 // already been loaded.
1170 // However we need to check if there is more content that can
1171 // yet be loaded for the specific module instance.
1172 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1173 if ($activitynode) {
1174 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1176 break;
1179 $course = $this->page->course;
1180 $cm = $this->page->cm;
1182 // Load the course associated with the page into the navigation
1183 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1185 // If the course wasn't added then don't try going any further.
1186 if (!$coursenode) {
1187 $canviewcourseprofile = false;
1188 break;
1191 // If the user is not enrolled then we only want to show the
1192 // course node and not populate it.
1193 if (!can_access_course($course)) {
1194 $coursenode->make_active();
1195 $canviewcourseprofile = false;
1196 break;
1199 $this->add_course_essentials($coursenode, $course);
1201 // Load the course sections into the page
1202 $this->load_course_sections($course, $coursenode, null, $cm);
1203 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1204 // Finally load the cm specific navigaton information
1205 $this->load_activity($cm, $course, $activity);
1206 // Check if we have an active ndoe
1207 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1208 // And make the activity node active.
1209 $activity->make_active();
1211 break;
1212 case CONTEXT_USER :
1213 if ($issite) {
1214 // The users profile information etc is already loaded
1215 // for the front page.
1216 break;
1218 $course = $this->page->course;
1219 // Load the course associated with the user into the navigation
1220 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1222 // If the course wasn't added then don't try going any further.
1223 if (!$coursenode) {
1224 $canviewcourseprofile = false;
1225 break;
1228 // If the user is not enrolled then we only want to show the
1229 // course node and not populate it.
1230 if (!can_access_course($course)) {
1231 $coursenode->make_active();
1232 $canviewcourseprofile = false;
1233 break;
1235 $this->add_course_essentials($coursenode, $course);
1236 $this->load_course_sections($course, $coursenode);
1237 break;
1240 // Load for the current user
1241 $this->load_for_user();
1242 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1243 $this->load_for_user(null, true);
1245 // Load each extending user into the navigation.
1246 foreach ($this->extendforuser as $user) {
1247 if ($user->id != $USER->id) {
1248 $this->load_for_user($user);
1252 // Give the local plugins a chance to include some navigation if they want.
1253 foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1254 $function = "local_{$plugin}_extends_navigation";
1255 $oldfunction = "{$plugin}_extends_navigation";
1256 if (function_exists($function)) {
1257 // This is the preferred function name as there is less chance of conflicts
1258 $function($this);
1259 } else if (function_exists($oldfunction)) {
1260 // We continue to support the old function name to ensure backwards compatibility
1261 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);
1262 $oldfunction($this);
1266 // Remove any empty root nodes
1267 foreach ($this->rootnodes as $node) {
1268 // Dont remove the home node
1269 /** @var navigation_node $node */
1270 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1271 $node->remove();
1275 if (!$this->contains_active_node()) {
1276 $this->search_for_active_node();
1279 // If the user is not logged in modify the navigation structure as detailed
1280 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1281 if (!isloggedin()) {
1282 $activities = clone($this->rootnodes['site']->children);
1283 $this->rootnodes['site']->remove();
1284 $children = clone($this->children);
1285 $this->children = new navigation_node_collection();
1286 foreach ($activities as $child) {
1287 $this->children->add($child);
1289 foreach ($children as $child) {
1290 $this->children->add($child);
1293 return true;
1297 * Returns true if the current user is a parent of the user being currently viewed.
1299 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1300 * other user being viewed this function returns false.
1301 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1303 * @since 2.4
1304 * @return bool
1306 protected function current_user_is_parent_role() {
1307 global $USER, $DB;
1308 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1309 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1310 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1311 return false;
1313 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1314 return true;
1317 return false;
1321 * Returns true if courses should be shown within categories on the navigation.
1323 * @param bool $ismycourse Set to true if you are calculating this for a course.
1324 * @return bool
1326 protected function show_categories($ismycourse = false) {
1327 global $CFG, $DB;
1328 if ($ismycourse) {
1329 return $this->show_my_categories();
1331 if ($this->showcategories === null) {
1332 $show = false;
1333 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1334 $show = true;
1335 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1336 $show = true;
1338 $this->showcategories = $show;
1340 return $this->showcategories;
1344 * Returns true if we should show categories in the My Courses branch.
1345 * @return bool
1347 protected function show_my_categories() {
1348 global $CFG, $DB;
1349 if ($this->showmycategories === null) {
1350 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1352 return $this->showmycategories;
1356 * Loads the courses in Moodle into the navigation.
1358 * @global moodle_database $DB
1359 * @param string|array $categoryids An array containing categories to load courses
1360 * for, OR null to load courses for all categories.
1361 * @return array An array of navigation_nodes one for each course
1363 protected function load_all_courses($categoryids = null) {
1364 global $CFG, $DB, $SITE;
1366 // Work out the limit of courses.
1367 $limit = 20;
1368 if (!empty($CFG->navcourselimit)) {
1369 $limit = $CFG->navcourselimit;
1372 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1374 // If we are going to show all courses AND we are showing categories then
1375 // to save us repeated DB calls load all of the categories now
1376 if ($this->show_categories()) {
1377 $this->load_all_categories($toload);
1380 // Will be the return of our efforts
1381 $coursenodes = array();
1383 // Check if we need to show categories.
1384 if ($this->show_categories()) {
1385 // Hmmm we need to show categories... this is going to be painful.
1386 // We now need to fetch up to $limit courses for each category to
1387 // be displayed.
1388 if ($categoryids !== null) {
1389 if (!is_array($categoryids)) {
1390 $categoryids = array($categoryids);
1392 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1393 $categorywhere = 'WHERE cc.id '.$categorywhere;
1394 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1395 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1396 $categoryparams = array();
1397 } else {
1398 $categorywhere = '';
1399 $categoryparams = array();
1402 // First up we are going to get the categories that we are going to
1403 // need so that we can determine how best to load the courses from them.
1404 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1405 FROM {course_categories} cc
1406 LEFT JOIN {course} c ON c.category = cc.id
1407 {$categorywhere}
1408 GROUP BY cc.id";
1409 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1410 $fullfetch = array();
1411 $partfetch = array();
1412 foreach ($categories as $category) {
1413 if (!$this->can_add_more_courses_to_category($category->id)) {
1414 continue;
1416 if ($category->coursecount > $limit * 5) {
1417 $partfetch[] = $category->id;
1418 } else if ($category->coursecount > 0) {
1419 $fullfetch[] = $category->id;
1422 $categories->close();
1424 if (count($fullfetch)) {
1425 // First up fetch all of the courses in categories where we know that we are going to
1426 // need the majority of courses.
1427 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1428 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1429 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1430 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1431 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1432 FROM {course} c
1433 $ccjoin
1434 WHERE c.category {$categoryids}
1435 ORDER BY c.sortorder ASC";
1436 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1437 foreach ($coursesrs as $course) {
1438 if ($course->id == $SITE->id) {
1439 // This should not be necessary, frontpage is not in any category.
1440 continue;
1442 if (array_key_exists($course->id, $this->addedcourses)) {
1443 // It is probably better to not include the already loaded courses
1444 // directly in SQL because inequalities may confuse query optimisers
1445 // and may interfere with query caching.
1446 continue;
1448 if (!$this->can_add_more_courses_to_category($course->category)) {
1449 continue;
1451 context_helper::preload_from_record($course);
1452 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1453 continue;
1455 $coursenodes[$course->id] = $this->add_course($course);
1457 $coursesrs->close();
1460 if (count($partfetch)) {
1461 // Next we will work our way through the categories where we will likely only need a small
1462 // proportion of the courses.
1463 foreach ($partfetch as $categoryid) {
1464 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1465 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1466 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1467 FROM {course} c
1468 $ccjoin
1469 WHERE c.category = :categoryid
1470 ORDER BY c.sortorder ASC";
1471 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1472 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1473 foreach ($coursesrs as $course) {
1474 if ($course->id == $SITE->id) {
1475 // This should not be necessary, frontpage is not in any category.
1476 continue;
1478 if (array_key_exists($course->id, $this->addedcourses)) {
1479 // It is probably better to not include the already loaded courses
1480 // directly in SQL because inequalities may confuse query optimisers
1481 // and may interfere with query caching.
1482 // This also helps to respect expected $limit on repeated executions.
1483 continue;
1485 if (!$this->can_add_more_courses_to_category($course->category)) {
1486 break;
1488 context_helper::preload_from_record($course);
1489 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1490 continue;
1492 $coursenodes[$course->id] = $this->add_course($course);
1494 $coursesrs->close();
1497 } else {
1498 // Prepare the SQL to load the courses and their contexts
1499 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1500 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1501 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1502 $courseparams['contextlevel'] = CONTEXT_COURSE;
1503 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1504 FROM {course} c
1505 $ccjoin
1506 WHERE c.id {$courseids}
1507 ORDER BY c.sortorder ASC";
1508 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1509 foreach ($coursesrs as $course) {
1510 if ($course->id == $SITE->id) {
1511 // frotpage is not wanted here
1512 continue;
1514 if ($this->page->course && ($this->page->course->id == $course->id)) {
1515 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1516 continue;
1518 context_helper::preload_from_record($course);
1519 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1520 continue;
1522 $coursenodes[$course->id] = $this->add_course($course);
1523 if (count($coursenodes) >= $limit) {
1524 break;
1527 $coursesrs->close();
1530 return $coursenodes;
1534 * Returns true if more courses can be added to the provided category.
1536 * @param int|navigation_node|stdClass $category
1537 * @return bool
1539 protected function can_add_more_courses_to_category($category) {
1540 global $CFG;
1541 $limit = 20;
1542 if (!empty($CFG->navcourselimit)) {
1543 $limit = (int)$CFG->navcourselimit;
1545 if (is_numeric($category)) {
1546 if (!array_key_exists($category, $this->addedcategories)) {
1547 return true;
1549 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1550 } else if ($category instanceof navigation_node) {
1551 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1552 return false;
1554 $coursecount = count($category->children->type(self::TYPE_COURSE));
1555 } else if (is_object($category) && property_exists($category,'id')) {
1556 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1558 return ($coursecount <= $limit);
1562 * Loads all categories (top level or if an id is specified for that category)
1564 * @param int $categoryid The category id to load or null/0 to load all base level categories
1565 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1566 * as the requested category and any parent categories.
1567 * @return navigation_node|void returns a navigation node if a category has been loaded.
1569 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1570 global $CFG, $DB;
1572 // Check if this category has already been loaded
1573 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1574 return true;
1577 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1578 $sqlselect = "SELECT cc.*, $catcontextsql
1579 FROM {course_categories} cc
1580 JOIN {context} ctx ON cc.id = ctx.instanceid";
1581 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1582 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1583 $params = array();
1585 $categoriestoload = array();
1586 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1587 // We are going to load all categories regardless... prepare to fire
1588 // on the database server!
1589 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1590 // We are going to load all of the first level categories (categories without parents)
1591 $sqlwhere .= " AND cc.parent = 0";
1592 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1593 // The category itself has been loaded already so we just need to ensure its subcategories
1594 // have been loaded
1595 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1596 if ($showbasecategories) {
1597 // We need to include categories with parent = 0 as well
1598 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1599 } else {
1600 // All we need is categories that match the parent
1601 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1603 $params['categoryid'] = $categoryid;
1604 } else {
1605 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1606 // and load this category plus all its parents and subcategories
1607 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1608 $categoriestoload = explode('/', trim($category->path, '/'));
1609 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1610 // We are going to use select twice so double the params
1611 $params = array_merge($params, $params);
1612 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1613 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1616 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1617 $categories = array();
1618 foreach ($categoriesrs as $category) {
1619 // Preload the context.. we'll need it when adding the category in order
1620 // to format the category name.
1621 context_helper::preload_from_record($category);
1622 if (array_key_exists($category->id, $this->addedcategories)) {
1623 // Do nothing, its already been added.
1624 } else if ($category->parent == '0') {
1625 // This is a root category lets add it immediately
1626 $this->add_category($category, $this->rootnodes['courses']);
1627 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1628 // This categories parent has already been added we can add this immediately
1629 $this->add_category($category, $this->addedcategories[$category->parent]);
1630 } else {
1631 $categories[] = $category;
1634 $categoriesrs->close();
1636 // Now we have an array of categories we need to add them to the navigation.
1637 while (!empty($categories)) {
1638 $category = reset($categories);
1639 if (array_key_exists($category->id, $this->addedcategories)) {
1640 // Do nothing
1641 } else if ($category->parent == '0') {
1642 $this->add_category($category, $this->rootnodes['courses']);
1643 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1644 $this->add_category($category, $this->addedcategories[$category->parent]);
1645 } else {
1646 // This category isn't in the navigation and niether is it's parent (yet).
1647 // We need to go through the category path and add all of its components in order.
1648 $path = explode('/', trim($category->path, '/'));
1649 foreach ($path as $catid) {
1650 if (!array_key_exists($catid, $this->addedcategories)) {
1651 // This category isn't in the navigation yet so add it.
1652 $subcategory = $categories[$catid];
1653 if ($subcategory->parent == '0') {
1654 // Yay we have a root category - this likely means we will now be able
1655 // to add categories without problems.
1656 $this->add_category($subcategory, $this->rootnodes['courses']);
1657 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1658 // The parent is in the category (as we'd expect) so add it now.
1659 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1660 // Remove the category from the categories array.
1661 unset($categories[$catid]);
1662 } else {
1663 // We should never ever arrive here - if we have then there is a bigger
1664 // problem at hand.
1665 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1670 // Remove the category from the categories array now that we know it has been added.
1671 unset($categories[$category->id]);
1673 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1674 $this->allcategoriesloaded = true;
1676 // Check if there are any categories to load.
1677 if (count($categoriestoload) > 0) {
1678 $readytoloadcourses = array();
1679 foreach ($categoriestoload as $category) {
1680 if ($this->can_add_more_courses_to_category($category)) {
1681 $readytoloadcourses[] = $category;
1684 if (count($readytoloadcourses)) {
1685 $this->load_all_courses($readytoloadcourses);
1689 // Look for all categories which have been loaded
1690 if (!empty($this->addedcategories)) {
1691 $categoryids = array();
1692 foreach ($this->addedcategories as $category) {
1693 if ($this->can_add_more_courses_to_category($category)) {
1694 $categoryids[] = $category->key;
1697 if ($categoryids) {
1698 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1699 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1700 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1701 FROM {course_categories} cc
1702 JOIN {course} c ON c.category = cc.id
1703 WHERE cc.id {$categoriessql}
1704 GROUP BY cc.id
1705 HAVING COUNT(c.id) > :limit";
1706 $excessivecategories = $DB->get_records_sql($sql, $params);
1707 foreach ($categories as &$category) {
1708 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1709 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1710 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1718 * Adds a structured category to the navigation in the correct order/place
1720 * @param stdClass $category category to be added in navigation.
1721 * @param navigation_node $parent parent navigation node
1722 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1723 * @return void.
1725 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1726 if (array_key_exists($category->id, $this->addedcategories)) {
1727 return;
1729 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1730 $context = context_coursecat::instance($category->id);
1731 $categoryname = format_string($category->name, true, array('context' => $context));
1732 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1733 if (empty($category->visible)) {
1734 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1735 $categorynode->hidden = true;
1736 } else {
1737 $categorynode->display = false;
1740 $this->addedcategories[$category->id] = $categorynode;
1744 * Loads the given course into the navigation
1746 * @param stdClass $course
1747 * @return navigation_node
1749 protected function load_course(stdClass $course) {
1750 global $SITE;
1751 if ($course->id == $SITE->id) {
1752 // This is always loaded during initialisation
1753 return $this->rootnodes['site'];
1754 } else if (array_key_exists($course->id, $this->addedcourses)) {
1755 // The course has already been loaded so return a reference
1756 return $this->addedcourses[$course->id];
1757 } else {
1758 // Add the course
1759 return $this->add_course($course);
1764 * Loads all of the courses section into the navigation.
1766 * This function calls method from current course format, see
1767 * {@link format_base::extend_course_navigation()}
1768 * If course module ($cm) is specified but course format failed to create the node,
1769 * the activity node is created anyway.
1771 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1773 * @param stdClass $course Database record for the course
1774 * @param navigation_node $coursenode The course node within the navigation
1775 * @param null|int $sectionnum If specified load the contents of section with this relative number
1776 * @param null|cm_info $cm If specified make sure that activity node is created (either
1777 * in containg section or by calling load_stealth_activity() )
1779 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1780 global $CFG, $SITE;
1781 require_once($CFG->dirroot.'/course/lib.php');
1782 if (isset($cm->sectionnum)) {
1783 $sectionnum = $cm->sectionnum;
1785 if ($sectionnum !== null) {
1786 $this->includesectionnum = $sectionnum;
1788 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1789 if (isset($cm->id)) {
1790 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1791 if (empty($activity)) {
1792 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1798 * Generates an array of sections and an array of activities for the given course.
1800 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1802 * @param stdClass $course
1803 * @return array Array($sections, $activities)
1805 protected function generate_sections_and_activities(stdClass $course) {
1806 global $CFG;
1807 require_once($CFG->dirroot.'/course/lib.php');
1809 $modinfo = get_fast_modinfo($course);
1810 $sections = $modinfo->get_section_info_all();
1812 // For course formats using 'numsections' trim the sections list
1813 $courseformatoptions = course_get_format($course)->get_format_options();
1814 if (isset($courseformatoptions['numsections'])) {
1815 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1818 $activities = array();
1820 foreach ($sections as $key => $section) {
1821 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1822 $sections[$key] = clone($section);
1823 unset($sections[$key]->summary);
1824 $sections[$key]->hasactivites = false;
1825 if (!array_key_exists($section->section, $modinfo->sections)) {
1826 continue;
1828 foreach ($modinfo->sections[$section->section] as $cmid) {
1829 $cm = $modinfo->cms[$cmid];
1830 if (!$cm->uservisible) {
1831 continue;
1833 $activity = new stdClass;
1834 $activity->id = $cm->id;
1835 $activity->course = $course->id;
1836 $activity->section = $section->section;
1837 $activity->name = $cm->name;
1838 $activity->icon = $cm->icon;
1839 $activity->iconcomponent = $cm->iconcomponent;
1840 $activity->hidden = (!$cm->visible);
1841 $activity->modname = $cm->modname;
1842 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1843 $activity->onclick = $cm->get_on_click();
1844 $url = $cm->get_url();
1845 if (!$url) {
1846 $activity->url = null;
1847 $activity->display = false;
1848 } else {
1849 $activity->url = $cm->get_url()->out();
1850 $activity->display = true;
1851 if (self::module_extends_navigation($cm->modname)) {
1852 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1855 $activities[$cmid] = $activity;
1856 if ($activity->display) {
1857 $sections[$key]->hasactivites = true;
1862 return array($sections, $activities);
1866 * Generically loads the course sections into the course's navigation.
1868 * @param stdClass $course
1869 * @param navigation_node $coursenode
1870 * @return array An array of course section nodes
1872 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1873 global $CFG, $DB, $USER, $SITE;
1874 require_once($CFG->dirroot.'/course/lib.php');
1876 list($sections, $activities) = $this->generate_sections_and_activities($course);
1878 $navigationsections = array();
1879 foreach ($sections as $sectionid => $section) {
1880 $section = clone($section);
1881 if ($course->id == $SITE->id) {
1882 $this->load_section_activities($coursenode, $section->section, $activities);
1883 } else {
1884 if (!$section->uservisible || (!$this->showemptysections &&
1885 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1886 continue;
1889 $sectionname = get_section_name($course, $section);
1890 $url = course_get_url($course, $section->section, array('navigation' => true));
1892 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1893 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1894 $sectionnode->hidden = (!$section->visible || !$section->available);
1895 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1896 $this->load_section_activities($sectionnode, $section->section, $activities);
1898 $section->sectionnode = $sectionnode;
1899 $navigationsections[$sectionid] = $section;
1902 return $navigationsections;
1906 * Loads all of the activities for a section into the navigation structure.
1908 * @param navigation_node $sectionnode
1909 * @param int $sectionnumber
1910 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1911 * @param stdClass $course The course object the section and activities relate to.
1912 * @return array Array of activity nodes
1914 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1915 global $CFG, $SITE;
1916 // A static counter for JS function naming
1917 static $legacyonclickcounter = 0;
1919 $activitynodes = array();
1920 if (empty($activities)) {
1921 return $activitynodes;
1924 if (!is_object($course)) {
1925 $activity = reset($activities);
1926 $courseid = $activity->course;
1927 } else {
1928 $courseid = $course->id;
1930 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1932 foreach ($activities as $activity) {
1933 if ($activity->section != $sectionnumber) {
1934 continue;
1936 if ($activity->icon) {
1937 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1938 } else {
1939 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1942 // Prepare the default name and url for the node
1943 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1944 $action = new moodle_url($activity->url);
1946 // Check if the onclick property is set (puke!)
1947 if (!empty($activity->onclick)) {
1948 // Increment the counter so that we have a unique number.
1949 $legacyonclickcounter++;
1950 // Generate the function name we will use
1951 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1952 $propogrationhandler = '';
1953 // Check if we need to cancel propogation. Remember inline onclick
1954 // events would return false if they wanted to prevent propogation and the
1955 // default action.
1956 if (strpos($activity->onclick, 'return false')) {
1957 $propogrationhandler = 'e.halt();';
1959 // Decode the onclick - it has already been encoded for display (puke)
1960 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
1961 // Build the JS function the click event will call
1962 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1963 $this->page->requires->js_init_code($jscode);
1964 // Override the default url with the new action link
1965 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1968 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1969 $activitynode->title(get_string('modulename', $activity->modname));
1970 $activitynode->hidden = $activity->hidden;
1971 $activitynode->display = $showactivities && $activity->display;
1972 $activitynode->nodetype = $activity->nodetype;
1973 $activitynodes[$activity->id] = $activitynode;
1976 return $activitynodes;
1979 * Loads a stealth module from unavailable section
1980 * @param navigation_node $coursenode
1981 * @param stdClass $modinfo
1982 * @return navigation_node or null if not accessible
1984 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1985 if (empty($modinfo->cms[$this->page->cm->id])) {
1986 return null;
1988 $cm = $modinfo->cms[$this->page->cm->id];
1989 if (!$cm->uservisible) {
1990 return null;
1992 if ($cm->icon) {
1993 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1994 } else {
1995 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1997 $url = $cm->get_url();
1998 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1999 $activitynode->title(get_string('modulename', $cm->modname));
2000 $activitynode->hidden = (!$cm->visible);
2001 if (!$url) {
2002 // Don't show activities that don't have links!
2003 $activitynode->display = false;
2004 } else if (self::module_extends_navigation($cm->modname)) {
2005 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2007 return $activitynode;
2010 * Loads the navigation structure for the given activity into the activities node.
2012 * This method utilises a callback within the modules lib.php file to load the
2013 * content specific to activity given.
2015 * The callback is a method: {modulename}_extend_navigation()
2016 * Examples:
2017 * * {@link forum_extend_navigation()}
2018 * * {@link workshop_extend_navigation()}
2020 * @param cm_info|stdClass $cm
2021 * @param stdClass $course
2022 * @param navigation_node $activity
2023 * @return bool
2025 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2026 global $CFG, $DB;
2028 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2029 if (!($cm instanceof cm_info)) {
2030 $modinfo = get_fast_modinfo($course);
2031 $cm = $modinfo->get_cm($cm->id);
2033 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2034 $activity->make_active();
2035 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2036 $function = $cm->modname.'_extend_navigation';
2038 if (file_exists($file)) {
2039 require_once($file);
2040 if (function_exists($function)) {
2041 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2042 $function($activity, $course, $activtyrecord, $cm);
2046 // Allow the active advanced grading method plugin to append module navigation
2047 $featuresfunc = $cm->modname.'_supports';
2048 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2049 require_once($CFG->dirroot.'/grade/grading/lib.php');
2050 $gradingman = get_grading_manager($cm->context, $cm->modname);
2051 $gradingman->extend_navigation($this, $activity);
2054 return $activity->has_children();
2057 * Loads user specific information into the navigation in the appropriate place.
2059 * If no user is provided the current user is assumed.
2061 * @param stdClass $user
2062 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2063 * @return bool
2065 protected function load_for_user($user=null, $forceforcontext=false) {
2066 global $DB, $CFG, $USER, $SITE;
2068 if ($user === null) {
2069 // We can't require login here but if the user isn't logged in we don't
2070 // want to show anything
2071 if (!isloggedin() || isguestuser()) {
2072 return false;
2074 $user = $USER;
2075 } else if (!is_object($user)) {
2076 // If the user is not an object then get them from the database
2077 $select = context_helper::get_preload_record_columns_sql('ctx');
2078 $sql = "SELECT u.*, $select
2079 FROM {user} u
2080 JOIN {context} ctx ON u.id = ctx.instanceid
2081 WHERE u.id = :userid AND
2082 ctx.contextlevel = :contextlevel";
2083 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2084 context_helper::preload_from_record($user);
2087 $iscurrentuser = ($user->id == $USER->id);
2089 $usercontext = context_user::instance($user->id);
2091 // Get the course set against the page, by default this will be the site
2092 $course = $this->page->course;
2093 $baseargs = array('id'=>$user->id);
2094 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2095 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2096 $baseargs['course'] = $course->id;
2097 $coursecontext = context_course::instance($course->id);
2098 $issitecourse = false;
2099 } else {
2100 // Load all categories and get the context for the system
2101 $coursecontext = context_system::instance();
2102 $issitecourse = true;
2105 // Create a node to add user information under.
2106 if ($iscurrentuser && !$forceforcontext) {
2107 // If it's the current user the information will go under the profile root node
2108 $usernode = $this->rootnodes['myprofile'];
2109 $course = get_site();
2110 $coursecontext = context_course::instance($course->id);
2111 $issitecourse = true;
2112 } else {
2113 if (!$issitecourse) {
2114 // Not the current user so add it to the participants node for the current course
2115 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2116 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2117 } else {
2118 // This is the site so add a users node to the root branch
2119 $usersnode = $this->rootnodes['users'];
2120 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2121 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2123 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2125 if (!$usersnode) {
2126 // We should NEVER get here, if the course hasn't been populated
2127 // with a participants node then the navigaiton either wasn't generated
2128 // for it (you are missing a require_login or set_context call) or
2129 // you don't have access.... in the interests of no leaking informatin
2130 // we simply quit...
2131 return false;
2133 // Add a branch for the current user
2134 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2135 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2137 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2138 $usernode->make_active();
2142 // If the user is the current user or has permission to view the details of the requested
2143 // user than add a view profile link.
2144 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2145 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2146 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2147 } else {
2148 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2152 if (!empty($CFG->navadduserpostslinks)) {
2153 // Add nodes for forum posts and discussions if the user can view either or both
2154 // There are no capability checks here as the content of the page is based
2155 // purely on the forums the current user has access too.
2156 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2157 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2158 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2161 // Add blog nodes
2162 if (!empty($CFG->enableblogs)) {
2163 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2164 require_once($CFG->dirroot.'/blog/lib.php');
2165 // Get all options for the user
2166 $options = blog_get_options_for_user($user);
2167 $this->cache->set('userblogoptions'.$user->id, $options);
2168 } else {
2169 $options = $this->cache->{'userblogoptions'.$user->id};
2172 if (count($options) > 0) {
2173 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2174 foreach ($options as $type => $option) {
2175 if ($type == "rss") {
2176 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2177 } else {
2178 $blogs->add($option['string'], $option['link']);
2184 if (!empty($CFG->messaging)) {
2185 $messageargs = array('user1' => $USER->id);
2186 if ($USER->id != $user->id) {
2187 $messageargs['user2'] = $user->id;
2189 if ($course->id != $SITE->id) {
2190 $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
2192 $url = new moodle_url('/message/index.php',$messageargs);
2193 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2196 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
2197 $url = new moodle_url('/user/files.php');
2198 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2201 if (!empty($CFG->enablebadges) && $iscurrentuser &&
2202 has_capability('moodle/badges:manageownbadges', context_user::instance($USER->id))) {
2203 $url = new moodle_url('/badges/mybadges.php');
2204 $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2207 // Add a node to view the users notes if permitted
2208 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2209 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2210 if ($coursecontext->instanceid) {
2211 $url->param('course', $coursecontext->instanceid);
2213 $usernode->add(get_string('notes', 'notes'), $url);
2216 // If the user is the current user add the repositories for the current user
2217 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2218 if ($iscurrentuser) {
2219 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2220 require_once($CFG->dirroot . '/repository/lib.php');
2221 $editabletypes = repository::get_editable_types($usercontext);
2222 $haseditabletypes = !empty($editabletypes);
2223 unset($editabletypes);
2224 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2225 } else {
2226 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2228 if ($haseditabletypes) {
2229 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2231 } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2233 // Add view grade report is permitted
2234 $reports = core_component::get_plugin_list('gradereport');
2235 arsort($reports); // user is last, we want to test it first
2237 $userscourses = enrol_get_users_courses($user->id);
2238 $userscoursesnode = $usernode->add(get_string('courses'));
2240 foreach ($userscourses as $usercourse) {
2241 $usercoursecontext = context_course::instance($usercourse->id);
2242 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2243 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2245 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2246 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2247 foreach ($reports as $plugin => $plugindir) {
2248 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2249 //stop when the first visible plugin is found
2250 $gradeavailable = true;
2251 break;
2256 if ($gradeavailable) {
2257 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2258 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2261 // Add a node to view the users notes if permitted
2262 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2263 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2264 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2267 if (can_access_course($usercourse, $user->id)) {
2268 $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', ''));
2271 $reporttab = $usercoursenode->add(get_string('activityreports'));
2273 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2274 foreach ($reports as $reportfunction) {
2275 $reportfunction($reporttab, $user, $usercourse);
2278 $reporttab->trim_if_empty();
2281 return true;
2285 * This method simply checks to see if a given module can extend the navigation.
2287 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2289 * @param string $modname
2290 * @return bool
2292 public static function module_extends_navigation($modname) {
2293 global $CFG;
2294 static $extendingmodules = array();
2295 if (!array_key_exists($modname, $extendingmodules)) {
2296 $extendingmodules[$modname] = false;
2297 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2298 if (file_exists($file)) {
2299 $function = $modname.'_extend_navigation';
2300 require_once($file);
2301 $extendingmodules[$modname] = (function_exists($function));
2304 return $extendingmodules[$modname];
2307 * Extends the navigation for the given user.
2309 * @param stdClass $user A user from the database
2311 public function extend_for_user($user) {
2312 $this->extendforuser[] = $user;
2316 * Returns all of the users the navigation is being extended for
2318 * @return array An array of extending users.
2320 public function get_extending_users() {
2321 return $this->extendforuser;
2324 * Adds the given course to the navigation structure.
2326 * @param stdClass $course
2327 * @param bool $forcegeneric
2328 * @param bool $ismycourse
2329 * @return navigation_node
2331 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2332 global $CFG, $SITE;
2334 // We found the course... we can return it now :)
2335 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2336 return $this->addedcourses[$course->id];
2339 $coursecontext = context_course::instance($course->id);
2341 if ($course->id != $SITE->id && !$course->visible) {
2342 if (is_role_switched($course->id)) {
2343 // user has to be able to access course in order to switch, let's skip the visibility test here
2344 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2345 return false;
2349 $issite = ($course->id == $SITE->id);
2350 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2351 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2352 // This is the name that will be shown for the course.
2353 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2355 if ($issite) {
2356 $parent = $this;
2357 $url = null;
2358 if (empty($CFG->usesitenameforsitepages)) {
2359 $coursename = get_string('sitepages');
2361 } else if ($coursetype == self::COURSE_CURRENT) {
2362 $parent = $this->rootnodes['currentcourse'];
2363 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2364 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2365 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2366 // Nothing to do here the above statement set $parent to the category within mycourses.
2367 } else {
2368 $parent = $this->rootnodes['mycourses'];
2370 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2371 } else {
2372 $parent = $this->rootnodes['courses'];
2373 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2374 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2375 if (!$this->is_category_fully_loaded($course->category)) {
2376 // We need to load the category structure for this course
2377 $this->load_all_categories($course->category, false);
2379 if (array_key_exists($course->category, $this->addedcategories)) {
2380 $parent = $this->addedcategories[$course->category];
2381 // This could lead to the course being created so we should check whether it is the case again
2382 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2383 return $this->addedcourses[$course->id];
2389 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2390 $coursenode->nodetype = self::NODETYPE_BRANCH;
2391 $coursenode->hidden = (!$course->visible);
2392 // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
2393 // later.
2394 $coursenode->title(str_replace('&amp;', '&', $fullname));
2395 if (!$forcegeneric) {
2396 $this->addedcourses[$course->id] = $coursenode;
2399 return $coursenode;
2403 * Returns true if the category has already been loaded as have any child categories
2405 * @param int $categoryid
2406 * @return bool
2408 protected function is_category_fully_loaded($categoryid) {
2409 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2413 * Adds essential course nodes to the navigation for the given course.
2415 * This method adds nodes such as reports, blogs and participants
2417 * @param navigation_node $coursenode
2418 * @param stdClass $course
2419 * @return bool returns true on successful addition of a node.
2421 public function add_course_essentials($coursenode, stdClass $course) {
2422 global $CFG, $SITE;
2424 if ($course->id == $SITE->id) {
2425 return $this->add_front_page_course_essentials($coursenode, $course);
2428 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2429 return true;
2432 //Participants
2433 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2434 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2435 $currentgroup = groups_get_course_group($course, true);
2436 if ($course->id == $SITE->id) {
2437 $filtervar = 'courseid';
2438 $filterselect = '';
2439 } else if ($course->id && !$currentgroup) {
2440 $filtervar = 'courseid';
2441 $filterselect = $course->id;
2442 } else {
2443 $filtervar = 'groupid';
2444 $filterselect = $currentgroup;
2446 $filterselect = clean_param($filterselect, PARAM_INT);
2447 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2448 and has_capability('moodle/blog:view', context_system::instance())) {
2449 $blogsurls = new moodle_url('/blog/index.php', array($filtervar => $filterselect));
2450 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2452 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2453 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2455 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2456 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2459 // Badges.
2460 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2461 has_capability('moodle/badges:viewbadges', $this->page->context)) {
2462 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2464 $coursenode->add(get_string('coursebadges', 'badges'), null,
2465 navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2466 $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2467 navigation_node::TYPE_SETTING, null, 'badgesview',
2468 new pix_icon('i/badge', get_string('badgesview', 'badges')));
2471 return true;
2474 * This generates the structure of the course that won't be generated when
2475 * the modules and sections are added.
2477 * Things such as the reports branch, the participants branch, blogs... get
2478 * added to the course node by this method.
2480 * @param navigation_node $coursenode
2481 * @param stdClass $course
2482 * @return bool True for successfull generation
2484 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2485 global $CFG;
2487 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2488 return true;
2491 // Hidden node that we use to determine if the front page navigation is loaded.
2492 // This required as there are not other guaranteed nodes that may be loaded.
2493 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2495 //Participants
2496 if (has_capability('moodle/course:viewparticipants', context_system::instance())) {
2497 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2500 $filterselect = 0;
2502 // Blogs
2503 if (!empty($CFG->enableblogs)
2504 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2505 and has_capability('moodle/blog:view', context_system::instance())) {
2506 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2507 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2510 //Badges
2511 if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2512 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2513 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2516 // Notes
2517 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2518 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2521 // Tags
2522 if (!empty($CFG->usetags) && isloggedin()) {
2523 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2526 if (isloggedin()) {
2527 // Calendar
2528 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2529 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2532 return true;
2536 * Clears the navigation cache
2538 public function clear_cache() {
2539 $this->cache->clear();
2543 * Sets an expansion limit for the navigation
2545 * The expansion limit is used to prevent the display of content that has a type
2546 * greater than the provided $type.
2548 * Can be used to ensure things such as activities or activity content don't get
2549 * shown on the navigation.
2550 * They are still generated in order to ensure the navbar still makes sense.
2552 * @param int $type One of navigation_node::TYPE_*
2553 * @return bool true when complete.
2555 public function set_expansion_limit($type) {
2556 global $SITE;
2557 $nodes = $this->find_all_of_type($type);
2559 // We only want to hide specific types of nodes.
2560 // Only nodes that represent "structure" in the navigation tree should be hidden.
2561 // If we hide all nodes then we risk hiding vital information.
2562 $typestohide = array(
2563 self::TYPE_CATEGORY,
2564 self::TYPE_COURSE,
2565 self::TYPE_SECTION,
2566 self::TYPE_ACTIVITY
2569 foreach ($nodes as $node) {
2570 // We need to generate the full site node
2571 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2572 continue;
2574 foreach ($node->children as $child) {
2575 $child->hide($typestohide);
2578 return true;
2581 * Attempts to get the navigation with the given key from this nodes children.
2583 * This function only looks at this nodes children, it does NOT look recursivily.
2584 * If the node can't be found then false is returned.
2586 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2588 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2589 * may be of more use to you.
2591 * @param string|int $key The key of the node you wish to receive.
2592 * @param int $type One of navigation_node::TYPE_*
2593 * @return navigation_node|false
2595 public function get($key, $type = null) {
2596 if (!$this->initialised) {
2597 $this->initialise();
2599 return parent::get($key, $type);
2603 * Searches this nodes children and their children to find a navigation node
2604 * with the matching key and type.
2606 * This method is recursive and searches children so until either a node is
2607 * found or there are no more nodes to search.
2609 * If you know that the node being searched for is a child of this node
2610 * then use the {@link global_navigation::get()} method instead.
2612 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2613 * may be of more use to you.
2615 * @param string|int $key The key of the node you wish to receive.
2616 * @param int $type One of navigation_node::TYPE_*
2617 * @return navigation_node|false
2619 public function find($key, $type) {
2620 if (!$this->initialised) {
2621 $this->initialise();
2623 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2624 return $this->rootnodes[$key];
2626 return parent::find($key, $type);
2630 * They've expanded the 'my courses' branch.
2632 protected function load_courses_enrolled() {
2633 global $CFG, $DB;
2634 $sortorder = 'visible DESC';
2635 // Prevent undefined $CFG->navsortmycoursessort errors.
2636 if (empty($CFG->navsortmycoursessort)) {
2637 $CFG->navsortmycoursessort = 'sortorder';
2639 // Append the chosen sortorder.
2640 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2641 $courses = enrol_get_my_courses(null, $sortorder);
2642 if (count($courses) && $this->show_my_categories()) {
2643 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2644 // In order to make sure we load everything required we must first find the categories that are not
2645 // base categories and work out the bottom category in thier path.
2646 $categoryids = array();
2647 foreach ($courses as $course) {
2648 $categoryids[] = $course->category;
2650 $categoryids = array_unique($categoryids);
2651 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2652 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2653 foreach ($categories as $category) {
2654 $bits = explode('/', trim($category->path,'/'));
2655 $categoryids[] = array_shift($bits);
2657 $categoryids = array_unique($categoryids);
2658 $categories->close();
2660 // Now we load the base categories.
2661 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2662 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2663 foreach ($categories as $category) {
2664 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2666 $categories->close();
2667 } else {
2668 foreach ($courses as $course) {
2669 $this->add_course($course, false, self::COURSE_MY);
2676 * The global navigation class used especially for AJAX requests.
2678 * The primary methods that are used in the global navigation class have been overriden
2679 * to ensure that only the relevant branch is generated at the root of the tree.
2680 * This can be done because AJAX is only used when the backwards structure for the
2681 * requested branch exists.
2682 * This has been done only because it shortens the amounts of information that is generated
2683 * which of course will speed up the response time.. because no one likes laggy AJAX.
2685 * @package core
2686 * @category navigation
2687 * @copyright 2009 Sam Hemelryk
2688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2690 class global_navigation_for_ajax extends global_navigation {
2692 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2693 protected $branchtype;
2695 /** @var int the instance id */
2696 protected $instanceid;
2698 /** @var array Holds an array of expandable nodes */
2699 protected $expandable = array();
2702 * Constructs the navigation for use in an AJAX request
2704 * @param moodle_page $page moodle_page object
2705 * @param int $branchtype
2706 * @param int $id
2708 public function __construct($page, $branchtype, $id) {
2709 $this->page = $page;
2710 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2711 $this->children = new navigation_node_collection();
2712 $this->branchtype = $branchtype;
2713 $this->instanceid = $id;
2714 $this->initialise();
2717 * Initialise the navigation given the type and id for the branch to expand.
2719 * @return array An array of the expandable nodes
2721 public function initialise() {
2722 global $DB, $SITE;
2724 if ($this->initialised || during_initial_install()) {
2725 return $this->expandable;
2727 $this->initialised = true;
2729 $this->rootnodes = array();
2730 $this->rootnodes['site'] = $this->add_course($SITE);
2731 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2732 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2734 // Branchtype will be one of navigation_node::TYPE_*
2735 switch ($this->branchtype) {
2736 case 0:
2737 if ($this->instanceid === 'mycourses') {
2738 $this->load_courses_enrolled();
2739 } else if ($this->instanceid === 'courses') {
2740 $this->load_courses_other();
2742 break;
2743 case self::TYPE_CATEGORY :
2744 $this->load_category($this->instanceid);
2745 break;
2746 case self::TYPE_MY_CATEGORY :
2747 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2748 break;
2749 case self::TYPE_COURSE :
2750 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2751 require_course_login($course, true, null, false, true);
2752 $this->page->set_context(context_course::instance($course->id));
2753 $coursenode = $this->add_course($course);
2754 $this->add_course_essentials($coursenode, $course);
2755 $this->load_course_sections($course, $coursenode);
2756 break;
2757 case self::TYPE_SECTION :
2758 $sql = 'SELECT c.*, cs.section AS sectionnumber
2759 FROM {course} c
2760 LEFT JOIN {course_sections} cs ON cs.course = c.id
2761 WHERE cs.id = ?';
2762 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2763 require_course_login($course, true, null, false, true);
2764 $this->page->set_context(context_course::instance($course->id));
2765 $coursenode = $this->add_course($course);
2766 $this->add_course_essentials($coursenode, $course);
2767 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2768 break;
2769 case self::TYPE_ACTIVITY :
2770 $sql = "SELECT c.*
2771 FROM {course} c
2772 JOIN {course_modules} cm ON cm.course = c.id
2773 WHERE cm.id = :cmid";
2774 $params = array('cmid' => $this->instanceid);
2775 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2776 $modinfo = get_fast_modinfo($course);
2777 $cm = $modinfo->get_cm($this->instanceid);
2778 require_course_login($course, true, $cm, false, true);
2779 $this->page->set_context(context_module::instance($cm->id));
2780 $coursenode = $this->load_course($course);
2781 if ($course->id != $SITE->id) {
2782 $this->load_course_sections($course, $coursenode, null, $cm);
2784 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2785 break;
2786 default:
2787 throw new Exception('Unknown type');
2788 return $this->expandable;
2791 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2792 $this->load_for_user(null, true);
2795 $this->find_expandable($this->expandable);
2796 return $this->expandable;
2800 * They've expanded the general 'courses' branch.
2802 protected function load_courses_other() {
2803 $this->load_all_courses();
2807 * Loads a single category into the AJAX navigation.
2809 * This function is special in that it doesn't concern itself with the parent of
2810 * the requested category or its siblings.
2811 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2812 * request that.
2814 * @global moodle_database $DB
2815 * @param int $categoryid id of category to load in navigation.
2816 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2817 * @return void.
2819 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2820 global $CFG, $DB;
2822 $limit = 20;
2823 if (!empty($CFG->navcourselimit)) {
2824 $limit = (int)$CFG->navcourselimit;
2827 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2828 $sql = "SELECT cc.*, $catcontextsql
2829 FROM {course_categories} cc
2830 JOIN {context} ctx ON cc.id = ctx.instanceid
2831 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2832 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2833 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2834 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2835 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2836 $categorylist = array();
2837 $subcategories = array();
2838 $basecategory = null;
2839 foreach ($categories as $category) {
2840 $categorylist[] = $category->id;
2841 context_helper::preload_from_record($category);
2842 if ($category->id == $categoryid) {
2843 $this->add_category($category, $this, $nodetype);
2844 $basecategory = $this->addedcategories[$category->id];
2845 } else {
2846 $subcategories[$category->id] = $category;
2849 $categories->close();
2852 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2853 // else show all courses.
2854 if ($nodetype === self::TYPE_MY_CATEGORY) {
2855 $courses = enrol_get_my_courses();
2856 $categoryids = array();
2858 // Only search for categories if basecategory was found.
2859 if (!is_null($basecategory)) {
2860 // Get course parent category ids.
2861 foreach ($courses as $course) {
2862 $categoryids[] = $course->category;
2865 // Get a unique list of category ids which a part of the path
2866 // to user's courses.
2867 $coursesubcategories = array();
2868 $addedsubcategories = array();
2870 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2871 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
2873 foreach ($categories as $category){
2874 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
2876 $coursesubcategories = array_unique($coursesubcategories);
2878 // Only add a subcategory if it is part of the path to user's course and
2879 // wasn't already added.
2880 foreach ($subcategories as $subid => $subcategory) {
2881 if (in_array($subid, $coursesubcategories) &&
2882 !in_array($subid, $addedsubcategories)) {
2883 $this->add_category($subcategory, $basecategory, $nodetype);
2884 $addedsubcategories[] = $subid;
2889 foreach ($courses as $course) {
2890 // Add course if it's in category.
2891 if (in_array($course->category, $categorylist)) {
2892 $this->add_course($course, true, self::COURSE_MY);
2895 } else {
2896 if (!is_null($basecategory)) {
2897 foreach ($subcategories as $key=>$category) {
2898 $this->add_category($category, $basecategory, $nodetype);
2901 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2902 foreach ($courses as $course) {
2903 $this->add_course($course);
2905 $courses->close();
2910 * Returns an array of expandable nodes
2911 * @return array
2913 public function get_expandable() {
2914 return $this->expandable;
2919 * Navbar class
2921 * This class is used to manage the navbar, which is initialised from the navigation
2922 * object held by PAGE
2924 * @package core
2925 * @category navigation
2926 * @copyright 2009 Sam Hemelryk
2927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2929 class navbar extends navigation_node {
2930 /** @var bool A switch for whether the navbar is initialised or not */
2931 protected $initialised = false;
2932 /** @var mixed keys used to reference the nodes on the navbar */
2933 protected $keys = array();
2934 /** @var null|string content of the navbar */
2935 protected $content = null;
2936 /** @var moodle_page object the moodle page that this navbar belongs to */
2937 protected $page;
2938 /** @var bool A switch for whether to ignore the active navigation information */
2939 protected $ignoreactive = false;
2940 /** @var bool A switch to let us know if we are in the middle of an install */
2941 protected $duringinstall = false;
2942 /** @var bool A switch for whether the navbar has items */
2943 protected $hasitems = false;
2944 /** @var array An array of navigation nodes for the navbar */
2945 protected $items;
2946 /** @var array An array of child node objects */
2947 public $children = array();
2948 /** @var bool A switch for whether we want to include the root node in the navbar */
2949 public $includesettingsbase = false;
2950 /** @var navigation_node[] $prependchildren */
2951 protected $prependchildren = array();
2953 * The almighty constructor
2955 * @param moodle_page $page
2957 public function __construct(moodle_page $page) {
2958 global $CFG;
2959 if (during_initial_install()) {
2960 $this->duringinstall = true;
2961 return false;
2963 $this->page = $page;
2964 $this->text = get_string('home');
2965 $this->shorttext = get_string('home');
2966 $this->action = new moodle_url($CFG->wwwroot);
2967 $this->nodetype = self::NODETYPE_BRANCH;
2968 $this->type = self::TYPE_SYSTEM;
2972 * Quick check to see if the navbar will have items in.
2974 * @return bool Returns true if the navbar will have items, false otherwise
2976 public function has_items() {
2977 if ($this->duringinstall) {
2978 return false;
2979 } else if ($this->hasitems !== false) {
2980 return true;
2982 $this->page->navigation->initialise($this->page);
2984 $activenodefound = ($this->page->navigation->contains_active_node() ||
2985 $this->page->settingsnav->contains_active_node());
2987 $outcome = (count($this->children) > 0 || count($this->prependchildren) || (!$this->ignoreactive && $activenodefound));
2988 $this->hasitems = $outcome;
2989 return $outcome;
2993 * Turn on/off ignore active
2995 * @param bool $setting
2997 public function ignore_active($setting=true) {
2998 $this->ignoreactive = ($setting);
3002 * Gets a navigation node
3004 * @param string|int $key for referencing the navbar nodes
3005 * @param int $type navigation_node::TYPE_*
3006 * @return navigation_node|bool
3008 public function get($key, $type = null) {
3009 foreach ($this->children as &$child) {
3010 if ($child->key === $key && ($type == null || $type == $child->type)) {
3011 return $child;
3014 foreach ($this->prependchildren as &$child) {
3015 if ($child->key === $key && ($type == null || $type == $child->type)) {
3016 return $child;
3019 return false;
3022 * Returns an array of navigation_node's that make up the navbar.
3024 * @return array
3026 public function get_items() {
3027 global $CFG;
3028 $items = array();
3029 // Make sure that navigation is initialised
3030 if (!$this->has_items()) {
3031 return $items;
3033 if ($this->items !== null) {
3034 return $this->items;
3037 if (count($this->children) > 0) {
3038 // Add the custom children.
3039 $items = array_reverse($this->children);
3042 $navigationactivenode = $this->page->navigation->find_active_node();
3043 $settingsactivenode = $this->page->settingsnav->find_active_node();
3045 // Check if navigation contains the active node
3046 if (!$this->ignoreactive) {
3048 if ($navigationactivenode && $settingsactivenode) {
3049 // Parse a combined navigation tree
3050 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3051 if (!$settingsactivenode->mainnavonly) {
3052 $items[] = $settingsactivenode;
3054 $settingsactivenode = $settingsactivenode->parent;
3056 if (!$this->includesettingsbase) {
3057 // Removes the first node from the settings (root node) from the list
3058 array_pop($items);
3060 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3061 if (!$navigationactivenode->mainnavonly) {
3062 $items[] = $navigationactivenode;
3064 if (!empty($CFG->navshowcategories) &&
3065 $navigationactivenode->type === self::TYPE_COURSE &&
3066 $navigationactivenode->parent->key === 'currentcourse') {
3067 $items = array_merge($items, $this->get_course_categories());
3069 $navigationactivenode = $navigationactivenode->parent;
3071 } else if ($navigationactivenode) {
3072 // Parse the navigation tree to get the active node
3073 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3074 if (!$navigationactivenode->mainnavonly) {
3075 $items[] = $navigationactivenode;
3077 if (!empty($CFG->navshowcategories) &&
3078 $navigationactivenode->type === self::TYPE_COURSE &&
3079 $navigationactivenode->parent->key === 'currentcourse') {
3080 $items = array_merge($items, $this->get_course_categories());
3082 $navigationactivenode = $navigationactivenode->parent;
3084 } else if ($settingsactivenode) {
3085 // Parse the settings navigation to get the active node
3086 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3087 if (!$settingsactivenode->mainnavonly) {
3088 $items[] = $settingsactivenode;
3090 $settingsactivenode = $settingsactivenode->parent;
3095 $items[] = new navigation_node(array(
3096 'text'=>$this->page->navigation->text,
3097 'shorttext'=>$this->page->navigation->shorttext,
3098 'key'=>$this->page->navigation->key,
3099 'action'=>$this->page->navigation->action
3102 if (count($this->prependchildren) > 0) {
3103 // Add the custom children
3104 $items = array_merge($items, array_reverse($this->prependchildren));
3107 $this->items = array_reverse($items);
3108 return $this->items;
3112 * Get the list of categories leading to this course.
3114 * This function is used by {@link navbar::get_items()} to add back the "courses"
3115 * node and category chain leading to the current course. Note that this is only ever
3116 * called for the current course, so we don't need to bother taking in any parameters.
3118 * @return array
3120 private function get_course_categories() {
3121 $categories = array();
3122 foreach ($this->page->categories as $category) {
3123 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3124 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3125 $categories[] = navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3126 $id = $category->parent;
3128 if (is_enrolled(context_course::instance($this->page->course->id))) {
3129 $courses = $this->page->navigation->get('mycourses');
3130 } else {
3131 $courses = $this->page->navigation->get('courses');
3133 if (!$courses) {
3134 // Courses node may not be present.
3135 $courses = navigation_node::create(
3136 get_string('courses'),
3137 new moodle_url('/course/index.php'),
3138 self::TYPE_CONTAINER
3141 $categories[] = $courses;
3142 return $categories;
3146 * Add a new navigation_node to the navbar, overrides parent::add
3148 * This function overrides {@link navigation_node::add()} so that we can change
3149 * the way nodes get added to allow us to simply call add and have the node added to the
3150 * end of the navbar
3152 * @param string $text
3153 * @param string|moodle_url|action_link $action An action to associate with this node.
3154 * @param int $type One of navigation_node::TYPE_*
3155 * @param string $shorttext
3156 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3157 * @param pix_icon $icon An optional icon to use for this node.
3158 * @return navigation_node
3160 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3161 if ($this->content !== null) {
3162 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3165 // Properties array used when creating the new navigation node
3166 $itemarray = array(
3167 'text' => $text,
3168 'type' => $type
3170 // Set the action if one was provided
3171 if ($action!==null) {
3172 $itemarray['action'] = $action;
3174 // Set the shorttext if one was provided
3175 if ($shorttext!==null) {
3176 $itemarray['shorttext'] = $shorttext;
3178 // Set the icon if one was provided
3179 if ($icon!==null) {
3180 $itemarray['icon'] = $icon;
3182 // Default the key to the number of children if not provided
3183 if ($key === null) {
3184 $key = count($this->children);
3186 // Set the key
3187 $itemarray['key'] = $key;
3188 // Set the parent to this node
3189 $itemarray['parent'] = $this;
3190 // Add the child using the navigation_node_collections add method
3191 $this->children[] = new navigation_node($itemarray);
3192 return $this;
3196 * Prepends a new navigation_node to the start of the navbar
3198 * @param string $text
3199 * @param string|moodle_url|action_link $action An action to associate with this node.
3200 * @param int $type One of navigation_node::TYPE_*
3201 * @param string $shorttext
3202 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3203 * @param pix_icon $icon An optional icon to use for this node.
3204 * @return navigation_node
3206 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3207 if ($this->content !== null) {
3208 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3210 // Properties array used when creating the new navigation node.
3211 $itemarray = array(
3212 'text' => $text,
3213 'type' => $type
3215 // Set the action if one was provided.
3216 if ($action!==null) {
3217 $itemarray['action'] = $action;
3219 // Set the shorttext if one was provided.
3220 if ($shorttext!==null) {
3221 $itemarray['shorttext'] = $shorttext;
3223 // Set the icon if one was provided.
3224 if ($icon!==null) {
3225 $itemarray['icon'] = $icon;
3227 // Default the key to the number of children if not provided.
3228 if ($key === null) {
3229 $key = count($this->children);
3231 // Set the key.
3232 $itemarray['key'] = $key;
3233 // Set the parent to this node.
3234 $itemarray['parent'] = $this;
3235 // Add the child node to the prepend list.
3236 $this->prependchildren[] = new navigation_node($itemarray);
3237 return $this;
3242 * Class used to manage the settings option for the current page
3244 * This class is used to manage the settings options in a tree format (recursively)
3245 * and was created initially for use with the settings blocks.
3247 * @package core
3248 * @category navigation
3249 * @copyright 2009 Sam Hemelryk
3250 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3252 class settings_navigation extends navigation_node {
3253 /** @var stdClass the current context */
3254 protected $context;
3255 /** @var moodle_page the moodle page that the navigation belongs to */
3256 protected $page;
3257 /** @var string contains administration section navigation_nodes */
3258 protected $adminsection;
3259 /** @var bool A switch to see if the navigation node is initialised */
3260 protected $initialised = false;
3261 /** @var array An array of users that the nodes can extend for. */
3262 protected $userstoextendfor = array();
3263 /** @var navigation_cache **/
3264 protected $cache;
3267 * Sets up the object with basic settings and preparse it for use
3269 * @param moodle_page $page
3271 public function __construct(moodle_page &$page) {
3272 if (during_initial_install()) {
3273 return false;
3275 $this->page = $page;
3276 // Initialise the main navigation. It is most important that this is done
3277 // before we try anything
3278 $this->page->navigation->initialise();
3279 // Initialise the navigation cache
3280 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3281 $this->children = new navigation_node_collection();
3284 * Initialise the settings navigation based on the current context
3286 * This function initialises the settings navigation tree for a given context
3287 * by calling supporting functions to generate major parts of the tree.
3290 public function initialise() {
3291 global $DB, $SESSION, $SITE;
3293 if (during_initial_install()) {
3294 return false;
3295 } else if ($this->initialised) {
3296 return true;
3298 $this->id = 'settingsnav';
3299 $this->context = $this->page->context;
3301 $context = $this->context;
3302 if ($context->contextlevel == CONTEXT_BLOCK) {
3303 $this->load_block_settings();
3304 $context = $context->get_parent_context();
3307 switch ($context->contextlevel) {
3308 case CONTEXT_SYSTEM:
3309 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3310 $this->load_front_page_settings(($context->id == $this->context->id));
3312 break;
3313 case CONTEXT_COURSECAT:
3314 $this->load_category_settings();
3315 break;
3316 case CONTEXT_COURSE:
3317 if ($this->page->course->id != $SITE->id) {
3318 $this->load_course_settings(($context->id == $this->context->id));
3319 } else {
3320 $this->load_front_page_settings(($context->id == $this->context->id));
3322 break;
3323 case CONTEXT_MODULE:
3324 $this->load_module_settings();
3325 $this->load_course_settings();
3326 break;
3327 case CONTEXT_USER:
3328 if ($this->page->course->id != $SITE->id) {
3329 $this->load_course_settings();
3331 break;
3334 $settings = $this->load_user_settings($this->page->course->id);
3336 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
3337 $admin = $this->load_administration_settings();
3338 $SESSION->load_navigation_admin = ($admin->has_children());
3339 } else {
3340 $admin = false;
3343 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
3344 $admin->force_open();
3345 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
3346 $settings->force_open();
3349 // Check if the user is currently logged in as another user
3350 if (session_is_loggedinas()) {
3351 // Get the actual user, we need this so we can display an informative return link
3352 $realuser = session_get_realuser();
3353 // Add the informative return to original user link
3354 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3355 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3358 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3359 $this->load_local_plugin_settings();
3361 foreach ($this->children as $key=>$node) {
3362 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3363 $node->remove();
3366 $this->initialised = true;
3369 * Override the parent function so that we can add preceeding hr's and set a
3370 * root node class against all first level element
3372 * It does this by first calling the parent's add method {@link navigation_node::add()}
3373 * and then proceeds to use the key to set class and hr
3375 * @param string $text text to be used for the link.
3376 * @param string|moodle_url $url url for the new node
3377 * @param int $type the type of node navigation_node::TYPE_*
3378 * @param string $shorttext
3379 * @param string|int $key a key to access the node by.
3380 * @param pix_icon $icon An icon that appears next to the node.
3381 * @return navigation_node with the new node added to it.
3383 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3384 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3385 $node->add_class('root_node');
3386 return $node;
3390 * This function allows the user to add something to the start of the settings
3391 * navigation, which means it will be at the top of the settings navigation block
3393 * @param string $text text to be used for the link.
3394 * @param string|moodle_url $url url for the new node
3395 * @param int $type the type of node navigation_node::TYPE_*
3396 * @param string $shorttext
3397 * @param string|int $key a key to access the node by.
3398 * @param pix_icon $icon An icon that appears next to the node.
3399 * @return navigation_node $node with the new node added to it.
3401 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3402 $children = $this->children;
3403 $childrenclass = get_class($children);
3404 $this->children = new $childrenclass;
3405 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3406 foreach ($children as $child) {
3407 $this->children->add($child);
3409 return $node;
3412 * Load the site administration tree
3414 * This function loads the site administration tree by using the lib/adminlib library functions
3416 * @param navigation_node $referencebranch A reference to a branch in the settings
3417 * navigation tree
3418 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3419 * tree and start at the beginning
3420 * @return mixed A key to access the admin tree by
3422 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3423 global $CFG;
3425 // Check if we are just starting to generate this navigation.
3426 if ($referencebranch === null) {
3428 // Require the admin lib then get an admin structure
3429 if (!function_exists('admin_get_root')) {
3430 require_once($CFG->dirroot.'/lib/adminlib.php');
3432 $adminroot = admin_get_root(false, false);
3433 // This is the active section identifier
3434 $this->adminsection = $this->page->url->param('section');
3436 // Disable the navigation from automatically finding the active node
3437 navigation_node::$autofindactive = false;
3438 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
3439 foreach ($adminroot->children as $adminbranch) {
3440 $this->load_administration_settings($referencebranch, $adminbranch);
3442 navigation_node::$autofindactive = true;
3444 // Use the admin structure to locate the active page
3445 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3446 $currentnode = $this;
3447 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3448 $currentnode = $currentnode->get($pathkey);
3450 if ($currentnode) {
3451 $currentnode->make_active();
3453 } else {
3454 $this->scan_for_active_node($referencebranch);
3456 return $referencebranch;
3457 } else if ($adminbranch->check_access()) {
3458 // We have a reference branch that we can access and is not hidden `hurrah`
3459 // Now we need to display it and any children it may have
3460 $url = null;
3461 $icon = null;
3462 if ($adminbranch instanceof admin_settingpage) {
3463 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3464 } else if ($adminbranch instanceof admin_externalpage) {
3465 $url = $adminbranch->url;
3466 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3467 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3470 // Add the branch
3471 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3473 if ($adminbranch->is_hidden()) {
3474 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3475 $reference->add_class('hidden');
3476 } else {
3477 $reference->display = false;
3481 // Check if we are generating the admin notifications and whether notificiations exist
3482 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3483 $reference->add_class('criticalnotification');
3485 // Check if this branch has children
3486 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3487 foreach ($adminbranch->children as $branch) {
3488 // Generate the child branches as well now using this branch as the reference
3489 $this->load_administration_settings($reference, $branch);
3491 } else {
3492 $reference->icon = new pix_icon('i/settings', '');
3498 * This function recursivily scans nodes until it finds the active node or there
3499 * are no more nodes.
3500 * @param navigation_node $node
3502 protected function scan_for_active_node(navigation_node $node) {
3503 if (!$node->check_if_active() && $node->children->count()>0) {
3504 foreach ($node->children as &$child) {
3505 $this->scan_for_active_node($child);
3511 * Gets a navigation node given an array of keys that represent the path to
3512 * the desired node.
3514 * @param array $path
3515 * @return navigation_node|false
3517 protected function get_by_path(array $path) {
3518 $node = $this->get(array_shift($path));
3519 foreach ($path as $key) {
3520 $node->get($key);
3522 return $node;
3526 * Generate the list of modules for the given course.
3528 * @param stdClass $course The course to get modules for
3530 protected function get_course_modules($course) {
3531 global $CFG;
3532 // This function is included when we include course/lib.php at the top
3533 // of this file
3534 $modnames = get_module_types_names();
3535 $resources = array();
3536 $activities = array();
3537 foreach($modnames as $modname=>$modnamestr) {
3538 if (!course_allowed_module($course, $modname)) {
3539 continue;
3542 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3543 if (!file_exists($libfile)) {
3544 continue;
3546 include_once($libfile);
3547 $gettypesfunc = $modname.'_get_types';
3548 if (function_exists($gettypesfunc)) {
3549 $types = $gettypesfunc();
3550 foreach($types as $type) {
3551 if (!isset($type->modclass) || !isset($type->typestr)) {
3552 debugging('Incorrect activity type in '.$modname);
3553 continue;
3555 if ($type->modclass == MOD_CLASS_RESOURCE) {
3556 $resources[html_entity_decode($type->type, ENT_QUOTES, 'UTF-8')] = $type->typestr;
3557 } else {
3558 $activities[html_entity_decode($type->type, ENT_QUOTES, 'UTF-8')] = $type->typestr;
3561 } else {
3562 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3563 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
3564 $resources[$modname] = $modnamestr;
3565 } else {
3566 // all other archetypes are considered activity
3567 $activities[$modname] = $modnamestr;
3571 return array($resources, $activities);
3575 * This function loads the course settings that are available for the user
3577 * @param bool $forceopen If set to true the course node will be forced open
3578 * @return navigation_node|false
3580 protected function load_course_settings($forceopen = false) {
3581 global $CFG;
3583 $course = $this->page->course;
3584 $coursecontext = context_course::instance($course->id);
3586 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3588 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3589 if ($forceopen) {
3590 $coursenode->force_open();
3593 if ($this->page->user_allowed_editing()) {
3594 // Add the turn on/off settings
3596 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3597 // We are on the course page, retain the current page params e.g. section.
3598 $baseurl = clone($this->page->url);
3599 $baseurl->param('sesskey', sesskey());
3600 } else {
3601 // Edit on the main course page.
3602 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3605 $editurl = clone($baseurl);
3606 if ($this->page->user_is_editing()) {
3607 $editurl->param('edit', 'off');
3608 $editstring = get_string('turneditingoff');
3609 } else {
3610 $editurl->param('edit', 'on');
3611 $editstring = get_string('turneditingon');
3613 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
3616 if (has_capability('moodle/course:update', $coursecontext)) {
3617 // Add the course settings link
3618 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3619 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
3621 // Add the course completion settings link
3622 if ($CFG->enablecompletion && $course->enablecompletion) {
3623 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3624 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3628 // add enrol nodes
3629 enrol_add_course_navigation($coursenode, $course);
3631 // Manage filters
3632 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3633 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3634 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3637 // View course reports.
3638 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
3639 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
3640 new pix_icon('i/stats', ''));
3641 $coursereports = core_component::get_plugin_list('coursereport');
3642 foreach ($coursereports as $report => $dir) {
3643 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
3644 if (file_exists($libfile)) {
3645 require_once($libfile);
3646 $reportfunction = $report.'_report_extend_navigation';
3647 if (function_exists($report.'_report_extend_navigation')) {
3648 $reportfunction($reportnav, $course, $coursecontext);
3653 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
3654 foreach ($reports as $reportfunction) {
3655 $reportfunction($reportnav, $course, $coursecontext);
3659 // Add view grade report is permitted
3660 $reportavailable = false;
3661 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3662 $reportavailable = true;
3663 } else if (!empty($course->showgrades)) {
3664 $reports = core_component::get_plugin_list('gradereport');
3665 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3666 arsort($reports); // user is last, we want to test it first
3667 foreach ($reports as $plugin => $plugindir) {
3668 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3669 //stop when the first visible plugin is found
3670 $reportavailable = true;
3671 break;
3676 if ($reportavailable) {
3677 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3678 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3681 // Add outcome if permitted
3682 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3683 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3684 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3687 //Add badges navigation
3688 require_once($CFG->libdir .'/badgeslib.php');
3689 badges_add_course_navigation($coursenode, $course);
3691 // Backup this course
3692 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3693 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3694 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3697 // Restore to this course
3698 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3699 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3700 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3703 // Import data from other courses
3704 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3705 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3706 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
3709 // Publish course on a hub
3710 if (has_capability('moodle/course:publish', $coursecontext)) {
3711 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3712 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3715 // Reset this course
3716 if (has_capability('moodle/course:reset', $coursecontext)) {
3717 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3718 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3721 // Questions
3722 require_once($CFG->libdir . '/questionlib.php');
3723 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3725 if (has_capability('moodle/course:update', $coursecontext)) {
3726 // Repository Instances
3727 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3728 require_once($CFG->dirroot . '/repository/lib.php');
3729 $editabletypes = repository::get_editable_types($coursecontext);
3730 $haseditabletypes = !empty($editabletypes);
3731 unset($editabletypes);
3732 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3733 } else {
3734 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3736 if ($haseditabletypes) {
3737 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3738 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3742 // Manage files
3743 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3744 // hidden in new courses and courses where legacy files were turned off
3745 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3746 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
3750 // Switch roles
3751 $roles = array();
3752 $assumedrole = $this->in_alternative_role();
3753 if ($assumedrole !== false) {
3754 $roles[0] = get_string('switchrolereturn');
3756 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3757 $availableroles = get_switchable_roles($coursecontext);
3758 if (is_array($availableroles)) {
3759 foreach ($availableroles as $key=>$role) {
3760 if ($assumedrole == (int)$key) {
3761 continue;
3763 $roles[$key] = $role;
3767 if (is_array($roles) && count($roles)>0) {
3768 $switchroles = $this->add(get_string('switchroleto'));
3769 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3770 $switchroles->force_open();
3772 foreach ($roles as $key => $name) {
3773 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$this->page->url->out_as_local_url(false)));
3774 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
3777 // Return we are done
3778 return $coursenode;
3782 * This function calls the module function to inject module settings into the
3783 * settings navigation tree.
3785 * This only gets called if there is a corrosponding function in the modules
3786 * lib file.
3788 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3790 * @return navigation_node|false
3792 protected function load_module_settings() {
3793 global $CFG;
3795 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3796 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3797 $this->page->set_cm($cm, $this->page->course);
3800 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3801 if (file_exists($file)) {
3802 require_once($file);
3805 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
3806 $modulenode->force_open();
3808 // Settings for the module
3809 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3810 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3811 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3813 // Assign local roles
3814 if (count(get_assignable_roles($this->page->cm->context))>0) {
3815 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3816 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3818 // Override roles
3819 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3820 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3821 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3823 // Check role permissions
3824 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3825 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3826 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3828 // Manage filters
3829 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3830 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3831 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3833 // Add reports
3834 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3835 foreach ($reports as $reportfunction) {
3836 $reportfunction($modulenode, $this->page->cm);
3838 // Add a backup link
3839 $featuresfunc = $this->page->activityname.'_supports';
3840 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3841 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3842 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3845 // Restore this activity
3846 $featuresfunc = $this->page->activityname.'_supports';
3847 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3848 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3849 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3852 // Allow the active advanced grading method plugin to append its settings
3853 $featuresfunc = $this->page->activityname.'_supports';
3854 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3855 require_once($CFG->dirroot.'/grade/grading/lib.php');
3856 $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
3857 $gradingman->extend_settings_navigation($this, $modulenode);
3860 $function = $this->page->activityname.'_extend_settings_navigation';
3861 if (!function_exists($function)) {
3862 return $modulenode;
3865 $function($this, $modulenode);
3867 // Remove the module node if there are no children
3868 if (empty($modulenode->children)) {
3869 $modulenode->remove();
3872 return $modulenode;
3876 * Loads the user settings block of the settings nav
3878 * This function is simply works out the userid and whether we need to load
3879 * just the current users profile settings, or the current user and the user the
3880 * current user is viewing.
3882 * This function has some very ugly code to work out the user, if anyone has
3883 * any bright ideas please feel free to intervene.
3885 * @param int $courseid The course id of the current course
3886 * @return navigation_node|false
3888 protected function load_user_settings($courseid = SITEID) {
3889 global $USER, $CFG;
3891 if (isguestuser() || !isloggedin()) {
3892 return false;
3895 $navusers = $this->page->navigation->get_extending_users();
3897 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3898 $usernode = null;
3899 foreach ($this->userstoextendfor as $userid) {
3900 if ($userid == $USER->id) {
3901 continue;
3903 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3904 if (is_null($usernode)) {
3905 $usernode = $node;
3908 foreach ($navusers as $user) {
3909 if ($user->id == $USER->id) {
3910 continue;
3912 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3913 if (is_null($usernode)) {
3914 $usernode = $node;
3917 $this->generate_user_settings($courseid, $USER->id);
3918 } else {
3919 $usernode = $this->generate_user_settings($courseid, $USER->id);
3921 return $usernode;
3925 * Extends the settings navigation for the given user.
3927 * Note: This method gets called automatically if you call
3928 * $PAGE->navigation->extend_for_user($userid)
3930 * @param int $userid
3932 public function extend_for_user($userid) {
3933 global $CFG;
3935 if (!in_array($userid, $this->userstoextendfor)) {
3936 $this->userstoextendfor[] = $userid;
3937 if ($this->initialised) {
3938 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3939 $children = array();
3940 foreach ($this->children as $child) {
3941 $children[] = $child;
3943 array_unshift($children, array_pop($children));
3944 $this->children = new navigation_node_collection();
3945 foreach ($children as $child) {
3946 $this->children->add($child);
3953 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3954 * what can be shown/done
3956 * @param int $courseid The current course' id
3957 * @param int $userid The user id to load for
3958 * @param string $gstitle The string to pass to get_string for the branch title
3959 * @return navigation_node|false
3961 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3962 global $DB, $CFG, $USER, $SITE;
3964 if ($courseid != $SITE->id) {
3965 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3966 $course = $this->page->course;
3967 } else {
3968 $select = context_helper::get_preload_record_columns_sql('ctx');
3969 $sql = "SELECT c.*, $select
3970 FROM {course} c
3971 JOIN {context} ctx ON c.id = ctx.instanceid
3972 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
3973 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
3974 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3975 context_helper::preload_from_record($course);
3977 } else {
3978 $course = $SITE;
3981 $coursecontext = context_course::instance($course->id); // Course context
3982 $systemcontext = context_system::instance();
3983 $currentuser = ($USER->id == $userid);
3985 if ($currentuser) {
3986 $user = $USER;
3987 $usercontext = context_user::instance($user->id); // User context
3988 } else {
3989 $select = context_helper::get_preload_record_columns_sql('ctx');
3990 $sql = "SELECT u.*, $select
3991 FROM {user} u
3992 JOIN {context} ctx ON u.id = ctx.instanceid
3993 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
3994 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
3995 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
3996 if (!$user) {
3997 return false;
3999 context_helper::preload_from_record($user);
4001 // Check that the user can view the profile
4002 $usercontext = context_user::instance($user->id); // User context
4003 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4005 if ($course->id == $SITE->id) {
4006 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4007 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4008 return false;
4010 } else {
4011 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4012 $userisenrolled = is_enrolled($coursecontext, $user->id);
4013 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4014 return false;
4016 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4017 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
4018 // If groups are in use, make sure we can see that group
4019 return false;
4024 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4026 $key = $gstitle;
4027 if ($gstitle != 'usercurrentsettings') {
4028 $key .= $userid;
4031 // Add a user setting branch
4032 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
4033 $usersetting->id = 'usersettings';
4034 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
4035 // Automatically start by making it active
4036 $usersetting->make_active();
4039 // Check if the user has been deleted
4040 if ($user->deleted) {
4041 if (!has_capability('moodle/user:update', $coursecontext)) {
4042 // We can't edit the user so just show the user deleted message
4043 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4044 } else {
4045 // We can edit the user so show the user deleted message and link it to the profile
4046 if ($course->id == $SITE->id) {
4047 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4048 } else {
4049 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4051 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4053 return true;
4056 $userauthplugin = false;
4057 if (!empty($user->auth)) {
4058 $userauthplugin = get_auth_plugin($user->auth);
4061 // Add the profile edit link
4062 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4063 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
4064 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4065 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4066 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4067 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4068 $url = $userauthplugin->edit_profile_url();
4069 if (empty($url)) {
4070 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4072 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4077 // Change password link
4078 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4079 $passwordchangeurl = $userauthplugin->change_password_url();
4080 if (empty($passwordchangeurl)) {
4081 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4083 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
4086 // View the roles settings
4087 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
4088 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4090 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4091 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4093 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4095 if (!empty($assignableroles)) {
4096 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4097 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4100 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4101 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4102 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4105 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4106 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4109 // Portfolio
4110 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4111 require_once($CFG->libdir . '/portfoliolib.php');
4112 if (portfolio_has_visible_instances()) {
4113 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4115 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4116 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4118 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4119 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4123 $enablemanagetokens = false;
4124 if (!empty($CFG->enablerssfeeds)) {
4125 $enablemanagetokens = true;
4126 } else if (!is_siteadmin($USER->id)
4127 && !empty($CFG->enablewebservices)
4128 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4129 $enablemanagetokens = true;
4131 // Security keys
4132 if ($currentuser && $enablemanagetokens) {
4133 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4134 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4137 // Messaging
4138 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4139 $url = new moodle_url('/message/edit.php', array('id'=>$user->id));
4140 $usersetting->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
4143 // Blogs
4144 if ($currentuser && !empty($CFG->enableblogs)) {
4145 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4146 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
4147 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
4148 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
4149 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
4153 // Badges.
4154 if ($currentuser && !empty($CFG->enablebadges)) {
4155 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
4156 $badges->add(get_string('preferences'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
4157 if (!empty($CFG->badges_allowexternalbackpack)) {
4158 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
4162 // Add reports node.
4163 $reporttab = $usersetting->add(get_string('activityreports'));
4164 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
4165 foreach ($reports as $reportfunction) {
4166 $reportfunction($reporttab, $user, $course);
4168 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
4169 if ($anyreport || ($course->showreports && $currentuser)) {
4170 // Add grade hardcoded grade report if necessary.
4171 $gradeaccess = false;
4172 if (has_capability('moodle/grade:viewall', $coursecontext)) {
4173 // Can view all course grades.
4174 $gradeaccess = true;
4175 } else if ($course->showgrades) {
4176 if ($currentuser && has_capability('moodle/grade:view', $coursecontext)) {
4177 // Can view own grades.
4178 $gradeaccess = true;
4179 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
4180 // Can view grades of this user - parent most probably.
4181 $gradeaccess = true;
4182 } else if ($anyreport) {
4183 // Can view grades of this user - parent most probably.
4184 $gradeaccess = true;
4187 if ($gradeaccess) {
4188 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id,
4189 'user'=>$usercontext->instanceid)));
4192 // Check the number of nodes in the report node... if there are none remove the node
4193 $reporttab->trim_if_empty();
4195 // Login as ...
4196 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
4197 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
4198 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
4201 return $usersetting;
4205 * Loads block specific settings in the navigation
4207 * @return navigation_node
4209 protected function load_block_settings() {
4210 global $CFG;
4212 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
4213 $blocknode->force_open();
4215 // Assign local roles
4216 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4217 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4219 // Override roles
4220 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4221 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4222 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4224 // Check role permissions
4225 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4226 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4227 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4230 return $blocknode;
4234 * Loads category specific settings in the navigation
4236 * @return navigation_node
4238 protected function load_category_settings() {
4239 global $CFG;
4241 $categorynode = $this->add($this->context->get_context_name(), null, null, null, 'categorysettings');
4242 $categorynode->force_open();
4243 $onmanagepage = $this->page->url->compare(new moodle_url('/course/manage.php'), URL_MATCH_BASE);
4245 if (can_edit_in_category($this->context->instanceid) && !$onmanagepage) {
4246 $url = new moodle_url('/course/manage.php', array('categoryid' => $this->context->instanceid));
4247 $editstring = get_string('managecategorythis');
4248 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4251 if (has_capability('moodle/category:manage', $this->context)) {
4252 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
4253 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4255 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
4256 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4259 // Assign local roles
4260 if (has_capability('moodle/role:assign', $this->context)) {
4261 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4262 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4265 // Override roles
4266 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4267 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4268 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4270 // Check role permissions
4271 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4272 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4273 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4276 // Cohorts
4277 if (has_capability('moodle/cohort:manage', $this->context) or has_capability('moodle/cohort:view', $this->context)) {
4278 $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', ''));
4281 // Manage filters
4282 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
4283 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
4284 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4287 return $categorynode;
4291 * Determine whether the user is assuming another role
4293 * This function checks to see if the user is assuming another role by means of
4294 * role switching. In doing this we compare each RSW key (context path) against
4295 * the current context path. This ensures that we can provide the switching
4296 * options against both the course and any page shown under the course.
4298 * @return bool|int The role(int) if the user is in another role, false otherwise
4300 protected function in_alternative_role() {
4301 global $USER;
4302 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4303 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4304 return $USER->access['rsw'][$this->page->context->path];
4306 foreach ($USER->access['rsw'] as $key=>$role) {
4307 if (strpos($this->context->path,$key)===0) {
4308 return $role;
4312 return false;
4316 * This function loads all of the front page settings into the settings navigation.
4317 * This function is called when the user is on the front page, or $COURSE==$SITE
4318 * @param bool $forceopen (optional)
4319 * @return navigation_node
4321 protected function load_front_page_settings($forceopen = false) {
4322 global $SITE, $CFG;
4324 $course = clone($SITE);
4325 $coursecontext = context_course::instance($course->id); // Course context
4327 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4328 if ($forceopen) {
4329 $frontpage->force_open();
4331 $frontpage->id = 'frontpagesettings';
4333 if ($this->page->user_allowed_editing()) {
4335 // Add the turn on/off settings
4336 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4337 if ($this->page->user_is_editing()) {
4338 $url->param('edit', 'off');
4339 $editstring = get_string('turneditingoff');
4340 } else {
4341 $url->param('edit', 'on');
4342 $editstring = get_string('turneditingon');
4344 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4347 if (has_capability('moodle/course:update', $coursecontext)) {
4348 // Add the course settings link
4349 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4350 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4353 // add enrol nodes
4354 enrol_add_course_navigation($frontpage, $course);
4356 // Manage filters
4357 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4358 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4359 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4362 // View course reports.
4363 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
4364 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
4365 new pix_icon('i/stats', ''));
4366 $coursereports = core_component::get_plugin_list('coursereport');
4367 foreach ($coursereports as $report=>$dir) {
4368 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4369 if (file_exists($libfile)) {
4370 require_once($libfile);
4371 $reportfunction = $report.'_report_extend_navigation';
4372 if (function_exists($report.'_report_extend_navigation')) {
4373 $reportfunction($frontpagenav, $course, $coursecontext);
4378 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4379 foreach ($reports as $reportfunction) {
4380 $reportfunction($frontpagenav, $course, $coursecontext);
4384 // Backup this course
4385 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4386 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4387 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4390 // Restore to this course
4391 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4392 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4393 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4396 // Questions
4397 require_once($CFG->libdir . '/questionlib.php');
4398 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4400 // Manage files
4401 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4402 //hiden in new installs
4403 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
4404 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
4406 return $frontpage;
4410 * This function gives local plugins an opportunity to modify the settings navigation.
4412 protected function load_local_plugin_settings() {
4413 // Get all local plugins with an extend_settings_navigation function in their lib.php file
4414 foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
4415 // Call each function providing this (the settings navigation) and the current context.
4416 $function($this, $this->context);
4421 * This function marks the cache as volatile so it is cleared during shutdown
4423 public function clear_cache() {
4424 $this->cache->volatile();
4429 * Simple class used to output a navigation branch in XML
4431 * @package core
4432 * @category navigation
4433 * @copyright 2009 Sam Hemelryk
4434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4436 class navigation_json {
4437 /** @var array An array of different node types */
4438 protected $nodetype = array('node','branch');
4439 /** @var array An array of node keys and types */
4440 protected $expandable = array();
4442 * Turns a branch and all of its children into XML
4444 * @param navigation_node $branch
4445 * @return string XML string
4447 public function convert($branch) {
4448 $xml = $this->convert_child($branch);
4449 return $xml;
4452 * Set the expandable items in the array so that we have enough information
4453 * to attach AJAX events
4454 * @param array $expandable
4456 public function set_expandable($expandable) {
4457 foreach ($expandable as $node) {
4458 $this->expandable[$node['key'].':'.$node['type']] = $node;
4462 * Recusively converts a child node and its children to XML for output
4464 * @param navigation_node $child The child to convert
4465 * @param int $depth Pointlessly used to track the depth of the XML structure
4466 * @return string JSON
4468 protected function convert_child($child, $depth=1) {
4469 if (!$child->display) {
4470 return '';
4472 $attributes = array();
4473 $attributes['id'] = $child->id;
4474 $attributes['name'] = $child->text;
4475 $attributes['type'] = $child->type;
4476 $attributes['key'] = $child->key;
4477 $attributes['class'] = $child->get_css_type();
4479 if ($child->icon instanceof pix_icon) {
4480 $attributes['icon'] = array(
4481 'component' => $child->icon->component,
4482 'pix' => $child->icon->pix,
4484 foreach ($child->icon->attributes as $key=>$value) {
4485 if ($key == 'class') {
4486 $attributes['icon']['classes'] = explode(' ', $value);
4487 } else if (!array_key_exists($key, $attributes['icon'])) {
4488 $attributes['icon'][$key] = $value;
4492 } else if (!empty($child->icon)) {
4493 $attributes['icon'] = (string)$child->icon;
4496 if ($child->forcetitle || $child->title !== $child->text) {
4497 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
4499 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4500 $attributes['expandable'] = $child->key;
4501 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4504 if (count($child->classes)>0) {
4505 $attributes['class'] .= ' '.join(' ',$child->classes);
4507 if (is_string($child->action)) {
4508 $attributes['link'] = $child->action;
4509 } else if ($child->action instanceof moodle_url) {
4510 $attributes['link'] = $child->action->out();
4511 } else if ($child->action instanceof action_link) {
4512 $attributes['link'] = $child->action->url->out();
4514 $attributes['hidden'] = ($child->hidden);
4515 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4516 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
4518 if ($child->children->count() > 0) {
4519 $attributes['children'] = array();
4520 foreach ($child->children as $subchild) {
4521 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4525 if ($depth > 1) {
4526 return $attributes;
4527 } else {
4528 return json_encode($attributes);
4534 * The cache class used by global navigation and settings navigation.
4536 * It is basically an easy access point to session with a bit of smarts to make
4537 * sure that the information that is cached is valid still.
4539 * Example use:
4540 * <code php>
4541 * if (!$cache->viewdiscussion()) {
4542 * // Code to do stuff and produce cachable content
4543 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4545 * $content = $cache->viewdiscussion;
4546 * </code>
4548 * @package core
4549 * @category navigation
4550 * @copyright 2009 Sam Hemelryk
4551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4553 class navigation_cache {
4554 /** @var int represents the time created */
4555 protected $creation;
4556 /** @var array An array of session keys */
4557 protected $session;
4559 * The string to use to segregate this particular cache. It can either be
4560 * unique to start a fresh cache or if you want to share a cache then make
4561 * it the string used in the original cache.
4562 * @var string
4564 protected $area;
4565 /** @var int a time that the information will time out */
4566 protected $timeout;
4567 /** @var stdClass The current context */
4568 protected $currentcontext;
4569 /** @var int cache time information */
4570 const CACHETIME = 0;
4571 /** @var int cache user id */
4572 const CACHEUSERID = 1;
4573 /** @var int cache value */
4574 const CACHEVALUE = 2;
4575 /** @var null|array An array of navigation cache areas to expire on shutdown */
4576 public static $volatilecaches;
4579 * Contructor for the cache. Requires two arguments
4581 * @param string $area The string to use to segregate this particular cache
4582 * it can either be unique to start a fresh cache or if you want
4583 * to share a cache then make it the string used in the original
4584 * cache
4585 * @param int $timeout The number of seconds to time the information out after
4587 public function __construct($area, $timeout=1800) {
4588 $this->creation = time();
4589 $this->area = $area;
4590 $this->timeout = time() - $timeout;
4591 if (rand(0,100) === 0) {
4592 $this->garbage_collection();
4597 * Used to set up the cache within the SESSION.
4599 * This is called for each access and ensure that we don't put anything into the session before
4600 * it is required.
4602 protected function ensure_session_cache_initialised() {
4603 global $SESSION;
4604 if (empty($this->session)) {
4605 if (!isset($SESSION->navcache)) {
4606 $SESSION->navcache = new stdClass;
4608 if (!isset($SESSION->navcache->{$this->area})) {
4609 $SESSION->navcache->{$this->area} = array();
4611 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
4616 * Magic Method to retrieve something by simply calling using = cache->key
4618 * @param mixed $key The identifier for the information you want out again
4619 * @return void|mixed Either void or what ever was put in
4621 public function __get($key) {
4622 if (!$this->cached($key)) {
4623 return;
4625 $information = $this->session[$key][self::CACHEVALUE];
4626 return unserialize($information);
4630 * Magic method that simply uses {@link set();} to store something in the cache
4632 * @param string|int $key
4633 * @param mixed $information
4635 public function __set($key, $information) {
4636 $this->set($key, $information);
4640 * Sets some information against the cache (session) for later retrieval
4642 * @param string|int $key
4643 * @param mixed $information
4645 public function set($key, $information) {
4646 global $USER;
4647 $this->ensure_session_cache_initialised();
4648 $information = serialize($information);
4649 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4652 * Check the existence of the identifier in the cache
4654 * @param string|int $key
4655 * @return bool
4657 public function cached($key) {
4658 global $USER;
4659 $this->ensure_session_cache_initialised();
4660 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) {
4661 return false;
4663 return true;
4666 * Compare something to it's equivilant in the cache
4668 * @param string $key
4669 * @param mixed $value
4670 * @param bool $serialise Whether to serialise the value before comparison
4671 * this should only be set to false if the value is already
4672 * serialised
4673 * @return bool If the value is the same false if it is not set or doesn't match
4675 public function compare($key, $value, $serialise = true) {
4676 if ($this->cached($key)) {
4677 if ($serialise) {
4678 $value = serialize($value);
4680 if ($this->session[$key][self::CACHEVALUE] === $value) {
4681 return true;
4684 return false;
4687 * Wipes the entire cache, good to force regeneration
4689 public function clear() {
4690 global $SESSION;
4691 unset($SESSION->navcache);
4692 $this->session = null;
4695 * Checks all cache entries and removes any that have expired, good ole cleanup
4697 protected function garbage_collection() {
4698 if (empty($this->session)) {
4699 return true;
4701 foreach ($this->session as $key=>$cachedinfo) {
4702 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4703 unset($this->session[$key]);
4709 * Marks the cache as being volatile (likely to change)
4711 * Any caches marked as volatile will be destroyed at the on shutdown by
4712 * {@link navigation_node::destroy_volatile_caches()} which is registered
4713 * as a shutdown function if any caches are marked as volatile.
4715 * @param bool $setting True to destroy the cache false not too
4717 public function volatile($setting = true) {
4718 if (self::$volatilecaches===null) {
4719 self::$volatilecaches = array();
4720 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4723 if ($setting) {
4724 self::$volatilecaches[$this->area] = $this->area;
4725 } else if (array_key_exists($this->area, self::$volatilecaches)) {
4726 unset(self::$volatilecaches[$this->area]);
4731 * Destroys all caches marked as volatile
4733 * This function is static and works in conjunction with the static volatilecaches
4734 * property of navigation cache.
4735 * Because this function is static it manually resets the cached areas back to an
4736 * empty array.
4738 public static function destroy_volatile_caches() {
4739 global $SESSION;
4740 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4741 foreach (self::$volatilecaches as $area) {
4742 $SESSION->navcache->{$area} = array();
4744 } else {
4745 $SESSION->navcache = new stdClass;