Merge branch 'MDL-38112-24' of git://github.com/danpoltawski/moodle into MOODLE_24_STABLE
[moodle.git] / lib / navigationlib.php
blobbc9e1b0129ebe67672cdf6df3a43729b6293c547
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_'.(count($expandable)+1);
593 $this->add_class('canexpand');
594 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
596 $child->find_expandable($expandable);
601 * Finds all nodes of a given type (recursive)
603 * @param int $type One of navigation_node::TYPE_*
604 * @return array
606 public function find_all_of_type($type) {
607 $nodes = $this->children->type($type);
608 foreach ($this->children as &$node) {
609 $childnodes = $node->find_all_of_type($type);
610 $nodes = array_merge($nodes, $childnodes);
612 return $nodes;
616 * Removes this node if it is empty
618 public function trim_if_empty() {
619 if ($this->children->count() == 0) {
620 $this->remove();
625 * Creates a tab representation of this nodes children that can be used
626 * with print_tabs to produce the tabs on a page.
628 * call_user_func_array('print_tabs', $node->get_tabs_array());
630 * @param array $inactive
631 * @param bool $return
632 * @return array Array (tabs, selected, inactive, activated, return)
634 public function get_tabs_array(array $inactive=array(), $return=false) {
635 $tabs = array();
636 $rows = array();
637 $selected = null;
638 $activated = array();
639 foreach ($this->children as $node) {
640 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
641 if ($node->contains_active_node()) {
642 if ($node->children->count() > 0) {
643 $activated[] = $node->key;
644 foreach ($node->children as $child) {
645 if ($child->contains_active_node()) {
646 $selected = $child->key;
648 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
650 } else {
651 $selected = $node->key;
655 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
659 * Sets the parent for this node and if this node is active ensures that the tree is properly
660 * adjusted as well.
662 * @param navigation_node $parent
664 public function set_parent(navigation_node $parent) {
665 // Set the parent (thats the easy part)
666 $this->parent = $parent;
667 // Check if this node is active (this is checked during construction)
668 if ($this->isactive) {
669 // Force all of the parent nodes open so you can see this node
670 $this->parent->force_open();
671 // Make all parents inactive so that its clear where we are.
672 $this->parent->make_inactive();
677 * Hides the node and any children it has.
679 * @since 2.4.2
681 public function hide() {
682 $this->display = false;
683 if ($this->has_children()) {
684 foreach ($this->children as $child) {
685 $child->hide();
692 * Navigation node collection
694 * This class is responsible for managing a collection of navigation nodes.
695 * It is required because a node's unique identifier is a combination of both its
696 * key and its type.
698 * Originally an array was used with a string key that was a combination of the two
699 * however it was decided that a better solution would be to use a class that
700 * implements the standard IteratorAggregate interface.
702 * @package core
703 * @category navigation
704 * @copyright 2010 Sam Hemelryk
705 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
707 class navigation_node_collection implements IteratorAggregate {
709 * A multidimensional array to where the first key is the type and the second
710 * key is the nodes key.
711 * @var array
713 protected $collection = array();
715 * An array that contains references to nodes in the same order they were added.
716 * This is maintained as a progressive array.
717 * @var array
719 protected $orderedcollection = array();
721 * A reference to the last node that was added to the collection
722 * @var navigation_node
724 protected $last = null;
726 * The total number of items added to this array.
727 * @var int
729 protected $count = 0;
732 * Adds a navigation node to the collection
734 * @param navigation_node $node Node to add
735 * @param string $beforekey If specified, adds before a node with this key,
736 * otherwise adds at end
737 * @return navigation_node Added node
739 public function add(navigation_node $node, $beforekey=null) {
740 global $CFG;
741 $key = $node->key;
742 $type = $node->type;
744 // First check we have a 2nd dimension for this type
745 if (!array_key_exists($type, $this->orderedcollection)) {
746 $this->orderedcollection[$type] = array();
748 // Check for a collision and report if debugging is turned on
749 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
750 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
753 // Find the key to add before
754 $newindex = $this->count;
755 $last = true;
756 if ($beforekey !== null) {
757 foreach ($this->collection as $index => $othernode) {
758 if ($othernode->key === $beforekey) {
759 $newindex = $index;
760 $last = false;
761 break;
764 if ($newindex === $this->count) {
765 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
766 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
770 // Add the node to the appropriate place in the by-type structure (which
771 // is not ordered, despite the variable name)
772 $this->orderedcollection[$type][$key] = $node;
773 if (!$last) {
774 // Update existing references in the ordered collection (which is the
775 // one that isn't called 'ordered') to shuffle them along if required
776 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
777 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
780 // Add a reference to the node to the progressive collection.
781 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
782 // Update the last property to a reference to this new node.
783 $this->last = $this->orderedcollection[$type][$key];
785 // Reorder the array by index if needed
786 if (!$last) {
787 ksort($this->collection);
789 $this->count++;
790 // Return the reference to the now added node
791 return $node;
795 * Return a list of all the keys of all the nodes.
796 * @return array the keys.
798 public function get_key_list() {
799 $keys = array();
800 foreach ($this->collection as $node) {
801 $keys[] = $node->key;
803 return $keys;
807 * Fetches a node from this collection.
809 * @param string|int $key The key of the node we want to find.
810 * @param int $type One of navigation_node::TYPE_*.
811 * @return navigation_node|null
813 public function get($key, $type=null) {
814 if ($type !== null) {
815 // If the type is known then we can simply check and fetch
816 if (!empty($this->orderedcollection[$type][$key])) {
817 return $this->orderedcollection[$type][$key];
819 } else {
820 // Because we don't know the type we look in the progressive array
821 foreach ($this->collection as $node) {
822 if ($node->key === $key) {
823 return $node;
827 return false;
831 * Searches for a node with matching key and type.
833 * This function searches both the nodes in this collection and all of
834 * the nodes in each collection belonging to the nodes in this collection.
836 * Recursive.
838 * @param string|int $key The key of the node we want to find.
839 * @param int $type One of navigation_node::TYPE_*.
840 * @return navigation_node|null
842 public function find($key, $type=null) {
843 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
844 return $this->orderedcollection[$type][$key];
845 } else {
846 $nodes = $this->getIterator();
847 // Search immediate children first
848 foreach ($nodes as &$node) {
849 if ($node->key === $key && ($type === null || $type === $node->type)) {
850 return $node;
853 // Now search each childs children
854 foreach ($nodes as &$node) {
855 $result = $node->children->find($key, $type);
856 if ($result !== false) {
857 return $result;
861 return false;
865 * Fetches the last node that was added to this collection
867 * @return navigation_node
869 public function last() {
870 return $this->last;
874 * Fetches all nodes of a given type from this collection
876 * @param string|int $type node type being searched for.
877 * @return array ordered collection
879 public function type($type) {
880 if (!array_key_exists($type, $this->orderedcollection)) {
881 $this->orderedcollection[$type] = array();
883 return $this->orderedcollection[$type];
886 * Removes the node with the given key and type from the collection
888 * @param string|int $key The key of the node we want to find.
889 * @param int $type
890 * @return bool
892 public function remove($key, $type=null) {
893 $child = $this->get($key, $type);
894 if ($child !== false) {
895 foreach ($this->collection as $colkey => $node) {
896 if ($node->key == $key && $node->type == $type) {
897 unset($this->collection[$colkey]);
898 break;
901 unset($this->orderedcollection[$child->type][$child->key]);
902 $this->count--;
903 return true;
905 return false;
909 * Gets the number of nodes in this collection
911 * This option uses an internal count rather than counting the actual options to avoid
912 * a performance hit through the count function.
914 * @return int
916 public function count() {
917 return $this->count;
920 * Gets an array iterator for the collection.
922 * This is required by the IteratorAggregator interface and is used by routines
923 * such as the foreach loop.
925 * @return ArrayIterator
927 public function getIterator() {
928 return new ArrayIterator($this->collection);
933 * The global navigation class used for... the global navigation
935 * This class is used by PAGE to store the global navigation for the site
936 * and is then used by the settings nav and navbar to save on processing and DB calls
938 * See
939 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
940 * {@link lib/ajax/getnavbranch.php} Called by ajax
942 * @package core
943 * @category navigation
944 * @copyright 2009 Sam Hemelryk
945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
947 class global_navigation extends navigation_node {
948 /** @var moodle_page The Moodle page this navigation object belongs to. */
949 protected $page;
950 /** @var bool switch to let us know if the navigation object is initialised*/
951 protected $initialised = false;
952 /** @var array An array of course information */
953 protected $mycourses = array();
954 /** @var array An array for containing root navigation nodes */
955 protected $rootnodes = array();
956 /** @var bool A switch for whether to show empty sections in the navigation */
957 protected $showemptysections = true;
958 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
959 protected $showcategories = null;
960 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
961 protected $showmycategories = null;
962 /** @var array An array of stdClasses for users that the navigation is extended for */
963 protected $extendforuser = array();
964 /** @var navigation_cache */
965 protected $cache;
966 /** @var array An array of course ids that are present in the navigation */
967 protected $addedcourses = array();
968 /** @var bool */
969 protected $allcategoriesloaded = false;
970 /** @var array An array of category ids that are included in the navigation */
971 protected $addedcategories = array();
972 /** @var int expansion limit */
973 protected $expansionlimit = 0;
974 /** @var int userid to allow parent to see child's profile page navigation */
975 protected $useridtouseforparentchecks = 0;
977 /** Used when loading categories to load all top level categories [parent = 0] **/
978 const LOAD_ROOT_CATEGORIES = 0;
979 /** Used when loading categories to load all categories **/
980 const LOAD_ALL_CATEGORIES = -1;
983 * Constructs a new global navigation
985 * @param moodle_page $page The page this navigation object belongs to
987 public function __construct(moodle_page $page) {
988 global $CFG, $SITE, $USER;
990 if (during_initial_install()) {
991 return;
994 if (get_home_page() == HOMEPAGE_SITE) {
995 // We are using the site home for the root element
996 $properties = array(
997 'key' => 'home',
998 'type' => navigation_node::TYPE_SYSTEM,
999 'text' => get_string('home'),
1000 'action' => new moodle_url('/')
1002 } else {
1003 // We are using the users my moodle for the root element
1004 $properties = array(
1005 'key' => 'myhome',
1006 'type' => navigation_node::TYPE_SYSTEM,
1007 'text' => get_string('myhome'),
1008 'action' => new moodle_url('/my/')
1012 // Use the parents constructor.... good good reuse
1013 parent::__construct($properties);
1015 // Initalise and set defaults
1016 $this->page = $page;
1017 $this->forceopen = true;
1018 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1022 * Mutator to set userid to allow parent to see child's profile
1023 * page navigation. See MDL-25805 for initial issue. Linked to it
1024 * is an issue explaining why this is a REALLY UGLY HACK thats not
1025 * for you to use!
1027 * @param int $userid userid of profile page that parent wants to navigate around.
1029 public function set_userid_for_parent_checks($userid) {
1030 $this->useridtouseforparentchecks = $userid;
1035 * Initialises the navigation object.
1037 * This causes the navigation object to look at the current state of the page
1038 * that it is associated with and then load the appropriate content.
1040 * This should only occur the first time that the navigation structure is utilised
1041 * which will normally be either when the navbar is called to be displayed or
1042 * when a block makes use of it.
1044 * @return bool
1046 public function initialise() {
1047 global $CFG, $SITE, $USER;
1048 // Check if it has already been initialised
1049 if ($this->initialised || during_initial_install()) {
1050 return true;
1052 $this->initialised = true;
1054 // Set up the five base root nodes. These are nodes where we will put our
1055 // content and are as follows:
1056 // site: Navigation for the front page.
1057 // myprofile: User profile information goes here.
1058 // currentcourse: The course being currently viewed.
1059 // mycourses: The users courses get added here.
1060 // courses: Additional courses are added here.
1061 // users: Other users information loaded here.
1062 $this->rootnodes = array();
1063 if (get_home_page() == HOMEPAGE_SITE) {
1064 // The home element should be my moodle because the root element is the site
1065 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1066 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1068 } else {
1069 // The home element should be the site because the root node is my moodle
1070 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1071 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1072 // We need to stop automatic redirection
1073 $this->rootnodes['home']->action->param('redirect', '0');
1076 $this->rootnodes['site'] = $this->add_course($SITE);
1077 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1078 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1079 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
1080 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1081 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1083 // We always load the frontpage course to ensure it is available without
1084 // JavaScript enabled.
1085 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1086 $this->load_course_sections($SITE, $this->rootnodes['site']);
1088 $course = $this->page->course;
1090 // $issite gets set to true if the current pages course is the sites frontpage course
1091 $issite = ($this->page->course->id == $SITE->id);
1092 // Determine if the user is enrolled in any course.
1093 $enrolledinanycourse = enrol_user_sees_own_courses();
1095 $this->rootnodes['currentcourse']->mainnavonly = true;
1096 if ($enrolledinanycourse) {
1097 $this->rootnodes['mycourses']->isexpandable = true;
1098 if ($CFG->navshowallcourses) {
1099 // When we show all courses we need to show both the my courses and the regular courses branch.
1100 $this->rootnodes['courses']->isexpandable = true;
1102 } else {
1103 $this->rootnodes['courses']->isexpandable = true;
1106 if ($this->rootnodes['mycourses']->isactive) {
1107 $this->load_courses_enrolled();
1110 $canviewcourseprofile = true;
1112 // Next load context specific content into the navigation
1113 switch ($this->page->context->contextlevel) {
1114 case CONTEXT_SYSTEM :
1115 // Nothing left to do here I feel.
1116 break;
1117 case CONTEXT_COURSECAT :
1118 // This is essential, we must load categories.
1119 $this->load_all_categories($this->page->context->instanceid, true);
1120 break;
1121 case CONTEXT_BLOCK :
1122 case CONTEXT_COURSE :
1123 if ($issite) {
1124 // Nothing left to do here.
1125 break;
1128 // Load the course associated with the current page into the navigation.
1129 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1130 // If the course wasn't added then don't try going any further.
1131 if (!$coursenode) {
1132 $canviewcourseprofile = false;
1133 break;
1136 // If the user is not enrolled then we only want to show the
1137 // course node and not populate it.
1139 // Not enrolled, can't view, and hasn't switched roles
1140 if (!can_access_course($course)) {
1141 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1142 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1143 if (!$this->current_user_is_parent_role()) {
1144 $coursenode->make_active();
1145 $canviewcourseprofile = false;
1146 break;
1150 // Add the essentials such as reports etc...
1151 $this->add_course_essentials($coursenode, $course);
1152 // Extend course navigation with it's sections/activities
1153 $this->load_course_sections($course, $coursenode);
1154 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1155 $coursenode->make_active();
1158 break;
1159 case CONTEXT_MODULE :
1160 if ($issite) {
1161 // If this is the site course then most information will have
1162 // already been loaded.
1163 // However we need to check if there is more content that can
1164 // yet be loaded for the specific module instance.
1165 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1166 if ($activitynode) {
1167 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1169 break;
1172 $course = $this->page->course;
1173 $cm = $this->page->cm;
1175 // Load the course associated with the page into the navigation
1176 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1178 // If the course wasn't added then don't try going any further.
1179 if (!$coursenode) {
1180 $canviewcourseprofile = false;
1181 break;
1184 // If the user is not enrolled then we only want to show the
1185 // course node and not populate it.
1186 if (!can_access_course($course)) {
1187 $coursenode->make_active();
1188 $canviewcourseprofile = false;
1189 break;
1192 $this->add_course_essentials($coursenode, $course);
1194 // Load the course sections into the page
1195 $this->load_course_sections($course, $coursenode, null, $cm);
1196 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1197 // Finally load the cm specific navigaton information
1198 $this->load_activity($cm, $course, $activity);
1199 // Check if we have an active ndoe
1200 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1201 // And make the activity node active.
1202 $activity->make_active();
1204 break;
1205 case CONTEXT_USER :
1206 if ($issite) {
1207 // The users profile information etc is already loaded
1208 // for the front page.
1209 break;
1211 $course = $this->page->course;
1212 // Load the course associated with the user into the navigation
1213 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1215 // If the course wasn't added then don't try going any further.
1216 if (!$coursenode) {
1217 $canviewcourseprofile = false;
1218 break;
1221 // If the user is not enrolled then we only want to show the
1222 // course node and not populate it.
1223 if (!can_access_course($course)) {
1224 $coursenode->make_active();
1225 $canviewcourseprofile = false;
1226 break;
1228 $this->add_course_essentials($coursenode, $course);
1229 $this->load_course_sections($course, $coursenode);
1230 break;
1233 // Load for the current user
1234 $this->load_for_user();
1235 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1236 $this->load_for_user(null, true);
1238 // Load each extending user into the navigation.
1239 foreach ($this->extendforuser as $user) {
1240 if ($user->id != $USER->id) {
1241 $this->load_for_user($user);
1245 // Give the local plugins a chance to include some navigation if they want.
1246 foreach (get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1247 $function = "local_{$plugin}_extends_navigation";
1248 $oldfunction = "{$plugin}_extends_navigation";
1249 if (function_exists($function)) {
1250 // This is the preferred function name as there is less chance of conflicts
1251 $function($this);
1252 } else if (function_exists($oldfunction)) {
1253 // We continue to support the old function name to ensure backwards compatibility
1254 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);
1255 $oldfunction($this);
1259 // Remove any empty root nodes
1260 foreach ($this->rootnodes as $node) {
1261 // Dont remove the home node
1262 if ($node->key !== 'home' && !$node->has_children()) {
1263 $node->remove();
1267 if (!$this->contains_active_node()) {
1268 $this->search_for_active_node();
1271 // If the user is not logged in modify the navigation structure as detailed
1272 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1273 if (!isloggedin()) {
1274 $activities = clone($this->rootnodes['site']->children);
1275 $this->rootnodes['site']->remove();
1276 $children = clone($this->children);
1277 $this->children = new navigation_node_collection();
1278 foreach ($activities as $child) {
1279 $this->children->add($child);
1281 foreach ($children as $child) {
1282 $this->children->add($child);
1285 return true;
1289 * Returns true if the current user is a parent of the user being currently viewed.
1291 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1292 * other user being viewed this function returns false.
1293 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1295 * @since 2.4
1296 * @return bool
1298 protected function current_user_is_parent_role() {
1299 global $USER, $DB;
1300 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1301 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1302 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1303 return false;
1305 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1306 return true;
1309 return false;
1313 * Returns true if courses should be shown within categories on the navigation.
1315 * @param bool $ismycourse Set to true if you are calculating this for a course.
1316 * @return bool
1318 protected function show_categories($ismycourse = false) {
1319 global $CFG, $DB;
1320 if ($ismycourse) {
1321 return $this->show_my_categories();
1323 if ($this->showcategories === null) {
1324 $show = false;
1325 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1326 $show = true;
1327 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1328 $show = true;
1330 $this->showcategories = $show;
1332 return $this->showcategories;
1336 * Returns true if we should show categories in the My Courses branch.
1337 * @return bool
1339 protected function show_my_categories() {
1340 global $CFG, $DB;
1341 if ($this->showmycategories === null) {
1342 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1344 return $this->showmycategories;
1348 * Loads the courses in Moodle into the navigation.
1350 * @global moodle_database $DB
1351 * @param string|array $categoryids An array containing categories to load courses
1352 * for, OR null to load courses for all categories.
1353 * @return array An array of navigation_nodes one for each course
1355 protected function load_all_courses($categoryids = null) {
1356 global $CFG, $DB, $SITE;
1358 // Work out the limit of courses.
1359 $limit = 20;
1360 if (!empty($CFG->navcourselimit)) {
1361 $limit = $CFG->navcourselimit;
1364 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1366 // If we are going to show all courses AND we are showing categories then
1367 // to save us repeated DB calls load all of the categories now
1368 if ($this->show_categories()) {
1369 $this->load_all_categories($toload);
1372 // Will be the return of our efforts
1373 $coursenodes = array();
1375 // Check if we need to show categories.
1376 if ($this->show_categories()) {
1377 // Hmmm we need to show categories... this is going to be painful.
1378 // We now need to fetch up to $limit courses for each category to
1379 // be displayed.
1380 if ($categoryids !== null) {
1381 if (!is_array($categoryids)) {
1382 $categoryids = array($categoryids);
1384 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1385 $categorywhere = 'WHERE cc.id '.$categorywhere;
1386 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1387 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1388 $categoryparams = array();
1389 } else {
1390 $categorywhere = '';
1391 $categoryparams = array();
1394 // First up we are going to get the categories that we are going to
1395 // need so that we can determine how best to load the courses from them.
1396 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1397 FROM {course_categories} cc
1398 LEFT JOIN {course} c ON c.category = cc.id
1399 {$categorywhere}
1400 GROUP BY cc.id";
1401 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1402 $fullfetch = array();
1403 $partfetch = array();
1404 foreach ($categories as $category) {
1405 if (!$this->can_add_more_courses_to_category($category->id)) {
1406 continue;
1408 if ($category->coursecount > $limit * 5) {
1409 $partfetch[] = $category->id;
1410 } else if ($category->coursecount > 0) {
1411 $fullfetch[] = $category->id;
1414 $categories->close();
1416 if (count($fullfetch)) {
1417 // First up fetch all of the courses in categories where we know that we are going to
1418 // need the majority of courses.
1419 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1420 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1421 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1422 FROM {course} c
1423 $ccjoin
1424 WHERE c.category {$categoryids}
1425 ORDER BY c.sortorder ASC";
1426 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1427 foreach ($coursesrs as $course) {
1428 if ($course->id == $SITE->id) {
1429 // This should not be necessary, frontpage is not in any category.
1430 continue;
1432 if (array_key_exists($course->id, $this->addedcourses)) {
1433 // It is probably better to not include the already loaded courses
1434 // directly in SQL because inequalities may confuse query optimisers
1435 // and may interfere with query caching.
1436 continue;
1438 if (!$this->can_add_more_courses_to_category($course->category)) {
1439 continue;
1441 context_instance_preload($course);
1442 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1443 continue;
1445 $coursenodes[$course->id] = $this->add_course($course);
1447 $coursesrs->close();
1450 if (count($partfetch)) {
1451 // Next we will work our way through the categories where we will likely only need a small
1452 // proportion of the courses.
1453 foreach ($partfetch as $categoryid) {
1454 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1455 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1456 FROM {course} c
1457 $ccjoin
1458 WHERE c.category = :categoryid
1459 ORDER BY c.sortorder ASC";
1460 $courseparams = array('categoryid' => $categoryid);
1461 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1462 foreach ($coursesrs as $course) {
1463 if ($course->id == $SITE->id) {
1464 // This should not be necessary, frontpage is not in any category.
1465 continue;
1467 if (array_key_exists($course->id, $this->addedcourses)) {
1468 // It is probably better to not include the already loaded courses
1469 // directly in SQL because inequalities may confuse query optimisers
1470 // and may interfere with query caching.
1471 // This also helps to respect expected $limit on repeated executions.
1472 continue;
1474 if (!$this->can_add_more_courses_to_category($course->category)) {
1475 break;
1477 context_instance_preload($course);
1478 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1479 continue;
1481 $coursenodes[$course->id] = $this->add_course($course);
1483 $coursesrs->close();
1486 } else {
1487 // Prepare the SQL to load the courses and their contexts
1488 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1489 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1490 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1491 FROM {course} c
1492 $ccjoin
1493 WHERE c.id {$courseids}
1494 ORDER BY c.sortorder ASC";
1495 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1496 foreach ($coursesrs as $course) {
1497 if ($course->id == $SITE->id) {
1498 // frotpage is not wanted here
1499 continue;
1501 if ($this->page->course && ($this->page->course->id == $course->id)) {
1502 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1503 continue;
1505 context_instance_preload($course);
1506 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1507 continue;
1509 $coursenodes[$course->id] = $this->add_course($course);
1510 if (count($coursenodes) >= $limit) {
1511 break;
1514 $coursesrs->close();
1517 return $coursenodes;
1521 * Returns true if more courses can be added to the provided category.
1523 * @param int|navigation_node|stdClass $category
1524 * @return bool
1526 protected function can_add_more_courses_to_category($category) {
1527 global $CFG;
1528 $limit = 20;
1529 if (!empty($CFG->navcourselimit)) {
1530 $limit = (int)$CFG->navcourselimit;
1532 if (is_numeric($category)) {
1533 if (!array_key_exists($category, $this->addedcategories)) {
1534 return true;
1536 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1537 } else if ($category instanceof navigation_node) {
1538 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1539 return false;
1541 $coursecount = count($category->children->type(self::TYPE_COURSE));
1542 } else if (is_object($category) && property_exists($category,'id')) {
1543 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1545 return ($coursecount <= $limit);
1549 * Loads all categories (top level or if an id is specified for that category)
1551 * @param int $categoryid The category id to load or null/0 to load all base level categories
1552 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1553 * as the requested category and any parent categories.
1554 * @return navigation_node|void returns a navigation node if a category has been loaded.
1556 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1557 global $CFG, $DB;
1559 // Check if this category has already been loaded
1560 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1561 return true;
1564 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1565 $sqlselect = "SELECT cc.*, $catcontextsql
1566 FROM {course_categories} cc
1567 JOIN {context} ctx ON cc.id = ctx.instanceid";
1568 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1569 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1570 $params = array();
1572 $categoriestoload = array();
1573 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1574 // We are going to load all categories regardless... prepare to fire
1575 // on the database server!
1576 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1577 // We are going to load all of the first level categories (categories without parents)
1578 $sqlwhere .= " AND cc.parent = 0";
1579 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1580 // The category itself has been loaded already so we just need to ensure its subcategories
1581 // have been loaded
1582 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1583 if ($showbasecategories) {
1584 // We need to include categories with parent = 0 as well
1585 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1586 } else {
1587 // All we need is categories that match the parent
1588 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1590 $params['categoryid'] = $categoryid;
1591 } else {
1592 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1593 // and load this category plus all its parents and subcategories
1594 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1595 $categoriestoload = explode('/', trim($category->path, '/'));
1596 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1597 // We are going to use select twice so double the params
1598 $params = array_merge($params, $params);
1599 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1600 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1603 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1604 $categories = array();
1605 foreach ($categoriesrs as $category) {
1606 // Preload the context.. we'll need it when adding the category in order
1607 // to format the category name.
1608 context_helper::preload_from_record($category);
1609 if (array_key_exists($category->id, $this->addedcategories)) {
1610 // Do nothing, its already been added.
1611 } else if ($category->parent == '0') {
1612 // This is a root category lets add it immediately
1613 $this->add_category($category, $this->rootnodes['courses']);
1614 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1615 // This categories parent has already been added we can add this immediately
1616 $this->add_category($category, $this->addedcategories[$category->parent]);
1617 } else {
1618 $categories[] = $category;
1621 $categoriesrs->close();
1623 // Now we have an array of categories we need to add them to the navigation.
1624 while (!empty($categories)) {
1625 $category = reset($categories);
1626 if (array_key_exists($category->id, $this->addedcategories)) {
1627 // Do nothing
1628 } else if ($category->parent == '0') {
1629 $this->add_category($category, $this->rootnodes['courses']);
1630 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1631 $this->add_category($category, $this->addedcategories[$category->parent]);
1632 } else {
1633 // This category isn't in the navigation and niether is it's parent (yet).
1634 // We need to go through the category path and add all of its components in order.
1635 $path = explode('/', trim($category->path, '/'));
1636 foreach ($path as $catid) {
1637 if (!array_key_exists($catid, $this->addedcategories)) {
1638 // This category isn't in the navigation yet so add it.
1639 $subcategory = $categories[$catid];
1640 if ($subcategory->parent == '0') {
1641 // Yay we have a root category - this likely means we will now be able
1642 // to add categories without problems.
1643 $this->add_category($subcategory, $this->rootnodes['courses']);
1644 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1645 // The parent is in the category (as we'd expect) so add it now.
1646 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1647 // Remove the category from the categories array.
1648 unset($categories[$catid]);
1649 } else {
1650 // We should never ever arrive here - if we have then there is a bigger
1651 // problem at hand.
1652 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1657 // Remove the category from the categories array now that we know it has been added.
1658 unset($categories[$category->id]);
1660 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1661 $this->allcategoriesloaded = true;
1663 // Check if there are any categories to load.
1664 if (count($categoriestoload) > 0) {
1665 $readytoloadcourses = array();
1666 foreach ($categoriestoload as $category) {
1667 if ($this->can_add_more_courses_to_category($category)) {
1668 $readytoloadcourses[] = $category;
1671 if (count($readytoloadcourses)) {
1672 $this->load_all_courses($readytoloadcourses);
1676 // Look for all categories which have been loaded
1677 if (!empty($this->addedcategories)) {
1678 $categoryids = array();
1679 foreach ($this->addedcategories as $category) {
1680 if ($this->can_add_more_courses_to_category($category)) {
1681 $categoryids[] = $category->key;
1684 if ($categoryids) {
1685 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1686 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1687 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1688 FROM {course_categories} cc
1689 JOIN {course} c ON c.category = cc.id
1690 WHERE cc.id {$categoriessql}
1691 GROUP BY cc.id
1692 HAVING COUNT(c.id) > :limit";
1693 $excessivecategories = $DB->get_records_sql($sql, $params);
1694 foreach ($categories as &$category) {
1695 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1696 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1697 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1705 * Adds a structured category to the navigation in the correct order/place
1707 * @param stdClass $category category to be added in navigation.
1708 * @param navigation_node $parent parent navigation node
1709 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1710 * @return void.
1712 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1713 if (array_key_exists($category->id, $this->addedcategories)) {
1714 return;
1716 $url = new moodle_url('/course/category.php', array('id' => $category->id));
1717 $context = context_coursecat::instance($category->id);
1718 $categoryname = format_string($category->name, true, array('context' => $context));
1719 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1720 if (empty($category->visible)) {
1721 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1722 $categorynode->hidden = true;
1723 } else {
1724 $categorynode->display = false;
1727 $this->addedcategories[$category->id] = $categorynode;
1731 * Loads the given course into the navigation
1733 * @param stdClass $course
1734 * @return navigation_node
1736 protected function load_course(stdClass $course) {
1737 global $SITE;
1738 if ($course->id == $SITE->id) {
1739 // This is always loaded during initialisation
1740 return $this->rootnodes['site'];
1741 } else if (array_key_exists($course->id, $this->addedcourses)) {
1742 // The course has already been loaded so return a reference
1743 return $this->addedcourses[$course->id];
1744 } else {
1745 // Add the course
1746 return $this->add_course($course);
1751 * Loads all of the courses section into the navigation.
1753 * This function calls method from current course format, see
1754 * {@link format_base::extend_course_navigation()}
1755 * If course module ($cm) is specified but course format failed to create the node,
1756 * the activity node is created anyway.
1758 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1760 * @param stdClass $course Database record for the course
1761 * @param navigation_node $coursenode The course node within the navigation
1762 * @param null|int $sectionnum If specified load the contents of section with this relative number
1763 * @param null|cm_info $cm If specified make sure that activity node is created (either
1764 * in containg section or by calling load_stealth_activity() )
1766 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1767 global $CFG, $SITE;
1768 require_once($CFG->dirroot.'/course/lib.php');
1769 if (isset($cm->sectionnum)) {
1770 $sectionnum = $cm->sectionnum;
1772 if ($sectionnum !== null) {
1773 $this->includesectionnum = $sectionnum;
1775 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1776 if (isset($cm->id)) {
1777 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1778 if (empty($activity)) {
1779 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1785 * Generates an array of sections and an array of activities for the given course.
1787 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1789 * @param stdClass $course
1790 * @return array Array($sections, $activities)
1792 protected function generate_sections_and_activities(stdClass $course) {
1793 global $CFG;
1794 require_once($CFG->dirroot.'/course/lib.php');
1796 $modinfo = get_fast_modinfo($course);
1797 $sections = $modinfo->get_section_info_all();
1799 // For course formats using 'numsections' trim the sections list
1800 $courseformatoptions = course_get_format($course)->get_format_options();
1801 if (isset($courseformatoptions['numsections'])) {
1802 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1805 $activities = array();
1807 foreach ($sections as $key => $section) {
1808 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1809 $sections[$key] = clone($section);
1810 unset($sections[$key]->summary);
1811 $sections[$key]->hasactivites = false;
1812 if (!array_key_exists($section->section, $modinfo->sections)) {
1813 continue;
1815 foreach ($modinfo->sections[$section->section] as $cmid) {
1816 $cm = $modinfo->cms[$cmid];
1817 if (!$cm->uservisible) {
1818 continue;
1820 $activity = new stdClass;
1821 $activity->id = $cm->id;
1822 $activity->course = $course->id;
1823 $activity->section = $section->section;
1824 $activity->name = $cm->name;
1825 $activity->icon = $cm->icon;
1826 $activity->iconcomponent = $cm->iconcomponent;
1827 $activity->hidden = (!$cm->visible);
1828 $activity->modname = $cm->modname;
1829 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1830 $activity->onclick = $cm->get_on_click();
1831 $url = $cm->get_url();
1832 if (!$url) {
1833 $activity->url = null;
1834 $activity->display = false;
1835 } else {
1836 $activity->url = $cm->get_url()->out();
1837 $activity->display = true;
1838 if (self::module_extends_navigation($cm->modname)) {
1839 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1842 $activities[$cmid] = $activity;
1843 if ($activity->display) {
1844 $sections[$key]->hasactivites = true;
1849 return array($sections, $activities);
1853 * Generically loads the course sections into the course's navigation.
1855 * @param stdClass $course
1856 * @param navigation_node $coursenode
1857 * @return array An array of course section nodes
1859 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1860 global $CFG, $DB, $USER, $SITE;
1861 require_once($CFG->dirroot.'/course/lib.php');
1863 list($sections, $activities) = $this->generate_sections_and_activities($course);
1865 $navigationsections = array();
1866 foreach ($sections as $sectionid => $section) {
1867 $section = clone($section);
1868 if ($course->id == $SITE->id) {
1869 $this->load_section_activities($coursenode, $section->section, $activities);
1870 } else {
1871 if (!$section->uservisible || (!$this->showemptysections &&
1872 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1873 continue;
1876 $sectionname = get_section_name($course, $section);
1877 $url = course_get_url($course, $section->section, array('navigation' => true));
1879 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1880 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1881 $sectionnode->hidden = (!$section->visible || !$section->available);
1882 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1883 $this->load_section_activities($sectionnode, $section->section, $activities);
1885 $section->sectionnode = $sectionnode;
1886 $navigationsections[$sectionid] = $section;
1889 return $navigationsections;
1893 * Loads all of the activities for a section into the navigation structure.
1895 * @param navigation_node $sectionnode
1896 * @param int $sectionnumber
1897 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1898 * @param stdClass $course The course object the section and activities relate to.
1899 * @return array Array of activity nodes
1901 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1902 global $CFG, $SITE;
1903 // A static counter for JS function naming
1904 static $legacyonclickcounter = 0;
1906 $activitynodes = array();
1907 if (empty($activities)) {
1908 return $activitynodes;
1911 if (!is_object($course)) {
1912 $activity = reset($activities);
1913 $courseid = $activity->course;
1914 } else {
1915 $courseid = $course->id;
1917 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1919 foreach ($activities as $activity) {
1920 if ($activity->section != $sectionnumber) {
1921 continue;
1923 if ($activity->icon) {
1924 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1925 } else {
1926 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1929 // Prepare the default name and url for the node
1930 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1931 $action = new moodle_url($activity->url);
1933 // Check if the onclick property is set (puke!)
1934 if (!empty($activity->onclick)) {
1935 // Increment the counter so that we have a unique number.
1936 $legacyonclickcounter++;
1937 // Generate the function name we will use
1938 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1939 $propogrationhandler = '';
1940 // Check if we need to cancel propogation. Remember inline onclick
1941 // events would return false if they wanted to prevent propogation and the
1942 // default action.
1943 if (strpos($activity->onclick, 'return false')) {
1944 $propogrationhandler = 'e.halt();';
1946 // Decode the onclick - it has already been encoded for display (puke)
1947 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
1948 // Build the JS function the click event will call
1949 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1950 $this->page->requires->js_init_code($jscode);
1951 // Override the default url with the new action link
1952 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1955 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1956 $activitynode->title(get_string('modulename', $activity->modname));
1957 $activitynode->hidden = $activity->hidden;
1958 $activitynode->display = $showactivities && $activity->display;
1959 $activitynode->nodetype = $activity->nodetype;
1960 $activitynodes[$activity->id] = $activitynode;
1963 return $activitynodes;
1966 * Loads a stealth module from unavailable section
1967 * @param navigation_node $coursenode
1968 * @param stdClass $modinfo
1969 * @return navigation_node or null if not accessible
1971 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1972 if (empty($modinfo->cms[$this->page->cm->id])) {
1973 return null;
1975 $cm = $modinfo->cms[$this->page->cm->id];
1976 if (!$cm->uservisible) {
1977 return null;
1979 if ($cm->icon) {
1980 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1981 } else {
1982 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1984 $url = $cm->get_url();
1985 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1986 $activitynode->title(get_string('modulename', $cm->modname));
1987 $activitynode->hidden = (!$cm->visible);
1988 if (!$url) {
1989 // Don't show activities that don't have links!
1990 $activitynode->display = false;
1991 } else if (self::module_extends_navigation($cm->modname)) {
1992 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1994 return $activitynode;
1997 * Loads the navigation structure for the given activity into the activities node.
1999 * This method utilises a callback within the modules lib.php file to load the
2000 * content specific to activity given.
2002 * The callback is a method: {modulename}_extend_navigation()
2003 * Examples:
2004 * * {@link forum_extend_navigation()}
2005 * * {@link workshop_extend_navigation()}
2007 * @param cm_info|stdClass $cm
2008 * @param stdClass $course
2009 * @param navigation_node $activity
2010 * @return bool
2012 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2013 global $CFG, $DB;
2015 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2016 if (!($cm instanceof cm_info)) {
2017 $modinfo = get_fast_modinfo($course);
2018 $cm = $modinfo->get_cm($cm->id);
2020 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2021 $activity->make_active();
2022 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2023 $function = $cm->modname.'_extend_navigation';
2025 if (file_exists($file)) {
2026 require_once($file);
2027 if (function_exists($function)) {
2028 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2029 $function($activity, $course, $activtyrecord, $cm);
2033 // Allow the active advanced grading method plugin to append module navigation
2034 $featuresfunc = $cm->modname.'_supports';
2035 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2036 require_once($CFG->dirroot.'/grade/grading/lib.php');
2037 $gradingman = get_grading_manager($cm->context, $cm->modname);
2038 $gradingman->extend_navigation($this, $activity);
2041 return $activity->has_children();
2044 * Loads user specific information into the navigation in the appropriate place.
2046 * If no user is provided the current user is assumed.
2048 * @param stdClass $user
2049 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2050 * @return bool
2052 protected function load_for_user($user=null, $forceforcontext=false) {
2053 global $DB, $CFG, $USER, $SITE;
2055 if ($user === null) {
2056 // We can't require login here but if the user isn't logged in we don't
2057 // want to show anything
2058 if (!isloggedin() || isguestuser()) {
2059 return false;
2061 $user = $USER;
2062 } else if (!is_object($user)) {
2063 // If the user is not an object then get them from the database
2064 $select = context_helper::get_preload_record_columns_sql('ctx');
2065 $sql = "SELECT u.*, $select
2066 FROM {user} u
2067 JOIN {context} ctx ON u.id = ctx.instanceid
2068 WHERE u.id = :userid AND
2069 ctx.contextlevel = :contextlevel";
2070 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2071 context_helper::preload_from_record($user);
2074 $iscurrentuser = ($user->id == $USER->id);
2076 $usercontext = context_user::instance($user->id);
2078 // Get the course set against the page, by default this will be the site
2079 $course = $this->page->course;
2080 $baseargs = array('id'=>$user->id);
2081 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2082 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2083 $baseargs['course'] = $course->id;
2084 $coursecontext = context_course::instance($course->id);
2085 $issitecourse = false;
2086 } else {
2087 // Load all categories and get the context for the system
2088 $coursecontext = context_system::instance();
2089 $issitecourse = true;
2092 // Create a node to add user information under.
2093 if ($iscurrentuser && !$forceforcontext) {
2094 // If it's the current user the information will go under the profile root node
2095 $usernode = $this->rootnodes['myprofile'];
2096 $course = get_site();
2097 $coursecontext = context_course::instance($course->id);
2098 $issitecourse = true;
2099 } else {
2100 if (!$issitecourse) {
2101 // Not the current user so add it to the participants node for the current course
2102 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2103 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2104 } else {
2105 // This is the site so add a users node to the root branch
2106 $usersnode = $this->rootnodes['users'];
2107 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2108 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2110 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2112 if (!$usersnode) {
2113 // We should NEVER get here, if the course hasn't been populated
2114 // with a participants node then the navigaiton either wasn't generated
2115 // for it (you are missing a require_login or set_context call) or
2116 // you don't have access.... in the interests of no leaking informatin
2117 // we simply quit...
2118 return false;
2120 // Add a branch for the current user
2121 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2122 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2124 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2125 $usernode->make_active();
2129 // If the user is the current user or has permission to view the details of the requested
2130 // user than add a view profile link.
2131 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2132 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2133 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2134 } else {
2135 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2139 if (!empty($CFG->navadduserpostslinks)) {
2140 // Add nodes for forum posts and discussions if the user can view either or both
2141 // There are no capability checks here as the content of the page is based
2142 // purely on the forums the current user has access too.
2143 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2144 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2145 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2148 // Add blog nodes
2149 if (!empty($CFG->enableblogs)) {
2150 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2151 require_once($CFG->dirroot.'/blog/lib.php');
2152 // Get all options for the user
2153 $options = blog_get_options_for_user($user);
2154 $this->cache->set('userblogoptions'.$user->id, $options);
2155 } else {
2156 $options = $this->cache->{'userblogoptions'.$user->id};
2159 if (count($options) > 0) {
2160 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2161 foreach ($options as $type => $option) {
2162 if ($type == "rss") {
2163 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2164 } else {
2165 $blogs->add($option['string'], $option['link']);
2171 if (!empty($CFG->messaging)) {
2172 $messageargs = null;
2173 if ($USER->id != $user->id) {
2174 $messageargs = array('user1' => $user->id);
2176 $url = new moodle_url('/message/index.php',$messageargs);
2177 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2180 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
2181 $url = new moodle_url('/user/files.php');
2182 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2185 // Add a node to view the users notes if permitted
2186 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2187 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2188 if ($coursecontext->instanceid) {
2189 $url->param('course', $coursecontext->instanceid);
2191 $usernode->add(get_string('notes', 'notes'), $url);
2194 // Add reports node
2195 $reporttab = $usernode->add(get_string('activityreports'));
2196 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2197 foreach ($reports as $reportfunction) {
2198 $reportfunction($reporttab, $user, $course);
2200 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
2201 if ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext)) {
2202 // Add grade hardcoded grade report if necessary
2203 $gradeaccess = false;
2204 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2205 //ok - can view all course grades
2206 $gradeaccess = true;
2207 } else if ($course->showgrades) {
2208 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
2209 //ok - can view own grades
2210 $gradeaccess = true;
2211 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
2212 // ok - can view grades of this user - parent most probably
2213 $gradeaccess = true;
2214 } else if ($anyreport) {
2215 // ok - can view grades of this user - parent most probably
2216 $gradeaccess = true;
2219 if ($gradeaccess) {
2220 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id, 'user'=>$usercontext->instanceid)));
2223 // Check the number of nodes in the report node... if there are none remove the node
2224 $reporttab->trim_if_empty();
2226 // If the user is the current user add the repositories for the current user
2227 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2228 if ($iscurrentuser) {
2229 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2230 require_once($CFG->dirroot . '/repository/lib.php');
2231 $editabletypes = repository::get_editable_types($usercontext);
2232 $haseditabletypes = !empty($editabletypes);
2233 unset($editabletypes);
2234 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2235 } else {
2236 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2238 if ($haseditabletypes) {
2239 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2241 } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2243 // Add view grade report is permitted
2244 $reports = get_plugin_list('gradereport');
2245 arsort($reports); // user is last, we want to test it first
2247 $userscourses = enrol_get_users_courses($user->id);
2248 $userscoursesnode = $usernode->add(get_string('courses'));
2250 foreach ($userscourses as $usercourse) {
2251 $usercoursecontext = context_course::instance($usercourse->id);
2252 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2253 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2255 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2256 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2257 foreach ($reports as $plugin => $plugindir) {
2258 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2259 //stop when the first visible plugin is found
2260 $gradeavailable = true;
2261 break;
2266 if ($gradeavailable) {
2267 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2268 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2271 // Add a node to view the users notes if permitted
2272 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2273 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2274 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2277 if (can_access_course($usercourse, $user->id)) {
2278 $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', ''));
2281 $reporttab = $usercoursenode->add(get_string('activityreports'));
2283 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2284 foreach ($reports as $reportfunction) {
2285 $reportfunction($reporttab, $user, $usercourse);
2288 $reporttab->trim_if_empty();
2291 return true;
2295 * This method simply checks to see if a given module can extend the navigation.
2297 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2299 * @param string $modname
2300 * @return bool
2302 public static function module_extends_navigation($modname) {
2303 global $CFG;
2304 static $extendingmodules = array();
2305 if (!array_key_exists($modname, $extendingmodules)) {
2306 $extendingmodules[$modname] = false;
2307 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2308 if (file_exists($file)) {
2309 $function = $modname.'_extend_navigation';
2310 require_once($file);
2311 $extendingmodules[$modname] = (function_exists($function));
2314 return $extendingmodules[$modname];
2317 * Extends the navigation for the given user.
2319 * @param stdClass $user A user from the database
2321 public function extend_for_user($user) {
2322 $this->extendforuser[] = $user;
2326 * Returns all of the users the navigation is being extended for
2328 * @return array An array of extending users.
2330 public function get_extending_users() {
2331 return $this->extendforuser;
2334 * Adds the given course to the navigation structure.
2336 * @param stdClass $course
2337 * @param bool $forcegeneric
2338 * @param bool $ismycourse
2339 * @return navigation_node
2341 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2342 global $CFG, $SITE;
2344 // We found the course... we can return it now :)
2345 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2346 return $this->addedcourses[$course->id];
2349 $coursecontext = context_course::instance($course->id);
2351 if ($course->id != $SITE->id && !$course->visible) {
2352 if (is_role_switched($course->id)) {
2353 // user has to be able to access course in order to switch, let's skip the visibility test here
2354 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2355 return false;
2359 $issite = ($course->id == $SITE->id);
2360 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2362 if ($issite) {
2363 $parent = $this;
2364 $url = null;
2365 if (empty($CFG->usesitenameforsitepages)) {
2366 $shortname = get_string('sitepages');
2368 } else if ($coursetype == self::COURSE_CURRENT) {
2369 $parent = $this->rootnodes['currentcourse'];
2370 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2371 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2372 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2373 // Nothing to do here the above statement set $parent to the category within mycourses.
2374 } else {
2375 $parent = $this->rootnodes['mycourses'];
2377 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2378 } else {
2379 $parent = $this->rootnodes['courses'];
2380 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2381 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2382 if (!$this->is_category_fully_loaded($course->category)) {
2383 // We need to load the category structure for this course
2384 $this->load_all_categories($course->category, false);
2386 if (array_key_exists($course->category, $this->addedcategories)) {
2387 $parent = $this->addedcategories[$course->category];
2388 // This could lead to the course being created so we should check whether it is the case again
2389 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2390 return $this->addedcourses[$course->id];
2396 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
2397 $coursenode->nodetype = self::NODETYPE_BRANCH;
2398 $coursenode->hidden = (!$course->visible);
2399 $coursenode->title(format_string($course->fullname, true, array('context' => context_course::instance($course->id))));
2400 if (!$forcegeneric) {
2401 $this->addedcourses[$course->id] = $coursenode;
2404 return $coursenode;
2408 * Returns true if the category has already been loaded as have any child categories
2410 * @param int $categoryid
2411 * @return bool
2413 protected function is_category_fully_loaded($categoryid) {
2414 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2418 * Adds essential course nodes to the navigation for the given course.
2420 * This method adds nodes such as reports, blogs and participants
2422 * @param navigation_node $coursenode
2423 * @param stdClass $course
2424 * @return bool returns true on successful addition of a node.
2426 public function add_course_essentials($coursenode, stdClass $course) {
2427 global $CFG, $SITE;
2429 if ($course->id == $SITE->id) {
2430 return $this->add_front_page_course_essentials($coursenode, $course);
2433 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2434 return true;
2437 //Participants
2438 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2439 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2440 $currentgroup = groups_get_course_group($course, true);
2441 if ($course->id == $SITE->id) {
2442 $filtervar = 'courseid';
2443 $filterselect = '';
2444 } else if ($course->id && !$currentgroup) {
2445 $filtervar = 'courseid';
2446 $filterselect = $course->id;
2447 } else {
2448 $filtervar = 'groupid';
2449 $filterselect = $currentgroup;
2451 $filterselect = clean_param($filterselect, PARAM_INT);
2452 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2453 and has_capability('moodle/blog:view', context_system::instance())) {
2454 $blogsurls = new moodle_url('/blog/index.php', array($filtervar => $filterselect));
2455 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2457 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2458 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2460 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2461 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2464 // View course reports
2465 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2466 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2467 $coursereports = get_plugin_list('coursereport'); // deprecated
2468 foreach ($coursereports as $report=>$dir) {
2469 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2470 if (file_exists($libfile)) {
2471 require_once($libfile);
2472 $reportfunction = $report.'_report_extend_navigation';
2473 if (function_exists($report.'_report_extend_navigation')) {
2474 $reportfunction($reportnav, $course, $this->page->context);
2479 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2480 foreach ($reports as $reportfunction) {
2481 $reportfunction($reportnav, $course, $this->page->context);
2484 return true;
2487 * This generates the structure of the course that won't be generated when
2488 * the modules and sections are added.
2490 * Things such as the reports branch, the participants branch, blogs... get
2491 * added to the course node by this method.
2493 * @param navigation_node $coursenode
2494 * @param stdClass $course
2495 * @return bool True for successfull generation
2497 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2498 global $CFG;
2500 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2501 return true;
2504 // Hidden node that we use to determine if the front page navigation is loaded.
2505 // This required as there are not other guaranteed nodes that may be loaded.
2506 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2508 //Participants
2509 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2510 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2513 $filterselect = 0;
2515 // Blogs
2516 if (!empty($CFG->enableblogs)
2517 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2518 and has_capability('moodle/blog:view', context_system::instance())) {
2519 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2520 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2523 // Notes
2524 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2525 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2528 // Tags
2529 if (!empty($CFG->usetags) && isloggedin()) {
2530 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2533 if (isloggedin()) {
2534 // Calendar
2535 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2536 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2539 // View course reports
2540 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2541 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2542 $coursereports = get_plugin_list('coursereport'); // deprecated
2543 foreach ($coursereports as $report=>$dir) {
2544 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2545 if (file_exists($libfile)) {
2546 require_once($libfile);
2547 $reportfunction = $report.'_report_extend_navigation';
2548 if (function_exists($report.'_report_extend_navigation')) {
2549 $reportfunction($reportnav, $course, $this->page->context);
2554 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2555 foreach ($reports as $reportfunction) {
2556 $reportfunction($reportnav, $course, $this->page->context);
2559 return true;
2563 * Clears the navigation cache
2565 public function clear_cache() {
2566 $this->cache->clear();
2570 * Sets an expansion limit for the navigation
2572 * The expansion limit is used to prevent the display of content that has a type
2573 * greater than the provided $type.
2575 * Can be used to ensure things such as activities or activity content don't get
2576 * shown on the navigation.
2577 * They are still generated in order to ensure the navbar still makes sense.
2579 * @param int $type One of navigation_node::TYPE_*
2580 * @return bool true when complete.
2582 public function set_expansion_limit($type) {
2583 global $SITE;
2584 $nodes = $this->find_all_of_type($type);
2585 foreach ($nodes as $node) {
2586 // We need to generate the full site node
2587 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2588 continue;
2590 foreach ($node->children as $child) {
2591 // We still want to show course reports and participants containers
2592 // or there will be navigation missing.
2593 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2594 continue;
2596 $child->hide();
2599 return true;
2602 * Attempts to get the navigation with the given key from this nodes children.
2604 * This function only looks at this nodes children, it does NOT look recursivily.
2605 * If the node can't be found then false is returned.
2607 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2609 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2610 * may be of more use to you.
2612 * @param string|int $key The key of the node you wish to receive.
2613 * @param int $type One of navigation_node::TYPE_*
2614 * @return navigation_node|false
2616 public function get($key, $type = null) {
2617 if (!$this->initialised) {
2618 $this->initialise();
2620 return parent::get($key, $type);
2624 * Searches this nodes children and their children to find a navigation node
2625 * with the matching key and type.
2627 * This method is recursive and searches children so until either a node is
2628 * found or there are no more nodes to search.
2630 * If you know that the node being searched for is a child of this node
2631 * then use the {@link global_navigation::get()} method instead.
2633 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2634 * may be of more use to you.
2636 * @param string|int $key The key of the node you wish to receive.
2637 * @param int $type One of navigation_node::TYPE_*
2638 * @return navigation_node|false
2640 public function find($key, $type) {
2641 if (!$this->initialised) {
2642 $this->initialise();
2644 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2645 return $this->rootnodes[$key];
2647 return parent::find($key, $type);
2651 * They've expanded the 'my courses' branch.
2653 protected function load_courses_enrolled() {
2654 global $CFG, $DB;
2655 $sortorder = 'visible DESC';
2656 // Prevent undefined $CFG->navsortmycoursessort errors.
2657 if (empty($CFG->navsortmycoursessort)) {
2658 $CFG->navsortmycoursessort = 'sortorder';
2660 // Append the chosen sortorder.
2661 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2662 $courses = enrol_get_my_courses(null, $sortorder);
2663 if (count($courses) && $this->show_my_categories()) {
2664 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2665 // In order to make sure we load everything required we must first find the categories that are not
2666 // base categories and work out the bottom category in thier path.
2667 $categoryids = array();
2668 foreach ($courses as $course) {
2669 $categoryids[] = $course->category;
2671 $categoryids = array_unique($categoryids);
2672 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2673 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2674 foreach ($categories as $category) {
2675 $bits = explode('/', trim($category->path,'/'));
2676 $categoryids[] = array_shift($bits);
2678 $categoryids = array_unique($categoryids);
2679 $categories->close();
2681 // Now we load the base categories.
2682 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2683 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2684 foreach ($categories as $category) {
2685 $this->add_category($category, $this->rootnodes['mycourses']);
2687 $categories->close();
2688 } else {
2689 foreach ($courses as $course) {
2690 $this->add_course($course, false, self::COURSE_MY);
2697 * The global navigation class used especially for AJAX requests.
2699 * The primary methods that are used in the global navigation class have been overriden
2700 * to ensure that only the relevant branch is generated at the root of the tree.
2701 * This can be done because AJAX is only used when the backwards structure for the
2702 * requested branch exists.
2703 * This has been done only because it shortens the amounts of information that is generated
2704 * which of course will speed up the response time.. because no one likes laggy AJAX.
2706 * @package core
2707 * @category navigation
2708 * @copyright 2009 Sam Hemelryk
2709 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2711 class global_navigation_for_ajax extends global_navigation {
2713 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2714 protected $branchtype;
2716 /** @var int the instance id */
2717 protected $instanceid;
2719 /** @var array Holds an array of expandable nodes */
2720 protected $expandable = array();
2723 * Constructs the navigation for use in an AJAX request
2725 * @param moodle_page $page moodle_page object
2726 * @param int $branchtype
2727 * @param int $id
2729 public function __construct($page, $branchtype, $id) {
2730 $this->page = $page;
2731 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2732 $this->children = new navigation_node_collection();
2733 $this->branchtype = $branchtype;
2734 $this->instanceid = $id;
2735 $this->initialise();
2738 * Initialise the navigation given the type and id for the branch to expand.
2740 * @return array An array of the expandable nodes
2742 public function initialise() {
2743 global $DB, $SITE;
2745 if ($this->initialised || during_initial_install()) {
2746 return $this->expandable;
2748 $this->initialised = true;
2750 $this->rootnodes = array();
2751 $this->rootnodes['site'] = $this->add_course($SITE);
2752 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2753 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2755 // Branchtype will be one of navigation_node::TYPE_*
2756 switch ($this->branchtype) {
2757 case 0:
2758 if ($this->instanceid === 'mycourses') {
2759 $this->load_courses_enrolled();
2760 } else if ($this->instanceid === 'courses') {
2761 $this->load_courses_other();
2763 break;
2764 case self::TYPE_CATEGORY :
2765 $this->load_category($this->instanceid);
2766 break;
2767 case self::TYPE_MY_CATEGORY :
2768 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2769 break;
2770 case self::TYPE_COURSE :
2771 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2772 require_course_login($course, true, null, false, true);
2773 $this->page->set_context(context_course::instance($course->id));
2774 $coursenode = $this->add_course($course);
2775 $this->add_course_essentials($coursenode, $course);
2776 $this->load_course_sections($course, $coursenode);
2777 break;
2778 case self::TYPE_SECTION :
2779 $sql = 'SELECT c.*, cs.section AS sectionnumber
2780 FROM {course} c
2781 LEFT JOIN {course_sections} cs ON cs.course = c.id
2782 WHERE cs.id = ?';
2783 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2784 require_course_login($course, true, null, false, true);
2785 $this->page->set_context(context_course::instance($course->id));
2786 $coursenode = $this->add_course($course);
2787 $this->add_course_essentials($coursenode, $course);
2788 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2789 break;
2790 case self::TYPE_ACTIVITY :
2791 $sql = "SELECT c.*
2792 FROM {course} c
2793 JOIN {course_modules} cm ON cm.course = c.id
2794 WHERE cm.id = :cmid";
2795 $params = array('cmid' => $this->instanceid);
2796 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2797 $modinfo = get_fast_modinfo($course);
2798 $cm = $modinfo->get_cm($this->instanceid);
2799 require_course_login($course, true, $cm, false, true);
2800 $this->page->set_context(context_module::instance($cm->id));
2801 $coursenode = $this->load_course($course);
2802 if ($course->id != $SITE->id) {
2803 $this->load_course_sections($course, $coursenode, null, $cm);
2805 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2806 break;
2807 default:
2808 throw new Exception('Unknown type');
2809 return $this->expandable;
2812 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2813 $this->load_for_user(null, true);
2816 $this->find_expandable($this->expandable);
2817 return $this->expandable;
2821 * They've expanded the general 'courses' branch.
2823 protected function load_courses_other() {
2824 $this->load_all_courses();
2828 * Loads a single category into the AJAX navigation.
2830 * This function is special in that it doesn't concern itself with the parent of
2831 * the requested category or its siblings.
2832 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2833 * request that.
2835 * @global moodle_database $DB
2836 * @param int $categoryid id of category to load in navigation.
2837 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2838 * @return void.
2840 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2841 global $CFG, $DB;
2843 $limit = 20;
2844 if (!empty($CFG->navcourselimit)) {
2845 $limit = (int)$CFG->navcourselimit;
2848 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2849 $sql = "SELECT cc.*, $catcontextsql
2850 FROM {course_categories} cc
2851 JOIN {context} ctx ON cc.id = ctx.instanceid
2852 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2853 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2854 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2855 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2856 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2857 $categorylist = array();
2858 $subcategories = array();
2859 $basecategory = null;
2860 foreach ($categories as $category) {
2861 $categorylist[] = $category->id;
2862 context_helper::preload_from_record($category);
2863 if ($category->id == $categoryid) {
2864 $this->add_category($category, $this, $nodetype);
2865 $basecategory = $this->addedcategories[$category->id];
2866 } else {
2867 $subcategories[] = $category;
2870 $categories->close();
2872 if (!is_null($basecategory)) {
2873 foreach ($subcategories as $category) {
2874 $this->add_category($category, $basecategory, $nodetype);
2878 // If category is shown in MyHome then only show enrolled courses, else show all courses.
2879 if ($nodetype === self::TYPE_MY_CATEGORY) {
2880 $courses = enrol_get_my_courses();
2881 foreach ($courses as $course) {
2882 // Add course if it's in category.
2883 if (in_array($course->category, $categorylist)) {
2884 $this->add_course($course, true, self::COURSE_MY);
2887 } else {
2888 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2889 foreach ($courses as $course) {
2890 $this->add_course($course);
2892 $courses->close();
2897 * Returns an array of expandable nodes
2898 * @return array
2900 public function get_expandable() {
2901 return $this->expandable;
2906 * Navbar class
2908 * This class is used to manage the navbar, which is initialised from the navigation
2909 * object held by PAGE
2911 * @package core
2912 * @category navigation
2913 * @copyright 2009 Sam Hemelryk
2914 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2916 class navbar extends navigation_node {
2917 /** @var bool A switch for whether the navbar is initialised or not */
2918 protected $initialised = false;
2919 /** @var mixed keys used to reference the nodes on the navbar */
2920 protected $keys = array();
2921 /** @var null|string content of the navbar */
2922 protected $content = null;
2923 /** @var moodle_page object the moodle page that this navbar belongs to */
2924 protected $page;
2925 /** @var bool A switch for whether to ignore the active navigation information */
2926 protected $ignoreactive = false;
2927 /** @var bool A switch to let us know if we are in the middle of an install */
2928 protected $duringinstall = false;
2929 /** @var bool A switch for whether the navbar has items */
2930 protected $hasitems = false;
2931 /** @var array An array of navigation nodes for the navbar */
2932 protected $items;
2933 /** @var array An array of child node objects */
2934 public $children = array();
2935 /** @var bool A switch for whether we want to include the root node in the navbar */
2936 public $includesettingsbase = false;
2938 * The almighty constructor
2940 * @param moodle_page $page
2942 public function __construct(moodle_page $page) {
2943 global $CFG;
2944 if (during_initial_install()) {
2945 $this->duringinstall = true;
2946 return false;
2948 $this->page = $page;
2949 $this->text = get_string('home');
2950 $this->shorttext = get_string('home');
2951 $this->action = new moodle_url($CFG->wwwroot);
2952 $this->nodetype = self::NODETYPE_BRANCH;
2953 $this->type = self::TYPE_SYSTEM;
2957 * Quick check to see if the navbar will have items in.
2959 * @return bool Returns true if the navbar will have items, false otherwise
2961 public function has_items() {
2962 if ($this->duringinstall) {
2963 return false;
2964 } else if ($this->hasitems !== false) {
2965 return true;
2967 $this->page->navigation->initialise($this->page);
2969 $activenodefound = ($this->page->navigation->contains_active_node() ||
2970 $this->page->settingsnav->contains_active_node());
2972 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2973 $this->hasitems = $outcome;
2974 return $outcome;
2978 * Turn on/off ignore active
2980 * @param bool $setting
2982 public function ignore_active($setting=true) {
2983 $this->ignoreactive = ($setting);
2987 * Gets a navigation node
2989 * @param string|int $key for referencing the navbar nodes
2990 * @param int $type navigation_node::TYPE_*
2991 * @return navigation_node|bool
2993 public function get($key, $type = null) {
2994 foreach ($this->children as &$child) {
2995 if ($child->key === $key && ($type == null || $type == $child->type)) {
2996 return $child;
2999 return false;
3002 * Returns an array of navigation_node's that make up the navbar.
3004 * @return array
3006 public function get_items() {
3007 $items = array();
3008 // Make sure that navigation is initialised
3009 if (!$this->has_items()) {
3010 return $items;
3012 if ($this->items !== null) {
3013 return $this->items;
3016 if (count($this->children) > 0) {
3017 // Add the custom children
3018 $items = array_reverse($this->children);
3021 $navigationactivenode = $this->page->navigation->find_active_node();
3022 $settingsactivenode = $this->page->settingsnav->find_active_node();
3024 // Check if navigation contains the active node
3025 if (!$this->ignoreactive) {
3027 if ($navigationactivenode && $settingsactivenode) {
3028 // Parse a combined navigation tree
3029 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3030 if (!$settingsactivenode->mainnavonly) {
3031 $items[] = $settingsactivenode;
3033 $settingsactivenode = $settingsactivenode->parent;
3035 if (!$this->includesettingsbase) {
3036 // Removes the first node from the settings (root node) from the list
3037 array_pop($items);
3039 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3040 if (!$navigationactivenode->mainnavonly) {
3041 $items[] = $navigationactivenode;
3043 $navigationactivenode = $navigationactivenode->parent;
3045 } else if ($navigationactivenode) {
3046 // Parse the navigation tree to get the active node
3047 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3048 if (!$navigationactivenode->mainnavonly) {
3049 $items[] = $navigationactivenode;
3051 $navigationactivenode = $navigationactivenode->parent;
3053 } else if ($settingsactivenode) {
3054 // Parse the settings navigation to get the active node
3055 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3056 if (!$settingsactivenode->mainnavonly) {
3057 $items[] = $settingsactivenode;
3059 $settingsactivenode = $settingsactivenode->parent;
3064 $items[] = new navigation_node(array(
3065 'text'=>$this->page->navigation->text,
3066 'shorttext'=>$this->page->navigation->shorttext,
3067 'key'=>$this->page->navigation->key,
3068 'action'=>$this->page->navigation->action
3071 $this->items = array_reverse($items);
3072 return $this->items;
3076 * Add a new navigation_node to the navbar, overrides parent::add
3078 * This function overrides {@link navigation_node::add()} so that we can change
3079 * the way nodes get added to allow us to simply call add and have the node added to the
3080 * end of the navbar
3082 * @param string $text
3083 * @param string|moodle_url|action_link $action An action to associate with this node.
3084 * @param int $type One of navigation_node::TYPE_*
3085 * @param string $shorttext
3086 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3087 * @param pix_icon $icon An optional icon to use for this node.
3088 * @return navigation_node
3090 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3091 if ($this->content !== null) {
3092 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3095 // Properties array used when creating the new navigation node
3096 $itemarray = array(
3097 'text' => $text,
3098 'type' => $type
3100 // Set the action if one was provided
3101 if ($action!==null) {
3102 $itemarray['action'] = $action;
3104 // Set the shorttext if one was provided
3105 if ($shorttext!==null) {
3106 $itemarray['shorttext'] = $shorttext;
3108 // Set the icon if one was provided
3109 if ($icon!==null) {
3110 $itemarray['icon'] = $icon;
3112 // Default the key to the number of children if not provided
3113 if ($key === null) {
3114 $key = count($this->children);
3116 // Set the key
3117 $itemarray['key'] = $key;
3118 // Set the parent to this node
3119 $itemarray['parent'] = $this;
3120 // Add the child using the navigation_node_collections add method
3121 $this->children[] = new navigation_node($itemarray);
3122 return $this;
3127 * Class used to manage the settings option for the current page
3129 * This class is used to manage the settings options in a tree format (recursively)
3130 * and was created initially for use with the settings blocks.
3132 * @package core
3133 * @category navigation
3134 * @copyright 2009 Sam Hemelryk
3135 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3137 class settings_navigation extends navigation_node {
3138 /** @var stdClass the current context */
3139 protected $context;
3140 /** @var moodle_page the moodle page that the navigation belongs to */
3141 protected $page;
3142 /** @var string contains administration section navigation_nodes */
3143 protected $adminsection;
3144 /** @var bool A switch to see if the navigation node is initialised */
3145 protected $initialised = false;
3146 /** @var array An array of users that the nodes can extend for. */
3147 protected $userstoextendfor = array();
3148 /** @var navigation_cache **/
3149 protected $cache;
3152 * Sets up the object with basic settings and preparse it for use
3154 * @param moodle_page $page
3156 public function __construct(moodle_page &$page) {
3157 if (during_initial_install()) {
3158 return false;
3160 $this->page = $page;
3161 // Initialise the main navigation. It is most important that this is done
3162 // before we try anything
3163 $this->page->navigation->initialise();
3164 // Initialise the navigation cache
3165 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3166 $this->children = new navigation_node_collection();
3169 * Initialise the settings navigation based on the current context
3171 * This function initialises the settings navigation tree for a given context
3172 * by calling supporting functions to generate major parts of the tree.
3175 public function initialise() {
3176 global $DB, $SESSION, $SITE;
3178 if (during_initial_install()) {
3179 return false;
3180 } else if ($this->initialised) {
3181 return true;
3183 $this->id = 'settingsnav';
3184 $this->context = $this->page->context;
3186 $context = $this->context;
3187 if ($context->contextlevel == CONTEXT_BLOCK) {
3188 $this->load_block_settings();
3189 $context = $context->get_parent_context();
3192 switch ($context->contextlevel) {
3193 case CONTEXT_SYSTEM:
3194 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3195 $this->load_front_page_settings(($context->id == $this->context->id));
3197 break;
3198 case CONTEXT_COURSECAT:
3199 $this->load_category_settings();
3200 break;
3201 case CONTEXT_COURSE:
3202 if ($this->page->course->id != $SITE->id) {
3203 $this->load_course_settings(($context->id == $this->context->id));
3204 } else {
3205 $this->load_front_page_settings(($context->id == $this->context->id));
3207 break;
3208 case CONTEXT_MODULE:
3209 $this->load_module_settings();
3210 $this->load_course_settings();
3211 break;
3212 case CONTEXT_USER:
3213 if ($this->page->course->id != $SITE->id) {
3214 $this->load_course_settings();
3216 break;
3219 $settings = $this->load_user_settings($this->page->course->id);
3221 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
3222 $admin = $this->load_administration_settings();
3223 $SESSION->load_navigation_admin = ($admin->has_children());
3224 } else {
3225 $admin = false;
3228 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
3229 $admin->force_open();
3230 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
3231 $settings->force_open();
3234 // Check if the user is currently logged in as another user
3235 if (session_is_loggedinas()) {
3236 // Get the actual user, we need this so we can display an informative return link
3237 $realuser = session_get_realuser();
3238 // Add the informative return to original user link
3239 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3240 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3243 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3244 $this->load_local_plugin_settings();
3246 foreach ($this->children as $key=>$node) {
3247 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3248 $node->remove();
3251 $this->initialised = true;
3254 * Override the parent function so that we can add preceeding hr's and set a
3255 * root node class against all first level element
3257 * It does this by first calling the parent's add method {@link navigation_node::add()}
3258 * and then proceeds to use the key to set class and hr
3260 * @param string $text text to be used for the link.
3261 * @param string|moodle_url $url url for the new node
3262 * @param int $type the type of node navigation_node::TYPE_*
3263 * @param string $shorttext
3264 * @param string|int $key a key to access the node by.
3265 * @param pix_icon $icon An icon that appears next to the node.
3266 * @return navigation_node with the new node added to it.
3268 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3269 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3270 $node->add_class('root_node');
3271 return $node;
3275 * This function allows the user to add something to the start of the settings
3276 * navigation, which means it will be at the top of the settings navigation block
3278 * @param string $text text to be used for the link.
3279 * @param string|moodle_url $url url for the new node
3280 * @param int $type the type of node navigation_node::TYPE_*
3281 * @param string $shorttext
3282 * @param string|int $key a key to access the node by.
3283 * @param pix_icon $icon An icon that appears next to the node.
3284 * @return navigation_node $node with the new node added to it.
3286 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3287 $children = $this->children;
3288 $childrenclass = get_class($children);
3289 $this->children = new $childrenclass;
3290 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3291 foreach ($children as $child) {
3292 $this->children->add($child);
3294 return $node;
3297 * Load the site administration tree
3299 * This function loads the site administration tree by using the lib/adminlib library functions
3301 * @param navigation_node $referencebranch A reference to a branch in the settings
3302 * navigation tree
3303 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3304 * tree and start at the beginning
3305 * @return mixed A key to access the admin tree by
3307 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3308 global $CFG;
3310 // Check if we are just starting to generate this navigation.
3311 if ($referencebranch === null) {
3313 // Require the admin lib then get an admin structure
3314 if (!function_exists('admin_get_root')) {
3315 require_once($CFG->dirroot.'/lib/adminlib.php');
3317 $adminroot = admin_get_root(false, false);
3318 // This is the active section identifier
3319 $this->adminsection = $this->page->url->param('section');
3321 // Disable the navigation from automatically finding the active node
3322 navigation_node::$autofindactive = false;
3323 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
3324 foreach ($adminroot->children as $adminbranch) {
3325 $this->load_administration_settings($referencebranch, $adminbranch);
3327 navigation_node::$autofindactive = true;
3329 // Use the admin structure to locate the active page
3330 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3331 $currentnode = $this;
3332 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3333 $currentnode = $currentnode->get($pathkey);
3335 if ($currentnode) {
3336 $currentnode->make_active();
3338 } else {
3339 $this->scan_for_active_node($referencebranch);
3341 return $referencebranch;
3342 } else if ($adminbranch->check_access()) {
3343 // We have a reference branch that we can access and is not hidden `hurrah`
3344 // Now we need to display it and any children it may have
3345 $url = null;
3346 $icon = null;
3347 if ($adminbranch instanceof admin_settingpage) {
3348 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3349 } else if ($adminbranch instanceof admin_externalpage) {
3350 $url = $adminbranch->url;
3351 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3352 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3355 // Add the branch
3356 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3358 if ($adminbranch->is_hidden()) {
3359 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3360 $reference->add_class('hidden');
3361 } else {
3362 $reference->display = false;
3366 // Check if we are generating the admin notifications and whether notificiations exist
3367 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3368 $reference->add_class('criticalnotification');
3370 // Check if this branch has children
3371 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3372 foreach ($adminbranch->children as $branch) {
3373 // Generate the child branches as well now using this branch as the reference
3374 $this->load_administration_settings($reference, $branch);
3376 } else {
3377 $reference->icon = new pix_icon('i/settings', '');
3383 * This function recursivily scans nodes until it finds the active node or there
3384 * are no more nodes.
3385 * @param navigation_node $node
3387 protected function scan_for_active_node(navigation_node $node) {
3388 if (!$node->check_if_active() && $node->children->count()>0) {
3389 foreach ($node->children as &$child) {
3390 $this->scan_for_active_node($child);
3396 * Gets a navigation node given an array of keys that represent the path to
3397 * the desired node.
3399 * @param array $path
3400 * @return navigation_node|false
3402 protected function get_by_path(array $path) {
3403 $node = $this->get(array_shift($path));
3404 foreach ($path as $key) {
3405 $node->get($key);
3407 return $node;
3411 * Generate the list of modules for the given course.
3413 * @param stdClass $course The course to get modules for
3415 protected function get_course_modules($course) {
3416 global $CFG;
3417 // This function is included when we include course/lib.php at the top
3418 // of this file
3419 $modnames = get_module_types_names();
3420 $resources = array();
3421 $activities = array();
3422 foreach($modnames as $modname=>$modnamestr) {
3423 if (!course_allowed_module($course, $modname)) {
3424 continue;
3427 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3428 if (!file_exists($libfile)) {
3429 continue;
3431 include_once($libfile);
3432 $gettypesfunc = $modname.'_get_types';
3433 if (function_exists($gettypesfunc)) {
3434 $types = $gettypesfunc();
3435 foreach($types as $type) {
3436 if (!isset($type->modclass) || !isset($type->typestr)) {
3437 debugging('Incorrect activity type in '.$modname);
3438 continue;
3440 if ($type->modclass == MOD_CLASS_RESOURCE) {
3441 $resources[html_entity_decode($type->type, ENT_QUOTES, 'UTF-8')] = $type->typestr;
3442 } else {
3443 $activities[html_entity_decode($type->type, ENT_QUOTES, 'UTF-8')] = $type->typestr;
3446 } else {
3447 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3448 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
3449 $resources[$modname] = $modnamestr;
3450 } else {
3451 // all other archetypes are considered activity
3452 $activities[$modname] = $modnamestr;
3456 return array($resources, $activities);
3460 * This function loads the course settings that are available for the user
3462 * @param bool $forceopen If set to true the course node will be forced open
3463 * @return navigation_node|false
3465 protected function load_course_settings($forceopen = false) {
3466 global $CFG;
3468 $course = $this->page->course;
3469 $coursecontext = context_course::instance($course->id);
3471 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3473 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3474 if ($forceopen) {
3475 $coursenode->force_open();
3478 if (has_capability('moodle/course:update', $coursecontext)) {
3479 // Add the turn on/off settings
3481 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3482 // We are on the course page, retain the current page params e.g. section.
3483 $baseurl = clone($this->page->url);
3484 $baseurl->param('sesskey', sesskey());
3485 } else {
3486 // Edit on the main course page.
3487 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3490 $editurl = clone($baseurl);
3491 if ($this->page->user_is_editing()) {
3492 $editurl->param('edit', 'off');
3493 $editstring = get_string('turneditingoff');
3494 } else {
3495 $editurl->param('edit', 'on');
3496 $editstring = get_string('turneditingon');
3498 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3500 // Add the module chooser toggle
3501 $modchoosertoggleurl = clone($baseurl);
3502 if ($this->page->user_is_editing() && course_ajax_enabled($course)) {
3503 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
3504 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
3505 $modchoosertoggleurl->param('modchooser', 'off');
3506 } else {
3507 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
3508 $modchoosertoggleurl->param('modchooser', 'on');
3510 $modchoosertoggle = $coursenode->add($modchoosertogglestring, $modchoosertoggleurl, self::TYPE_SETTING);
3511 $modchoosertoggle->add_class('modchoosertoggle');
3512 $modchoosertoggle->add_class('visibleifjs');
3513 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
3516 // Add the course settings link
3517 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3518 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3520 // Add the course completion settings link
3521 if ($CFG->enablecompletion && $course->enablecompletion) {
3522 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3523 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3527 // add enrol nodes
3528 enrol_add_course_navigation($coursenode, $course);
3530 // Manage filters
3531 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3532 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3533 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3536 // Add view grade report is permitted
3537 $reportavailable = false;
3538 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3539 $reportavailable = true;
3540 } else if (!empty($course->showgrades)) {
3541 $reports = get_plugin_list('gradereport');
3542 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3543 arsort($reports); // user is last, we want to test it first
3544 foreach ($reports as $plugin => $plugindir) {
3545 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3546 //stop when the first visible plugin is found
3547 $reportavailable = true;
3548 break;
3553 if ($reportavailable) {
3554 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3555 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3558 // Add outcome if permitted
3559 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3560 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3561 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3564 // Backup this course
3565 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3566 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3567 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3570 // Restore to this course
3571 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3572 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3573 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3576 // Import data from other courses
3577 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3578 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3579 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
3582 // Publish course on a hub
3583 if (has_capability('moodle/course:publish', $coursecontext)) {
3584 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3585 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3588 // Reset this course
3589 if (has_capability('moodle/course:reset', $coursecontext)) {
3590 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3591 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3594 // Questions
3595 require_once($CFG->libdir . '/questionlib.php');
3596 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3598 if (has_capability('moodle/course:update', $coursecontext)) {
3599 // Repository Instances
3600 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3601 require_once($CFG->dirroot . '/repository/lib.php');
3602 $editabletypes = repository::get_editable_types($coursecontext);
3603 $haseditabletypes = !empty($editabletypes);
3604 unset($editabletypes);
3605 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3606 } else {
3607 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3609 if ($haseditabletypes) {
3610 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3611 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3615 // Manage files
3616 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3617 // hidden in new courses and courses where legacy files were turned off
3618 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3619 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
3623 // Switch roles
3624 $roles = array();
3625 $assumedrole = $this->in_alternative_role();
3626 if ($assumedrole !== false) {
3627 $roles[0] = get_string('switchrolereturn');
3629 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3630 $availableroles = get_switchable_roles($coursecontext);
3631 if (is_array($availableroles)) {
3632 foreach ($availableroles as $key=>$role) {
3633 if ($assumedrole == (int)$key) {
3634 continue;
3636 $roles[$key] = $role;
3640 if (is_array($roles) && count($roles)>0) {
3641 $switchroles = $this->add(get_string('switchroleto'));
3642 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3643 $switchroles->force_open();
3645 $returnurl = $this->page->url;
3646 $returnurl->param('sesskey', sesskey());
3647 foreach ($roles as $key => $name) {
3648 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3649 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
3652 // Return we are done
3653 return $coursenode;
3657 * This function calls the module function to inject module settings into the
3658 * settings navigation tree.
3660 * This only gets called if there is a corrosponding function in the modules
3661 * lib file.
3663 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3665 * @return navigation_node|false
3667 protected function load_module_settings() {
3668 global $CFG;
3670 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3671 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3672 $this->page->set_cm($cm, $this->page->course);
3675 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3676 if (file_exists($file)) {
3677 require_once($file);
3680 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3681 $modulenode->force_open();
3683 // Settings for the module
3684 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3685 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3686 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3688 // Assign local roles
3689 if (count(get_assignable_roles($this->page->cm->context))>0) {
3690 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3691 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3693 // Override roles
3694 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3695 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3696 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3698 // Check role permissions
3699 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3700 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3701 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3703 // Manage filters
3704 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3705 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3706 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3708 // Add reports
3709 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3710 foreach ($reports as $reportfunction) {
3711 $reportfunction($modulenode, $this->page->cm);
3713 // Add a backup link
3714 $featuresfunc = $this->page->activityname.'_supports';
3715 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3716 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3717 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3720 // Restore this activity
3721 $featuresfunc = $this->page->activityname.'_supports';
3722 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3723 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3724 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3727 // Allow the active advanced grading method plugin to append its settings
3728 $featuresfunc = $this->page->activityname.'_supports';
3729 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3730 require_once($CFG->dirroot.'/grade/grading/lib.php');
3731 $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
3732 $gradingman->extend_settings_navigation($this, $modulenode);
3735 $function = $this->page->activityname.'_extend_settings_navigation';
3736 if (!function_exists($function)) {
3737 return $modulenode;
3740 $function($this, $modulenode);
3742 // Remove the module node if there are no children
3743 if (empty($modulenode->children)) {
3744 $modulenode->remove();
3747 return $modulenode;
3751 * Loads the user settings block of the settings nav
3753 * This function is simply works out the userid and whether we need to load
3754 * just the current users profile settings, or the current user and the user the
3755 * current user is viewing.
3757 * This function has some very ugly code to work out the user, if anyone has
3758 * any bright ideas please feel free to intervene.
3760 * @param int $courseid The course id of the current course
3761 * @return navigation_node|false
3763 protected function load_user_settings($courseid = SITEID) {
3764 global $USER, $CFG;
3766 if (isguestuser() || !isloggedin()) {
3767 return false;
3770 $navusers = $this->page->navigation->get_extending_users();
3772 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3773 $usernode = null;
3774 foreach ($this->userstoextendfor as $userid) {
3775 if ($userid == $USER->id) {
3776 continue;
3778 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3779 if (is_null($usernode)) {
3780 $usernode = $node;
3783 foreach ($navusers as $user) {
3784 if ($user->id == $USER->id) {
3785 continue;
3787 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3788 if (is_null($usernode)) {
3789 $usernode = $node;
3792 $this->generate_user_settings($courseid, $USER->id);
3793 } else {
3794 $usernode = $this->generate_user_settings($courseid, $USER->id);
3796 return $usernode;
3800 * Extends the settings navigation for the given user.
3802 * Note: This method gets called automatically if you call
3803 * $PAGE->navigation->extend_for_user($userid)
3805 * @param int $userid
3807 public function extend_for_user($userid) {
3808 global $CFG;
3810 if (!in_array($userid, $this->userstoextendfor)) {
3811 $this->userstoextendfor[] = $userid;
3812 if ($this->initialised) {
3813 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3814 $children = array();
3815 foreach ($this->children as $child) {
3816 $children[] = $child;
3818 array_unshift($children, array_pop($children));
3819 $this->children = new navigation_node_collection();
3820 foreach ($children as $child) {
3821 $this->children->add($child);
3828 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3829 * what can be shown/done
3831 * @param int $courseid The current course' id
3832 * @param int $userid The user id to load for
3833 * @param string $gstitle The string to pass to get_string for the branch title
3834 * @return navigation_node|false
3836 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3837 global $DB, $CFG, $USER, $SITE;
3839 if ($courseid != $SITE->id) {
3840 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3841 $course = $this->page->course;
3842 } else {
3843 $select = context_helper::get_preload_record_columns_sql('ctx');
3844 $sql = "SELECT c.*, $select
3845 FROM {course} c
3846 JOIN {context} ctx ON c.id = ctx.instanceid
3847 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
3848 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
3849 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3850 context_helper::preload_from_record($course);
3852 } else {
3853 $course = $SITE;
3856 $coursecontext = context_course::instance($course->id); // Course context
3857 $systemcontext = get_system_context();
3858 $currentuser = ($USER->id == $userid);
3860 if ($currentuser) {
3861 $user = $USER;
3862 $usercontext = context_user::instance($user->id); // User context
3863 } else {
3864 $select = context_helper::get_preload_record_columns_sql('ctx');
3865 $sql = "SELECT u.*, $select
3866 FROM {user} u
3867 JOIN {context} ctx ON u.id = ctx.instanceid
3868 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
3869 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
3870 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
3871 if (!$user) {
3872 return false;
3874 context_helper::preload_from_record($user);
3876 // Check that the user can view the profile
3877 $usercontext = context_user::instance($user->id); // User context
3878 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3880 if ($course->id == $SITE->id) {
3881 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
3882 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3883 return false;
3885 } else {
3886 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
3887 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
3888 if ((!$canviewusercourse && !$canviewuser) || !can_access_course($course, $user->id)) {
3889 return false;
3891 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
3892 // If groups are in use, make sure we can see that group
3893 return false;
3898 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3900 $key = $gstitle;
3901 if ($gstitle != 'usercurrentsettings') {
3902 $key .= $userid;
3905 // Add a user setting branch
3906 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3907 $usersetting->id = 'usersettings';
3908 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3909 // Automatically start by making it active
3910 $usersetting->make_active();
3913 // Check if the user has been deleted
3914 if ($user->deleted) {
3915 if (!has_capability('moodle/user:update', $coursecontext)) {
3916 // We can't edit the user so just show the user deleted message
3917 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3918 } else {
3919 // We can edit the user so show the user deleted message and link it to the profile
3920 if ($course->id == $SITE->id) {
3921 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3922 } else {
3923 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3925 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3927 return true;
3930 $userauthplugin = false;
3931 if (!empty($user->auth)) {
3932 $userauthplugin = get_auth_plugin($user->auth);
3935 // Add the profile edit link
3936 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3937 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3938 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3939 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3940 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3941 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
3942 $url = $userauthplugin->edit_profile_url();
3943 if (empty($url)) {
3944 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3946 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3951 // Change password link
3952 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
3953 $passwordchangeurl = $userauthplugin->change_password_url();
3954 if (empty($passwordchangeurl)) {
3955 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3957 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3960 // View the roles settings
3961 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3962 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3964 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3965 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3967 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3969 if (!empty($assignableroles)) {
3970 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3971 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3974 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3975 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3976 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3979 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3980 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3983 // Portfolio
3984 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3985 require_once($CFG->libdir . '/portfoliolib.php');
3986 if (portfolio_instances(true, false)) {
3987 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3989 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3990 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
3992 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
3993 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
3997 $enablemanagetokens = false;
3998 if (!empty($CFG->enablerssfeeds)) {
3999 $enablemanagetokens = true;
4000 } else if (!is_siteadmin($USER->id)
4001 && !empty($CFG->enablewebservices)
4002 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
4003 $enablemanagetokens = true;
4005 // Security keys
4006 if ($currentuser && $enablemanagetokens) {
4007 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4008 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4011 // Repository
4012 if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
4013 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
4014 require_once($CFG->dirroot . '/repository/lib.php');
4015 $editabletypes = repository::get_editable_types($usercontext);
4016 $haseditabletypes = !empty($editabletypes);
4017 unset($editabletypes);
4018 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
4019 } else {
4020 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
4022 if ($haseditabletypes) {
4023 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
4024 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
4028 // Messaging
4029 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4030 $url = new moodle_url('/message/edit.php', array('id'=>$user->id));
4031 $usersetting->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
4034 // Blogs
4035 if ($currentuser && !empty($CFG->enableblogs)) {
4036 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4037 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
4038 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
4039 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
4040 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
4044 // Login as ...
4045 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
4046 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
4047 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
4050 return $usersetting;
4054 * Loads block specific settings in the navigation
4056 * @return navigation_node
4058 protected function load_block_settings() {
4059 global $CFG;
4061 $blocknode = $this->add(print_context_name($this->context));
4062 $blocknode->force_open();
4064 // Assign local roles
4065 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4066 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4068 // Override roles
4069 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4070 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4071 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4073 // Check role permissions
4074 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4075 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4076 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4079 return $blocknode;
4083 * Loads category specific settings in the navigation
4085 * @return navigation_node
4087 protected function load_category_settings() {
4088 global $CFG;
4090 $categorynode = $this->add(print_context_name($this->context), null, null, null, 'categorysettings');
4091 $categorynode->force_open();
4093 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context)) {
4094 $url = new moodle_url('/course/category.php', array('id'=>$this->context->instanceid, 'sesskey'=>sesskey()));
4095 if ($this->page->user_is_editing()) {
4096 $url->param('categoryedit', '0');
4097 $editstring = get_string('turneditingoff');
4098 } else {
4099 $url->param('categoryedit', '1');
4100 $editstring = get_string('turneditingon');
4102 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4105 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
4106 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
4107 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4109 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
4110 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4113 // Assign local roles
4114 if (has_capability('moodle/role:assign', $this->context)) {
4115 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4116 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4119 // Override roles
4120 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4121 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4122 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4124 // Check role permissions
4125 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4126 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4127 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4130 // Cohorts
4131 if (has_capability('moodle/cohort:manage', $this->context) or has_capability('moodle/cohort:view', $this->context)) {
4132 $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', ''));
4135 // Manage filters
4136 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
4137 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
4138 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4141 return $categorynode;
4145 * Determine whether the user is assuming another role
4147 * This function checks to see if the user is assuming another role by means of
4148 * role switching. In doing this we compare each RSW key (context path) against
4149 * the current context path. This ensures that we can provide the switching
4150 * options against both the course and any page shown under the course.
4152 * @return bool|int The role(int) if the user is in another role, false otherwise
4154 protected function in_alternative_role() {
4155 global $USER;
4156 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4157 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4158 return $USER->access['rsw'][$this->page->context->path];
4160 foreach ($USER->access['rsw'] as $key=>$role) {
4161 if (strpos($this->context->path,$key)===0) {
4162 return $role;
4166 return false;
4170 * This function loads all of the front page settings into the settings navigation.
4171 * This function is called when the user is on the front page, or $COURSE==$SITE
4172 * @param bool $forceopen (optional)
4173 * @return navigation_node
4175 protected function load_front_page_settings($forceopen = false) {
4176 global $SITE, $CFG;
4178 $course = clone($SITE);
4179 $coursecontext = context_course::instance($course->id); // Course context
4181 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4182 if ($forceopen) {
4183 $frontpage->force_open();
4185 $frontpage->id = 'frontpagesettings';
4187 if (has_capability('moodle/course:update', $coursecontext)) {
4189 // Add the turn on/off settings
4190 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4191 if ($this->page->user_is_editing()) {
4192 $url->param('edit', 'off');
4193 $editstring = get_string('turneditingoff');
4194 } else {
4195 $url->param('edit', 'on');
4196 $editstring = get_string('turneditingon');
4198 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4200 // Add the course settings link
4201 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4202 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4205 // add enrol nodes
4206 enrol_add_course_navigation($frontpage, $course);
4208 // Manage filters
4209 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4210 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4211 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4214 // Backup this course
4215 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4216 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4217 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4220 // Restore to this course
4221 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4222 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4223 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4226 // Questions
4227 require_once($CFG->libdir . '/questionlib.php');
4228 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4230 // Manage files
4231 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4232 //hiden in new installs
4233 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
4234 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
4236 return $frontpage;
4240 * This function gives local plugins an opportunity to modify the settings navigation.
4242 protected function load_local_plugin_settings() {
4243 // Get all local plugins with an extend_settings_navigation function in their lib.php file
4244 foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
4245 // Call each function providing this (the settings navigation) and the current context.
4246 $function($this, $this->context);
4251 * This function marks the cache as volatile so it is cleared during shutdown
4253 public function clear_cache() {
4254 $this->cache->volatile();
4259 * Simple class used to output a navigation branch in XML
4261 * @package core
4262 * @category navigation
4263 * @copyright 2009 Sam Hemelryk
4264 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4266 class navigation_json {
4267 /** @var array An array of different node types */
4268 protected $nodetype = array('node','branch');
4269 /** @var array An array of node keys and types */
4270 protected $expandable = array();
4272 * Turns a branch and all of its children into XML
4274 * @param navigation_node $branch
4275 * @return string XML string
4277 public function convert($branch) {
4278 $xml = $this->convert_child($branch);
4279 return $xml;
4282 * Set the expandable items in the array so that we have enough information
4283 * to attach AJAX events
4284 * @param array $expandable
4286 public function set_expandable($expandable) {
4287 foreach ($expandable as $node) {
4288 $this->expandable[$node['key'].':'.$node['type']] = $node;
4292 * Recusively converts a child node and its children to XML for output
4294 * @param navigation_node $child The child to convert
4295 * @param int $depth Pointlessly used to track the depth of the XML structure
4296 * @return string JSON
4298 protected function convert_child($child, $depth=1) {
4299 if (!$child->display) {
4300 return '';
4302 $attributes = array();
4303 $attributes['id'] = $child->id;
4304 $attributes['name'] = $child->text;
4305 $attributes['type'] = $child->type;
4306 $attributes['key'] = $child->key;
4307 $attributes['class'] = $child->get_css_type();
4309 if ($child->icon instanceof pix_icon) {
4310 $attributes['icon'] = array(
4311 'component' => $child->icon->component,
4312 'pix' => $child->icon->pix,
4314 foreach ($child->icon->attributes as $key=>$value) {
4315 if ($key == 'class') {
4316 $attributes['icon']['classes'] = explode(' ', $value);
4317 } else if (!array_key_exists($key, $attributes['icon'])) {
4318 $attributes['icon'][$key] = $value;
4322 } else if (!empty($child->icon)) {
4323 $attributes['icon'] = (string)$child->icon;
4326 if ($child->forcetitle || $child->title !== $child->text) {
4327 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
4329 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4330 $attributes['expandable'] = $child->key;
4331 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4334 if (count($child->classes)>0) {
4335 $attributes['class'] .= ' '.join(' ',$child->classes);
4337 if (is_string($child->action)) {
4338 $attributes['link'] = $child->action;
4339 } else if ($child->action instanceof moodle_url) {
4340 $attributes['link'] = $child->action->out();
4341 } else if ($child->action instanceof action_link) {
4342 $attributes['link'] = $child->action->url->out();
4344 $attributes['hidden'] = ($child->hidden);
4345 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4346 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
4348 if ($child->children->count() > 0) {
4349 $attributes['children'] = array();
4350 foreach ($child->children as $subchild) {
4351 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4355 if ($depth > 1) {
4356 return $attributes;
4357 } else {
4358 return json_encode($attributes);
4364 * The cache class used by global navigation and settings navigation.
4366 * It is basically an easy access point to session with a bit of smarts to make
4367 * sure that the information that is cached is valid still.
4369 * Example use:
4370 * <code php>
4371 * if (!$cache->viewdiscussion()) {
4372 * // Code to do stuff and produce cachable content
4373 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4375 * $content = $cache->viewdiscussion;
4376 * </code>
4378 * @package core
4379 * @category navigation
4380 * @copyright 2009 Sam Hemelryk
4381 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4383 class navigation_cache {
4384 /** @var int represents the time created */
4385 protected $creation;
4386 /** @var array An array of session keys */
4387 protected $session;
4389 * The string to use to segregate this particular cache. It can either be
4390 * unique to start a fresh cache or if you want to share a cache then make
4391 * it the string used in the original cache.
4392 * @var string
4394 protected $area;
4395 /** @var int a time that the information will time out */
4396 protected $timeout;
4397 /** @var stdClass The current context */
4398 protected $currentcontext;
4399 /** @var int cache time information */
4400 const CACHETIME = 0;
4401 /** @var int cache user id */
4402 const CACHEUSERID = 1;
4403 /** @var int cache value */
4404 const CACHEVALUE = 2;
4405 /** @var null|array An array of navigation cache areas to expire on shutdown */
4406 public static $volatilecaches;
4409 * Contructor for the cache. Requires two arguments
4411 * @param string $area The string to use to segregate this particular cache
4412 * it can either be unique to start a fresh cache or if you want
4413 * to share a cache then make it the string used in the original
4414 * cache
4415 * @param int $timeout The number of seconds to time the information out after
4417 public function __construct($area, $timeout=1800) {
4418 $this->creation = time();
4419 $this->area = $area;
4420 $this->timeout = time() - $timeout;
4421 if (rand(0,100) === 0) {
4422 $this->garbage_collection();
4427 * Used to set up the cache within the SESSION.
4429 * This is called for each access and ensure that we don't put anything into the session before
4430 * it is required.
4432 protected function ensure_session_cache_initialised() {
4433 global $SESSION;
4434 if (empty($this->session)) {
4435 if (!isset($SESSION->navcache)) {
4436 $SESSION->navcache = new stdClass;
4438 if (!isset($SESSION->navcache->{$this->area})) {
4439 $SESSION->navcache->{$this->area} = array();
4441 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
4446 * Magic Method to retrieve something by simply calling using = cache->key
4448 * @param mixed $key The identifier for the information you want out again
4449 * @return void|mixed Either void or what ever was put in
4451 public function __get($key) {
4452 if (!$this->cached($key)) {
4453 return;
4455 $information = $this->session[$key][self::CACHEVALUE];
4456 return unserialize($information);
4460 * Magic method that simply uses {@link set();} to store something in the cache
4462 * @param string|int $key
4463 * @param mixed $information
4465 public function __set($key, $information) {
4466 $this->set($key, $information);
4470 * Sets some information against the cache (session) for later retrieval
4472 * @param string|int $key
4473 * @param mixed $information
4475 public function set($key, $information) {
4476 global $USER;
4477 $this->ensure_session_cache_initialised();
4478 $information = serialize($information);
4479 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4482 * Check the existence of the identifier in the cache
4484 * @param string|int $key
4485 * @return bool
4487 public function cached($key) {
4488 global $USER;
4489 $this->ensure_session_cache_initialised();
4490 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) {
4491 return false;
4493 return true;
4496 * Compare something to it's equivilant in the cache
4498 * @param string $key
4499 * @param mixed $value
4500 * @param bool $serialise Whether to serialise the value before comparison
4501 * this should only be set to false if the value is already
4502 * serialised
4503 * @return bool If the value is the same false if it is not set or doesn't match
4505 public function compare($key, $value, $serialise = true) {
4506 if ($this->cached($key)) {
4507 if ($serialise) {
4508 $value = serialize($value);
4510 if ($this->session[$key][self::CACHEVALUE] === $value) {
4511 return true;
4514 return false;
4517 * Wipes the entire cache, good to force regeneration
4519 public function clear() {
4520 global $SESSION;
4521 unset($SESSION->navcache);
4522 $this->session = null;
4525 * Checks all cache entries and removes any that have expired, good ole cleanup
4527 protected function garbage_collection() {
4528 if (empty($this->session)) {
4529 return true;
4531 foreach ($this->session as $key=>$cachedinfo) {
4532 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4533 unset($this->session[$key]);
4539 * Marks the cache as being volatile (likely to change)
4541 * Any caches marked as volatile will be destroyed at the on shutdown by
4542 * {@link navigation_node::destroy_volatile_caches()} which is registered
4543 * as a shutdown function if any caches are marked as volatile.
4545 * @param bool $setting True to destroy the cache false not too
4547 public function volatile($setting = true) {
4548 if (self::$volatilecaches===null) {
4549 self::$volatilecaches = array();
4550 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4553 if ($setting) {
4554 self::$volatilecaches[$this->area] = $this->area;
4555 } else if (array_key_exists($this->area, self::$volatilecaches)) {
4556 unset(self::$volatilecaches[$this->area]);
4561 * Destroys all caches marked as volatile
4563 * This function is static and works in conjunction with the static volatilecaches
4564 * property of navigation cache.
4565 * Because this function is static it manually resets the cached areas back to an
4566 * empty array.
4568 public static function destroy_volatile_caches() {
4569 global $SESSION;
4570 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4571 foreach (self::$volatilecaches as $area) {
4572 $SESSION->navcache->{$area} = array();
4574 } else {
4575 $SESSION->navcache = new stdClass;