Merge branch 'MDL-44620_master' of git://github.com/dmonllao/moodle into MOODLE_27_STABLE
[moodle.git] / lib / navigationlib.php
blobeac7afe009591b24ec20a7494f9a55958c6ce9d6
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 Moodle 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');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
34 /**
35 * This class is used to represent a node in a navigation tree
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
43 * @package core
44 * @category navigation
45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF = 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH = 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN = null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY = 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
77 /** @var int Setting node type, used only within settings nav 80 */
78 const TYPE_USER = 80;
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
88 /** @var int Parameter to aid the coder in tracking [optional] */
89 public $id = null;
90 /** @var string|int The identifier for the node, used to retrieve the node */
91 public $key = null;
92 /** @var string The text to use for the node */
93 public $text = null;
94 /** @var string Short text to use if requested [optional] */
95 public $shorttext = null;
96 /** @var string The title attribute for an action if one is defined */
97 public $title = null;
98 /** @var string A string that can be used to build a help button */
99 public $helpbutton = null;
100 /** @var moodle_url|action_link|null An action for the node (link) */
101 public $action = null;
102 /** @var pix_icon The path to an icon to use for this node */
103 public $icon = null;
104 /** @var int See TYPE_* constants defined for this class */
105 public $type = self::TYPE_UNKNOWN;
106 /** @var int See NODETYPE_* constants defined for this class */
107 public $nodetype = self::NODETYPE_LEAF;
108 /** @var bool If set to true the node will be collapsed by default */
109 public $collapse = false;
110 /** @var bool If set to true the node will be expanded by default */
111 public $forceopen = false;
112 /** @var array An array of CSS classes for the node */
113 public $classes = array();
114 /** @var navigation_node_collection An array of child nodes */
115 public $children = array();
116 /** @var bool If set to true the node will be recognised as active */
117 public $isactive = false;
118 /** @var bool If set to true the node will be dimmed */
119 public $hidden = false;
120 /** @var bool If set to false the node will not be displayed */
121 public $display = true;
122 /** @var bool If set to true then an HR will be printed before the node */
123 public $preceedwithhr = false;
124 /** @var bool If set to true the the navigation bar should ignore this node */
125 public $mainnavonly = false;
126 /** @var bool If set to true a title will be added to the action no matter what */
127 public $forcetitle = false;
128 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
129 public $parent = null;
130 /** @var bool Override to not display the icon even if one is provided **/
131 public $hideicon = false;
132 /** @var bool Set to true if we KNOW that this node can be expanded. */
133 public $isexpandable = false;
134 /** @var array */
135 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting',71=>'siteadmin', 80=>'user');
136 /** @var moodle_url */
137 protected static $fullmeurl = null;
138 /** @var bool toogles auto matching of active node */
139 public static $autofindactive = true;
140 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
141 protected static $loadadmintree = false;
142 /** @var mixed If set to an int, that section will be included even if it has no activities */
143 public $includesectionnum = false;
146 * Constructs a new navigation_node
148 * @param array|string $properties Either an array of properties or a string to use
149 * as the text for the node
151 public function __construct($properties) {
152 if (is_array($properties)) {
153 // Check the array for each property that we allow to set at construction.
154 // text - The main content for the node
155 // shorttext - A short text if required for the node
156 // icon - The icon to display for the node
157 // type - The type of the node
158 // key - The key to use to identify the node
159 // parent - A reference to the nodes parent
160 // action - The action to attribute to this node, usually a URL to link to
161 if (array_key_exists('text', $properties)) {
162 $this->text = $properties['text'];
164 if (array_key_exists('shorttext', $properties)) {
165 $this->shorttext = $properties['shorttext'];
167 if (!array_key_exists('icon', $properties)) {
168 $properties['icon'] = new pix_icon('i/navigationitem', '');
170 $this->icon = $properties['icon'];
171 if ($this->icon instanceof pix_icon) {
172 if (empty($this->icon->attributes['class'])) {
173 $this->icon->attributes['class'] = 'navicon';
174 } else {
175 $this->icon->attributes['class'] .= ' navicon';
178 if (array_key_exists('type', $properties)) {
179 $this->type = $properties['type'];
180 } else {
181 $this->type = self::TYPE_CUSTOM;
183 if (array_key_exists('key', $properties)) {
184 $this->key = $properties['key'];
186 // This needs to happen last because of the check_if_active call that occurs
187 if (array_key_exists('action', $properties)) {
188 $this->action = $properties['action'];
189 if (is_string($this->action)) {
190 $this->action = new moodle_url($this->action);
192 if (self::$autofindactive) {
193 $this->check_if_active();
196 if (array_key_exists('parent', $properties)) {
197 $this->set_parent($properties['parent']);
199 } else if (is_string($properties)) {
200 $this->text = $properties;
202 if ($this->text === null) {
203 throw new coding_exception('You must set the text for the node when you create it.');
205 // Instantiate a new navigation node collection for this nodes children
206 $this->children = new navigation_node_collection();
210 * Checks if this node is the active node.
212 * This is determined by comparing the action for the node against the
213 * defined URL for the page. A match will see this node marked as active.
215 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
216 * @return bool
218 public function check_if_active($strength=URL_MATCH_EXACT) {
219 global $FULLME, $PAGE;
220 // Set fullmeurl if it hasn't already been set
221 if (self::$fullmeurl == null) {
222 if ($PAGE->has_set_url()) {
223 self::override_active_url(new moodle_url($PAGE->url));
224 } else {
225 self::override_active_url(new moodle_url($FULLME));
229 // Compare the action of this node against the fullmeurl
230 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
231 $this->make_active();
232 return true;
234 return false;
238 * This sets the URL that the URL of new nodes get compared to when locating
239 * the active node.
241 * The active node is the node that matches the URL set here. By default this
242 * is either $PAGE->url or if that hasn't been set $FULLME.
244 * @param moodle_url $url The url to use for the fullmeurl.
245 * @param bool $loadadmintree use true if the URL point to administration tree
247 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
248 // Clone the URL, in case the calling script changes their URL later.
249 self::$fullmeurl = new moodle_url($url);
250 // True means we do not want AJAX loaded admin tree, required for all admin pages.
251 if ($loadadmintree) {
252 // Do not change back to false if already set.
253 self::$loadadmintree = true;
258 * Use when page is linked from the admin tree,
259 * if not used navigation could not find the page using current URL
260 * because the tree is not fully loaded.
262 public static function require_admin_tree() {
263 self::$loadadmintree = true;
267 * Creates a navigation node, ready to add it as a child using add_node
268 * function. (The created node needs to be added before you can use it.)
269 * @param string $text
270 * @param moodle_url|action_link $action
271 * @param int $type
272 * @param string $shorttext
273 * @param string|int $key
274 * @param pix_icon $icon
275 * @return navigation_node
277 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
278 $shorttext=null, $key=null, pix_icon $icon=null) {
279 // Properties array used when creating the new navigation node
280 $itemarray = array(
281 'text' => $text,
282 'type' => $type
284 // Set the action if one was provided
285 if ($action!==null) {
286 $itemarray['action'] = $action;
288 // Set the shorttext if one was provided
289 if ($shorttext!==null) {
290 $itemarray['shorttext'] = $shorttext;
292 // Set the icon if one was provided
293 if ($icon!==null) {
294 $itemarray['icon'] = $icon;
296 // Set the key
297 $itemarray['key'] = $key;
298 // Construct and return
299 return new navigation_node($itemarray);
303 * Adds a navigation node as a child of this node.
305 * @param string $text
306 * @param moodle_url|action_link $action
307 * @param int $type
308 * @param string $shorttext
309 * @param string|int $key
310 * @param pix_icon $icon
311 * @return navigation_node
313 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
314 // Create child node
315 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
317 // Add the child to end and return
318 return $this->add_node($childnode);
322 * Adds a navigation node as a child of this one, given a $node object
323 * created using the create function.
324 * @param navigation_node $childnode Node to add
325 * @param string $beforekey
326 * @return navigation_node The added node
328 public function add_node(navigation_node $childnode, $beforekey=null) {
329 // First convert the nodetype for this node to a branch as it will now have children
330 if ($this->nodetype !== self::NODETYPE_BRANCH) {
331 $this->nodetype = self::NODETYPE_BRANCH;
333 // Set the parent to this node
334 $childnode->set_parent($this);
336 // Default the key to the number of children if not provided
337 if ($childnode->key === null) {
338 $childnode->key = $this->children->count();
341 // Add the child using the navigation_node_collections add method
342 $node = $this->children->add($childnode, $beforekey);
344 // If added node is a category node or the user is logged in and it's a course
345 // then mark added node as a branch (makes it expandable by AJAX)
346 $type = $childnode->type;
347 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
348 ($type === self::TYPE_SITE_ADMIN)) {
349 $node->nodetype = self::NODETYPE_BRANCH;
351 // If this node is hidden mark it's children as hidden also
352 if ($this->hidden) {
353 $node->hidden = true;
355 // Return added node (reference returned by $this->children->add()
356 return $node;
360 * Return a list of all the keys of all the child nodes.
361 * @return array the keys.
363 public function get_children_key_list() {
364 return $this->children->get_key_list();
368 * Searches for a node of the given type with the given key.
370 * This searches this node plus all of its children, and their children....
371 * If you know the node you are looking for is a child of this node then please
372 * use the get method instead.
374 * @param int|string $key The key of the node we are looking for
375 * @param int $type One of navigation_node::TYPE_*
376 * @return navigation_node|false
378 public function find($key, $type) {
379 return $this->children->find($key, $type);
383 * Get the child of this node that has the given key + (optional) type.
385 * If you are looking for a node and want to search all children + thier children
386 * then please use the find method instead.
388 * @param int|string $key The key of the node we are looking for
389 * @param int $type One of navigation_node::TYPE_*
390 * @return navigation_node|false
392 public function get($key, $type=null) {
393 return $this->children->get($key, $type);
397 * Removes this node.
399 * @return bool
401 public function remove() {
402 return $this->parent->children->remove($this->key, $this->type);
406 * Checks if this node has or could have any children
408 * @return bool Returns true if it has children or could have (by AJAX expansion)
410 public function has_children() {
411 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
415 * Marks this node as active and forces it open.
417 * Important: If you are here because you need to mark a node active to get
418 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
419 * You can use it to specify a different URL to match the active navigation node on
420 * rather than having to locate and manually mark a node active.
422 public function make_active() {
423 $this->isactive = true;
424 $this->add_class('active_tree_node');
425 $this->force_open();
426 if ($this->parent !== null) {
427 $this->parent->make_inactive();
432 * Marks a node as inactive and recusised back to the base of the tree
433 * doing the same to all parents.
435 public function make_inactive() {
436 $this->isactive = false;
437 $this->remove_class('active_tree_node');
438 if ($this->parent !== null) {
439 $this->parent->make_inactive();
444 * Forces this node to be open and at the same time forces open all
445 * parents until the root node.
447 * Recursive.
449 public function force_open() {
450 $this->forceopen = true;
451 if ($this->parent !== null) {
452 $this->parent->force_open();
457 * Adds a CSS class to this node.
459 * @param string $class
460 * @return bool
462 public function add_class($class) {
463 if (!in_array($class, $this->classes)) {
464 $this->classes[] = $class;
466 return true;
470 * Removes a CSS class from this node.
472 * @param string $class
473 * @return bool True if the class was successfully removed.
475 public function remove_class($class) {
476 if (in_array($class, $this->classes)) {
477 $key = array_search($class,$this->classes);
478 if ($key!==false) {
479 unset($this->classes[$key]);
480 return true;
483 return false;
487 * Sets the title for this node and forces Moodle to utilise it.
488 * @param string $title
490 public function title($title) {
491 $this->title = $title;
492 $this->forcetitle = true;
496 * Resets the page specific information on this node if it is being unserialised.
498 public function __wakeup(){
499 $this->forceopen = false;
500 $this->isactive = false;
501 $this->remove_class('active_tree_node');
505 * Checks if this node or any of its children contain the active node.
507 * Recursive.
509 * @return bool
511 public function contains_active_node() {
512 if ($this->isactive) {
513 return true;
514 } else {
515 foreach ($this->children as $child) {
516 if ($child->isactive || $child->contains_active_node()) {
517 return true;
521 return false;
525 * Finds the active node.
527 * Searches this nodes children plus all of the children for the active node
528 * and returns it if found.
530 * Recursive.
532 * @return navigation_node|false
534 public function find_active_node() {
535 if ($this->isactive) {
536 return $this;
537 } else {
538 foreach ($this->children as &$child) {
539 $outcome = $child->find_active_node();
540 if ($outcome !== false) {
541 return $outcome;
545 return false;
549 * Searches all children for the best matching active node
550 * @return navigation_node|false
552 public function search_for_active_node() {
553 if ($this->check_if_active(URL_MATCH_BASE)) {
554 return $this;
555 } else {
556 foreach ($this->children as &$child) {
557 $outcome = $child->search_for_active_node();
558 if ($outcome !== false) {
559 return $outcome;
563 return false;
567 * Gets the content for this node.
569 * @param bool $shorttext If true shorttext is used rather than the normal text
570 * @return string
572 public function get_content($shorttext=false) {
573 if ($shorttext && $this->shorttext!==null) {
574 return format_string($this->shorttext);
575 } else {
576 return format_string($this->text);
581 * Gets the title to use for this node.
583 * @return string
585 public function get_title() {
586 if ($this->forcetitle || $this->action != null){
587 return $this->title;
588 } else {
589 return '';
594 * Gets the CSS class to add to this node to describe its type
596 * @return string
598 public function get_css_type() {
599 if (array_key_exists($this->type, $this->namedtypes)) {
600 return 'type_'.$this->namedtypes[$this->type];
602 return 'type_unknown';
606 * Finds all nodes that are expandable by AJAX
608 * @param array $expandable An array by reference to populate with expandable nodes.
610 public function find_expandable(array &$expandable) {
611 foreach ($this->children as &$child) {
612 if ($child->display && $child->has_children() && $child->children->count() == 0) {
613 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
614 $this->add_class('canexpand');
615 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
617 $child->find_expandable($expandable);
622 * Finds all nodes of a given type (recursive)
624 * @param int $type One of navigation_node::TYPE_*
625 * @return array
627 public function find_all_of_type($type) {
628 $nodes = $this->children->type($type);
629 foreach ($this->children as &$node) {
630 $childnodes = $node->find_all_of_type($type);
631 $nodes = array_merge($nodes, $childnodes);
633 return $nodes;
637 * Removes this node if it is empty
639 public function trim_if_empty() {
640 if ($this->children->count() == 0) {
641 $this->remove();
646 * Creates a tab representation of this nodes children that can be used
647 * with print_tabs to produce the tabs on a page.
649 * call_user_func_array('print_tabs', $node->get_tabs_array());
651 * @param array $inactive
652 * @param bool $return
653 * @return array Array (tabs, selected, inactive, activated, return)
655 public function get_tabs_array(array $inactive=array(), $return=false) {
656 $tabs = array();
657 $rows = array();
658 $selected = null;
659 $activated = array();
660 foreach ($this->children as $node) {
661 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
662 if ($node->contains_active_node()) {
663 if ($node->children->count() > 0) {
664 $activated[] = $node->key;
665 foreach ($node->children as $child) {
666 if ($child->contains_active_node()) {
667 $selected = $child->key;
669 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
671 } else {
672 $selected = $node->key;
676 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
680 * Sets the parent for this node and if this node is active ensures that the tree is properly
681 * adjusted as well.
683 * @param navigation_node $parent
685 public function set_parent(navigation_node $parent) {
686 // Set the parent (thats the easy part)
687 $this->parent = $parent;
688 // Check if this node is active (this is checked during construction)
689 if ($this->isactive) {
690 // Force all of the parent nodes open so you can see this node
691 $this->parent->force_open();
692 // Make all parents inactive so that its clear where we are.
693 $this->parent->make_inactive();
698 * Hides the node and any children it has.
700 * @since Moodle 2.5
701 * @param array $typestohide Optional. An array of node types that should be hidden.
702 * If null all nodes will be hidden.
703 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
704 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
706 public function hide(array $typestohide = null) {
707 if ($typestohide === null || in_array($this->type, $typestohide)) {
708 $this->display = false;
709 if ($this->has_children()) {
710 foreach ($this->children as $child) {
711 $child->hide($typestohide);
719 * Navigation node collection
721 * This class is responsible for managing a collection of navigation nodes.
722 * It is required because a node's unique identifier is a combination of both its
723 * key and its type.
725 * Originally an array was used with a string key that was a combination of the two
726 * however it was decided that a better solution would be to use a class that
727 * implements the standard IteratorAggregate interface.
729 * @package core
730 * @category navigation
731 * @copyright 2010 Sam Hemelryk
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 class navigation_node_collection implements IteratorAggregate {
736 * A multidimensional array to where the first key is the type and the second
737 * key is the nodes key.
738 * @var array
740 protected $collection = array();
742 * An array that contains references to nodes in the same order they were added.
743 * This is maintained as a progressive array.
744 * @var array
746 protected $orderedcollection = array();
748 * A reference to the last node that was added to the collection
749 * @var navigation_node
751 protected $last = null;
753 * The total number of items added to this array.
754 * @var int
756 protected $count = 0;
759 * Adds a navigation node to the collection
761 * @param navigation_node $node Node to add
762 * @param string $beforekey If specified, adds before a node with this key,
763 * otherwise adds at end
764 * @return navigation_node Added node
766 public function add(navigation_node $node, $beforekey=null) {
767 global $CFG;
768 $key = $node->key;
769 $type = $node->type;
771 // First check we have a 2nd dimension for this type
772 if (!array_key_exists($type, $this->orderedcollection)) {
773 $this->orderedcollection[$type] = array();
775 // Check for a collision and report if debugging is turned on
776 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
777 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
780 // Find the key to add before
781 $newindex = $this->count;
782 $last = true;
783 if ($beforekey !== null) {
784 foreach ($this->collection as $index => $othernode) {
785 if ($othernode->key === $beforekey) {
786 $newindex = $index;
787 $last = false;
788 break;
791 if ($newindex === $this->count) {
792 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
793 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
797 // Add the node to the appropriate place in the by-type structure (which
798 // is not ordered, despite the variable name)
799 $this->orderedcollection[$type][$key] = $node;
800 if (!$last) {
801 // Update existing references in the ordered collection (which is the
802 // one that isn't called 'ordered') to shuffle them along if required
803 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
804 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
807 // Add a reference to the node to the progressive collection.
808 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
809 // Update the last property to a reference to this new node.
810 $this->last = $this->orderedcollection[$type][$key];
812 // Reorder the array by index if needed
813 if (!$last) {
814 ksort($this->collection);
816 $this->count++;
817 // Return the reference to the now added node
818 return $node;
822 * Return a list of all the keys of all the nodes.
823 * @return array the keys.
825 public function get_key_list() {
826 $keys = array();
827 foreach ($this->collection as $node) {
828 $keys[] = $node->key;
830 return $keys;
834 * Fetches a node from this collection.
836 * @param string|int $key The key of the node we want to find.
837 * @param int $type One of navigation_node::TYPE_*.
838 * @return navigation_node|null
840 public function get($key, $type=null) {
841 if ($type !== null) {
842 // If the type is known then we can simply check and fetch
843 if (!empty($this->orderedcollection[$type][$key])) {
844 return $this->orderedcollection[$type][$key];
846 } else {
847 // Because we don't know the type we look in the progressive array
848 foreach ($this->collection as $node) {
849 if ($node->key === $key) {
850 return $node;
854 return false;
858 * Searches for a node with matching key and type.
860 * This function searches both the nodes in this collection and all of
861 * the nodes in each collection belonging to the nodes in this collection.
863 * Recursive.
865 * @param string|int $key The key of the node we want to find.
866 * @param int $type One of navigation_node::TYPE_*.
867 * @return navigation_node|null
869 public function find($key, $type=null) {
870 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
871 return $this->orderedcollection[$type][$key];
872 } else {
873 $nodes = $this->getIterator();
874 // Search immediate children first
875 foreach ($nodes as &$node) {
876 if ($node->key === $key && ($type === null || $type === $node->type)) {
877 return $node;
880 // Now search each childs children
881 foreach ($nodes as &$node) {
882 $result = $node->children->find($key, $type);
883 if ($result !== false) {
884 return $result;
888 return false;
892 * Fetches the last node that was added to this collection
894 * @return navigation_node
896 public function last() {
897 return $this->last;
901 * Fetches all nodes of a given type from this collection
903 * @param string|int $type node type being searched for.
904 * @return array ordered collection
906 public function type($type) {
907 if (!array_key_exists($type, $this->orderedcollection)) {
908 $this->orderedcollection[$type] = array();
910 return $this->orderedcollection[$type];
913 * Removes the node with the given key and type from the collection
915 * @param string|int $key The key of the node we want to find.
916 * @param int $type
917 * @return bool
919 public function remove($key, $type=null) {
920 $child = $this->get($key, $type);
921 if ($child !== false) {
922 foreach ($this->collection as $colkey => $node) {
923 if ($node->key === $key && $node->type == $type) {
924 unset($this->collection[$colkey]);
925 $this->collection = array_values($this->collection);
926 break;
929 unset($this->orderedcollection[$child->type][$child->key]);
930 $this->count--;
931 return true;
933 return false;
937 * Gets the number of nodes in this collection
939 * This option uses an internal count rather than counting the actual options to avoid
940 * a performance hit through the count function.
942 * @return int
944 public function count() {
945 return $this->count;
948 * Gets an array iterator for the collection.
950 * This is required by the IteratorAggregator interface and is used by routines
951 * such as the foreach loop.
953 * @return ArrayIterator
955 public function getIterator() {
956 return new ArrayIterator($this->collection);
961 * The global navigation class used for... the global navigation
963 * This class is used by PAGE to store the global navigation for the site
964 * and is then used by the settings nav and navbar to save on processing and DB calls
966 * See
967 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
968 * {@link lib/ajax/getnavbranch.php} Called by ajax
970 * @package core
971 * @category navigation
972 * @copyright 2009 Sam Hemelryk
973 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
975 class global_navigation extends navigation_node {
976 /** @var moodle_page The Moodle page this navigation object belongs to. */
977 protected $page;
978 /** @var bool switch to let us know if the navigation object is initialised*/
979 protected $initialised = false;
980 /** @var array An array of course information */
981 protected $mycourses = array();
982 /** @var array An array for containing root navigation nodes */
983 protected $rootnodes = array();
984 /** @var bool A switch for whether to show empty sections in the navigation */
985 protected $showemptysections = true;
986 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
987 protected $showcategories = null;
988 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
989 protected $showmycategories = null;
990 /** @var array An array of stdClasses for users that the navigation is extended for */
991 protected $extendforuser = array();
992 /** @var navigation_cache */
993 protected $cache;
994 /** @var array An array of course ids that are present in the navigation */
995 protected $addedcourses = array();
996 /** @var bool */
997 protected $allcategoriesloaded = false;
998 /** @var array An array of category ids that are included in the navigation */
999 protected $addedcategories = array();
1000 /** @var int expansion limit */
1001 protected $expansionlimit = 0;
1002 /** @var int userid to allow parent to see child's profile page navigation */
1003 protected $useridtouseforparentchecks = 0;
1005 /** Used when loading categories to load all top level categories [parent = 0] **/
1006 const LOAD_ROOT_CATEGORIES = 0;
1007 /** Used when loading categories to load all categories **/
1008 const LOAD_ALL_CATEGORIES = -1;
1011 * Constructs a new global navigation
1013 * @param moodle_page $page The page this navigation object belongs to
1015 public function __construct(moodle_page $page) {
1016 global $CFG, $SITE, $USER;
1018 if (during_initial_install()) {
1019 return;
1022 if (get_home_page() == HOMEPAGE_SITE) {
1023 // We are using the site home for the root element
1024 $properties = array(
1025 'key' => 'home',
1026 'type' => navigation_node::TYPE_SYSTEM,
1027 'text' => get_string('home'),
1028 'action' => new moodle_url('/')
1030 } else {
1031 // We are using the users my moodle for the root element
1032 $properties = array(
1033 'key' => 'myhome',
1034 'type' => navigation_node::TYPE_SYSTEM,
1035 'text' => get_string('myhome'),
1036 'action' => new moodle_url('/my/')
1040 // Use the parents constructor.... good good reuse
1041 parent::__construct($properties);
1043 // Initalise and set defaults
1044 $this->page = $page;
1045 $this->forceopen = true;
1046 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1050 * Mutator to set userid to allow parent to see child's profile
1051 * page navigation. See MDL-25805 for initial issue. Linked to it
1052 * is an issue explaining why this is a REALLY UGLY HACK thats not
1053 * for you to use!
1055 * @param int $userid userid of profile page that parent wants to navigate around.
1057 public function set_userid_for_parent_checks($userid) {
1058 $this->useridtouseforparentchecks = $userid;
1063 * Initialises the navigation object.
1065 * This causes the navigation object to look at the current state of the page
1066 * that it is associated with and then load the appropriate content.
1068 * This should only occur the first time that the navigation structure is utilised
1069 * which will normally be either when the navbar is called to be displayed or
1070 * when a block makes use of it.
1072 * @return bool
1074 public function initialise() {
1075 global $CFG, $SITE, $USER;
1076 // Check if it has already been initialised
1077 if ($this->initialised || during_initial_install()) {
1078 return true;
1080 $this->initialised = true;
1082 // Set up the five base root nodes. These are nodes where we will put our
1083 // content and are as follows:
1084 // site: Navigation for the front page.
1085 // myprofile: User profile information goes here.
1086 // currentcourse: The course being currently viewed.
1087 // mycourses: The users courses get added here.
1088 // courses: Additional courses are added here.
1089 // users: Other users information loaded here.
1090 $this->rootnodes = array();
1091 if (get_home_page() == HOMEPAGE_SITE) {
1092 // The home element should be my moodle because the root element is the site
1093 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1094 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1096 } else {
1097 // The home element should be the site because the root node is my moodle
1098 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1099 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1100 // We need to stop automatic redirection
1101 $this->rootnodes['home']->action->param('redirect', '0');
1104 $this->rootnodes['site'] = $this->add_course($SITE);
1105 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1106 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1107 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
1108 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1109 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1111 // We always load the frontpage course to ensure it is available without
1112 // JavaScript enabled.
1113 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1114 $this->load_course_sections($SITE, $this->rootnodes['site']);
1116 $course = $this->page->course;
1118 // $issite gets set to true if the current pages course is the sites frontpage course
1119 $issite = ($this->page->course->id == $SITE->id);
1120 // Determine if the user is enrolled in any course.
1121 $enrolledinanycourse = enrol_user_sees_own_courses();
1123 $this->rootnodes['currentcourse']->mainnavonly = true;
1124 if ($enrolledinanycourse) {
1125 $this->rootnodes['mycourses']->isexpandable = true;
1126 if ($CFG->navshowallcourses) {
1127 // When we show all courses we need to show both the my courses and the regular courses branch.
1128 $this->rootnodes['courses']->isexpandable = true;
1130 } else {
1131 $this->rootnodes['courses']->isexpandable = true;
1134 if ($this->rootnodes['mycourses']->isactive) {
1135 $this->load_courses_enrolled();
1138 $canviewcourseprofile = true;
1140 // Next load context specific content into the navigation
1141 switch ($this->page->context->contextlevel) {
1142 case CONTEXT_SYSTEM :
1143 // Nothing left to do here I feel.
1144 break;
1145 case CONTEXT_COURSECAT :
1146 // This is essential, we must load categories.
1147 $this->load_all_categories($this->page->context->instanceid, true);
1148 break;
1149 case CONTEXT_BLOCK :
1150 case CONTEXT_COURSE :
1151 if ($issite) {
1152 // Nothing left to do here.
1153 break;
1156 // Load the course associated with the current page into the navigation.
1157 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1158 // If the course wasn't added then don't try going any further.
1159 if (!$coursenode) {
1160 $canviewcourseprofile = false;
1161 break;
1164 // If the user is not enrolled then we only want to show the
1165 // course node and not populate it.
1167 // Not enrolled, can't view, and hasn't switched roles
1168 if (!can_access_course($course)) {
1169 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1170 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1171 if (!$this->current_user_is_parent_role()) {
1172 $coursenode->make_active();
1173 $canviewcourseprofile = false;
1174 break;
1178 // Add the essentials such as reports etc...
1179 $this->add_course_essentials($coursenode, $course);
1180 // Extend course navigation with it's sections/activities
1181 $this->load_course_sections($course, $coursenode);
1182 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1183 $coursenode->make_active();
1186 break;
1187 case CONTEXT_MODULE :
1188 if ($issite) {
1189 // If this is the site course then most information will have
1190 // already been loaded.
1191 // However we need to check if there is more content that can
1192 // yet be loaded for the specific module instance.
1193 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1194 if ($activitynode) {
1195 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1197 break;
1200 $course = $this->page->course;
1201 $cm = $this->page->cm;
1203 // Load the course associated with the page into the navigation
1204 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1206 // If the course wasn't added then don't try going any further.
1207 if (!$coursenode) {
1208 $canviewcourseprofile = false;
1209 break;
1212 // If the user is not enrolled then we only want to show the
1213 // course node and not populate it.
1214 if (!can_access_course($course)) {
1215 $coursenode->make_active();
1216 $canviewcourseprofile = false;
1217 break;
1220 $this->add_course_essentials($coursenode, $course);
1222 // Load the course sections into the page
1223 $this->load_course_sections($course, $coursenode, null, $cm);
1224 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1225 if (!empty($activity)) {
1226 // Finally load the cm specific navigaton information
1227 $this->load_activity($cm, $course, $activity);
1228 // Check if we have an active ndoe
1229 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1230 // And make the activity node active.
1231 $activity->make_active();
1234 break;
1235 case CONTEXT_USER :
1236 if ($issite) {
1237 // The users profile information etc is already loaded
1238 // for the front page.
1239 break;
1241 $course = $this->page->course;
1242 // Load the course associated with the user into the navigation
1243 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1245 // If the course wasn't added then don't try going any further.
1246 if (!$coursenode) {
1247 $canviewcourseprofile = false;
1248 break;
1251 // If the user is not enrolled then we only want to show the
1252 // course node and not populate it.
1253 if (!can_access_course($course)) {
1254 $coursenode->make_active();
1255 $canviewcourseprofile = false;
1256 break;
1258 $this->add_course_essentials($coursenode, $course);
1259 $this->load_course_sections($course, $coursenode);
1260 break;
1263 // Load for the current user
1264 $this->load_for_user();
1265 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1266 $this->load_for_user(null, true);
1268 // Load each extending user into the navigation.
1269 foreach ($this->extendforuser as $user) {
1270 if ($user->id != $USER->id) {
1271 $this->load_for_user($user);
1275 // Give the local plugins a chance to include some navigation if they want.
1276 foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1277 $function = "local_{$plugin}_extends_navigation";
1278 $oldfunction = "{$plugin}_extends_navigation";
1279 if (function_exists($function)) {
1280 // This is the preferred function name as there is less chance of conflicts
1281 $function($this);
1282 } else if (function_exists($oldfunction)) {
1283 // We continue to support the old function name to ensure backwards compatibility
1284 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);
1285 $oldfunction($this);
1289 // Remove any empty root nodes
1290 foreach ($this->rootnodes as $node) {
1291 // Dont remove the home node
1292 /** @var navigation_node $node */
1293 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1294 $node->remove();
1298 if (!$this->contains_active_node()) {
1299 $this->search_for_active_node();
1302 // If the user is not logged in modify the navigation structure as detailed
1303 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1304 if (!isloggedin()) {
1305 $activities = clone($this->rootnodes['site']->children);
1306 $this->rootnodes['site']->remove();
1307 $children = clone($this->children);
1308 $this->children = new navigation_node_collection();
1309 foreach ($activities as $child) {
1310 $this->children->add($child);
1312 foreach ($children as $child) {
1313 $this->children->add($child);
1316 return true;
1320 * Returns true if the current user is a parent of the user being currently viewed.
1322 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1323 * other user being viewed this function returns false.
1324 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1326 * @since Moodle 2.4
1327 * @return bool
1329 protected function current_user_is_parent_role() {
1330 global $USER, $DB;
1331 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1332 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1333 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1334 return false;
1336 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1337 return true;
1340 return false;
1344 * Returns true if courses should be shown within categories on the navigation.
1346 * @param bool $ismycourse Set to true if you are calculating this for a course.
1347 * @return bool
1349 protected function show_categories($ismycourse = false) {
1350 global $CFG, $DB;
1351 if ($ismycourse) {
1352 return $this->show_my_categories();
1354 if ($this->showcategories === null) {
1355 $show = false;
1356 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1357 $show = true;
1358 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1359 $show = true;
1361 $this->showcategories = $show;
1363 return $this->showcategories;
1367 * Returns true if we should show categories in the My Courses branch.
1368 * @return bool
1370 protected function show_my_categories() {
1371 global $CFG, $DB;
1372 if ($this->showmycategories === null) {
1373 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1375 return $this->showmycategories;
1379 * Loads the courses in Moodle into the navigation.
1381 * @global moodle_database $DB
1382 * @param string|array $categoryids An array containing categories to load courses
1383 * for, OR null to load courses for all categories.
1384 * @return array An array of navigation_nodes one for each course
1386 protected function load_all_courses($categoryids = null) {
1387 global $CFG, $DB, $SITE;
1389 // Work out the limit of courses.
1390 $limit = 20;
1391 if (!empty($CFG->navcourselimit)) {
1392 $limit = $CFG->navcourselimit;
1395 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1397 // If we are going to show all courses AND we are showing categories then
1398 // to save us repeated DB calls load all of the categories now
1399 if ($this->show_categories()) {
1400 $this->load_all_categories($toload);
1403 // Will be the return of our efforts
1404 $coursenodes = array();
1406 // Check if we need to show categories.
1407 if ($this->show_categories()) {
1408 // Hmmm we need to show categories... this is going to be painful.
1409 // We now need to fetch up to $limit courses for each category to
1410 // be displayed.
1411 if ($categoryids !== null) {
1412 if (!is_array($categoryids)) {
1413 $categoryids = array($categoryids);
1415 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1416 $categorywhere = 'WHERE cc.id '.$categorywhere;
1417 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1418 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1419 $categoryparams = array();
1420 } else {
1421 $categorywhere = '';
1422 $categoryparams = array();
1425 // First up we are going to get the categories that we are going to
1426 // need so that we can determine how best to load the courses from them.
1427 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1428 FROM {course_categories} cc
1429 LEFT JOIN {course} c ON c.category = cc.id
1430 {$categorywhere}
1431 GROUP BY cc.id";
1432 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1433 $fullfetch = array();
1434 $partfetch = array();
1435 foreach ($categories as $category) {
1436 if (!$this->can_add_more_courses_to_category($category->id)) {
1437 continue;
1439 if ($category->coursecount > $limit * 5) {
1440 $partfetch[] = $category->id;
1441 } else if ($category->coursecount > 0) {
1442 $fullfetch[] = $category->id;
1445 $categories->close();
1447 if (count($fullfetch)) {
1448 // First up fetch all of the courses in categories where we know that we are going to
1449 // need the majority of courses.
1450 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1451 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1452 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1453 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1454 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1455 FROM {course} c
1456 $ccjoin
1457 WHERE c.category {$categoryids}
1458 ORDER BY c.sortorder ASC";
1459 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1460 foreach ($coursesrs as $course) {
1461 if ($course->id == $SITE->id) {
1462 // This should not be necessary, frontpage is not in any category.
1463 continue;
1465 if (array_key_exists($course->id, $this->addedcourses)) {
1466 // It is probably better to not include the already loaded courses
1467 // directly in SQL because inequalities may confuse query optimisers
1468 // and may interfere with query caching.
1469 continue;
1471 if (!$this->can_add_more_courses_to_category($course->category)) {
1472 continue;
1474 context_helper::preload_from_record($course);
1475 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1476 continue;
1478 $coursenodes[$course->id] = $this->add_course($course);
1480 $coursesrs->close();
1483 if (count($partfetch)) {
1484 // Next we will work our way through the categories where we will likely only need a small
1485 // proportion of the courses.
1486 foreach ($partfetch as $categoryid) {
1487 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1488 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1489 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1490 FROM {course} c
1491 $ccjoin
1492 WHERE c.category = :categoryid
1493 ORDER BY c.sortorder ASC";
1494 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1495 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1496 foreach ($coursesrs as $course) {
1497 if ($course->id == $SITE->id) {
1498 // This should not be necessary, frontpage is not in any category.
1499 continue;
1501 if (array_key_exists($course->id, $this->addedcourses)) {
1502 // It is probably better to not include the already loaded courses
1503 // directly in SQL because inequalities may confuse query optimisers
1504 // and may interfere with query caching.
1505 // This also helps to respect expected $limit on repeated executions.
1506 continue;
1508 if (!$this->can_add_more_courses_to_category($course->category)) {
1509 break;
1511 context_helper::preload_from_record($course);
1512 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1513 continue;
1515 $coursenodes[$course->id] = $this->add_course($course);
1517 $coursesrs->close();
1520 } else {
1521 // Prepare the SQL to load the courses and their contexts
1522 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1523 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1524 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1525 $courseparams['contextlevel'] = CONTEXT_COURSE;
1526 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1527 FROM {course} c
1528 $ccjoin
1529 WHERE c.id {$courseids}
1530 ORDER BY c.sortorder ASC";
1531 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1532 foreach ($coursesrs as $course) {
1533 if ($course->id == $SITE->id) {
1534 // frotpage is not wanted here
1535 continue;
1537 if ($this->page->course && ($this->page->course->id == $course->id)) {
1538 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1539 continue;
1541 context_helper::preload_from_record($course);
1542 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1543 continue;
1545 $coursenodes[$course->id] = $this->add_course($course);
1546 if (count($coursenodes) >= $limit) {
1547 break;
1550 $coursesrs->close();
1553 return $coursenodes;
1557 * Returns true if more courses can be added to the provided category.
1559 * @param int|navigation_node|stdClass $category
1560 * @return bool
1562 protected function can_add_more_courses_to_category($category) {
1563 global $CFG;
1564 $limit = 20;
1565 if (!empty($CFG->navcourselimit)) {
1566 $limit = (int)$CFG->navcourselimit;
1568 if (is_numeric($category)) {
1569 if (!array_key_exists($category, $this->addedcategories)) {
1570 return true;
1572 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1573 } else if ($category instanceof navigation_node) {
1574 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1575 return false;
1577 $coursecount = count($category->children->type(self::TYPE_COURSE));
1578 } else if (is_object($category) && property_exists($category,'id')) {
1579 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1581 return ($coursecount <= $limit);
1585 * Loads all categories (top level or if an id is specified for that category)
1587 * @param int $categoryid The category id to load or null/0 to load all base level categories
1588 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1589 * as the requested category and any parent categories.
1590 * @return navigation_node|void returns a navigation node if a category has been loaded.
1592 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1593 global $CFG, $DB;
1595 // Check if this category has already been loaded
1596 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1597 return true;
1600 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1601 $sqlselect = "SELECT cc.*, $catcontextsql
1602 FROM {course_categories} cc
1603 JOIN {context} ctx ON cc.id = ctx.instanceid";
1604 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1605 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1606 $params = array();
1608 $categoriestoload = array();
1609 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1610 // We are going to load all categories regardless... prepare to fire
1611 // on the database server!
1612 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1613 // We are going to load all of the first level categories (categories without parents)
1614 $sqlwhere .= " AND cc.parent = 0";
1615 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1616 // The category itself has been loaded already so we just need to ensure its subcategories
1617 // have been loaded
1618 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1619 if ($showbasecategories) {
1620 // We need to include categories with parent = 0 as well
1621 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1622 } else {
1623 // All we need is categories that match the parent
1624 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1626 $params['categoryid'] = $categoryid;
1627 } else {
1628 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1629 // and load this category plus all its parents and subcategories
1630 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1631 $categoriestoload = explode('/', trim($category->path, '/'));
1632 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1633 // We are going to use select twice so double the params
1634 $params = array_merge($params, $params);
1635 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1636 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1639 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1640 $categories = array();
1641 foreach ($categoriesrs as $category) {
1642 // Preload the context.. we'll need it when adding the category in order
1643 // to format the category name.
1644 context_helper::preload_from_record($category);
1645 if (array_key_exists($category->id, $this->addedcategories)) {
1646 // Do nothing, its already been added.
1647 } else if ($category->parent == '0') {
1648 // This is a root category lets add it immediately
1649 $this->add_category($category, $this->rootnodes['courses']);
1650 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1651 // This categories parent has already been added we can add this immediately
1652 $this->add_category($category, $this->addedcategories[$category->parent]);
1653 } else {
1654 $categories[] = $category;
1657 $categoriesrs->close();
1659 // Now we have an array of categories we need to add them to the navigation.
1660 while (!empty($categories)) {
1661 $category = reset($categories);
1662 if (array_key_exists($category->id, $this->addedcategories)) {
1663 // Do nothing
1664 } else if ($category->parent == '0') {
1665 $this->add_category($category, $this->rootnodes['courses']);
1666 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1667 $this->add_category($category, $this->addedcategories[$category->parent]);
1668 } else {
1669 // This category isn't in the navigation and niether is it's parent (yet).
1670 // We need to go through the category path and add all of its components in order.
1671 $path = explode('/', trim($category->path, '/'));
1672 foreach ($path as $catid) {
1673 if (!array_key_exists($catid, $this->addedcategories)) {
1674 // This category isn't in the navigation yet so add it.
1675 $subcategory = $categories[$catid];
1676 if ($subcategory->parent == '0') {
1677 // Yay we have a root category - this likely means we will now be able
1678 // to add categories without problems.
1679 $this->add_category($subcategory, $this->rootnodes['courses']);
1680 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1681 // The parent is in the category (as we'd expect) so add it now.
1682 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1683 // Remove the category from the categories array.
1684 unset($categories[$catid]);
1685 } else {
1686 // We should never ever arrive here - if we have then there is a bigger
1687 // problem at hand.
1688 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1693 // Remove the category from the categories array now that we know it has been added.
1694 unset($categories[$category->id]);
1696 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1697 $this->allcategoriesloaded = true;
1699 // Check if there are any categories to load.
1700 if (count($categoriestoload) > 0) {
1701 $readytoloadcourses = array();
1702 foreach ($categoriestoload as $category) {
1703 if ($this->can_add_more_courses_to_category($category)) {
1704 $readytoloadcourses[] = $category;
1707 if (count($readytoloadcourses)) {
1708 $this->load_all_courses($readytoloadcourses);
1712 // Look for all categories which have been loaded
1713 if (!empty($this->addedcategories)) {
1714 $categoryids = array();
1715 foreach ($this->addedcategories as $category) {
1716 if ($this->can_add_more_courses_to_category($category)) {
1717 $categoryids[] = $category->key;
1720 if ($categoryids) {
1721 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1722 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1723 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1724 FROM {course_categories} cc
1725 JOIN {course} c ON c.category = cc.id
1726 WHERE cc.id {$categoriessql}
1727 GROUP BY cc.id
1728 HAVING COUNT(c.id) > :limit";
1729 $excessivecategories = $DB->get_records_sql($sql, $params);
1730 foreach ($categories as &$category) {
1731 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1732 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1733 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1741 * Adds a structured category to the navigation in the correct order/place
1743 * @param stdClass $category category to be added in navigation.
1744 * @param navigation_node $parent parent navigation node
1745 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1746 * @return void.
1748 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1749 if (array_key_exists($category->id, $this->addedcategories)) {
1750 return;
1752 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1753 $context = context_coursecat::instance($category->id);
1754 $categoryname = format_string($category->name, true, array('context' => $context));
1755 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1756 if (empty($category->visible)) {
1757 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1758 $categorynode->hidden = true;
1759 } else {
1760 $categorynode->display = false;
1763 $this->addedcategories[$category->id] = $categorynode;
1767 * Loads the given course into the navigation
1769 * @param stdClass $course
1770 * @return navigation_node
1772 protected function load_course(stdClass $course) {
1773 global $SITE;
1774 if ($course->id == $SITE->id) {
1775 // This is always loaded during initialisation
1776 return $this->rootnodes['site'];
1777 } else if (array_key_exists($course->id, $this->addedcourses)) {
1778 // The course has already been loaded so return a reference
1779 return $this->addedcourses[$course->id];
1780 } else {
1781 // Add the course
1782 return $this->add_course($course);
1787 * Loads all of the courses section into the navigation.
1789 * This function calls method from current course format, see
1790 * {@link format_base::extend_course_navigation()}
1791 * If course module ($cm) is specified but course format failed to create the node,
1792 * the activity node is created anyway.
1794 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1796 * @param stdClass $course Database record for the course
1797 * @param navigation_node $coursenode The course node within the navigation
1798 * @param null|int $sectionnum If specified load the contents of section with this relative number
1799 * @param null|cm_info $cm If specified make sure that activity node is created (either
1800 * in containg section or by calling load_stealth_activity() )
1802 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1803 global $CFG, $SITE;
1804 require_once($CFG->dirroot.'/course/lib.php');
1805 if (isset($cm->sectionnum)) {
1806 $sectionnum = $cm->sectionnum;
1808 if ($sectionnum !== null) {
1809 $this->includesectionnum = $sectionnum;
1811 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1812 if (isset($cm->id)) {
1813 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1814 if (empty($activity)) {
1815 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1821 * Generates an array of sections and an array of activities for the given course.
1823 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1825 * @param stdClass $course
1826 * @return array Array($sections, $activities)
1828 protected function generate_sections_and_activities(stdClass $course) {
1829 global $CFG;
1830 require_once($CFG->dirroot.'/course/lib.php');
1832 $modinfo = get_fast_modinfo($course);
1833 $sections = $modinfo->get_section_info_all();
1835 // For course formats using 'numsections' trim the sections list
1836 $courseformatoptions = course_get_format($course)->get_format_options();
1837 if (isset($courseformatoptions['numsections'])) {
1838 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1841 $activities = array();
1843 foreach ($sections as $key => $section) {
1844 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1845 $sections[$key] = clone($section);
1846 unset($sections[$key]->summary);
1847 $sections[$key]->hasactivites = false;
1848 if (!array_key_exists($section->section, $modinfo->sections)) {
1849 continue;
1851 foreach ($modinfo->sections[$section->section] as $cmid) {
1852 $cm = $modinfo->cms[$cmid];
1853 $activity = new stdClass;
1854 $activity->id = $cm->id;
1855 $activity->course = $course->id;
1856 $activity->section = $section->section;
1857 $activity->name = $cm->name;
1858 $activity->icon = $cm->icon;
1859 $activity->iconcomponent = $cm->iconcomponent;
1860 $activity->hidden = (!$cm->visible);
1861 $activity->modname = $cm->modname;
1862 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1863 $activity->onclick = $cm->onclick;
1864 $url = $cm->url;
1865 if (!$url) {
1866 $activity->url = null;
1867 $activity->display = false;
1868 } else {
1869 $activity->url = $url->out();
1870 $activity->display = $cm->uservisible ? true : false;
1871 if (self::module_extends_navigation($cm->modname)) {
1872 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1875 $activities[$cmid] = $activity;
1876 if ($activity->display) {
1877 $sections[$key]->hasactivites = true;
1882 return array($sections, $activities);
1886 * Generically loads the course sections into the course's navigation.
1888 * @param stdClass $course
1889 * @param navigation_node $coursenode
1890 * @return array An array of course section nodes
1892 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1893 global $CFG, $DB, $USER, $SITE;
1894 require_once($CFG->dirroot.'/course/lib.php');
1896 list($sections, $activities) = $this->generate_sections_and_activities($course);
1898 $navigationsections = array();
1899 foreach ($sections as $sectionid => $section) {
1900 $section = clone($section);
1901 if ($course->id == $SITE->id) {
1902 $this->load_section_activities($coursenode, $section->section, $activities);
1903 } else {
1904 if (!$section->uservisible || (!$this->showemptysections &&
1905 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1906 continue;
1909 $sectionname = get_section_name($course, $section);
1910 $url = course_get_url($course, $section->section, array('navigation' => true));
1912 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1913 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1914 $sectionnode->hidden = (!$section->visible || !$section->available);
1915 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1916 $this->load_section_activities($sectionnode, $section->section, $activities);
1918 $section->sectionnode = $sectionnode;
1919 $navigationsections[$sectionid] = $section;
1922 return $navigationsections;
1926 * Loads all of the activities for a section into the navigation structure.
1928 * @param navigation_node $sectionnode
1929 * @param int $sectionnumber
1930 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1931 * @param stdClass $course The course object the section and activities relate to.
1932 * @return array Array of activity nodes
1934 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1935 global $CFG, $SITE;
1936 // A static counter for JS function naming
1937 static $legacyonclickcounter = 0;
1939 $activitynodes = array();
1940 if (empty($activities)) {
1941 return $activitynodes;
1944 if (!is_object($course)) {
1945 $activity = reset($activities);
1946 $courseid = $activity->course;
1947 } else {
1948 $courseid = $course->id;
1950 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1952 foreach ($activities as $activity) {
1953 if ($activity->section != $sectionnumber) {
1954 continue;
1956 if ($activity->icon) {
1957 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1958 } else {
1959 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1962 // Prepare the default name and url for the node
1963 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1964 $action = new moodle_url($activity->url);
1966 // Check if the onclick property is set (puke!)
1967 if (!empty($activity->onclick)) {
1968 // Increment the counter so that we have a unique number.
1969 $legacyonclickcounter++;
1970 // Generate the function name we will use
1971 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1972 $propogrationhandler = '';
1973 // Check if we need to cancel propogation. Remember inline onclick
1974 // events would return false if they wanted to prevent propogation and the
1975 // default action.
1976 if (strpos($activity->onclick, 'return false')) {
1977 $propogrationhandler = 'e.halt();';
1979 // Decode the onclick - it has already been encoded for display (puke)
1980 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
1981 // Build the JS function the click event will call
1982 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1983 $this->page->requires->js_init_code($jscode);
1984 // Override the default url with the new action link
1985 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1988 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1989 $activitynode->title(get_string('modulename', $activity->modname));
1990 $activitynode->hidden = $activity->hidden;
1991 $activitynode->display = $showactivities && $activity->display;
1992 $activitynode->nodetype = $activity->nodetype;
1993 $activitynodes[$activity->id] = $activitynode;
1996 return $activitynodes;
1999 * Loads a stealth module from unavailable section
2000 * @param navigation_node $coursenode
2001 * @param stdClass $modinfo
2002 * @return navigation_node or null if not accessible
2004 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2005 if (empty($modinfo->cms[$this->page->cm->id])) {
2006 return null;
2008 $cm = $modinfo->cms[$this->page->cm->id];
2009 if ($cm->icon) {
2010 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2011 } else {
2012 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2014 $url = $cm->url;
2015 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2016 $activitynode->title(get_string('modulename', $cm->modname));
2017 $activitynode->hidden = (!$cm->visible);
2018 if (!$cm->uservisible) {
2019 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2020 // Also there may be no exception at all in case when teacher is logged in as student.
2021 $activitynode->display = false;
2022 } else if (!$url) {
2023 // Don't show activities that don't have links!
2024 $activitynode->display = false;
2025 } else if (self::module_extends_navigation($cm->modname)) {
2026 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2028 return $activitynode;
2031 * Loads the navigation structure for the given activity into the activities node.
2033 * This method utilises a callback within the modules lib.php file to load the
2034 * content specific to activity given.
2036 * The callback is a method: {modulename}_extend_navigation()
2037 * Examples:
2038 * * {@link forum_extend_navigation()}
2039 * * {@link workshop_extend_navigation()}
2041 * @param cm_info|stdClass $cm
2042 * @param stdClass $course
2043 * @param navigation_node $activity
2044 * @return bool
2046 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2047 global $CFG, $DB;
2049 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2050 if (!($cm instanceof cm_info)) {
2051 $modinfo = get_fast_modinfo($course);
2052 $cm = $modinfo->get_cm($cm->id);
2054 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2055 $activity->make_active();
2056 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2057 $function = $cm->modname.'_extend_navigation';
2059 if (file_exists($file)) {
2060 require_once($file);
2061 if (function_exists($function)) {
2062 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2063 $function($activity, $course, $activtyrecord, $cm);
2067 // Allow the active advanced grading method plugin to append module navigation
2068 $featuresfunc = $cm->modname.'_supports';
2069 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2070 require_once($CFG->dirroot.'/grade/grading/lib.php');
2071 $gradingman = get_grading_manager($cm->context, $cm->modname);
2072 $gradingman->extend_navigation($this, $activity);
2075 return $activity->has_children();
2078 * Loads user specific information into the navigation in the appropriate place.
2080 * If no user is provided the current user is assumed.
2082 * @param stdClass $user
2083 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2084 * @return bool
2086 protected function load_for_user($user=null, $forceforcontext=false) {
2087 global $DB, $CFG, $USER, $SITE;
2089 if ($user === null) {
2090 // We can't require login here but if the user isn't logged in we don't
2091 // want to show anything
2092 if (!isloggedin() || isguestuser()) {
2093 return false;
2095 $user = $USER;
2096 } else if (!is_object($user)) {
2097 // If the user is not an object then get them from the database
2098 $select = context_helper::get_preload_record_columns_sql('ctx');
2099 $sql = "SELECT u.*, $select
2100 FROM {user} u
2101 JOIN {context} ctx ON u.id = ctx.instanceid
2102 WHERE u.id = :userid AND
2103 ctx.contextlevel = :contextlevel";
2104 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2105 context_helper::preload_from_record($user);
2108 $iscurrentuser = ($user->id == $USER->id);
2110 $usercontext = context_user::instance($user->id);
2112 // Get the course set against the page, by default this will be the site
2113 $course = $this->page->course;
2114 $baseargs = array('id'=>$user->id);
2115 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2116 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2117 $baseargs['course'] = $course->id;
2118 $coursecontext = context_course::instance($course->id);
2119 $issitecourse = false;
2120 } else {
2121 // Load all categories and get the context for the system
2122 $coursecontext = context_system::instance();
2123 $issitecourse = true;
2126 // Create a node to add user information under.
2127 if ($iscurrentuser && !$forceforcontext) {
2128 // If it's the current user the information will go under the profile root node
2129 $usernode = $this->rootnodes['myprofile'];
2130 $course = get_site();
2131 $coursecontext = context_course::instance($course->id);
2132 $issitecourse = true;
2133 } else {
2134 if (!$issitecourse) {
2135 // Not the current user so add it to the participants node for the current course
2136 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2137 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2138 } else {
2139 // This is the site so add a users node to the root branch
2140 $usersnode = $this->rootnodes['users'];
2141 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2142 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2144 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2146 if (!$usersnode) {
2147 // We should NEVER get here, if the course hasn't been populated
2148 // with a participants node then the navigaiton either wasn't generated
2149 // for it (you are missing a require_login or set_context call) or
2150 // you don't have access.... in the interests of no leaking informatin
2151 // we simply quit...
2152 return false;
2154 // Add a branch for the current user
2155 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2156 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2158 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2159 $usernode->make_active();
2163 // If the user is the current user or has permission to view the details of the requested
2164 // user than add a view profile link.
2165 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2166 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2167 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2168 } else {
2169 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2173 if (!empty($CFG->navadduserpostslinks)) {
2174 // Add nodes for forum posts and discussions if the user can view either or both
2175 // There are no capability checks here as the content of the page is based
2176 // purely on the forums the current user has access too.
2177 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2178 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2179 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2182 // Add blog nodes
2183 if (!empty($CFG->enableblogs)) {
2184 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2185 require_once($CFG->dirroot.'/blog/lib.php');
2186 // Get all options for the user
2187 $options = blog_get_options_for_user($user);
2188 $this->cache->set('userblogoptions'.$user->id, $options);
2189 } else {
2190 $options = $this->cache->{'userblogoptions'.$user->id};
2193 if (count($options) > 0) {
2194 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2195 foreach ($options as $type => $option) {
2196 if ($type == "rss") {
2197 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2198 } else {
2199 $blogs->add($option['string'], $option['link']);
2205 if (!empty($CFG->messaging)) {
2206 $messageargs = array('user1' => $USER->id);
2207 if ($USER->id != $user->id) {
2208 $messageargs['user2'] = $user->id;
2210 if ($course->id != $SITE->id) {
2211 $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
2213 $url = new moodle_url('/message/index.php',$messageargs);
2214 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2217 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
2218 $url = new moodle_url('/user/files.php');
2219 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2222 if (!empty($CFG->enablebadges) && $iscurrentuser &&
2223 has_capability('moodle/badges:manageownbadges', context_user::instance($USER->id))) {
2224 $url = new moodle_url('/badges/mybadges.php');
2225 $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2228 // Add a node to view the users notes if permitted
2229 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2230 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2231 if ($coursecontext->instanceid != SITEID) {
2232 $url->param('course', $coursecontext->instanceid);
2234 $usernode->add(get_string('notes', 'notes'), $url);
2237 // If the user is the current user add the repositories for the current user
2238 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2239 if ($iscurrentuser) {
2240 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2241 require_once($CFG->dirroot . '/repository/lib.php');
2242 $editabletypes = repository::get_editable_types($usercontext);
2243 $haseditabletypes = !empty($editabletypes);
2244 unset($editabletypes);
2245 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2246 } else {
2247 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2249 if ($haseditabletypes) {
2250 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2252 } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2254 // Add view grade report is permitted
2255 $reports = core_component::get_plugin_list('gradereport');
2256 arsort($reports); // user is last, we want to test it first
2258 $userscourses = enrol_get_users_courses($user->id);
2259 $userscoursesnode = $usernode->add(get_string('courses'));
2261 foreach ($userscourses as $usercourse) {
2262 $usercoursecontext = context_course::instance($usercourse->id);
2263 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2264 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2266 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2267 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2268 foreach ($reports as $plugin => $plugindir) {
2269 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2270 //stop when the first visible plugin is found
2271 $gradeavailable = true;
2272 break;
2277 if ($gradeavailable) {
2278 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2279 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2282 // Add a node to view the users notes if permitted
2283 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2284 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2285 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2288 if (can_access_course($usercourse, $user->id)) {
2289 $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', ''));
2292 $reporttab = $usercoursenode->add(get_string('activityreports'));
2294 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2295 foreach ($reports as $reportfunction) {
2296 $reportfunction($reporttab, $user, $usercourse);
2299 $reporttab->trim_if_empty();
2302 return true;
2306 * This method simply checks to see if a given module can extend the navigation.
2308 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2310 * @param string $modname
2311 * @return bool
2313 public static function module_extends_navigation($modname) {
2314 global $CFG;
2315 static $extendingmodules = array();
2316 if (!array_key_exists($modname, $extendingmodules)) {
2317 $extendingmodules[$modname] = false;
2318 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2319 if (file_exists($file)) {
2320 $function = $modname.'_extend_navigation';
2321 require_once($file);
2322 $extendingmodules[$modname] = (function_exists($function));
2325 return $extendingmodules[$modname];
2328 * Extends the navigation for the given user.
2330 * @param stdClass $user A user from the database
2332 public function extend_for_user($user) {
2333 $this->extendforuser[] = $user;
2337 * Returns all of the users the navigation is being extended for
2339 * @return array An array of extending users.
2341 public function get_extending_users() {
2342 return $this->extendforuser;
2345 * Adds the given course to the navigation structure.
2347 * @param stdClass $course
2348 * @param bool $forcegeneric
2349 * @param bool $ismycourse
2350 * @return navigation_node
2352 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2353 global $CFG, $SITE;
2355 // We found the course... we can return it now :)
2356 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2357 return $this->addedcourses[$course->id];
2360 $coursecontext = context_course::instance($course->id);
2362 if ($course->id != $SITE->id && !$course->visible) {
2363 if (is_role_switched($course->id)) {
2364 // user has to be able to access course in order to switch, let's skip the visibility test here
2365 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2366 return false;
2370 $issite = ($course->id == $SITE->id);
2371 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2372 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2373 // This is the name that will be shown for the course.
2374 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2376 if ($issite) {
2377 $parent = $this;
2378 $url = null;
2379 if (empty($CFG->usesitenameforsitepages)) {
2380 $coursename = get_string('sitepages');
2382 } else if ($coursetype == self::COURSE_CURRENT) {
2383 $parent = $this->rootnodes['currentcourse'];
2384 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2385 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2386 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2387 // Nothing to do here the above statement set $parent to the category within mycourses.
2388 } else {
2389 $parent = $this->rootnodes['mycourses'];
2391 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2392 } else {
2393 $parent = $this->rootnodes['courses'];
2394 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2395 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2396 if (!$this->is_category_fully_loaded($course->category)) {
2397 // We need to load the category structure for this course
2398 $this->load_all_categories($course->category, false);
2400 if (array_key_exists($course->category, $this->addedcategories)) {
2401 $parent = $this->addedcategories[$course->category];
2402 // This could lead to the course being created so we should check whether it is the case again
2403 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2404 return $this->addedcourses[$course->id];
2410 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2411 $coursenode->nodetype = self::NODETYPE_BRANCH;
2412 $coursenode->hidden = (!$course->visible);
2413 // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
2414 // later.
2415 $coursenode->title(str_replace('&amp;', '&', $fullname));
2416 if (!$forcegeneric) {
2417 $this->addedcourses[$course->id] = $coursenode;
2420 return $coursenode;
2424 * Returns true if the category has already been loaded as have any child categories
2426 * @param int $categoryid
2427 * @return bool
2429 protected function is_category_fully_loaded($categoryid) {
2430 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2434 * Adds essential course nodes to the navigation for the given course.
2436 * This method adds nodes such as reports, blogs and participants
2438 * @param navigation_node $coursenode
2439 * @param stdClass $course
2440 * @return bool returns true on successful addition of a node.
2442 public function add_course_essentials($coursenode, stdClass $course) {
2443 global $CFG, $SITE;
2445 if ($course->id == $SITE->id) {
2446 return $this->add_front_page_course_essentials($coursenode, $course);
2449 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2450 return true;
2453 //Participants
2454 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2455 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2456 if (!empty($CFG->enableblogs)) {
2457 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2458 and has_capability('moodle/blog:view', context_system::instance())) {
2459 $blogsurls = new moodle_url('/blog/index.php');
2460 if ($course->id == $SITE->id) {
2461 $blogsurls->param('courseid', 0);
2462 } else if ($currentgroup = groups_get_course_group($course, true)) {
2463 $blogsurls->param('groupid', $currentgroup);
2464 } else {
2465 $blogsurls->param('courseid', $course->id);
2467 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2470 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2471 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2473 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2474 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2477 // Badges.
2478 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2479 has_capability('moodle/badges:viewbadges', $this->page->context)) {
2480 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2482 $coursenode->add(get_string('coursebadges', 'badges'), null,
2483 navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2484 $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2485 navigation_node::TYPE_SETTING, null, 'badgesview',
2486 new pix_icon('i/badge', get_string('badgesview', 'badges')));
2489 return true;
2492 * This generates the structure of the course that won't be generated when
2493 * the modules and sections are added.
2495 * Things such as the reports branch, the participants branch, blogs... get
2496 * added to the course node by this method.
2498 * @param navigation_node $coursenode
2499 * @param stdClass $course
2500 * @return bool True for successfull generation
2502 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2503 global $CFG;
2505 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2506 return true;
2509 // Hidden node that we use to determine if the front page navigation is loaded.
2510 // This required as there are not other guaranteed nodes that may be loaded.
2511 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2513 //Participants
2514 if (has_capability('moodle/course:viewparticipants', context_system::instance())) {
2515 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2518 $filterselect = 0;
2520 // Blogs
2521 if (!empty($CFG->enableblogs)
2522 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2523 and has_capability('moodle/blog:view', context_system::instance())) {
2524 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2525 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2528 //Badges
2529 if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2530 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2531 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2534 // Notes
2535 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2536 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2539 // Tags
2540 if (!empty($CFG->usetags) && isloggedin()) {
2541 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2544 if (isloggedin()) {
2545 // Calendar
2546 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2547 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2550 return true;
2554 * Clears the navigation cache
2556 public function clear_cache() {
2557 $this->cache->clear();
2561 * Sets an expansion limit for the navigation
2563 * The expansion limit is used to prevent the display of content that has a type
2564 * greater than the provided $type.
2566 * Can be used to ensure things such as activities or activity content don't get
2567 * shown on the navigation.
2568 * They are still generated in order to ensure the navbar still makes sense.
2570 * @param int $type One of navigation_node::TYPE_*
2571 * @return bool true when complete.
2573 public function set_expansion_limit($type) {
2574 global $SITE;
2575 $nodes = $this->find_all_of_type($type);
2577 // We only want to hide specific types of nodes.
2578 // Only nodes that represent "structure" in the navigation tree should be hidden.
2579 // If we hide all nodes then we risk hiding vital information.
2580 $typestohide = array(
2581 self::TYPE_CATEGORY,
2582 self::TYPE_COURSE,
2583 self::TYPE_SECTION,
2584 self::TYPE_ACTIVITY
2587 foreach ($nodes as $node) {
2588 // We need to generate the full site node
2589 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2590 continue;
2592 foreach ($node->children as $child) {
2593 $child->hide($typestohide);
2596 return true;
2599 * Attempts to get the navigation with the given key from this nodes children.
2601 * This function only looks at this nodes children, it does NOT look recursivily.
2602 * If the node can't be found then false is returned.
2604 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2606 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2607 * may be of more use to you.
2609 * @param string|int $key The key of the node you wish to receive.
2610 * @param int $type One of navigation_node::TYPE_*
2611 * @return navigation_node|false
2613 public function get($key, $type = null) {
2614 if (!$this->initialised) {
2615 $this->initialise();
2617 return parent::get($key, $type);
2621 * Searches this nodes children and their children to find a navigation node
2622 * with the matching key and type.
2624 * This method is recursive and searches children so until either a node is
2625 * found or there are no more nodes to search.
2627 * If you know that the node being searched for is a child of this node
2628 * then use the {@link global_navigation::get()} method instead.
2630 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2631 * may be of more use to you.
2633 * @param string|int $key The key of the node you wish to receive.
2634 * @param int $type One of navigation_node::TYPE_*
2635 * @return navigation_node|false
2637 public function find($key, $type) {
2638 if (!$this->initialised) {
2639 $this->initialise();
2641 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2642 return $this->rootnodes[$key];
2644 return parent::find($key, $type);
2648 * They've expanded the 'my courses' branch.
2650 protected function load_courses_enrolled() {
2651 global $CFG, $DB;
2652 $sortorder = 'visible DESC';
2653 // Prevent undefined $CFG->navsortmycoursessort errors.
2654 if (empty($CFG->navsortmycoursessort)) {
2655 $CFG->navsortmycoursessort = 'sortorder';
2657 // Append the chosen sortorder.
2658 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2659 $courses = enrol_get_my_courses(null, $sortorder);
2660 if (count($courses) && $this->show_my_categories()) {
2661 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2662 // In order to make sure we load everything required we must first find the categories that are not
2663 // base categories and work out the bottom category in thier path.
2664 $categoryids = array();
2665 foreach ($courses as $course) {
2666 $categoryids[] = $course->category;
2668 $categoryids = array_unique($categoryids);
2669 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2670 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2671 foreach ($categories as $category) {
2672 $bits = explode('/', trim($category->path,'/'));
2673 $categoryids[] = array_shift($bits);
2675 $categoryids = array_unique($categoryids);
2676 $categories->close();
2678 // Now we load the base categories.
2679 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2680 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2681 foreach ($categories as $category) {
2682 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2684 $categories->close();
2685 } else {
2686 foreach ($courses as $course) {
2687 $this->add_course($course, false, self::COURSE_MY);
2694 * The global navigation class used especially for AJAX requests.
2696 * The primary methods that are used in the global navigation class have been overriden
2697 * to ensure that only the relevant branch is generated at the root of the tree.
2698 * This can be done because AJAX is only used when the backwards structure for the
2699 * requested branch exists.
2700 * This has been done only because it shortens the amounts of information that is generated
2701 * which of course will speed up the response time.. because no one likes laggy AJAX.
2703 * @package core
2704 * @category navigation
2705 * @copyright 2009 Sam Hemelryk
2706 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2708 class global_navigation_for_ajax extends global_navigation {
2710 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2711 protected $branchtype;
2713 /** @var int the instance id */
2714 protected $instanceid;
2716 /** @var array Holds an array of expandable nodes */
2717 protected $expandable = array();
2720 * Constructs the navigation for use in an AJAX request
2722 * @param moodle_page $page moodle_page object
2723 * @param int $branchtype
2724 * @param int $id
2726 public function __construct($page, $branchtype, $id) {
2727 $this->page = $page;
2728 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2729 $this->children = new navigation_node_collection();
2730 $this->branchtype = $branchtype;
2731 $this->instanceid = $id;
2732 $this->initialise();
2735 * Initialise the navigation given the type and id for the branch to expand.
2737 * @return array An array of the expandable nodes
2739 public function initialise() {
2740 global $DB, $SITE;
2742 if ($this->initialised || during_initial_install()) {
2743 return $this->expandable;
2745 $this->initialised = true;
2747 $this->rootnodes = array();
2748 $this->rootnodes['site'] = $this->add_course($SITE);
2749 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2750 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2751 // The courses branch is always displayed, and is always expandable (although may be empty).
2752 // This mimicks what is done during {@link global_navigation::initialise()}.
2753 $this->rootnodes['courses']->isexpandable = true;
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 if (!can_access_course($course)) {
2773 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
2774 // add the course node and break. This leads to an empty node.
2775 $this->add_course($course);
2776 break;
2778 require_course_login($course, true, null, false, true);
2779 $this->page->set_context(context_course::instance($course->id));
2780 $coursenode = $this->add_course($course);
2781 $this->add_course_essentials($coursenode, $course);
2782 $this->load_course_sections($course, $coursenode);
2783 break;
2784 case self::TYPE_SECTION :
2785 $sql = 'SELECT c.*, cs.section AS sectionnumber
2786 FROM {course} c
2787 LEFT JOIN {course_sections} cs ON cs.course = c.id
2788 WHERE cs.id = ?';
2789 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2790 require_course_login($course, true, null, false, true);
2791 $this->page->set_context(context_course::instance($course->id));
2792 $coursenode = $this->add_course($course);
2793 $this->add_course_essentials($coursenode, $course);
2794 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2795 break;
2796 case self::TYPE_ACTIVITY :
2797 $sql = "SELECT c.*
2798 FROM {course} c
2799 JOIN {course_modules} cm ON cm.course = c.id
2800 WHERE cm.id = :cmid";
2801 $params = array('cmid' => $this->instanceid);
2802 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2803 $modinfo = get_fast_modinfo($course);
2804 $cm = $modinfo->get_cm($this->instanceid);
2805 require_course_login($course, true, $cm, false, true);
2806 $this->page->set_context(context_module::instance($cm->id));
2807 $coursenode = $this->load_course($course);
2808 if ($course->id != $SITE->id) {
2809 $this->load_course_sections($course, $coursenode, null, $cm);
2811 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2812 break;
2813 default:
2814 throw new Exception('Unknown type');
2815 return $this->expandable;
2818 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2819 $this->load_for_user(null, true);
2822 $this->find_expandable($this->expandable);
2823 return $this->expandable;
2827 * They've expanded the general 'courses' branch.
2829 protected function load_courses_other() {
2830 $this->load_all_courses();
2834 * Loads a single category into the AJAX navigation.
2836 * This function is special in that it doesn't concern itself with the parent of
2837 * the requested category or its siblings.
2838 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2839 * request that.
2841 * @global moodle_database $DB
2842 * @param int $categoryid id of category to load in navigation.
2843 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2844 * @return void.
2846 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2847 global $CFG, $DB;
2849 $limit = 20;
2850 if (!empty($CFG->navcourselimit)) {
2851 $limit = (int)$CFG->navcourselimit;
2854 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2855 $sql = "SELECT cc.*, $catcontextsql
2856 FROM {course_categories} cc
2857 JOIN {context} ctx ON cc.id = ctx.instanceid
2858 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2859 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2860 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2861 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2862 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2863 $categorylist = array();
2864 $subcategories = array();
2865 $basecategory = null;
2866 foreach ($categories as $category) {
2867 $categorylist[] = $category->id;
2868 context_helper::preload_from_record($category);
2869 if ($category->id == $categoryid) {
2870 $this->add_category($category, $this, $nodetype);
2871 $basecategory = $this->addedcategories[$category->id];
2872 } else {
2873 $subcategories[$category->id] = $category;
2876 $categories->close();
2879 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2880 // else show all courses.
2881 if ($nodetype === self::TYPE_MY_CATEGORY) {
2882 $courses = enrol_get_my_courses();
2883 $categoryids = array();
2885 // Only search for categories if basecategory was found.
2886 if (!is_null($basecategory)) {
2887 // Get course parent category ids.
2888 foreach ($courses as $course) {
2889 $categoryids[] = $course->category;
2892 // Get a unique list of category ids which a part of the path
2893 // to user's courses.
2894 $coursesubcategories = array();
2895 $addedsubcategories = array();
2897 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2898 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
2900 foreach ($categories as $category){
2901 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
2903 $coursesubcategories = array_unique($coursesubcategories);
2905 // Only add a subcategory if it is part of the path to user's course and
2906 // wasn't already added.
2907 foreach ($subcategories as $subid => $subcategory) {
2908 if (in_array($subid, $coursesubcategories) &&
2909 !in_array($subid, $addedsubcategories)) {
2910 $this->add_category($subcategory, $basecategory, $nodetype);
2911 $addedsubcategories[] = $subid;
2916 foreach ($courses as $course) {
2917 // Add course if it's in category.
2918 if (in_array($course->category, $categorylist)) {
2919 $this->add_course($course, true, self::COURSE_MY);
2922 } else {
2923 if (!is_null($basecategory)) {
2924 foreach ($subcategories as $key=>$category) {
2925 $this->add_category($category, $basecategory, $nodetype);
2928 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2929 foreach ($courses as $course) {
2930 $this->add_course($course);
2932 $courses->close();
2937 * Returns an array of expandable nodes
2938 * @return array
2940 public function get_expandable() {
2941 return $this->expandable;
2946 * Navbar class
2948 * This class is used to manage the navbar, which is initialised from the navigation
2949 * object held by PAGE
2951 * @package core
2952 * @category navigation
2953 * @copyright 2009 Sam Hemelryk
2954 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2956 class navbar extends navigation_node {
2957 /** @var bool A switch for whether the navbar is initialised or not */
2958 protected $initialised = false;
2959 /** @var mixed keys used to reference the nodes on the navbar */
2960 protected $keys = array();
2961 /** @var null|string content of the navbar */
2962 protected $content = null;
2963 /** @var moodle_page object the moodle page that this navbar belongs to */
2964 protected $page;
2965 /** @var bool A switch for whether to ignore the active navigation information */
2966 protected $ignoreactive = false;
2967 /** @var bool A switch to let us know if we are in the middle of an install */
2968 protected $duringinstall = false;
2969 /** @var bool A switch for whether the navbar has items */
2970 protected $hasitems = false;
2971 /** @var array An array of navigation nodes for the navbar */
2972 protected $items;
2973 /** @var array An array of child node objects */
2974 public $children = array();
2975 /** @var bool A switch for whether we want to include the root node in the navbar */
2976 public $includesettingsbase = false;
2977 /** @var navigation_node[] $prependchildren */
2978 protected $prependchildren = array();
2980 * The almighty constructor
2982 * @param moodle_page $page
2984 public function __construct(moodle_page $page) {
2985 global $CFG;
2986 if (during_initial_install()) {
2987 $this->duringinstall = true;
2988 return false;
2990 $this->page = $page;
2991 $this->text = get_string('home');
2992 $this->shorttext = get_string('home');
2993 $this->action = new moodle_url($CFG->wwwroot);
2994 $this->nodetype = self::NODETYPE_BRANCH;
2995 $this->type = self::TYPE_SYSTEM;
2999 * Quick check to see if the navbar will have items in.
3001 * @return bool Returns true if the navbar will have items, false otherwise
3003 public function has_items() {
3004 if ($this->duringinstall) {
3005 return false;
3006 } else if ($this->hasitems !== false) {
3007 return true;
3009 $this->page->navigation->initialise($this->page);
3011 $activenodefound = ($this->page->navigation->contains_active_node() ||
3012 $this->page->settingsnav->contains_active_node());
3014 $outcome = (count($this->children) > 0 || count($this->prependchildren) || (!$this->ignoreactive && $activenodefound));
3015 $this->hasitems = $outcome;
3016 return $outcome;
3020 * Turn on/off ignore active
3022 * @param bool $setting
3024 public function ignore_active($setting=true) {
3025 $this->ignoreactive = ($setting);
3029 * Gets a navigation node
3031 * @param string|int $key for referencing the navbar nodes
3032 * @param int $type navigation_node::TYPE_*
3033 * @return navigation_node|bool
3035 public function get($key, $type = null) {
3036 foreach ($this->children as &$child) {
3037 if ($child->key === $key && ($type == null || $type == $child->type)) {
3038 return $child;
3041 foreach ($this->prependchildren as &$child) {
3042 if ($child->key === $key && ($type == null || $type == $child->type)) {
3043 return $child;
3046 return false;
3049 * Returns an array of navigation_node's that make up the navbar.
3051 * @return array
3053 public function get_items() {
3054 global $CFG;
3055 $items = array();
3056 // Make sure that navigation is initialised
3057 if (!$this->has_items()) {
3058 return $items;
3060 if ($this->items !== null) {
3061 return $this->items;
3064 if (count($this->children) > 0) {
3065 // Add the custom children.
3066 $items = array_reverse($this->children);
3069 $navigationactivenode = $this->page->navigation->find_active_node();
3070 $settingsactivenode = $this->page->settingsnav->find_active_node();
3072 // Check if navigation contains the active node
3073 if (!$this->ignoreactive) {
3075 if ($navigationactivenode && $settingsactivenode) {
3076 // Parse a combined navigation tree
3077 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3078 if (!$settingsactivenode->mainnavonly) {
3079 $items[] = $settingsactivenode;
3081 $settingsactivenode = $settingsactivenode->parent;
3083 if (!$this->includesettingsbase) {
3084 // Removes the first node from the settings (root node) from the list
3085 array_pop($items);
3087 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3088 if (!$navigationactivenode->mainnavonly) {
3089 $items[] = $navigationactivenode;
3091 if (!empty($CFG->navshowcategories) &&
3092 $navigationactivenode->type === self::TYPE_COURSE &&
3093 $navigationactivenode->parent->key === 'currentcourse') {
3094 $items = array_merge($items, $this->get_course_categories());
3096 $navigationactivenode = $navigationactivenode->parent;
3098 } else if ($navigationactivenode) {
3099 // Parse the navigation tree to get the active node
3100 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3101 if (!$navigationactivenode->mainnavonly) {
3102 $items[] = $navigationactivenode;
3104 if (!empty($CFG->navshowcategories) &&
3105 $navigationactivenode->type === self::TYPE_COURSE &&
3106 $navigationactivenode->parent->key === 'currentcourse') {
3107 $items = array_merge($items, $this->get_course_categories());
3109 $navigationactivenode = $navigationactivenode->parent;
3111 } else if ($settingsactivenode) {
3112 // Parse the settings navigation to get the active node
3113 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3114 if (!$settingsactivenode->mainnavonly) {
3115 $items[] = $settingsactivenode;
3117 $settingsactivenode = $settingsactivenode->parent;
3122 $items[] = new navigation_node(array(
3123 'text'=>$this->page->navigation->text,
3124 'shorttext'=>$this->page->navigation->shorttext,
3125 'key'=>$this->page->navigation->key,
3126 'action'=>$this->page->navigation->action
3129 if (count($this->prependchildren) > 0) {
3130 // Add the custom children
3131 $items = array_merge($items, array_reverse($this->prependchildren));
3134 $this->items = array_reverse($items);
3135 return $this->items;
3139 * Get the list of categories leading to this course.
3141 * This function is used by {@link navbar::get_items()} to add back the "courses"
3142 * node and category chain leading to the current course. Note that this is only ever
3143 * called for the current course, so we don't need to bother taking in any parameters.
3145 * @return array
3147 private function get_course_categories() {
3148 global $CFG;
3150 require_once($CFG->dirroot.'/course/lib.php');
3151 $categories = array();
3152 $cap = 'moodle/category:viewhiddencategories';
3153 foreach ($this->page->categories as $category) {
3154 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3155 continue;
3157 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3158 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3159 $categorynode = navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3160 if (!$category->visible) {
3161 $categorynode->hidden = true;
3163 $categories[] = $categorynode;
3165 if (is_enrolled(context_course::instance($this->page->course->id))) {
3166 $courses = $this->page->navigation->get('mycourses');
3167 } else {
3168 $courses = $this->page->navigation->get('courses');
3170 if (!$courses) {
3171 // Courses node may not be present.
3172 $courses = navigation_node::create(
3173 get_string('courses'),
3174 new moodle_url('/course/index.php'),
3175 self::TYPE_CONTAINER
3178 $categories[] = $courses;
3179 return $categories;
3183 * Add a new navigation_node to the navbar, overrides parent::add
3185 * This function overrides {@link navigation_node::add()} so that we can change
3186 * the way nodes get added to allow us to simply call add and have the node added to the
3187 * end of the navbar
3189 * @param string $text
3190 * @param string|moodle_url|action_link $action An action to associate with this node.
3191 * @param int $type One of navigation_node::TYPE_*
3192 * @param string $shorttext
3193 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3194 * @param pix_icon $icon An optional icon to use for this node.
3195 * @return navigation_node
3197 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3198 if ($this->content !== null) {
3199 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3202 // Properties array used when creating the new navigation node
3203 $itemarray = array(
3204 'text' => $text,
3205 'type' => $type
3207 // Set the action if one was provided
3208 if ($action!==null) {
3209 $itemarray['action'] = $action;
3211 // Set the shorttext if one was provided
3212 if ($shorttext!==null) {
3213 $itemarray['shorttext'] = $shorttext;
3215 // Set the icon if one was provided
3216 if ($icon!==null) {
3217 $itemarray['icon'] = $icon;
3219 // Default the key to the number of children if not provided
3220 if ($key === null) {
3221 $key = count($this->children);
3223 // Set the key
3224 $itemarray['key'] = $key;
3225 // Set the parent to this node
3226 $itemarray['parent'] = $this;
3227 // Add the child using the navigation_node_collections add method
3228 $this->children[] = new navigation_node($itemarray);
3229 return $this;
3233 * Prepends a new navigation_node to the start of the navbar
3235 * @param string $text
3236 * @param string|moodle_url|action_link $action An action to associate with this node.
3237 * @param int $type One of navigation_node::TYPE_*
3238 * @param string $shorttext
3239 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3240 * @param pix_icon $icon An optional icon to use for this node.
3241 * @return navigation_node
3243 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3244 if ($this->content !== null) {
3245 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3247 // Properties array used when creating the new navigation node.
3248 $itemarray = array(
3249 'text' => $text,
3250 'type' => $type
3252 // Set the action if one was provided.
3253 if ($action!==null) {
3254 $itemarray['action'] = $action;
3256 // Set the shorttext if one was provided.
3257 if ($shorttext!==null) {
3258 $itemarray['shorttext'] = $shorttext;
3260 // Set the icon if one was provided.
3261 if ($icon!==null) {
3262 $itemarray['icon'] = $icon;
3264 // Default the key to the number of children if not provided.
3265 if ($key === null) {
3266 $key = count($this->children);
3268 // Set the key.
3269 $itemarray['key'] = $key;
3270 // Set the parent to this node.
3271 $itemarray['parent'] = $this;
3272 // Add the child node to the prepend list.
3273 $this->prependchildren[] = new navigation_node($itemarray);
3274 return $this;
3279 * Class used to manage the settings option for the current page
3281 * This class is used to manage the settings options in a tree format (recursively)
3282 * and was created initially for use with the settings blocks.
3284 * @package core
3285 * @category navigation
3286 * @copyright 2009 Sam Hemelryk
3287 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3289 class settings_navigation extends navigation_node {
3290 /** @var stdClass the current context */
3291 protected $context;
3292 /** @var moodle_page the moodle page that the navigation belongs to */
3293 protected $page;
3294 /** @var string contains administration section navigation_nodes */
3295 protected $adminsection;
3296 /** @var bool A switch to see if the navigation node is initialised */
3297 protected $initialised = false;
3298 /** @var array An array of users that the nodes can extend for. */
3299 protected $userstoextendfor = array();
3300 /** @var navigation_cache **/
3301 protected $cache;
3304 * Sets up the object with basic settings and preparse it for use
3306 * @param moodle_page $page
3308 public function __construct(moodle_page &$page) {
3309 if (during_initial_install()) {
3310 return false;
3312 $this->page = $page;
3313 // Initialise the main navigation. It is most important that this is done
3314 // before we try anything
3315 $this->page->navigation->initialise();
3316 // Initialise the navigation cache
3317 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3318 $this->children = new navigation_node_collection();
3321 * Initialise the settings navigation based on the current context
3323 * This function initialises the settings navigation tree for a given context
3324 * by calling supporting functions to generate major parts of the tree.
3327 public function initialise() {
3328 global $DB, $SESSION, $SITE;
3330 if (during_initial_install()) {
3331 return false;
3332 } else if ($this->initialised) {
3333 return true;
3335 $this->id = 'settingsnav';
3336 $this->context = $this->page->context;
3338 $context = $this->context;
3339 if ($context->contextlevel == CONTEXT_BLOCK) {
3340 $this->load_block_settings();
3341 $context = $context->get_parent_context();
3343 switch ($context->contextlevel) {
3344 case CONTEXT_SYSTEM:
3345 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3346 $this->load_front_page_settings(($context->id == $this->context->id));
3348 break;
3349 case CONTEXT_COURSECAT:
3350 $this->load_category_settings();
3351 break;
3352 case CONTEXT_COURSE:
3353 if ($this->page->course->id != $SITE->id) {
3354 $this->load_course_settings(($context->id == $this->context->id));
3355 } else {
3356 $this->load_front_page_settings(($context->id == $this->context->id));
3358 break;
3359 case CONTEXT_MODULE:
3360 $this->load_module_settings();
3361 $this->load_course_settings();
3362 break;
3363 case CONTEXT_USER:
3364 if ($this->page->course->id != $SITE->id) {
3365 $this->load_course_settings();
3367 break;
3370 $usersettings = $this->load_user_settings($this->page->course->id);
3372 $adminsettings = false;
3373 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
3374 $isadminpage = $this->is_admin_tree_needed();
3376 if (has_capability('moodle/site:config', context_system::instance())) {
3377 // Make sure this works even if config capability changes on the fly
3378 // and also make it fast for admin right after login.
3379 $SESSION->load_navigation_admin = 1;
3380 if ($isadminpage) {
3381 $adminsettings = $this->load_administration_settings();
3384 } else if (!isset($SESSION->load_navigation_admin)) {
3385 $adminsettings = $this->load_administration_settings();
3386 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
3388 } else if ($SESSION->load_navigation_admin) {
3389 if ($isadminpage) {
3390 $adminsettings = $this->load_administration_settings();
3394 // Print empty navigation node, if needed.
3395 if ($SESSION->load_navigation_admin && !$isadminpage) {
3396 if ($adminsettings) {
3397 // Do not print settings tree on pages that do not need it, this helps with performance.
3398 $adminsettings->remove();
3399 $adminsettings = false;
3401 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin'), self::TYPE_SITE_ADMIN, null, 'siteadministration');
3402 $siteadminnode->id = 'expandable_branch_'.$siteadminnode->type.'_'.clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
3403 $this->page->requires->data_for_js('siteadminexpansion', $siteadminnode);
3407 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
3408 $adminsettings->force_open();
3409 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
3410 $usersettings->force_open();
3413 // Check if the user is currently logged in as another user
3414 if (\core\session\manager::is_loggedinas()) {
3415 // Get the actual user, we need this so we can display an informative return link
3416 $realuser = \core\session\manager::get_realuser();
3417 // Add the informative return to original user link
3418 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3419 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3422 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3423 $this->load_local_plugin_settings();
3425 foreach ($this->children as $key=>$node) {
3426 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3427 // Site administration is shown as link.
3428 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
3429 continue;
3431 $node->remove();
3434 $this->initialised = true;
3437 * Override the parent function so that we can add preceeding hr's and set a
3438 * root node class against all first level element
3440 * It does this by first calling the parent's add method {@link navigation_node::add()}
3441 * and then proceeds to use the key to set class and hr
3443 * @param string $text text to be used for the link.
3444 * @param string|moodle_url $url url for the new node
3445 * @param int $type the type of node navigation_node::TYPE_*
3446 * @param string $shorttext
3447 * @param string|int $key a key to access the node by.
3448 * @param pix_icon $icon An icon that appears next to the node.
3449 * @return navigation_node with the new node added to it.
3451 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3452 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3453 $node->add_class('root_node');
3454 return $node;
3458 * This function allows the user to add something to the start of the settings
3459 * navigation, which means it will be at the top of the settings navigation block
3461 * @param string $text text to be used for the link.
3462 * @param string|moodle_url $url url for the new node
3463 * @param int $type the type of node navigation_node::TYPE_*
3464 * @param string $shorttext
3465 * @param string|int $key a key to access the node by.
3466 * @param pix_icon $icon An icon that appears next to the node.
3467 * @return navigation_node $node with the new node added to it.
3469 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3470 $children = $this->children;
3471 $childrenclass = get_class($children);
3472 $this->children = new $childrenclass;
3473 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3474 foreach ($children as $child) {
3475 $this->children->add($child);
3477 return $node;
3481 * Does this page require loading of full admin tree or is
3482 * it enough rely on AJAX?
3484 * @return bool
3486 protected function is_admin_tree_needed() {
3487 if (self::$loadadmintree) {
3488 // Usually external admin page or settings page.
3489 return true;
3492 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
3493 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
3494 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
3495 return false;
3497 return true;
3500 return false;
3504 * Load the site administration tree
3506 * This function loads the site administration tree by using the lib/adminlib library functions
3508 * @param navigation_node $referencebranch A reference to a branch in the settings
3509 * navigation tree
3510 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3511 * tree and start at the beginning
3512 * @return mixed A key to access the admin tree by
3514 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3515 global $CFG;
3517 // Check if we are just starting to generate this navigation.
3518 if ($referencebranch === null) {
3520 // Require the admin lib then get an admin structure
3521 if (!function_exists('admin_get_root')) {
3522 require_once($CFG->dirroot.'/lib/adminlib.php');
3524 $adminroot = admin_get_root(false, false);
3525 // This is the active section identifier
3526 $this->adminsection = $this->page->url->param('section');
3528 // Disable the navigation from automatically finding the active node
3529 navigation_node::$autofindactive = false;
3530 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SITE_ADMIN, null, 'root');
3531 foreach ($adminroot->children as $adminbranch) {
3532 $this->load_administration_settings($referencebranch, $adminbranch);
3534 navigation_node::$autofindactive = true;
3536 // Use the admin structure to locate the active page
3537 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
3538 $currentnode = $this;
3539 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
3540 $currentnode = $currentnode->get($pathkey);
3542 if ($currentnode) {
3543 $currentnode->make_active();
3545 } else {
3546 $this->scan_for_active_node($referencebranch);
3548 return $referencebranch;
3549 } else if ($adminbranch->check_access()) {
3550 // We have a reference branch that we can access and is not hidden `hurrah`
3551 // Now we need to display it and any children it may have
3552 $url = null;
3553 $icon = null;
3554 if ($adminbranch instanceof admin_settingpage) {
3555 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
3556 } else if ($adminbranch instanceof admin_externalpage) {
3557 $url = $adminbranch->url;
3558 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
3559 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
3562 // Add the branch
3563 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3565 if ($adminbranch->is_hidden()) {
3566 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3567 $reference->add_class('hidden');
3568 } else {
3569 $reference->display = false;
3573 // Check if we are generating the admin notifications and whether notificiations exist
3574 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3575 $reference->add_class('criticalnotification');
3577 // Check if this branch has children
3578 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3579 foreach ($adminbranch->children as $branch) {
3580 // Generate the child branches as well now using this branch as the reference
3581 $this->load_administration_settings($reference, $branch);
3583 } else {
3584 $reference->icon = new pix_icon('i/settings', '');
3590 * This function recursivily scans nodes until it finds the active node or there
3591 * are no more nodes.
3592 * @param navigation_node $node
3594 protected function scan_for_active_node(navigation_node $node) {
3595 if (!$node->check_if_active() && $node->children->count()>0) {
3596 foreach ($node->children as &$child) {
3597 $this->scan_for_active_node($child);
3603 * Gets a navigation node given an array of keys that represent the path to
3604 * the desired node.
3606 * @param array $path
3607 * @return navigation_node|false
3609 protected function get_by_path(array $path) {
3610 $node = $this->get(array_shift($path));
3611 foreach ($path as $key) {
3612 $node->get($key);
3614 return $node;
3618 * This function loads the course settings that are available for the user
3620 * @param bool $forceopen If set to true the course node will be forced open
3621 * @return navigation_node|false
3623 protected function load_course_settings($forceopen = false) {
3624 global $CFG;
3626 $course = $this->page->course;
3627 $coursecontext = context_course::instance($course->id);
3629 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3631 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3632 if ($forceopen) {
3633 $coursenode->force_open();
3636 if ($this->page->user_allowed_editing()) {
3637 // Add the turn on/off settings
3639 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
3640 // We are on the course page, retain the current page params e.g. section.
3641 $baseurl = clone($this->page->url);
3642 $baseurl->param('sesskey', sesskey());
3643 } else {
3644 // Edit on the main course page.
3645 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
3648 $editurl = clone($baseurl);
3649 if ($this->page->user_is_editing()) {
3650 $editurl->param('edit', 'off');
3651 $editstring = get_string('turneditingoff');
3652 } else {
3653 $editurl->param('edit', 'on');
3654 $editstring = get_string('turneditingon');
3656 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
3659 if (has_capability('moodle/course:update', $coursecontext)) {
3660 // Add the course settings link
3661 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3662 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
3664 // Add the course completion settings link
3665 if ($CFG->enablecompletion && $course->enablecompletion) {
3666 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3667 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3671 // add enrol nodes
3672 enrol_add_course_navigation($coursenode, $course);
3674 // Manage filters
3675 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3676 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3677 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3680 // View course reports.
3681 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
3682 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
3683 new pix_icon('i/stats', ''));
3684 $coursereports = core_component::get_plugin_list('coursereport');
3685 foreach ($coursereports as $report => $dir) {
3686 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
3687 if (file_exists($libfile)) {
3688 require_once($libfile);
3689 $reportfunction = $report.'_report_extend_navigation';
3690 if (function_exists($report.'_report_extend_navigation')) {
3691 $reportfunction($reportnav, $course, $coursecontext);
3696 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
3697 foreach ($reports as $reportfunction) {
3698 $reportfunction($reportnav, $course, $coursecontext);
3702 // Add view grade report is permitted
3703 $reportavailable = false;
3704 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3705 $reportavailable = true;
3706 } else if (!empty($course->showgrades)) {
3707 $reports = core_component::get_plugin_list('gradereport');
3708 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3709 arsort($reports); // user is last, we want to test it first
3710 foreach ($reports as $plugin => $plugindir) {
3711 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3712 //stop when the first visible plugin is found
3713 $reportavailable = true;
3714 break;
3719 if ($reportavailable) {
3720 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3721 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3724 // Add outcome if permitted
3725 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3726 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3727 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3730 //Add badges navigation
3731 require_once($CFG->libdir .'/badgeslib.php');
3732 badges_add_course_navigation($coursenode, $course);
3734 // Backup this course
3735 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3736 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3737 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3740 // Restore to this course
3741 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3742 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3743 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3746 // Import data from other courses
3747 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3748 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3749 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
3752 // Publish course on a hub
3753 if (has_capability('moodle/course:publish', $coursecontext)) {
3754 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3755 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3758 // Reset this course
3759 if (has_capability('moodle/course:reset', $coursecontext)) {
3760 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3761 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3764 // Questions
3765 require_once($CFG->libdir . '/questionlib.php');
3766 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3768 if (has_capability('moodle/course:update', $coursecontext)) {
3769 // Repository Instances
3770 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3771 require_once($CFG->dirroot . '/repository/lib.php');
3772 $editabletypes = repository::get_editable_types($coursecontext);
3773 $haseditabletypes = !empty($editabletypes);
3774 unset($editabletypes);
3775 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3776 } else {
3777 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3779 if ($haseditabletypes) {
3780 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3781 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3785 // Manage files
3786 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3787 // hidden in new courses and courses where legacy files were turned off
3788 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3789 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
3793 // Switch roles
3794 $roles = array();
3795 $assumedrole = $this->in_alternative_role();
3796 if ($assumedrole !== false) {
3797 $roles[0] = get_string('switchrolereturn');
3799 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3800 $availableroles = get_switchable_roles($coursecontext);
3801 if (is_array($availableroles)) {
3802 foreach ($availableroles as $key=>$role) {
3803 if ($assumedrole == (int)$key) {
3804 continue;
3806 $roles[$key] = $role;
3810 if (is_array($roles) && count($roles)>0) {
3811 $switchroles = $this->add(get_string('switchroleto'));
3812 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3813 $switchroles->force_open();
3815 foreach ($roles as $key => $name) {
3816 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$this->page->url->out_as_local_url(false)));
3817 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
3820 // Return we are done
3821 return $coursenode;
3825 * This function calls the module function to inject module settings into the
3826 * settings navigation tree.
3828 * This only gets called if there is a corrosponding function in the modules
3829 * lib file.
3831 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3833 * @return navigation_node|false
3835 protected function load_module_settings() {
3836 global $CFG;
3838 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3839 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3840 $this->page->set_cm($cm, $this->page->course);
3843 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3844 if (file_exists($file)) {
3845 require_once($file);
3848 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
3849 $modulenode->force_open();
3851 // Settings for the module
3852 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3853 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
3854 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3856 // Assign local roles
3857 if (count(get_assignable_roles($this->page->cm->context))>0) {
3858 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3859 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3861 // Override roles
3862 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3863 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3864 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3866 // Check role permissions
3867 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3868 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3869 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3871 // Manage filters
3872 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3873 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3874 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3876 // Add reports
3877 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3878 foreach ($reports as $reportfunction) {
3879 $reportfunction($modulenode, $this->page->cm);
3881 // Add a backup link
3882 $featuresfunc = $this->page->activityname.'_supports';
3883 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3884 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3885 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3888 // Restore this activity
3889 $featuresfunc = $this->page->activityname.'_supports';
3890 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3891 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3892 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3895 // Allow the active advanced grading method plugin to append its settings
3896 $featuresfunc = $this->page->activityname.'_supports';
3897 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3898 require_once($CFG->dirroot.'/grade/grading/lib.php');
3899 $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
3900 $gradingman->extend_settings_navigation($this, $modulenode);
3903 $function = $this->page->activityname.'_extend_settings_navigation';
3904 if (!function_exists($function)) {
3905 return $modulenode;
3908 $function($this, $modulenode);
3910 // Remove the module node if there are no children
3911 if (empty($modulenode->children)) {
3912 $modulenode->remove();
3915 return $modulenode;
3919 * Loads the user settings block of the settings nav
3921 * This function is simply works out the userid and whether we need to load
3922 * just the current users profile settings, or the current user and the user the
3923 * current user is viewing.
3925 * This function has some very ugly code to work out the user, if anyone has
3926 * any bright ideas please feel free to intervene.
3928 * @param int $courseid The course id of the current course
3929 * @return navigation_node|false
3931 protected function load_user_settings($courseid = SITEID) {
3932 global $USER, $CFG;
3934 if (isguestuser() || !isloggedin()) {
3935 return false;
3938 $navusers = $this->page->navigation->get_extending_users();
3940 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3941 $usernode = null;
3942 foreach ($this->userstoextendfor as $userid) {
3943 if ($userid == $USER->id) {
3944 continue;
3946 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3947 if (is_null($usernode)) {
3948 $usernode = $node;
3951 foreach ($navusers as $user) {
3952 if ($user->id == $USER->id) {
3953 continue;
3955 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3956 if (is_null($usernode)) {
3957 $usernode = $node;
3960 $this->generate_user_settings($courseid, $USER->id);
3961 } else {
3962 $usernode = $this->generate_user_settings($courseid, $USER->id);
3964 return $usernode;
3968 * Extends the settings navigation for the given user.
3970 * Note: This method gets called automatically if you call
3971 * $PAGE->navigation->extend_for_user($userid)
3973 * @param int $userid
3975 public function extend_for_user($userid) {
3976 global $CFG;
3978 if (!in_array($userid, $this->userstoextendfor)) {
3979 $this->userstoextendfor[] = $userid;
3980 if ($this->initialised) {
3981 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3982 $children = array();
3983 foreach ($this->children as $child) {
3984 $children[] = $child;
3986 array_unshift($children, array_pop($children));
3987 $this->children = new navigation_node_collection();
3988 foreach ($children as $child) {
3989 $this->children->add($child);
3996 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3997 * what can be shown/done
3999 * @param int $courseid The current course' id
4000 * @param int $userid The user id to load for
4001 * @param string $gstitle The string to pass to get_string for the branch title
4002 * @return navigation_node|false
4004 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4005 global $DB, $CFG, $USER, $SITE;
4007 if ($courseid != $SITE->id) {
4008 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4009 $course = $this->page->course;
4010 } else {
4011 $select = context_helper::get_preload_record_columns_sql('ctx');
4012 $sql = "SELECT c.*, $select
4013 FROM {course} c
4014 JOIN {context} ctx ON c.id = ctx.instanceid
4015 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4016 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4017 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4018 context_helper::preload_from_record($course);
4020 } else {
4021 $course = $SITE;
4024 $coursecontext = context_course::instance($course->id); // Course context
4025 $systemcontext = context_system::instance();
4026 $currentuser = ($USER->id == $userid);
4028 if ($currentuser) {
4029 $user = $USER;
4030 $usercontext = context_user::instance($user->id); // User context
4031 } else {
4032 $select = context_helper::get_preload_record_columns_sql('ctx');
4033 $sql = "SELECT u.*, $select
4034 FROM {user} u
4035 JOIN {context} ctx ON u.id = ctx.instanceid
4036 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4037 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4038 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4039 if (!$user) {
4040 return false;
4042 context_helper::preload_from_record($user);
4044 // Check that the user can view the profile
4045 $usercontext = context_user::instance($user->id); // User context
4046 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4048 if ($course->id == $SITE->id) {
4049 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4050 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4051 return false;
4053 } else {
4054 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4055 $userisenrolled = is_enrolled($coursecontext, $user->id);
4056 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4057 return false;
4059 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4060 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
4061 // If groups are in use, make sure we can see that group
4062 return false;
4067 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4069 $key = $gstitle;
4070 if ($gstitle != 'usercurrentsettings') {
4071 $key .= $userid;
4074 // Add a user setting branch
4075 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
4076 $usersetting->id = 'usersettings';
4077 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
4078 // Automatically start by making it active
4079 $usersetting->make_active();
4082 // Check if the user has been deleted
4083 if ($user->deleted) {
4084 if (!has_capability('moodle/user:update', $coursecontext)) {
4085 // We can't edit the user so just show the user deleted message
4086 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4087 } else {
4088 // We can edit the user so show the user deleted message and link it to the profile
4089 if ($course->id == $SITE->id) {
4090 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4091 } else {
4092 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4094 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4096 return true;
4099 $userauthplugin = false;
4100 if (!empty($user->auth)) {
4101 $userauthplugin = get_auth_plugin($user->auth);
4104 // Add the profile edit link
4105 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4106 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
4107 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4108 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4109 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4110 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4111 $url = $userauthplugin->edit_profile_url();
4112 if (empty($url)) {
4113 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4115 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
4120 // Change password link
4121 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4122 $passwordchangeurl = $userauthplugin->change_password_url();
4123 if (empty($passwordchangeurl)) {
4124 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4126 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
4129 // View the roles settings
4130 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
4131 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4133 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4134 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4136 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4138 if (!empty($assignableroles)) {
4139 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4140 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4143 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4144 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4145 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4148 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
4149 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4152 // Portfolio
4153 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4154 require_once($CFG->libdir . '/portfoliolib.php');
4155 if (portfolio_has_visible_instances()) {
4156 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4158 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4159 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4161 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4162 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4166 $enablemanagetokens = false;
4167 if (!empty($CFG->enablerssfeeds)) {
4168 $enablemanagetokens = true;
4169 } else if (!is_siteadmin($USER->id)
4170 && !empty($CFG->enablewebservices)
4171 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4172 $enablemanagetokens = true;
4174 // Security keys
4175 if ($currentuser && $enablemanagetokens) {
4176 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4177 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4180 // Messaging
4181 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4182 $url = new moodle_url('/message/edit.php', array('id'=>$user->id));
4183 $usersetting->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
4186 // Blogs
4187 if ($currentuser && !empty($CFG->enableblogs)) {
4188 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4189 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
4190 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
4191 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
4192 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
4196 // Badges.
4197 if ($currentuser && !empty($CFG->enablebadges)) {
4198 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
4199 $badges->add(get_string('preferences'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
4200 if (!empty($CFG->badges_allowexternalbackpack)) {
4201 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
4205 // Add reports node.
4206 $reporttab = $usersetting->add(get_string('activityreports'));
4207 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
4208 foreach ($reports as $reportfunction) {
4209 $reportfunction($reporttab, $user, $course);
4211 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
4212 if ($anyreport || ($course->showreports && $currentuser)) {
4213 // Add grade hardcoded grade report if necessary.
4214 $gradeaccess = false;
4215 if (has_capability('moodle/grade:viewall', $coursecontext)) {
4216 // Can view all course grades.
4217 $gradeaccess = true;
4218 } else if ($course->showgrades) {
4219 if ($currentuser && has_capability('moodle/grade:view', $coursecontext)) {
4220 // Can view own grades.
4221 $gradeaccess = true;
4222 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
4223 // Can view grades of this user - parent most probably.
4224 $gradeaccess = true;
4225 } else if ($anyreport) {
4226 // Can view grades of this user - parent most probably.
4227 $gradeaccess = true;
4230 if ($gradeaccess) {
4231 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id,
4232 'user'=>$usercontext->instanceid)));
4235 // Check the number of nodes in the report node... if there are none remove the node
4236 $reporttab->trim_if_empty();
4238 // Login as ...
4239 if (!$user->deleted and !$currentuser && !\core\session\manager::is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
4240 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
4241 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
4244 return $usersetting;
4248 * Loads block specific settings in the navigation
4250 * @return navigation_node
4252 protected function load_block_settings() {
4253 global $CFG;
4255 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
4256 $blocknode->force_open();
4258 // Assign local roles
4259 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4260 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
4262 // Override roles
4263 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4264 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4265 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4267 // Check role permissions
4268 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4269 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4270 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4273 return $blocknode;
4277 * Loads category specific settings in the navigation
4279 * @return navigation_node
4281 protected function load_category_settings() {
4282 global $CFG;
4284 $categorynode = $this->add($this->context->get_context_name(), null, null, null, 'categorysettings');
4285 $categorynode->force_open();
4287 if (can_edit_in_category($this->context->instanceid)) {
4288 $url = new moodle_url('/course/management.php', array('categoryid' => $this->context->instanceid));
4289 $editstring = get_string('managecategorythis');
4290 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4293 if (has_capability('moodle/category:manage', $this->context)) {
4294 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
4295 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4297 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
4298 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4301 // Assign local roles
4302 if (has_capability('moodle/role:assign', $this->context)) {
4303 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
4304 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4307 // Override roles
4308 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4309 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4310 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4312 // Check role permissions
4313 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4314 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4315 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4318 // Cohorts
4319 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->context)) {
4320 $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', ''));
4323 // Manage filters
4324 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
4325 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
4326 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
4329 // Restore.
4330 if (has_capability('moodle/course:create', $this->context)) {
4331 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $this->context->id));
4332 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
4335 return $categorynode;
4339 * Determine whether the user is assuming another role
4341 * This function checks to see if the user is assuming another role by means of
4342 * role switching. In doing this we compare each RSW key (context path) against
4343 * the current context path. This ensures that we can provide the switching
4344 * options against both the course and any page shown under the course.
4346 * @return bool|int The role(int) if the user is in another role, false otherwise
4348 protected function in_alternative_role() {
4349 global $USER;
4350 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
4351 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
4352 return $USER->access['rsw'][$this->page->context->path];
4354 foreach ($USER->access['rsw'] as $key=>$role) {
4355 if (strpos($this->context->path,$key)===0) {
4356 return $role;
4360 return false;
4364 * This function loads all of the front page settings into the settings navigation.
4365 * This function is called when the user is on the front page, or $COURSE==$SITE
4366 * @param bool $forceopen (optional)
4367 * @return navigation_node
4369 protected function load_front_page_settings($forceopen = false) {
4370 global $SITE, $CFG;
4372 $course = clone($SITE);
4373 $coursecontext = context_course::instance($course->id); // Course context
4375 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
4376 if ($forceopen) {
4377 $frontpage->force_open();
4379 $frontpage->id = 'frontpagesettings';
4381 if ($this->page->user_allowed_editing()) {
4383 // Add the turn on/off settings
4384 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
4385 if ($this->page->user_is_editing()) {
4386 $url->param('edit', 'off');
4387 $editstring = get_string('turneditingoff');
4388 } else {
4389 $url->param('edit', 'on');
4390 $editstring = get_string('turneditingon');
4392 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4395 if (has_capability('moodle/course:update', $coursecontext)) {
4396 // Add the course settings link
4397 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4398 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4401 // add enrol nodes
4402 enrol_add_course_navigation($frontpage, $course);
4404 // Manage filters
4405 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4406 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4407 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4410 // View course reports.
4411 if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
4412 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
4413 new pix_icon('i/stats', ''));
4414 $coursereports = core_component::get_plugin_list('coursereport');
4415 foreach ($coursereports as $report=>$dir) {
4416 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4417 if (file_exists($libfile)) {
4418 require_once($libfile);
4419 $reportfunction = $report.'_report_extend_navigation';
4420 if (function_exists($report.'_report_extend_navigation')) {
4421 $reportfunction($frontpagenav, $course, $coursecontext);
4426 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4427 foreach ($reports as $reportfunction) {
4428 $reportfunction($frontpagenav, $course, $coursecontext);
4432 // Backup this course
4433 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4434 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4435 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
4438 // Restore to this course
4439 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4440 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4441 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
4444 // Questions
4445 require_once($CFG->libdir . '/questionlib.php');
4446 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4448 // Manage files
4449 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
4450 //hiden in new installs
4451 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4452 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
4454 return $frontpage;
4458 * This function gives local plugins an opportunity to modify the settings navigation.
4460 protected function load_local_plugin_settings() {
4461 // Get all local plugins with an extend_settings_navigation function in their lib.php file
4462 foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
4463 // Call each function providing this (the settings navigation) and the current context.
4464 $function($this, $this->context);
4469 * This function marks the cache as volatile so it is cleared during shutdown
4471 public function clear_cache() {
4472 $this->cache->volatile();
4477 * Class used to populate site admin navigation for ajax.
4479 * @package core
4480 * @category navigation
4481 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
4482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4484 class settings_navigation_ajax extends settings_navigation {
4486 * Constructs the navigation for use in an AJAX request
4488 * @param moodle_page $page
4490 public function __construct(moodle_page &$page) {
4491 $this->page = $page;
4492 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4493 $this->children = new navigation_node_collection();
4494 $this->initialise();
4498 * Initialise the site admin navigation.
4500 * @return array An array of the expandable nodes
4502 public function initialise() {
4503 if ($this->initialised || during_initial_install()) {
4504 return false;
4506 $this->context = $this->page->context;
4507 $this->load_administration_settings();
4509 // Check if local plugins is adding node to site admin.
4510 $this->load_local_plugin_settings();
4512 $this->initialised = true;
4517 * Simple class used to output a navigation branch in XML
4519 * @package core
4520 * @category navigation
4521 * @copyright 2009 Sam Hemelryk
4522 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4524 class navigation_json {
4525 /** @var array An array of different node types */
4526 protected $nodetype = array('node','branch');
4527 /** @var array An array of node keys and types */
4528 protected $expandable = array();
4530 * Turns a branch and all of its children into XML
4532 * @param navigation_node $branch
4533 * @return string XML string
4535 public function convert($branch) {
4536 $xml = $this->convert_child($branch);
4537 return $xml;
4540 * Set the expandable items in the array so that we have enough information
4541 * to attach AJAX events
4542 * @param array $expandable
4544 public function set_expandable($expandable) {
4545 foreach ($expandable as $node) {
4546 $this->expandable[$node['key'].':'.$node['type']] = $node;
4550 * Recusively converts a child node and its children to XML for output
4552 * @param navigation_node $child The child to convert
4553 * @param int $depth Pointlessly used to track the depth of the XML structure
4554 * @return string JSON
4556 protected function convert_child($child, $depth=1) {
4557 if (!$child->display) {
4558 return '';
4560 $attributes = array();
4561 $attributes['id'] = $child->id;
4562 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
4563 $attributes['type'] = $child->type;
4564 $attributes['key'] = $child->key;
4565 $attributes['class'] = $child->get_css_type();
4567 if ($child->icon instanceof pix_icon) {
4568 $attributes['icon'] = array(
4569 'component' => $child->icon->component,
4570 'pix' => $child->icon->pix,
4572 foreach ($child->icon->attributes as $key=>$value) {
4573 if ($key == 'class') {
4574 $attributes['icon']['classes'] = explode(' ', $value);
4575 } else if (!array_key_exists($key, $attributes['icon'])) {
4576 $attributes['icon'][$key] = $value;
4580 } else if (!empty($child->icon)) {
4581 $attributes['icon'] = (string)$child->icon;
4584 if ($child->forcetitle || $child->title !== $child->text) {
4585 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
4587 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
4588 $attributes['expandable'] = $child->key;
4589 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
4592 if (count($child->classes)>0) {
4593 $attributes['class'] .= ' '.join(' ',$child->classes);
4595 if (is_string($child->action)) {
4596 $attributes['link'] = $child->action;
4597 } else if ($child->action instanceof moodle_url) {
4598 $attributes['link'] = $child->action->out();
4599 } else if ($child->action instanceof action_link) {
4600 $attributes['link'] = $child->action->url->out();
4602 $attributes['hidden'] = ($child->hidden);
4603 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
4604 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
4606 if ($child->children->count() > 0) {
4607 $attributes['children'] = array();
4608 foreach ($child->children as $subchild) {
4609 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
4613 if ($depth > 1) {
4614 return $attributes;
4615 } else {
4616 return json_encode($attributes);
4622 * The cache class used by global navigation and settings navigation.
4624 * It is basically an easy access point to session with a bit of smarts to make
4625 * sure that the information that is cached is valid still.
4627 * Example use:
4628 * <code php>
4629 * if (!$cache->viewdiscussion()) {
4630 * // Code to do stuff and produce cachable content
4631 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4633 * $content = $cache->viewdiscussion;
4634 * </code>
4636 * @package core
4637 * @category navigation
4638 * @copyright 2009 Sam Hemelryk
4639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4641 class navigation_cache {
4642 /** @var int represents the time created */
4643 protected $creation;
4644 /** @var array An array of session keys */
4645 protected $session;
4647 * The string to use to segregate this particular cache. It can either be
4648 * unique to start a fresh cache or if you want to share a cache then make
4649 * it the string used in the original cache.
4650 * @var string
4652 protected $area;
4653 /** @var int a time that the information will time out */
4654 protected $timeout;
4655 /** @var stdClass The current context */
4656 protected $currentcontext;
4657 /** @var int cache time information */
4658 const CACHETIME = 0;
4659 /** @var int cache user id */
4660 const CACHEUSERID = 1;
4661 /** @var int cache value */
4662 const CACHEVALUE = 2;
4663 /** @var null|array An array of navigation cache areas to expire on shutdown */
4664 public static $volatilecaches;
4667 * Contructor for the cache. Requires two arguments
4669 * @param string $area The string to use to segregate this particular cache
4670 * it can either be unique to start a fresh cache or if you want
4671 * to share a cache then make it the string used in the original
4672 * cache
4673 * @param int $timeout The number of seconds to time the information out after
4675 public function __construct($area, $timeout=1800) {
4676 $this->creation = time();
4677 $this->area = $area;
4678 $this->timeout = time() - $timeout;
4679 if (rand(0,100) === 0) {
4680 $this->garbage_collection();
4685 * Used to set up the cache within the SESSION.
4687 * This is called for each access and ensure that we don't put anything into the session before
4688 * it is required.
4690 protected function ensure_session_cache_initialised() {
4691 global $SESSION;
4692 if (empty($this->session)) {
4693 if (!isset($SESSION->navcache)) {
4694 $SESSION->navcache = new stdClass;
4696 if (!isset($SESSION->navcache->{$this->area})) {
4697 $SESSION->navcache->{$this->area} = array();
4699 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
4704 * Magic Method to retrieve something by simply calling using = cache->key
4706 * @param mixed $key The identifier for the information you want out again
4707 * @return void|mixed Either void or what ever was put in
4709 public function __get($key) {
4710 if (!$this->cached($key)) {
4711 return;
4713 $information = $this->session[$key][self::CACHEVALUE];
4714 return unserialize($information);
4718 * Magic method that simply uses {@link set();} to store something in the cache
4720 * @param string|int $key
4721 * @param mixed $information
4723 public function __set($key, $information) {
4724 $this->set($key, $information);
4728 * Sets some information against the cache (session) for later retrieval
4730 * @param string|int $key
4731 * @param mixed $information
4733 public function set($key, $information) {
4734 global $USER;
4735 $this->ensure_session_cache_initialised();
4736 $information = serialize($information);
4737 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
4740 * Check the existence of the identifier in the cache
4742 * @param string|int $key
4743 * @return bool
4745 public function cached($key) {
4746 global $USER;
4747 $this->ensure_session_cache_initialised();
4748 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) {
4749 return false;
4751 return true;
4754 * Compare something to it's equivilant in the cache
4756 * @param string $key
4757 * @param mixed $value
4758 * @param bool $serialise Whether to serialise the value before comparison
4759 * this should only be set to false if the value is already
4760 * serialised
4761 * @return bool If the value is the same false if it is not set or doesn't match
4763 public function compare($key, $value, $serialise = true) {
4764 if ($this->cached($key)) {
4765 if ($serialise) {
4766 $value = serialize($value);
4768 if ($this->session[$key][self::CACHEVALUE] === $value) {
4769 return true;
4772 return false;
4775 * Wipes the entire cache, good to force regeneration
4777 public function clear() {
4778 global $SESSION;
4779 unset($SESSION->navcache);
4780 $this->session = null;
4783 * Checks all cache entries and removes any that have expired, good ole cleanup
4785 protected function garbage_collection() {
4786 if (empty($this->session)) {
4787 return true;
4789 foreach ($this->session as $key=>$cachedinfo) {
4790 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
4791 unset($this->session[$key]);
4797 * Marks the cache as being volatile (likely to change)
4799 * Any caches marked as volatile will be destroyed at the on shutdown by
4800 * {@link navigation_node::destroy_volatile_caches()} which is registered
4801 * as a shutdown function if any caches are marked as volatile.
4803 * @param bool $setting True to destroy the cache false not too
4805 public function volatile($setting = true) {
4806 if (self::$volatilecaches===null) {
4807 self::$volatilecaches = array();
4808 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
4811 if ($setting) {
4812 self::$volatilecaches[$this->area] = $this->area;
4813 } else if (array_key_exists($this->area, self::$volatilecaches)) {
4814 unset(self::$volatilecaches[$this->area]);
4819 * Destroys all caches marked as volatile
4821 * This function is static and works in conjunction with the static volatilecaches
4822 * property of navigation cache.
4823 * Because this function is static it manually resets the cached areas back to an
4824 * empty array.
4826 public static function destroy_volatile_caches() {
4827 global $SESSION;
4828 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
4829 foreach (self::$volatilecaches as $area) {
4830 $SESSION->navcache->{$area} = array();
4832 } else {
4833 $SESSION->navcache = new stdClass;