2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * This file contains classes used to manage the navigation structures within Moodle.
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
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');
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.
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 */
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 */
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] */
90 /** @var string|int The identifier for the node, used to retrieve the node */
92 /** @var string The text to use for the node */
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 */
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 */
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;
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';
175 $this->icon->attributes['class'] .= ' navicon';
178 if (array_key_exists('type', $properties)) {
179 $this->type = $properties['type'];
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
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));
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();
238 * This sets the URL that the URL of new nodes get compared to when locating
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
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
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
294 $itemarray['icon'] = $icon;
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
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) {
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
353 $node->hidden = true;
355 // Return added node (reference returned by $this->children->add()
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 + their 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);
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');
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.
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
462 public function add_class($class) {
463 if (!in_array($class, $this->classes)) {
464 $this->classes[] = $class;
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);
479 unset($this->classes[$key]);
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.
511 public function contains_active_node() {
512 if ($this->isactive) {
515 foreach ($this->children as $child) {
516 if ($child->isactive || $child->contains_active_node()) {
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.
532 * @return navigation_node|false
534 public function find_active_node() {
535 if ($this->isactive) {
538 foreach ($this->children as &$child) {
539 $outcome = $child->find_active_node();
540 if ($outcome !== 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)) {
556 foreach ($this->children as &$child) {
557 $outcome = $child->search_for_active_node();
558 if ($outcome !== false) {
567 * Gets the content for this node.
569 * @param bool $shorttext If true shorttext is used rather than the normal text
572 public function get_content($shorttext=false) {
573 if ($shorttext && $this->shorttext!==null) {
574 return format_string($this->shorttext);
576 return format_string($this->text);
581 * Gets the title to use for this node.
585 public function get_title() {
586 if ($this->forcetitle || $this->action != null){
594 * Gets the CSS class to add to this node to describe its type
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_*
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);
637 * Removes this node if it is empty
639 public function trim_if_empty() {
640 if ($this->children->count() == 0) {
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) {
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());
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
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.
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
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.
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.
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.
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.
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) {
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;
783 if ($beforekey !== null) {
784 foreach ($this->collection as $index => $othernode) {
785 if ($othernode->key === $beforekey) {
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;
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
814 ksort($this->collection);
817 // Return the reference to the now added node
822 * Return a list of all the keys of all the nodes.
823 * @return array the keys.
825 public function get_key_list() {
827 foreach ($this->collection as $node) {
828 $keys[] = $node->key;
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];
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) {
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.
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];
873 $nodes = $this->getIterator();
874 // Search immediate children first
875 foreach ($nodes as &$node) {
876 if ($node->key === $key && ($type === null || $type === $node->type)) {
880 // Now search each childs children
881 foreach ($nodes as &$node) {
882 $result = $node->children->find($key, $type);
883 if ($result !== false) {
892 * Fetches the last node that was added to this collection
894 * @return navigation_node
896 public function 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.
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);
929 unset($this->orderedcollection[$child->type][$child->key]);
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.
944 public function 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
967 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
968 * {@link lib/ajax/getnavbranch.php} Called by ajax
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. */
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 navigation_node[] 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 */
994 /** @var array An array of course ids that are present in the navigation */
995 protected $addedcourses = array();
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;
1004 /** @var cache_session A cache that stores information on expanded courses */
1005 protected $cacheexpandcourse = null;
1007 /** Used when loading categories to load all top level categories [parent = 0] **/
1008 const LOAD_ROOT_CATEGORIES = 0;
1009 /** Used when loading categories to load all categories **/
1010 const LOAD_ALL_CATEGORIES = -1;
1013 * Constructs a new global navigation
1015 * @param moodle_page $page The page this navigation object belongs to
1017 public function __construct(moodle_page $page) {
1018 global $CFG, $SITE, $USER;
1020 if (during_initial_install()) {
1024 if (get_home_page() == HOMEPAGE_SITE) {
1025 // We are using the site home for the root element
1026 $properties = array(
1028 'type' => navigation_node::TYPE_SYSTEM,
1029 'text' => get_string('home'),
1030 'action' => new moodle_url('/')
1033 // We are using the users my moodle for the root element
1034 $properties = array(
1036 'type' => navigation_node::TYPE_SYSTEM,
1037 'text' => get_string('myhome'),
1038 'action' => new moodle_url('/my/')
1042 // Use the parents constructor.... good good reuse
1043 parent::__construct($properties);
1045 // Initalise and set defaults
1046 $this->page = $page;
1047 $this->forceopen = true;
1048 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1052 * Mutator to set userid to allow parent to see child's profile
1053 * page navigation. See MDL-25805 for initial issue. Linked to it
1054 * is an issue explaining why this is a REALLY UGLY HACK thats not
1057 * @param int $userid userid of profile page that parent wants to navigate around.
1059 public function set_userid_for_parent_checks($userid) {
1060 $this->useridtouseforparentchecks = $userid;
1065 * Initialises the navigation object.
1067 * This causes the navigation object to look at the current state of the page
1068 * that it is associated with and then load the appropriate content.
1070 * This should only occur the first time that the navigation structure is utilised
1071 * which will normally be either when the navbar is called to be displayed or
1072 * when a block makes use of it.
1076 public function initialise() {
1077 global $CFG, $SITE, $USER;
1078 // Check if it has already been initialised
1079 if ($this->initialised || during_initial_install()) {
1082 $this->initialised = true;
1084 // Set up the five base root nodes. These are nodes where we will put our
1085 // content and are as follows:
1086 // site: Navigation for the front page.
1087 // myprofile: User profile information goes here.
1088 // currentcourse: The course being currently viewed.
1089 // mycourses: The users courses get added here.
1090 // courses: Additional courses are added here.
1091 // users: Other users information loaded here.
1092 $this->rootnodes = array();
1093 if (get_home_page() == HOMEPAGE_SITE) {
1094 // The home element should be my moodle because the root element is the site
1095 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1096 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1099 // The home element should be the site because the root node is my moodle
1100 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1101 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1102 // We need to stop automatic redirection
1103 $this->rootnodes['home']->action->param('redirect', '0');
1106 $this->rootnodes['site'] = $this->add_course($SITE);
1107 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1108 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1109 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
1110 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1111 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1113 // We always load the frontpage course to ensure it is available without
1114 // JavaScript enabled.
1115 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1116 $this->load_course_sections($SITE, $this->rootnodes['site']);
1118 $course = $this->page->course;
1120 // $issite gets set to true if the current pages course is the sites frontpage course
1121 $issite = ($this->page->course->id == $SITE->id);
1122 // Determine if the user is enrolled in any course.
1123 $enrolledinanycourse = enrol_user_sees_own_courses();
1125 $this->rootnodes['currentcourse']->mainnavonly = true;
1126 if ($enrolledinanycourse) {
1127 $this->rootnodes['mycourses']->isexpandable = true;
1128 if ($CFG->navshowallcourses) {
1129 // When we show all courses we need to show both the my courses and the regular courses branch.
1130 $this->rootnodes['courses']->isexpandable = true;
1133 $this->rootnodes['courses']->isexpandable = true;
1136 // Load the users enrolled courses if they are viewing the My Moodle page AND the admin has not
1137 // set that they wish to keep the My Courses branch collapsed by default.
1138 if (!empty($CFG->navexpandmycourses) && $this->rootnodes['mycourses']->isactive){
1139 $this->load_courses_enrolled();
1141 $this->rootnodes['mycourses']->collapse = true;
1142 $this->rootnodes['mycourses']->make_inactive();
1145 $canviewcourseprofile = true;
1147 // Next load context specific content into the navigation
1148 switch ($this->page->context->contextlevel) {
1149 case CONTEXT_SYSTEM :
1150 // Nothing left to do here I feel.
1152 case CONTEXT_COURSECAT :
1153 // This is essential, we must load categories.
1154 $this->load_all_categories($this->page->context->instanceid, true);
1156 case CONTEXT_BLOCK :
1157 case CONTEXT_COURSE :
1159 // Nothing left to do here.
1163 // Load the course associated with the current page into the navigation.
1164 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1165 // If the course wasn't added then don't try going any further.
1167 $canviewcourseprofile = false;
1171 // If the user is not enrolled then we only want to show the
1172 // course node and not populate it.
1174 // Not enrolled, can't view, and hasn't switched roles
1175 if (!can_access_course($course)) {
1176 if ($coursenode->isexpandable === true) {
1177 // Obviously the situation has changed, update the cache and adjust the node.
1178 // This occurs if the user access to a course has been revoked (one way or another) after
1179 // initially logging in for this session.
1180 $this->get_expand_course_cache()->set($course->id, 1);
1181 $coursenode->isexpandable = true;
1182 $coursenode->nodetype = self::NODETYPE_BRANCH;
1184 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1185 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1186 if (!$this->current_user_is_parent_role()) {
1187 $coursenode->make_active();
1188 $canviewcourseprofile = false;
1193 if ($coursenode->isexpandable === false) {
1194 // Obviously the situation has changed, update the cache and adjust the node.
1195 // This occurs if the user has been granted access to a course (one way or another) after initially
1196 // logging in for this session.
1197 $this->get_expand_course_cache()->set($course->id, 1);
1198 $coursenode->isexpandable = true;
1199 $coursenode->nodetype = self::NODETYPE_BRANCH;
1202 // Add the essentials such as reports etc...
1203 $this->add_course_essentials($coursenode, $course);
1204 // Extend course navigation with it's sections/activities
1205 $this->load_course_sections($course, $coursenode);
1206 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1207 $coursenode->make_active();
1211 case CONTEXT_MODULE :
1213 // If this is the site course then most information will have
1214 // already been loaded.
1215 // However we need to check if there is more content that can
1216 // yet be loaded for the specific module instance.
1217 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1218 if ($activitynode) {
1219 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1224 $course = $this->page->course;
1225 $cm = $this->page->cm;
1227 // Load the course associated with the page into the navigation
1228 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1230 // If the course wasn't added then don't try going any further.
1232 $canviewcourseprofile = false;
1236 // If the user is not enrolled then we only want to show the
1237 // course node and not populate it.
1238 if (!can_access_course($course)) {
1239 $coursenode->make_active();
1240 $canviewcourseprofile = false;
1244 $this->add_course_essentials($coursenode, $course);
1246 // Load the course sections into the page
1247 $this->load_course_sections($course, $coursenode, null, $cm);
1248 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1249 if (!empty($activity)) {
1250 // Finally load the cm specific navigaton information
1251 $this->load_activity($cm, $course, $activity);
1252 // Check if we have an active ndoe
1253 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1254 // And make the activity node active.
1255 $activity->make_active();
1261 // The users profile information etc is already loaded
1262 // for the front page.
1265 $course = $this->page->course;
1266 // Load the course associated with the user into the navigation
1267 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1269 // If the course wasn't added then don't try going any further.
1271 $canviewcourseprofile = false;
1275 // If the user is not enrolled then we only want to show the
1276 // course node and not populate it.
1277 if (!can_access_course($course)) {
1278 $coursenode->make_active();
1279 $canviewcourseprofile = false;
1282 $this->add_course_essentials($coursenode, $course);
1283 $this->load_course_sections($course, $coursenode);
1287 // Load for the current user
1288 $this->load_for_user();
1289 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1290 $this->load_for_user(null, true);
1292 // Load each extending user into the navigation.
1293 foreach ($this->extendforuser as $user) {
1294 if ($user->id != $USER->id) {
1295 $this->load_for_user($user);
1299 // Give the local plugins a chance to include some navigation if they want.
1300 foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $unused) {
1301 $function = "local_{$plugin}_extend_navigation";
1302 $oldfunction = "local_{$plugin}_extends_navigation";
1304 if (function_exists($function)) {
1307 } else if (function_exists($oldfunction)) {
1308 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. ".
1309 "Support for the old callback will be dropped in Moodle 3.1", DEBUG_DEVELOPER);
1310 $oldfunction($this);
1314 // Remove any empty root nodes
1315 foreach ($this->rootnodes as $node) {
1316 // Dont remove the home node
1317 /** @var navigation_node $node */
1318 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1323 if (!$this->contains_active_node()) {
1324 $this->search_for_active_node();
1327 // If the user is not logged in modify the navigation structure as detailed
1328 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1329 if (!isloggedin()) {
1330 $activities = clone($this->rootnodes['site']->children);
1331 $this->rootnodes['site']->remove();
1332 $children = clone($this->children);
1333 $this->children = new navigation_node_collection();
1334 foreach ($activities as $child) {
1335 $this->children->add($child);
1337 foreach ($children as $child) {
1338 $this->children->add($child);
1345 * Returns true if the current user is a parent of the user being currently viewed.
1347 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1348 * other user being viewed this function returns false.
1349 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1354 protected function current_user_is_parent_role() {
1356 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1357 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1358 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1361 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1369 * Returns true if courses should be shown within categories on the navigation.
1371 * @param bool $ismycourse Set to true if you are calculating this for a course.
1374 protected function show_categories($ismycourse = false) {
1377 return $this->show_my_categories();
1379 if ($this->showcategories === null) {
1381 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1383 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1386 $this->showcategories = $show;
1388 return $this->showcategories;
1392 * Returns true if we should show categories in the My Courses branch.
1395 protected function show_my_categories() {
1397 if ($this->showmycategories === null) {
1398 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1400 return $this->showmycategories;
1404 * Loads the courses in Moodle into the navigation.
1406 * @global moodle_database $DB
1407 * @param string|array $categoryids An array containing categories to load courses
1408 * for, OR null to load courses for all categories.
1409 * @return array An array of navigation_nodes one for each course
1411 protected function load_all_courses($categoryids = null) {
1412 global $CFG, $DB, $SITE;
1414 // Work out the limit of courses.
1416 if (!empty($CFG->navcourselimit)) {
1417 $limit = $CFG->navcourselimit;
1420 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1422 // If we are going to show all courses AND we are showing categories then
1423 // to save us repeated DB calls load all of the categories now
1424 if ($this->show_categories()) {
1425 $this->load_all_categories($toload);
1428 // Will be the return of our efforts
1429 $coursenodes = array();
1431 // Check if we need to show categories.
1432 if ($this->show_categories()) {
1433 // Hmmm we need to show categories... this is going to be painful.
1434 // We now need to fetch up to $limit courses for each category to
1436 if ($categoryids !== null) {
1437 if (!is_array($categoryids)) {
1438 $categoryids = array($categoryids);
1440 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1441 $categorywhere = 'WHERE cc.id '.$categorywhere;
1442 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1443 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1444 $categoryparams = array();
1446 $categorywhere = '';
1447 $categoryparams = array();
1450 // First up we are going to get the categories that we are going to
1451 // need so that we can determine how best to load the courses from them.
1452 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1453 FROM {course_categories} cc
1454 LEFT JOIN {course} c ON c.category = cc.id
1457 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1458 $fullfetch = array();
1459 $partfetch = array();
1460 foreach ($categories as $category) {
1461 if (!$this->can_add_more_courses_to_category($category->id)) {
1464 if ($category->coursecount > $limit * 5) {
1465 $partfetch[] = $category->id;
1466 } else if ($category->coursecount > 0) {
1467 $fullfetch[] = $category->id;
1470 $categories->close();
1472 if (count($fullfetch)) {
1473 // First up fetch all of the courses in categories where we know that we are going to
1474 // need the majority of courses.
1475 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1476 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1477 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1478 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1479 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1482 WHERE c.category {$categoryids}
1483 ORDER BY c.sortorder ASC";
1484 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1485 foreach ($coursesrs as $course) {
1486 if ($course->id == $SITE->id) {
1487 // This should not be necessary, frontpage is not in any category.
1490 if (array_key_exists($course->id, $this->addedcourses)) {
1491 // It is probably better to not include the already loaded courses
1492 // directly in SQL because inequalities may confuse query optimisers
1493 // and may interfere with query caching.
1496 if (!$this->can_add_more_courses_to_category($course->category)) {
1499 context_helper::preload_from_record($course);
1500 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1503 $coursenodes[$course->id] = $this->add_course($course);
1505 $coursesrs->close();
1508 if (count($partfetch)) {
1509 // Next we will work our way through the categories where we will likely only need a small
1510 // proportion of the courses.
1511 foreach ($partfetch as $categoryid) {
1512 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1513 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1514 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1517 WHERE c.category = :categoryid
1518 ORDER BY c.sortorder ASC";
1519 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1520 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1521 foreach ($coursesrs as $course) {
1522 if ($course->id == $SITE->id) {
1523 // This should not be necessary, frontpage is not in any category.
1526 if (array_key_exists($course->id, $this->addedcourses)) {
1527 // It is probably better to not include the already loaded courses
1528 // directly in SQL because inequalities may confuse query optimisers
1529 // and may interfere with query caching.
1530 // This also helps to respect expected $limit on repeated executions.
1533 if (!$this->can_add_more_courses_to_category($course->category)) {
1536 context_helper::preload_from_record($course);
1537 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1540 $coursenodes[$course->id] = $this->add_course($course);
1542 $coursesrs->close();
1546 // Prepare the SQL to load the courses and their contexts
1547 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1548 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1549 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1550 $courseparams['contextlevel'] = CONTEXT_COURSE;
1551 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1554 WHERE c.id {$courseids}
1555 ORDER BY c.sortorder ASC";
1556 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1557 foreach ($coursesrs as $course) {
1558 if ($course->id == $SITE->id) {
1559 // frotpage is not wanted here
1562 if ($this->page->course && ($this->page->course->id == $course->id)) {
1563 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1566 context_helper::preload_from_record($course);
1567 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1570 $coursenodes[$course->id] = $this->add_course($course);
1571 if (count($coursenodes) >= $limit) {
1575 $coursesrs->close();
1578 return $coursenodes;
1582 * Returns true if more courses can be added to the provided category.
1584 * @param int|navigation_node|stdClass $category
1587 protected function can_add_more_courses_to_category($category) {
1590 if (!empty($CFG->navcourselimit)) {
1591 $limit = (int)$CFG->navcourselimit;
1593 if (is_numeric($category)) {
1594 if (!array_key_exists($category, $this->addedcategories)) {
1597 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1598 } else if ($category instanceof navigation_node) {
1599 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1602 $coursecount = count($category->children->type(self::TYPE_COURSE));
1603 } else if (is_object($category) && property_exists($category,'id')) {
1604 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1606 return ($coursecount <= $limit);
1610 * Loads all categories (top level or if an id is specified for that category)
1612 * @param int $categoryid The category id to load or null/0 to load all base level categories
1613 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1614 * as the requested category and any parent categories.
1615 * @return navigation_node|void returns a navigation node if a category has been loaded.
1617 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1620 // Check if this category has already been loaded
1621 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1625 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1626 $sqlselect = "SELECT cc.*, $catcontextsql
1627 FROM {course_categories} cc
1628 JOIN {context} ctx ON cc.id = ctx.instanceid";
1629 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1630 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1633 $categoriestoload = array();
1634 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1635 // We are going to load all categories regardless... prepare to fire
1636 // on the database server!
1637 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1638 // We are going to load all of the first level categories (categories without parents)
1639 $sqlwhere .= " AND cc.parent = 0";
1640 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1641 // The category itself has been loaded already so we just need to ensure its subcategories
1643 $addedcategories = $this->addedcategories;
1644 unset($addedcategories[$categoryid]);
1645 if (count($addedcategories) > 0) {
1646 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1647 if ($showbasecategories) {
1648 // We need to include categories with parent = 0 as well
1649 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1651 // All we need is categories that match the parent
1652 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1655 $params['categoryid'] = $categoryid;
1657 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1658 // and load this category plus all its parents and subcategories
1659 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1660 $categoriestoload = explode('/', trim($category->path, '/'));
1661 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1662 // We are going to use select twice so double the params
1663 $params = array_merge($params, $params);
1664 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1665 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1668 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1669 $categories = array();
1670 foreach ($categoriesrs as $category) {
1671 // Preload the context.. we'll need it when adding the category in order
1672 // to format the category name.
1673 context_helper::preload_from_record($category);
1674 if (array_key_exists($category->id, $this->addedcategories)) {
1675 // Do nothing, its already been added.
1676 } else if ($category->parent == '0') {
1677 // This is a root category lets add it immediately
1678 $this->add_category($category, $this->rootnodes['courses']);
1679 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1680 // This categories parent has already been added we can add this immediately
1681 $this->add_category($category, $this->addedcategories[$category->parent]);
1683 $categories[] = $category;
1686 $categoriesrs->close();
1688 // Now we have an array of categories we need to add them to the navigation.
1689 while (!empty($categories)) {
1690 $category = reset($categories);
1691 if (array_key_exists($category->id, $this->addedcategories)) {
1693 } else if ($category->parent == '0') {
1694 $this->add_category($category, $this->rootnodes['courses']);
1695 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1696 $this->add_category($category, $this->addedcategories[$category->parent]);
1698 // This category isn't in the navigation and niether is it's parent (yet).
1699 // We need to go through the category path and add all of its components in order.
1700 $path = explode('/', trim($category->path, '/'));
1701 foreach ($path as $catid) {
1702 if (!array_key_exists($catid, $this->addedcategories)) {
1703 // This category isn't in the navigation yet so add it.
1704 $subcategory = $categories[$catid];
1705 if ($subcategory->parent == '0') {
1706 // Yay we have a root category - this likely means we will now be able
1707 // to add categories without problems.
1708 $this->add_category($subcategory, $this->rootnodes['courses']);
1709 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1710 // The parent is in the category (as we'd expect) so add it now.
1711 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1712 // Remove the category from the categories array.
1713 unset($categories[$catid]);
1715 // We should never ever arrive here - if we have then there is a bigger
1717 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1722 // Remove the category from the categories array now that we know it has been added.
1723 unset($categories[$category->id]);
1725 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1726 $this->allcategoriesloaded = true;
1728 // Check if there are any categories to load.
1729 if (count($categoriestoload) > 0) {
1730 $readytoloadcourses = array();
1731 foreach ($categoriestoload as $category) {
1732 if ($this->can_add_more_courses_to_category($category)) {
1733 $readytoloadcourses[] = $category;
1736 if (count($readytoloadcourses)) {
1737 $this->load_all_courses($readytoloadcourses);
1741 // Look for all categories which have been loaded
1742 if (!empty($this->addedcategories)) {
1743 $categoryids = array();
1744 foreach ($this->addedcategories as $category) {
1745 if ($this->can_add_more_courses_to_category($category)) {
1746 $categoryids[] = $category->key;
1750 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1751 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1752 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1753 FROM {course_categories} cc
1754 JOIN {course} c ON c.category = cc.id
1755 WHERE cc.id {$categoriessql}
1757 HAVING COUNT(c.id) > :limit";
1758 $excessivecategories = $DB->get_records_sql($sql, $params);
1759 foreach ($categories as &$category) {
1760 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1761 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1762 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1770 * Adds a structured category to the navigation in the correct order/place
1772 * @param stdClass $category category to be added in navigation.
1773 * @param navigation_node $parent parent navigation node
1774 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1777 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1778 if (array_key_exists($category->id, $this->addedcategories)) {
1781 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1782 $context = context_coursecat::instance($category->id);
1783 $categoryname = format_string($category->name, true, array('context' => $context));
1784 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1785 if (empty($category->visible)) {
1786 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1787 $categorynode->hidden = true;
1789 $categorynode->display = false;
1792 $this->addedcategories[$category->id] = $categorynode;
1796 * Loads the given course into the navigation
1798 * @param stdClass $course
1799 * @return navigation_node
1801 protected function load_course(stdClass $course) {
1803 if ($course->id == $SITE->id) {
1804 // This is always loaded during initialisation
1805 return $this->rootnodes['site'];
1806 } else if (array_key_exists($course->id, $this->addedcourses)) {
1807 // The course has already been loaded so return a reference
1808 return $this->addedcourses[$course->id];
1811 return $this->add_course($course);
1816 * Loads all of the courses section into the navigation.
1818 * This function calls method from current course format, see
1819 * {@link format_base::extend_course_navigation()}
1820 * If course module ($cm) is specified but course format failed to create the node,
1821 * the activity node is created anyway.
1823 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1825 * @param stdClass $course Database record for the course
1826 * @param navigation_node $coursenode The course node within the navigation
1827 * @param null|int $sectionnum If specified load the contents of section with this relative number
1828 * @param null|cm_info $cm If specified make sure that activity node is created (either
1829 * in containg section or by calling load_stealth_activity() )
1831 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1833 require_once($CFG->dirroot.'/course/lib.php');
1834 if (isset($cm->sectionnum)) {
1835 $sectionnum = $cm->sectionnum;
1837 if ($sectionnum !== null) {
1838 $this->includesectionnum = $sectionnum;
1840 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1841 if (isset($cm->id)) {
1842 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1843 if (empty($activity)) {
1844 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1850 * Generates an array of sections and an array of activities for the given course.
1852 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1854 * @param stdClass $course
1855 * @return array Array($sections, $activities)
1857 protected function generate_sections_and_activities(stdClass $course) {
1859 require_once($CFG->dirroot.'/course/lib.php');
1861 $modinfo = get_fast_modinfo($course);
1862 $sections = $modinfo->get_section_info_all();
1864 // For course formats using 'numsections' trim the sections list
1865 $courseformatoptions = course_get_format($course)->get_format_options();
1866 if (isset($courseformatoptions['numsections'])) {
1867 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1870 $activities = array();
1872 foreach ($sections as $key => $section) {
1873 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1874 $sections[$key] = clone($section);
1875 unset($sections[$key]->summary);
1876 $sections[$key]->hasactivites = false;
1877 if (!array_key_exists($section->section, $modinfo->sections)) {
1880 foreach ($modinfo->sections[$section->section] as $cmid) {
1881 $cm = $modinfo->cms[$cmid];
1882 $activity = new stdClass;
1883 $activity->id = $cm->id;
1884 $activity->course = $course->id;
1885 $activity->section = $section->section;
1886 $activity->name = $cm->name;
1887 $activity->icon = $cm->icon;
1888 $activity->iconcomponent = $cm->iconcomponent;
1889 $activity->hidden = (!$cm->visible);
1890 $activity->modname = $cm->modname;
1891 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1892 $activity->onclick = $cm->onclick;
1895 $activity->url = null;
1896 $activity->display = false;
1898 $activity->url = $url->out();
1899 $activity->display = $cm->uservisible ? true : false;
1900 if (self::module_extends_navigation($cm->modname)) {
1901 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1904 $activities[$cmid] = $activity;
1905 if ($activity->display) {
1906 $sections[$key]->hasactivites = true;
1911 return array($sections, $activities);
1915 * Generically loads the course sections into the course's navigation.
1917 * @param stdClass $course
1918 * @param navigation_node $coursenode
1919 * @return array An array of course section nodes
1921 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1922 global $CFG, $DB, $USER, $SITE;
1923 require_once($CFG->dirroot.'/course/lib.php');
1925 list($sections, $activities) = $this->generate_sections_and_activities($course);
1927 $navigationsections = array();
1928 foreach ($sections as $sectionid => $section) {
1929 $section = clone($section);
1930 if ($course->id == $SITE->id) {
1931 $this->load_section_activities($coursenode, $section->section, $activities);
1933 if (!$section->uservisible || (!$this->showemptysections &&
1934 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1938 $sectionname = get_section_name($course, $section);
1939 $url = course_get_url($course, $section->section, array('navigation' => true));
1941 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1942 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1943 $sectionnode->hidden = (!$section->visible || !$section->available);
1944 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1945 $this->load_section_activities($sectionnode, $section->section, $activities);
1947 $section->sectionnode = $sectionnode;
1948 $navigationsections[$sectionid] = $section;
1951 return $navigationsections;
1955 * Loads all of the activities for a section into the navigation structure.
1957 * @param navigation_node $sectionnode
1958 * @param int $sectionnumber
1959 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1960 * @param stdClass $course The course object the section and activities relate to.
1961 * @return array Array of activity nodes
1963 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1965 // A static counter for JS function naming
1966 static $legacyonclickcounter = 0;
1968 $activitynodes = array();
1969 if (empty($activities)) {
1970 return $activitynodes;
1973 if (!is_object($course)) {
1974 $activity = reset($activities);
1975 $courseid = $activity->course;
1977 $courseid = $course->id;
1979 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1981 foreach ($activities as $activity) {
1982 if ($activity->section != $sectionnumber) {
1985 if ($activity->icon) {
1986 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1988 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1991 // Prepare the default name and url for the node
1992 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1993 $action = new moodle_url($activity->url);
1995 // Check if the onclick property is set (puke!)
1996 if (!empty($activity->onclick)) {
1997 // Increment the counter so that we have a unique number.
1998 $legacyonclickcounter++;
1999 // Generate the function name we will use
2000 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2001 $propogrationhandler = '';
2002 // Check if we need to cancel propogation. Remember inline onclick
2003 // events would return false if they wanted to prevent propogation and the
2005 if (strpos($activity->onclick, 'return false')) {
2006 $propogrationhandler = 'e.halt();';
2008 // Decode the onclick - it has already been encoded for display (puke)
2009 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2010 // Build the JS function the click event will call
2011 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2012 $this->page->requires->js_init_code($jscode);
2013 // Override the default url with the new action link
2014 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2017 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2018 $activitynode->title(get_string('modulename', $activity->modname));
2019 $activitynode->hidden = $activity->hidden;
2020 $activitynode->display = $showactivities && $activity->display;
2021 $activitynode->nodetype = $activity->nodetype;
2022 $activitynodes[$activity->id] = $activitynode;
2025 return $activitynodes;
2028 * Loads a stealth module from unavailable section
2029 * @param navigation_node $coursenode
2030 * @param stdClass $modinfo
2031 * @return navigation_node or null if not accessible
2033 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2034 if (empty($modinfo->cms[$this->page->cm->id])) {
2037 $cm = $modinfo->cms[$this->page->cm->id];
2039 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2041 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2044 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2045 $activitynode->title(get_string('modulename', $cm->modname));
2046 $activitynode->hidden = (!$cm->visible);
2047 if (!$cm->uservisible) {
2048 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2049 // Also there may be no exception at all in case when teacher is logged in as student.
2050 $activitynode->display = false;
2052 // Don't show activities that don't have links!
2053 $activitynode->display = false;
2054 } else if (self::module_extends_navigation($cm->modname)) {
2055 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2057 return $activitynode;
2060 * Loads the navigation structure for the given activity into the activities node.
2062 * This method utilises a callback within the modules lib.php file to load the
2063 * content specific to activity given.
2065 * The callback is a method: {modulename}_extend_navigation()
2067 * * {@link forum_extend_navigation()}
2068 * * {@link workshop_extend_navigation()}
2070 * @param cm_info|stdClass $cm
2071 * @param stdClass $course
2072 * @param navigation_node $activity
2075 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2078 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2079 if (!($cm instanceof cm_info)) {
2080 $modinfo = get_fast_modinfo($course);
2081 $cm = $modinfo->get_cm($cm->id);
2083 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2084 $activity->make_active();
2085 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2086 $function = $cm->modname.'_extend_navigation';
2088 if (file_exists($file)) {
2089 require_once($file);
2090 if (function_exists($function)) {
2091 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2092 $function($activity, $course, $activtyrecord, $cm);
2096 // Allow the active advanced grading method plugin to append module navigation
2097 $featuresfunc = $cm->modname.'_supports';
2098 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2099 require_once($CFG->dirroot.'/grade/grading/lib.php');
2100 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2101 $gradingman->extend_navigation($this, $activity);
2104 return $activity->has_children();
2107 * Loads user specific information into the navigation in the appropriate place.
2109 * If no user is provided the current user is assumed.
2111 * @param stdClass $user
2112 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2115 protected function load_for_user($user=null, $forceforcontext=false) {
2116 global $DB, $CFG, $USER, $SITE;
2118 if ($user === null) {
2119 // We can't require login here but if the user isn't logged in we don't
2120 // want to show anything
2121 if (!isloggedin() || isguestuser()) {
2125 } else if (!is_object($user)) {
2126 // If the user is not an object then get them from the database
2127 $select = context_helper::get_preload_record_columns_sql('ctx');
2128 $sql = "SELECT u.*, $select
2130 JOIN {context} ctx ON u.id = ctx.instanceid
2131 WHERE u.id = :userid AND
2132 ctx.contextlevel = :contextlevel";
2133 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2134 context_helper::preload_from_record($user);
2137 $iscurrentuser = ($user->id == $USER->id);
2139 $usercontext = context_user::instance($user->id);
2141 // Get the course set against the page, by default this will be the site
2142 $course = $this->page->course;
2143 $baseargs = array('id'=>$user->id);
2144 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2145 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2146 $baseargs['course'] = $course->id;
2147 $coursecontext = context_course::instance($course->id);
2148 $issitecourse = false;
2150 // Load all categories and get the context for the system
2151 $coursecontext = context_system::instance();
2152 $issitecourse = true;
2155 // Create a node to add user information under.
2157 if (!$issitecourse) {
2158 // Not the current user so add it to the participants node for the current course.
2159 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2160 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2161 } else if ($USER->id != $user->id) {
2162 // This is the site so add a users node to the root branch.
2163 $usersnode = $this->rootnodes['users'];
2164 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2165 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2167 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2170 // We should NEVER get here, if the course hasn't been populated
2171 // with a participants node then the navigaiton either wasn't generated
2172 // for it (you are missing a require_login or set_context call) or
2173 // you don't have access.... in the interests of no leaking informatin
2174 // we simply quit...
2177 // Add a branch for the current user.
2178 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2179 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2180 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2181 $usernode->make_active();
2184 // Add user information to the participants or user node.
2185 if ($issitecourse) {
2187 // If the user is the current user or has permission to view the details of the requested
2188 // user than add a view profile link.
2189 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2190 has_capability('moodle/user:viewdetails', $usercontext)) {
2191 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2192 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2194 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2198 if (!empty($CFG->navadduserpostslinks)) {
2199 // Add nodes for forum posts and discussions if the user can view either or both
2200 // There are no capability checks here as the content of the page is based
2201 // purely on the forums the current user has access too.
2202 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2203 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2204 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2205 array_merge($baseargs, array('mode' => 'discussions'))));
2209 if (!empty($CFG->enableblogs)) {
2210 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2211 require_once($CFG->dirroot.'/blog/lib.php');
2212 // Get all options for the user.
2213 $options = blog_get_options_for_user($user);
2214 $this->cache->set('userblogoptions'.$user->id, $options);
2216 $options = $this->cache->{'userblogoptions'.$user->id};
2219 if (count($options) > 0) {
2220 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2221 foreach ($options as $type => $option) {
2222 if ($type == "rss") {
2223 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2224 new pix_icon('i/rss', ''));
2226 $blogs->add($option['string'], $option['link']);
2232 // Add the messages link.
2233 // It is context based so can appear in "My profile" and in course participants information.
2234 if (!empty($CFG->messaging)) {
2235 $messageargs = array('user1' => $USER->id);
2236 if ($USER->id != $user->id) {
2237 $messageargs['user2'] = $user->id;
2239 if ($course->id != $SITE->id) {
2240 $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
2242 $url = new moodle_url('/message/index.php', $messageargs);
2243 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2246 // Add the "My private files" link.
2247 // This link doesn't have a unique display for course context so only display it under "My profile".
2248 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2249 $url = new moodle_url('/user/files.php');
2250 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2253 if (!empty($CFG->enablebadges) && $iscurrentuser &&
2254 has_capability('moodle/badges:manageownbadges', $usercontext)) {
2255 $url = new moodle_url('/badges/mybadges.php');
2256 $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2259 // Add a node to view the users notes if permitted.
2260 if (!empty($CFG->enablenotes) &&
2261 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2262 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2263 if ($coursecontext->instanceid != SITEID) {
2264 $url->param('course', $coursecontext->instanceid);
2266 $usernode->add(get_string('notes', 'notes'), $url);
2269 // Show the my grades node.
2270 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2271 require_once($CFG->dirroot . '/user/lib.php');
2272 // Set the grades node to link to the "My grades" page.
2273 if ($course->id == SITEID) {
2274 $url = user_mygrades_url($user->id, $course->id);
2275 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2276 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2278 if ($USER->id != $user->id) {
2279 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2281 $usernode->add(get_string('mygrades', 'grades'), $url);
2285 // If the user is the current user add the repositories for the current user.
2286 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2287 if (!$iscurrentuser &&
2288 $course->id == $SITE->id &&
2289 has_capability('moodle/user:viewdetails', $usercontext) &&
2290 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2292 // Add view grade report is permitted.
2293 $reports = core_component::get_plugin_list('gradereport');
2294 arsort($reports); // User is last, we want to test it first.
2296 $userscourses = enrol_get_users_courses($user->id);
2297 $userscoursesnode = $usernode->add(get_string('courses'));
2300 foreach ($userscourses as $usercourse) {
2301 if ($count === (int)$CFG->navcourselimit) {
2302 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2303 $userscoursesnode->add(get_string('showallcourses'), $url);
2307 $usercoursecontext = context_course::instance($usercourse->id);
2308 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2309 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2310 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2312 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2313 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2314 foreach ($reports as $plugin => $plugindir) {
2315 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2316 // Stop when the first visible plugin is found.
2317 $gradeavailable = true;
2323 if ($gradeavailable) {
2324 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2325 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2326 new pix_icon('i/grades', ''));
2329 // Add a node to view the users notes if permitted.
2330 if (!empty($CFG->enablenotes) &&
2331 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2332 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2333 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2336 if (can_access_course($usercourse, $user->id)) {
2337 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2338 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2341 $reporttab = $usercoursenode->add(get_string('activityreports'));
2343 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2344 foreach ($reports as $reportfunction) {
2345 $reportfunction($reporttab, $user, $usercourse);
2348 $reporttab->trim_if_empty();
2357 * This method simply checks to see if a given module can extend the navigation.
2359 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2361 * @param string $modname
2364 public static function module_extends_navigation($modname) {
2366 static $extendingmodules = array();
2367 if (!array_key_exists($modname, $extendingmodules)) {
2368 $extendingmodules[$modname] = false;
2369 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2370 if (file_exists($file)) {
2371 $function = $modname.'_extend_navigation';
2372 require_once($file);
2373 $extendingmodules[$modname] = (function_exists($function));
2376 return $extendingmodules[$modname];
2379 * Extends the navigation for the given user.
2381 * @param stdClass $user A user from the database
2383 public function extend_for_user($user) {
2384 $this->extendforuser[] = $user;
2388 * Returns all of the users the navigation is being extended for
2390 * @return array An array of extending users.
2392 public function get_extending_users() {
2393 return $this->extendforuser;
2396 * Adds the given course to the navigation structure.
2398 * @param stdClass $course
2399 * @param bool $forcegeneric
2400 * @param bool $ismycourse
2401 * @return navigation_node
2403 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2406 // We found the course... we can return it now :)
2407 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2408 return $this->addedcourses[$course->id];
2411 $coursecontext = context_course::instance($course->id);
2413 if ($course->id != $SITE->id && !$course->visible) {
2414 if (is_role_switched($course->id)) {
2415 // user has to be able to access course in order to switch, let's skip the visibility test here
2416 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2421 $issite = ($course->id == $SITE->id);
2422 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2423 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2424 // This is the name that will be shown for the course.
2425 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2427 // Can the user expand the course to see its content.
2428 $canexpandcourse = true;
2432 if (empty($CFG->usesitenameforsitepages)) {
2433 $coursename = get_string('sitepages');
2435 } else if ($coursetype == self::COURSE_CURRENT) {
2436 $parent = $this->rootnodes['currentcourse'];
2437 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2438 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2439 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2440 // Nothing to do here the above statement set $parent to the category within mycourses.
2442 $parent = $this->rootnodes['mycourses'];
2444 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2446 $parent = $this->rootnodes['courses'];
2447 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2448 // They can only expand the course if they can access it.
2449 $canexpandcourse = $this->can_expand_course($course);
2450 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2451 if (!$this->is_category_fully_loaded($course->category)) {
2452 // We need to load the category structure for this course
2453 $this->load_all_categories($course->category, false);
2455 if (array_key_exists($course->category, $this->addedcategories)) {
2456 $parent = $this->addedcategories[$course->category];
2457 // This could lead to the course being created so we should check whether it is the case again
2458 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2459 return $this->addedcourses[$course->id];
2465 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2466 $coursenode->hidden = (!$course->visible);
2467 // We need to decode &'s here as they will have been added by format_string above and attributes will be encoded again
2469 $coursenode->title(str_replace('&', '&', $fullname));
2470 if ($canexpandcourse) {
2471 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2472 $coursenode->nodetype = self::NODETYPE_BRANCH;
2473 $coursenode->isexpandable = true;
2475 $coursenode->nodetype = self::NODETYPE_LEAF;
2476 $coursenode->isexpandable = false;
2478 if (!$forcegeneric) {
2479 $this->addedcourses[$course->id] = $coursenode;
2486 * Returns a cache instance to use for the expand course cache.
2487 * @return cache_session
2489 protected function get_expand_course_cache() {
2490 if ($this->cacheexpandcourse === null) {
2491 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2493 return $this->cacheexpandcourse;
2497 * Checks if a user can expand a course in the navigation.
2499 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2500 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2501 * permits stale data.
2502 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2504 * It is brought up to date in only one of two ways.
2505 * 1. The user logs out and in again.
2506 * 2. The user browses to the course they've just being given access to.
2508 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2510 * @param stdClass $course
2513 protected function can_expand_course($course) {
2514 $cache = $this->get_expand_course_cache();
2515 $canexpand = $cache->get($course->id);
2516 if ($canexpand === false) {
2517 $canexpand = isloggedin() && can_access_course($course);
2518 $canexpand = (int)$canexpand;
2519 $cache->set($course->id, $canexpand);
2521 return ($canexpand === 1);
2525 * Returns true if the category has already been loaded as have any child categories
2527 * @param int $categoryid
2530 protected function is_category_fully_loaded($categoryid) {
2531 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2535 * Adds essential course nodes to the navigation for the given course.
2537 * This method adds nodes such as reports, blogs and participants
2539 * @param navigation_node $coursenode
2540 * @param stdClass $course
2541 * @return bool returns true on successful addition of a node.
2543 public function add_course_essentials($coursenode, stdClass $course) {
2546 if ($course->id == $SITE->id) {
2547 return $this->add_front_page_course_essentials($coursenode, $course);
2550 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2555 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2556 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2557 if (!empty($CFG->enableblogs)) {
2558 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2559 and has_capability('moodle/blog:view', context_system::instance())) {
2560 $blogsurls = new moodle_url('/blog/index.php');
2561 if ($course->id == $SITE->id) {
2562 $blogsurls->param('courseid', 0);
2563 } else if ($currentgroup = groups_get_course_group($course, true)) {
2564 $blogsurls->param('groupid', $currentgroup);
2566 $blogsurls->param('courseid', $course->id);
2568 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2571 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2572 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2574 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2575 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2579 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2580 has_capability('moodle/badges:viewbadges', $this->page->context)) {
2581 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2583 $coursenode->add(get_string('coursebadges', 'badges'), null,
2584 navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2585 $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2586 navigation_node::TYPE_SETTING, null, 'badgesview',
2587 new pix_icon('i/badge', get_string('badgesview', 'badges')));
2593 * This generates the structure of the course that won't be generated when
2594 * the modules and sections are added.
2596 * Things such as the reports branch, the participants branch, blogs... get
2597 * added to the course node by this method.
2599 * @param navigation_node $coursenode
2600 * @param stdClass $course
2601 * @return bool True for successfull generation
2603 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2606 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2610 // Hidden node that we use to determine if the front page navigation is loaded.
2611 // This required as there are not other guaranteed nodes that may be loaded.
2612 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2615 if (has_capability('moodle/course:viewparticipants', context_system::instance())) {
2616 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2622 if (!empty($CFG->enableblogs)
2623 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2624 and has_capability('moodle/blog:view', context_system::instance())) {
2625 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2626 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2630 if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2631 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2632 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2636 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2637 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2638 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2642 if (!empty($CFG->usetags) && isloggedin()) {
2643 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2644 self::TYPE_SETTING, null, 'tags');
2649 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2650 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2657 * Clears the navigation cache
2659 public function clear_cache() {
2660 $this->cache->clear();
2664 * Sets an expansion limit for the navigation
2666 * The expansion limit is used to prevent the display of content that has a type
2667 * greater than the provided $type.
2669 * Can be used to ensure things such as activities or activity content don't get
2670 * shown on the navigation.
2671 * They are still generated in order to ensure the navbar still makes sense.
2673 * @param int $type One of navigation_node::TYPE_*
2674 * @return bool true when complete.
2676 public function set_expansion_limit($type) {
2678 $nodes = $this->find_all_of_type($type);
2680 // We only want to hide specific types of nodes.
2681 // Only nodes that represent "structure" in the navigation tree should be hidden.
2682 // If we hide all nodes then we risk hiding vital information.
2683 $typestohide = array(
2684 self::TYPE_CATEGORY,
2690 foreach ($nodes as $node) {
2691 // We need to generate the full site node
2692 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2695 foreach ($node->children as $child) {
2696 $child->hide($typestohide);
2702 * Attempts to get the navigation with the given key from this nodes children.
2704 * This function only looks at this nodes children, it does NOT look recursivily.
2705 * If the node can't be found then false is returned.
2707 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2709 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2710 * may be of more use to you.
2712 * @param string|int $key The key of the node you wish to receive.
2713 * @param int $type One of navigation_node::TYPE_*
2714 * @return navigation_node|false
2716 public function get($key, $type = null) {
2717 if (!$this->initialised) {
2718 $this->initialise();
2720 return parent::get($key, $type);
2724 * Searches this nodes children and their children to find a navigation node
2725 * with the matching key and type.
2727 * This method is recursive and searches children so until either a node is
2728 * found or there are no more nodes to search.
2730 * If you know that the node being searched for is a child of this node
2731 * then use the {@link global_navigation::get()} method instead.
2733 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2734 * may be of more use to you.
2736 * @param string|int $key The key of the node you wish to receive.
2737 * @param int $type One of navigation_node::TYPE_*
2738 * @return navigation_node|false
2740 public function find($key, $type) {
2741 if (!$this->initialised) {
2742 $this->initialise();
2744 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2745 return $this->rootnodes[$key];
2747 return parent::find($key, $type);
2751 * They've expanded the 'my courses' branch.
2753 protected function load_courses_enrolled() {
2755 $sortorder = 'visible DESC';
2756 // Prevent undefined $CFG->navsortmycoursessort errors.
2757 if (empty($CFG->navsortmycoursessort)) {
2758 $CFG->navsortmycoursessort = 'sortorder';
2760 // Append the chosen sortorder.
2761 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2762 $courses = enrol_get_my_courses(null, $sortorder);
2763 if (count($courses) && $this->show_my_categories()) {
2764 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2765 // In order to make sure we load everything required we must first find the categories that are not
2766 // base categories and work out the bottom category in thier path.
2767 $categoryids = array();
2768 foreach ($courses as $course) {
2769 $categoryids[] = $course->category;
2771 $categoryids = array_unique($categoryids);
2772 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2773 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2774 foreach ($categories as $category) {
2775 $bits = explode('/', trim($category->path,'/'));
2776 $categoryids[] = array_shift($bits);
2778 $categoryids = array_unique($categoryids);
2779 $categories->close();
2781 // Now we load the base categories.
2782 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2783 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2784 foreach ($categories as $category) {
2785 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2787 $categories->close();
2789 foreach ($courses as $course) {
2790 $this->add_course($course, false, self::COURSE_MY);
2797 * The global navigation class used especially for AJAX requests.
2799 * The primary methods that are used in the global navigation class have been overriden
2800 * to ensure that only the relevant branch is generated at the root of the tree.
2801 * This can be done because AJAX is only used when the backwards structure for the
2802 * requested branch exists.
2803 * This has been done only because it shortens the amounts of information that is generated
2804 * which of course will speed up the response time.. because no one likes laggy AJAX.
2807 * @category navigation
2808 * @copyright 2009 Sam Hemelryk
2809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2811 class global_navigation_for_ajax extends global_navigation {
2813 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2814 protected $branchtype;
2816 /** @var int the instance id */
2817 protected $instanceid;
2819 /** @var array Holds an array of expandable nodes */
2820 protected $expandable = array();
2823 * Constructs the navigation for use in an AJAX request
2825 * @param moodle_page $page moodle_page object
2826 * @param int $branchtype
2829 public function __construct($page, $branchtype, $id) {
2830 $this->page = $page;
2831 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2832 $this->children = new navigation_node_collection();
2833 $this->branchtype = $branchtype;
2834 $this->instanceid = $id;
2835 $this->initialise();
2838 * Initialise the navigation given the type and id for the branch to expand.
2840 * @return array An array of the expandable nodes
2842 public function initialise() {
2845 if ($this->initialised || during_initial_install()) {
2846 return $this->expandable;
2848 $this->initialised = true;
2850 $this->rootnodes = array();
2851 $this->rootnodes['site'] = $this->add_course($SITE);
2852 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2853 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2854 // The courses branch is always displayed, and is always expandable (although may be empty).
2855 // This mimicks what is done during {@link global_navigation::initialise()}.
2856 $this->rootnodes['courses']->isexpandable = true;
2858 // Branchtype will be one of navigation_node::TYPE_*
2859 switch ($this->branchtype) {
2861 if ($this->instanceid === 'mycourses') {
2862 $this->load_courses_enrolled();
2863 } else if ($this->instanceid === 'courses') {
2864 $this->load_courses_other();
2867 case self::TYPE_CATEGORY :
2868 $this->load_category($this->instanceid);
2870 case self::TYPE_MY_CATEGORY :
2871 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2873 case self::TYPE_COURSE :
2874 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2875 if (!can_access_course($course)) {
2876 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
2877 // add the course node and break. This leads to an empty node.
2878 $this->add_course($course);
2881 require_course_login($course, true, null, false, true);
2882 $this->page->set_context(context_course::instance($course->id));
2883 $coursenode = $this->add_course($course);
2884 $this->add_course_essentials($coursenode, $course);
2885 $this->load_course_sections($course, $coursenode);
2887 case self::TYPE_SECTION :
2888 $sql = 'SELECT c.*, cs.section AS sectionnumber
2890 LEFT JOIN {course_sections} cs ON cs.course = c.id
2892 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2893 require_course_login($course, true, null, false, true);
2894 $this->page->set_context(context_course::instance($course->id));
2895 $coursenode = $this->add_course($course);
2896 $this->add_course_essentials($coursenode, $course);
2897 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2899 case self::TYPE_ACTIVITY :
2902 JOIN {course_modules} cm ON cm.course = c.id
2903 WHERE cm.id = :cmid";
2904 $params = array('cmid' => $this->instanceid);
2905 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2906 $modinfo = get_fast_modinfo($course);
2907 $cm = $modinfo->get_cm($this->instanceid);
2908 require_course_login($course, true, $cm, false, true);
2909 $this->page->set_context(context_module::instance($cm->id));
2910 $coursenode = $this->load_course($course);
2911 $this->load_course_sections($course, $coursenode, null, $cm);
2912 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2913 if ($activitynode) {
2914 $modulenode = $this->load_activity($cm, $course, $activitynode);
2918 throw new Exception('Unknown type');
2919 return $this->expandable;
2922 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2923 $this->load_for_user(null, true);
2926 $this->find_expandable($this->expandable);
2927 return $this->expandable;
2931 * They've expanded the general 'courses' branch.
2933 protected function load_courses_other() {
2934 $this->load_all_courses();
2938 * Loads a single category into the AJAX navigation.
2940 * This function is special in that it doesn't concern itself with the parent of
2941 * the requested category or its siblings.
2942 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2945 * @global moodle_database $DB
2946 * @param int $categoryid id of category to load in navigation.
2947 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2950 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2954 if (!empty($CFG->navcourselimit)) {
2955 $limit = (int)$CFG->navcourselimit;
2958 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2959 $sql = "SELECT cc.*, $catcontextsql
2960 FROM {course_categories} cc
2961 JOIN {context} ctx ON cc.id = ctx.instanceid
2962 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2963 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2964 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2965 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2966 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2967 $categorylist = array();
2968 $subcategories = array();
2969 $basecategory = null;
2970 foreach ($categories as $category) {
2971 $categorylist[] = $category->id;
2972 context_helper::preload_from_record($category);
2973 if ($category->id == $categoryid) {
2974 $this->add_category($category, $this, $nodetype);
2975 $basecategory = $this->addedcategories[$category->id];
2977 $subcategories[$category->id] = $category;
2980 $categories->close();
2983 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2984 // else show all courses.
2985 if ($nodetype === self::TYPE_MY_CATEGORY) {
2986 $courses = enrol_get_my_courses();
2987 $categoryids = array();
2989 // Only search for categories if basecategory was found.
2990 if (!is_null($basecategory)) {
2991 // Get course parent category ids.
2992 foreach ($courses as $course) {
2993 $categoryids[] = $course->category;
2996 // Get a unique list of category ids which a part of the path
2997 // to user's courses.
2998 $coursesubcategories = array();
2999 $addedsubcategories = array();
3001 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3002 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3004 foreach ($categories as $category){
3005 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3007 $coursesubcategories = array_unique($coursesubcategories);
3009 // Only add a subcategory if it is part of the path to user's course and
3010 // wasn't already added.
3011 foreach ($subcategories as $subid => $subcategory) {
3012 if (in_array($subid, $coursesubcategories) &&
3013 !in_array($subid, $addedsubcategories)) {
3014 $this->add_category($subcategory, $basecategory, $nodetype);
3015 $addedsubcategories[] = $subid;
3020 foreach ($courses as $course) {
3021 // Add course if it's in category.
3022 if (in_array($course->category, $categorylist)) {
3023 $this->add_course($course, true, self::COURSE_MY);
3027 if (!is_null($basecategory)) {
3028 foreach ($subcategories as $key=>$category) {
3029 $this->add_category($category, $basecategory, $nodetype);
3032 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3033 foreach ($courses as $course) {
3034 $this->add_course($course);
3041 * Returns an array of expandable nodes
3044 public function get_expandable() {
3045 return $this->expandable;
3052 * This class is used to manage the navbar, which is initialised from the navigation
3053 * object held by PAGE
3056 * @category navigation
3057 * @copyright 2009 Sam Hemelryk
3058 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3060 class navbar extends navigation_node {
3061 /** @var bool A switch for whether the navbar is initialised or not */
3062 protected $initialised = false;
3063 /** @var mixed keys used to reference the nodes on the navbar */
3064 protected $keys = array();
3065 /** @var null|string content of the navbar */
3066 protected $content = null;
3067 /** @var moodle_page object the moodle page that this navbar belongs to */
3069 /** @var bool A switch for whether to ignore the active navigation information */
3070 protected $ignoreactive = false;
3071 /** @var bool A switch to let us know if we are in the middle of an install */
3072 protected $duringinstall = false;
3073 /** @var bool A switch for whether the navbar has items */
3074 protected $hasitems = false;
3075 /** @var array An array of navigation nodes for the navbar */
3077 /** @var array An array of child node objects */
3078 public $children = array();
3079 /** @var bool A switch for whether we want to include the root node in the navbar */
3080 public $includesettingsbase = false;
3081 /** @var navigation_node[] $prependchildren */
3082 protected $prependchildren = array();
3084 * The almighty constructor
3086 * @param moodle_page $page
3088 public function __construct(moodle_page $page) {
3090 if (during_initial_install()) {
3091 $this->duringinstall = true;
3094 $this->page = $page;
3095 $this->text = get_string('home');
3096 $this->shorttext = get_string('home');
3097 $this->action = new moodle_url($CFG->wwwroot);
3098 $this->nodetype = self::NODETYPE_BRANCH;
3099 $this->type = self::TYPE_SYSTEM;
3103 * Quick check to see if the navbar will have items in.
3105 * @return bool Returns true if the navbar will have items, false otherwise
3107 public function has_items() {
3108 if ($this->duringinstall) {
3110 } else if ($this->hasitems !== false) {
3113 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3114 // There have been manually added items - there are definitely items.
3116 } else if (!$this->ignoreactive) {
3117 // We will need to initialise the navigation structure to check if there are active items.
3118 $this->page->navigation->initialise($this->page);
3119 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3121 $this->hasitems = $outcome;
3126 * Turn on/off ignore active
3128 * @param bool $setting
3130 public function ignore_active($setting=true) {
3131 $this->ignoreactive = ($setting);
3135 * Gets a navigation node
3137 * @param string|int $key for referencing the navbar nodes
3138 * @param int $type navigation_node::TYPE_*
3139 * @return navigation_node|bool
3141 public function get($key, $type = null) {
3142 foreach ($this->children as &$child) {
3143 if ($child->key === $key && ($type == null || $type == $child->type)) {
3147 foreach ($this->prependchildren as &$child) {
3148 if ($child->key === $key && ($type == null || $type == $child->type)) {
3155 * Returns an array of navigation_node's that make up the navbar.
3159 public function get_items() {
3162 // Make sure that navigation is initialised
3163 if (!$this->has_items()) {
3166 if ($this->items !== null) {
3167 return $this->items;
3170 if (count($this->children) > 0) {
3171 // Add the custom children.
3172 $items = array_reverse($this->children);
3175 // Check if navigation contains the active node
3176 if (!$this->ignoreactive) {
3177 // We will need to ensure the navigation has been initialised.
3178 $this->page->navigation->initialise($this->page);
3179 // Now find the active nodes on both the navigation and settings.
3180 $navigationactivenode = $this->page->navigation->find_active_node();
3181 $settingsactivenode = $this->page->settingsnav->find_active_node();
3183 if ($navigationactivenode && $settingsactivenode) {
3184 // Parse a combined navigation tree
3185 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3186 if (!$settingsactivenode->mainnavonly) {
3187 $items[] = $settingsactivenode;
3189 $settingsactivenode = $settingsactivenode->parent;
3191 if (!$this->includesettingsbase) {
3192 // Removes the first node from the settings (root node) from the list
3195 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3196 if (!$navigationactivenode->mainnavonly) {
3197 $items[] = $navigationactivenode;
3199 if (!empty($CFG->navshowcategories) &&
3200 $navigationactivenode->type === self::TYPE_COURSE &&
3201 $navigationactivenode->parent->key === 'currentcourse') {
3202 $items = array_merge($items, $this->get_course_categories());
3204 $navigationactivenode = $navigationactivenode->parent;
3206 } else if ($navigationactivenode) {
3207 // Parse the navigation tree to get the active node
3208 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3209 if (!$navigationactivenode->mainnavonly) {
3210 $items[] = $navigationactivenode;
3212 if (!empty($CFG->navshowcategories) &&
3213 $navigationactivenode->type === self::TYPE_COURSE &&
3214 $navigationactivenode->parent->key === 'currentcourse') {
3215 $items = array_merge($items, $this->get_course_categories());
3217 $navigationactivenode = $navigationactivenode->parent;
3219 } else if ($settingsactivenode) {
3220 // Parse the settings navigation to get the active node
3221 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3222 if (!$settingsactivenode->mainnavonly) {
3223 $items[] = $settingsactivenode;
3225 $settingsactivenode = $settingsactivenode->parent;
3230 $items[] = new navigation_node(array(
3231 'text'=>$this->page->navigation->text,
3232 'shorttext'=>$this->page->navigation->shorttext,
3233 'key'=>$this->page->navigation->key,
3234 'action'=>$this->page->navigation->action
3237 if (count($this->prependchildren) > 0) {
3238 // Add the custom children
3239 $items = array_merge($items, array_reverse($this->prependchildren));
3242 $this->items = array_reverse($items);
3243 return $this->items;
3247 * Get the list of categories leading to this course.
3249 * This function is used by {@link navbar::get_items()} to add back the "courses"
3250 * node and category chain leading to the current course. Note that this is only ever
3251 * called for the current course, so we don't need to bother taking in any parameters.
3255 private function get_course_categories() {
3257 require_once($CFG->dirroot.'/course/lib.php');
3258 require_once($CFG->libdir.'/coursecatlib.php');
3260 $categories = array();
3261 $cap = 'moodle/category:viewhiddencategories';
3262 $showcategories = coursecat::count_all() > 1;
3264 if ($showcategories) {
3265 foreach ($this->page->categories as $category) {
3266 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3269 $url = new moodle_url('/course/index.php