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;
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE = 'courseindexpage';
90 /** @var int Parameter to aid the coder in tracking [optional] */
92 /** @var string|int The identifier for the node, used to retrieve the node */
94 /** @var string The text to use for the node */
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
102 /** @var moodle_url|action_link|null An action for the node (link) */
103 public $action = null;
104 /** @var pix_icon The path to an icon to use for this node */
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self::TYPE_UNKNOWN;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self::NODETYPE_LEAF;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
114 /** @var array An array of CSS classes for the node */
115 public $classes = array();
116 /** @var navigation_node_collection An array of child nodes */
117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
120 /** @var bool If set to true the node will be dimmed */
121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
131 public $parent = null;
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
137 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
138 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
140 /** @var moodle_url */
141 protected static $fullmeurl = null;
142 /** @var bool toogles auto matching of active node */
143 public static $autofindactive = true;
144 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
145 protected static $loadadmintree = false;
146 /** @var mixed If set to an int, that section will be included even if it has no activities */
147 public $includesectionnum = false;
148 /** @var bool does the node need to be loaded via ajax */
149 public $requiresajaxloading = false;
150 /** @var bool If set to true this node will be added to the "flat" navigation */
151 public $showinflatnavigation = false;
154 * Constructs a new navigation_node
156 * @param array|string $properties Either an array of properties or a string to use
157 * as the text for the node
159 public function __construct($properties) {
160 if (is_array($properties)) {
161 // Check the array for each property that we allow to set at construction.
162 // text - The main content for the node
163 // shorttext - A short text if required for the node
164 // icon - The icon to display for the node
165 // type - The type of the node
166 // key - The key to use to identify the node
167 // parent - A reference to the nodes parent
168 // action - The action to attribute to this node, usually a URL to link to
169 if (array_key_exists('text', $properties)) {
170 $this->text = $properties['text'];
172 if (array_key_exists('shorttext', $properties)) {
173 $this->shorttext = $properties['shorttext'];
175 if (!array_key_exists('icon', $properties)) {
176 $properties['icon'] = new pix_icon('i/navigationitem', '');
178 $this->icon = $properties['icon'];
179 if ($this->icon instanceof pix_icon) {
180 if (empty($this->icon->attributes['class'])) {
181 $this->icon->attributes['class'] = 'navicon';
183 $this->icon->attributes['class'] .= ' navicon';
186 if (array_key_exists('type', $properties)) {
187 $this->type = $properties['type'];
189 $this->type = self::TYPE_CUSTOM;
191 if (array_key_exists('key', $properties)) {
192 $this->key = $properties['key'];
194 // This needs to happen last because of the check_if_active call that occurs
195 if (array_key_exists('action', $properties)) {
196 $this->action = $properties['action'];
197 if (is_string($this->action)) {
198 $this->action = new moodle_url($this->action);
200 if (self::$autofindactive) {
201 $this->check_if_active();
204 if (array_key_exists('parent', $properties)) {
205 $this->set_parent($properties['parent']);
207 } else if (is_string($properties)) {
208 $this->text = $properties;
210 if ($this->text === null) {
211 throw new coding_exception('You must set the text for the node when you create it.');
213 // Instantiate a new navigation node collection for this nodes children
214 $this->children = new navigation_node_collection();
218 * Checks if this node is the active node.
220 * This is determined by comparing the action for the node against the
221 * defined URL for the page. A match will see this node marked as active.
223 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
226 public function check_if_active($strength=URL_MATCH_EXACT) {
227 global $FULLME, $PAGE;
228 // Set fullmeurl if it hasn't already been set
229 if (self::$fullmeurl == null) {
230 if ($PAGE->has_set_url()) {
231 self::override_active_url(new moodle_url($PAGE->url));
233 self::override_active_url(new moodle_url($FULLME));
237 // Compare the action of this node against the fullmeurl
238 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
239 $this->make_active();
246 * True if this nav node has siblings in the tree.
250 public function has_siblings() {
251 if (empty($this->parent) || empty($this->parent->children)) {
254 if ($this->parent->children instanceof navigation_node_collection) {
255 $count = $this->parent->children->count();
257 $count = count($this->parent->children);
263 * Get a list of sibling navigation nodes at the same level as this one.
265 * @return bool|array of navigation_node
267 public function get_siblings() {
268 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
269 // the in-page links or the breadcrumb links.
272 if ($this->has_siblings()) {
274 foreach ($this->parent->children as $child) {
275 if ($child->display) {
276 $siblings[] = $child;
284 * This sets the URL that the URL of new nodes get compared to when locating
287 * The active node is the node that matches the URL set here. By default this
288 * is either $PAGE->url or if that hasn't been set $FULLME.
290 * @param moodle_url $url The url to use for the fullmeurl.
291 * @param bool $loadadmintree use true if the URL point to administration tree
293 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
294 // Clone the URL, in case the calling script changes their URL later.
295 self::$fullmeurl = new moodle_url($url);
296 // True means we do not want AJAX loaded admin tree, required for all admin pages.
297 if ($loadadmintree) {
298 // Do not change back to false if already set.
299 self::$loadadmintree = true;
304 * Use when page is linked from the admin tree,
305 * if not used navigation could not find the page using current URL
306 * because the tree is not fully loaded.
308 public static function require_admin_tree() {
309 self::$loadadmintree = true;
313 * Creates a navigation node, ready to add it as a child using add_node
314 * function. (The created node needs to be added before you can use it.)
315 * @param string $text
316 * @param moodle_url|action_link $action
318 * @param string $shorttext
319 * @param string|int $key
320 * @param pix_icon $icon
321 * @return navigation_node
323 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
324 $shorttext=null, $key=null, pix_icon $icon=null) {
325 // Properties array used when creating the new navigation node
330 // Set the action if one was provided
331 if ($action!==null) {
332 $itemarray['action'] = $action;
334 // Set the shorttext if one was provided
335 if ($shorttext!==null) {
336 $itemarray['shorttext'] = $shorttext;
338 // Set the icon if one was provided
340 $itemarray['icon'] = $icon;
343 $itemarray['key'] = $key;
344 // Construct and return
345 return new navigation_node($itemarray);
349 * Adds a navigation node as a child of this node.
351 * @param string $text
352 * @param moodle_url|action_link $action
354 * @param string $shorttext
355 * @param string|int $key
356 * @param pix_icon $icon
357 * @return navigation_node
359 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
361 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
363 // Add the child to end and return
364 return $this->add_node($childnode);
368 * Adds a navigation node as a child of this one, given a $node object
369 * created using the create function.
370 * @param navigation_node $childnode Node to add
371 * @param string $beforekey
372 * @return navigation_node The added node
374 public function add_node(navigation_node $childnode, $beforekey=null) {
375 // First convert the nodetype for this node to a branch as it will now have children
376 if ($this->nodetype !== self::NODETYPE_BRANCH) {
377 $this->nodetype = self::NODETYPE_BRANCH;
379 // Set the parent to this node
380 $childnode->set_parent($this);
382 // Default the key to the number of children if not provided
383 if ($childnode->key === null) {
384 $childnode->key = $this->children->count();
387 // Add the child using the navigation_node_collections add method
388 $node = $this->children->add($childnode, $beforekey);
390 // If added node is a category node or the user is logged in and it's a course
391 // then mark added node as a branch (makes it expandable by AJAX)
392 $type = $childnode->type;
393 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
394 ($type === self::TYPE_SITE_ADMIN)) {
395 $node->nodetype = self::NODETYPE_BRANCH;
397 // If this node is hidden mark it's children as hidden also
399 $node->hidden = true;
401 // Return added node (reference returned by $this->children->add()
406 * Return a list of all the keys of all the child nodes.
407 * @return array the keys.
409 public function get_children_key_list() {
410 return $this->children->get_key_list();
414 * Searches for a node of the given type with the given key.
416 * This searches this node plus all of its children, and their children....
417 * If you know the node you are looking for is a child of this node then please
418 * use the get method instead.
420 * @param int|string $key The key of the node we are looking for
421 * @param int $type One of navigation_node::TYPE_*
422 * @return navigation_node|false
424 public function find($key, $type) {
425 return $this->children->find($key, $type);
429 * Walk the tree building up a list of all the flat navigation nodes.
431 * @param flat_navigation $nodes List of the found flat navigation nodes.
432 * @param boolean $showdivider Show a divider before the first node.
434 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false) {
435 if ($this->showinflatnavigation) {
437 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
440 $flat = new flat_navigation_node($this, $indent);
441 $flat->set_showdivider($showdivider);
444 foreach ($this->children as $child) {
445 $child->build_flat_navigation_list($nodes, false);
450 * Get the child of this node that has the given key + (optional) type.
452 * If you are looking for a node and want to search all children + their children
453 * then please use the find method instead.
455 * @param int|string $key The key of the node we are looking for
456 * @param int $type One of navigation_node::TYPE_*
457 * @return navigation_node|false
459 public function get($key, $type=null) {
460 return $this->children->get($key, $type);
468 public function remove() {
469 return $this->parent->children->remove($this->key, $this->type);
473 * Checks if this node has or could have any children
475 * @return bool Returns true if it has children or could have (by AJAX expansion)
477 public function has_children() {
478 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
482 * Marks this node as active and forces it open.
484 * Important: If you are here because you need to mark a node active to get
485 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
486 * You can use it to specify a different URL to match the active navigation node on
487 * rather than having to locate and manually mark a node active.
489 public function make_active() {
490 $this->isactive = true;
491 $this->add_class('active_tree_node');
493 if ($this->parent !== null) {
494 $this->parent->make_inactive();
499 * Marks a node as inactive and recusised back to the base of the tree
500 * doing the same to all parents.
502 public function make_inactive() {
503 $this->isactive = false;
504 $this->remove_class('active_tree_node');
505 if ($this->parent !== null) {
506 $this->parent->make_inactive();
511 * Forces this node to be open and at the same time forces open all
512 * parents until the root node.
516 public function force_open() {
517 $this->forceopen = true;
518 if ($this->parent !== null) {
519 $this->parent->force_open();
524 * Adds a CSS class to this node.
526 * @param string $class
529 public function add_class($class) {
530 if (!in_array($class, $this->classes)) {
531 $this->classes[] = $class;
537 * Removes a CSS class from this node.
539 * @param string $class
540 * @return bool True if the class was successfully removed.
542 public function remove_class($class) {
543 if (in_array($class, $this->classes)) {
544 $key = array_search($class,$this->classes);
546 unset($this->classes[$key]);
554 * Sets the title for this node and forces Moodle to utilise it.
555 * @param string $title
557 public function title($title) {
558 $this->title = $title;
559 $this->forcetitle = true;
563 * Resets the page specific information on this node if it is being unserialised.
565 public function __wakeup(){
566 $this->forceopen = false;
567 $this->isactive = false;
568 $this->remove_class('active_tree_node');
572 * Checks if this node or any of its children contain the active node.
578 public function contains_active_node() {
579 if ($this->isactive) {
582 foreach ($this->children as $child) {
583 if ($child->isactive || $child->contains_active_node()) {
592 * To better balance the admin tree, we want to group all the short top branches together.
594 * This means < 8 nodes and no subtrees.
598 public function is_short_branch() {
600 if ($this->children->count() >= $limit) {
603 foreach ($this->children as $child) {
604 if ($child->has_children()) {
612 * Finds the active node.
614 * Searches this nodes children plus all of the children for the active node
615 * and returns it if found.
619 * @return navigation_node|false
621 public function find_active_node() {
622 if ($this->isactive) {
625 foreach ($this->children as &$child) {
626 $outcome = $child->find_active_node();
627 if ($outcome !== false) {
636 * Searches all children for the best matching active node
637 * @return navigation_node|false
639 public function search_for_active_node() {
640 if ($this->check_if_active(URL_MATCH_BASE)) {
643 foreach ($this->children as &$child) {
644 $outcome = $child->search_for_active_node();
645 if ($outcome !== false) {
654 * Gets the content for this node.
656 * @param bool $shorttext If true shorttext is used rather than the normal text
659 public function get_content($shorttext=false) {
660 if ($shorttext && $this->shorttext!==null) {
661 return format_string($this->shorttext);
663 return format_string($this->text);
668 * Gets the title to use for this node.
672 public function get_title() {
673 if ($this->forcetitle || $this->action != null){
681 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
685 public function has_action() {
686 return !empty($this->action);
690 * Used to easily determine if this link in the breadcrumbs is hidden.
694 public function is_hidden() {
695 return $this->hidden;
699 * Gets the CSS class to add to this node to describe its type
703 public function get_css_type() {
704 if (array_key_exists($this->type, $this->namedtypes)) {
705 return 'type_'.$this->namedtypes[$this->type];
707 return 'type_unknown';
711 * Finds all nodes that are expandable by AJAX
713 * @param array $expandable An array by reference to populate with expandable nodes.
715 public function find_expandable(array &$expandable) {
716 foreach ($this->children as &$child) {
717 if ($child->display && $child->has_children() && $child->children->count() == 0) {
718 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
719 $this->add_class('canexpand');
720 $child->requiresajaxloading = true;
721 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
723 $child->find_expandable($expandable);
728 * Finds all nodes of a given type (recursive)
730 * @param int $type One of navigation_node::TYPE_*
733 public function find_all_of_type($type) {
734 $nodes = $this->children->type($type);
735 foreach ($this->children as &$node) {
736 $childnodes = $node->find_all_of_type($type);
737 $nodes = array_merge($nodes, $childnodes);
743 * Removes this node if it is empty
745 public function trim_if_empty() {
746 if ($this->children->count() == 0) {
752 * Creates a tab representation of this nodes children that can be used
753 * with print_tabs to produce the tabs on a page.
755 * call_user_func_array('print_tabs', $node->get_tabs_array());
757 * @param array $inactive
758 * @param bool $return
759 * @return array Array (tabs, selected, inactive, activated, return)
761 public function get_tabs_array(array $inactive=array(), $return=false) {
765 $activated = array();
766 foreach ($this->children as $node) {
767 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
768 if ($node->contains_active_node()) {
769 if ($node->children->count() > 0) {
770 $activated[] = $node->key;
771 foreach ($node->children as $child) {
772 if ($child->contains_active_node()) {
773 $selected = $child->key;
775 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
778 $selected = $node->key;
782 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
786 * Sets the parent for this node and if this node is active ensures that the tree is properly
789 * @param navigation_node $parent
791 public function set_parent(navigation_node $parent) {
792 // Set the parent (thats the easy part)
793 $this->parent = $parent;
794 // Check if this node is active (this is checked during construction)
795 if ($this->isactive) {
796 // Force all of the parent nodes open so you can see this node
797 $this->parent->force_open();
798 // Make all parents inactive so that its clear where we are.
799 $this->parent->make_inactive();
804 * Hides the node and any children it has.
807 * @param array $typestohide Optional. An array of node types that should be hidden.
808 * If null all nodes will be hidden.
809 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
810 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
812 public function hide(array $typestohide = null) {
813 if ($typestohide === null || in_array($this->type, $typestohide)) {
814 $this->display = false;
815 if ($this->has_children()) {
816 foreach ($this->children as $child) {
817 $child->hide($typestohide);
824 * Get the action url for this navigation node.
825 * Called from templates.
829 public function action() {
830 if ($this->action instanceof moodle_url) {
831 return $this->action;
832 } else if ($this->action instanceof action_link) {
833 return $this->action->url;
835 return $this->action;
840 * Navigation node collection
842 * This class is responsible for managing a collection of navigation nodes.
843 * It is required because a node's unique identifier is a combination of both its
846 * Originally an array was used with a string key that was a combination of the two
847 * however it was decided that a better solution would be to use a class that
848 * implements the standard IteratorAggregate interface.
851 * @category navigation
852 * @copyright 2010 Sam Hemelryk
853 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
855 class navigation_node_collection implements IteratorAggregate, Countable {
857 * A multidimensional array to where the first key is the type and the second
858 * key is the nodes key.
861 protected $collection = array();
863 * An array that contains references to nodes in the same order they were added.
864 * This is maintained as a progressive array.
867 protected $orderedcollection = array();
869 * A reference to the last node that was added to the collection
870 * @var navigation_node
872 protected $last = null;
874 * The total number of items added to this array.
877 protected $count = 0;
880 * Adds a navigation node to the collection
882 * @param navigation_node $node Node to add
883 * @param string $beforekey If specified, adds before a node with this key,
884 * otherwise adds at end
885 * @return navigation_node Added node
887 public function add(navigation_node $node, $beforekey=null) {
892 // First check we have a 2nd dimension for this type
893 if (!array_key_exists($type, $this->orderedcollection)) {
894 $this->orderedcollection[$type] = array();
896 // Check for a collision and report if debugging is turned on
897 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
898 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
901 // Find the key to add before
902 $newindex = $this->count;
904 if ($beforekey !== null) {
905 foreach ($this->collection as $index => $othernode) {
906 if ($othernode->key === $beforekey) {
912 if ($newindex === $this->count) {
913 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
914 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
918 // Add the node to the appropriate place in the by-type structure (which
919 // is not ordered, despite the variable name)
920 $this->orderedcollection[$type][$key] = $node;
922 // Update existing references in the ordered collection (which is the
923 // one that isn't called 'ordered') to shuffle them along if required
924 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
925 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
928 // Add a reference to the node to the progressive collection.
929 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
930 // Update the last property to a reference to this new node.
931 $this->last = $this->orderedcollection[$type][$key];
933 // Reorder the array by index if needed
935 ksort($this->collection);
938 // Return the reference to the now added node
943 * Return a list of all the keys of all the nodes.
944 * @return array the keys.
946 public function get_key_list() {
948 foreach ($this->collection as $node) {
949 $keys[] = $node->key;
955 * Fetches a node from this collection.
957 * @param string|int $key The key of the node we want to find.
958 * @param int $type One of navigation_node::TYPE_*.
959 * @return navigation_node|null
961 public function get($key, $type=null) {
962 if ($type !== null) {
963 // If the type is known then we can simply check and fetch
964 if (!empty($this->orderedcollection[$type][$key])) {
965 return $this->orderedcollection[$type][$key];
968 // Because we don't know the type we look in the progressive array
969 foreach ($this->collection as $node) {
970 if ($node->key === $key) {
979 * Searches for a node with matching key and type.
981 * This function searches both the nodes in this collection and all of
982 * the nodes in each collection belonging to the nodes in this collection.
986 * @param string|int $key The key of the node we want to find.
987 * @param int $type One of navigation_node::TYPE_*.
988 * @return navigation_node|null
990 public function find($key, $type=null) {
991 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
992 return $this->orderedcollection[$type][$key];
994 $nodes = $this->getIterator();
995 // Search immediate children first
996 foreach ($nodes as &$node) {
997 if ($node->key === $key && ($type === null || $type === $node->type)) {
1001 // Now search each childs children
1002 foreach ($nodes as &$node) {
1003 $result = $node->children->find($key, $type);
1004 if ($result !== false) {
1013 * Fetches the last node that was added to this collection
1015 * @return navigation_node
1017 public function last() {
1022 * Fetches all nodes of a given type from this collection
1024 * @param string|int $type node type being searched for.
1025 * @return array ordered collection
1027 public function type($type) {
1028 if (!array_key_exists($type, $this->orderedcollection)) {
1029 $this->orderedcollection[$type] = array();
1031 return $this->orderedcollection[$type];
1034 * Removes the node with the given key and type from the collection
1036 * @param string|int $key The key of the node we want to find.
1040 public function remove($key, $type=null) {
1041 $child = $this->get($key, $type);
1042 if ($child !== false) {
1043 foreach ($this->collection as $colkey => $node) {
1044 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1045 unset($this->collection[$colkey]);
1046 $this->collection = array_values($this->collection);
1050 unset($this->orderedcollection[$child->type][$child->key]);
1058 * Gets the number of nodes in this collection
1060 * This option uses an internal count rather than counting the actual options to avoid
1061 * a performance hit through the count function.
1065 public function count() {
1066 return $this->count;
1069 * Gets an array iterator for the collection.
1071 * This is required by the IteratorAggregator interface and is used by routines
1072 * such as the foreach loop.
1074 * @return ArrayIterator
1076 public function getIterator() {
1077 return new ArrayIterator($this->collection);
1082 * The global navigation class used for... the global navigation
1084 * This class is used by PAGE to store the global navigation for the site
1085 * and is then used by the settings nav and navbar to save on processing and DB calls
1088 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1089 * {@link lib/ajax/getnavbranch.php} Called by ajax
1092 * @category navigation
1093 * @copyright 2009 Sam Hemelryk
1094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1096 class global_navigation extends navigation_node {
1097 /** @var moodle_page The Moodle page this navigation object belongs to. */
1099 /** @var bool switch to let us know if the navigation object is initialised*/
1100 protected $initialised = false;
1101 /** @var array An array of course information */
1102 protected $mycourses = array();
1103 /** @var navigation_node[] An array for containing root navigation nodes */
1104 protected $rootnodes = array();
1105 /** @var bool A switch for whether to show empty sections in the navigation */
1106 protected $showemptysections = true;
1107 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1108 protected $showcategories = null;
1109 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1110 protected $showmycategories = null;
1111 /** @var array An array of stdClasses for users that the navigation is extended for */
1112 protected $extendforuser = array();
1113 /** @var navigation_cache */
1115 /** @var array An array of course ids that are present in the navigation */
1116 protected $addedcourses = array();
1118 protected $allcategoriesloaded = false;
1119 /** @var array An array of category ids that are included in the navigation */
1120 protected $addedcategories = array();
1121 /** @var int expansion limit */
1122 protected $expansionlimit = 0;
1123 /** @var int userid to allow parent to see child's profile page navigation */
1124 protected $useridtouseforparentchecks = 0;
1125 /** @var cache_session A cache that stores information on expanded courses */
1126 protected $cacheexpandcourse = null;
1128 /** Used when loading categories to load all top level categories [parent = 0] **/
1129 const LOAD_ROOT_CATEGORIES = 0;
1130 /** Used when loading categories to load all categories **/
1131 const LOAD_ALL_CATEGORIES = -1;
1134 * Constructs a new global navigation
1136 * @param moodle_page $page The page this navigation object belongs to
1138 public function __construct(moodle_page $page) {
1139 global $CFG, $SITE, $USER;
1141 if (during_initial_install()) {
1145 if (get_home_page() == HOMEPAGE_SITE) {
1146 // We are using the site home for the root element
1147 $properties = array(
1149 'type' => navigation_node::TYPE_SYSTEM,
1150 'text' => get_string('home'),
1151 'action' => new moodle_url('/'),
1152 'icon' => new pix_icon('i/home', '')
1155 // We are using the users my moodle for the root element
1156 $properties = array(
1158 'type' => navigation_node::TYPE_SYSTEM,
1159 'text' => get_string('myhome'),
1160 'action' => new moodle_url('/my/'),
1161 'icon' => new pix_icon('i/dashboard', '')
1165 // Use the parents constructor.... good good reuse
1166 parent::__construct($properties);
1167 $this->showinflatnavigation = true;
1169 // Initalise and set defaults
1170 $this->page = $page;
1171 $this->forceopen = true;
1172 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1176 * Mutator to set userid to allow parent to see child's profile
1177 * page navigation. See MDL-25805 for initial issue. Linked to it
1178 * is an issue explaining why this is a REALLY UGLY HACK thats not
1181 * @param int $userid userid of profile page that parent wants to navigate around.
1183 public function set_userid_for_parent_checks($userid) {
1184 $this->useridtouseforparentchecks = $userid;
1189 * Initialises the navigation object.
1191 * This causes the navigation object to look at the current state of the page
1192 * that it is associated with and then load the appropriate content.
1194 * This should only occur the first time that the navigation structure is utilised
1195 * which will normally be either when the navbar is called to be displayed or
1196 * when a block makes use of it.
1200 public function initialise() {
1201 global $CFG, $SITE, $USER;
1202 // Check if it has already been initialised
1203 if ($this->initialised || during_initial_install()) {
1206 $this->initialised = true;
1208 // Set up the five base root nodes. These are nodes where we will put our
1209 // content and are as follows:
1210 // site: Navigation for the front page.
1211 // myprofile: User profile information goes here.
1212 // currentcourse: The course being currently viewed.
1213 // mycourses: The users courses get added here.
1214 // courses: Additional courses are added here.
1215 // users: Other users information loaded here.
1216 $this->rootnodes = array();
1217 if (get_home_page() == HOMEPAGE_SITE) {
1218 // The home element should be my moodle because the root element is the site
1219 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1220 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1221 self::TYPE_SETTING, null, 'home', new pix_icon('i/dashboard', ''));
1222 $this->rootnodes['home']->showinflatnavigation = true;
1225 // The home element should be the site because the root node is my moodle
1226 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1227 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1228 $this->rootnodes['home']->showinflatnavigation = true;
1229 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1230 // We need to stop automatic redirection
1231 $this->rootnodes['home']->action->param('redirect', '0');
1234 $this->rootnodes['site'] = $this->add_course($SITE);
1235 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1236 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1237 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
1238 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1239 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1241 // We always load the frontpage course to ensure it is available without
1242 // JavaScript enabled.
1243 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1244 $this->load_course_sections($SITE, $this->rootnodes['site']);
1246 $course = $this->page->course;
1247 $this->load_courses_enrolled();
1249 // $issite gets set to true if the current pages course is the sites frontpage course
1250 $issite = ($this->page->course->id == $SITE->id);
1252 // Determine if the user is enrolled in any course.
1253 $enrolledinanycourse = enrol_user_sees_own_courses();
1255 $this->rootnodes['currentcourse']->mainnavonly = true;
1256 if ($enrolledinanycourse) {
1257 $this->rootnodes['mycourses']->isexpandable = true;
1258 $this->rootnodes['mycourses']->showinflatnavigation = true;
1259 if ($CFG->navshowallcourses) {
1260 // When we show all courses we need to show both the my courses and the regular courses branch.
1261 $this->rootnodes['courses']->isexpandable = true;
1264 $this->rootnodes['courses']->isexpandable = true;
1266 $this->rootnodes['mycourses']->forceopen = true;
1268 $canviewcourseprofile = true;
1270 // Next load context specific content into the navigation
1271 switch ($this->page->context->contextlevel) {
1272 case CONTEXT_SYSTEM :
1273 // Nothing left to do here I feel.
1275 case CONTEXT_COURSECAT :
1276 // This is essential, we must load categories.
1277 $this->load_all_categories($this->page->context->instanceid, true);
1279 case CONTEXT_BLOCK :
1280 case CONTEXT_COURSE :
1282 // Nothing left to do here.
1286 // Load the course associated with the current page into the navigation.
1287 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1288 // If the course wasn't added then don't try going any further.
1290 $canviewcourseprofile = false;
1294 // If the user is not enrolled then we only want to show the
1295 // course node and not populate it.
1297 // Not enrolled, can't view, and hasn't switched roles
1298 if (!can_access_course($course, null, '', true)) {
1299 if ($coursenode->isexpandable === true) {
1300 // Obviously the situation has changed, update the cache and adjust the node.
1301 // This occurs if the user access to a course has been revoked (one way or another) after
1302 // initially logging in for this session.
1303 $this->get_expand_course_cache()->set($course->id, 1);
1304 $coursenode->isexpandable = true;
1305 $coursenode->nodetype = self::NODETYPE_BRANCH;
1307 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1308 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1309 if (!$this->current_user_is_parent_role()) {
1310 $coursenode->make_active();
1311 $canviewcourseprofile = false;
1314 } else if ($coursenode->isexpandable === false) {
1315 // Obviously the situation has changed, update the cache and adjust the node.
1316 // This occurs if the user has been granted access to a course (one way or another) after initially
1317 // logging in for this session.
1318 $this->get_expand_course_cache()->set($course->id, 1);
1319 $coursenode->isexpandable = true;
1320 $coursenode->nodetype = self::NODETYPE_BRANCH;
1323 // Add the essentials such as reports etc...
1324 $this->add_course_essentials($coursenode, $course);
1325 // Extend course navigation with it's sections/activities
1326 $this->load_course_sections($course, $coursenode);
1327 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1328 $coursenode->make_active();
1332 case CONTEXT_MODULE :
1334 // If this is the site course then most information will have
1335 // already been loaded.
1336 // However we need to check if there is more content that can
1337 // yet be loaded for the specific module instance.
1338 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1339 if ($activitynode) {
1340 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1345 $course = $this->page->course;
1346 $cm = $this->page->cm;
1348 // Load the course associated with the page into the navigation
1349 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1351 // If the course wasn't added then don't try going any further.
1353 $canviewcourseprofile = false;
1357 // If the user is not enrolled then we only want to show the
1358 // course node and not populate it.
1359 if (!can_access_course($course, null, '', true)) {
1360 $coursenode->make_active();
1361 $canviewcourseprofile = false;
1365 $this->add_course_essentials($coursenode, $course);
1367 // Load the course sections into the page
1368 $this->load_course_sections($course, $coursenode, null, $cm);
1369 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1370 if (!empty($activity)) {
1371 // Finally load the cm specific navigaton information
1372 $this->load_activity($cm, $course, $activity);
1373 // Check if we have an active ndoe
1374 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1375 // And make the activity node active.
1376 $activity->make_active();
1382 // The users profile information etc is already loaded
1383 // for the front page.
1386 $course = $this->page->course;
1387 // Load the course associated with the user into the navigation
1388 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1390 // If the course wasn't added then don't try going any further.
1392 $canviewcourseprofile = false;
1396 // If the user is not enrolled then we only want to show the
1397 // course node and not populate it.
1398 if (!can_access_course($course, null, '', true)) {
1399 $coursenode->make_active();
1400 $canviewcourseprofile = false;
1403 $this->add_course_essentials($coursenode, $course);
1404 $this->load_course_sections($course, $coursenode);
1408 // Load for the current user
1409 $this->load_for_user();
1410 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1411 $this->load_for_user(null, true);
1413 // Load each extending user into the navigation.
1414 foreach ($this->extendforuser as $user) {
1415 if ($user->id != $USER->id) {
1416 $this->load_for_user($user);
1420 // Give the local plugins a chance to include some navigation if they want.
1421 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1425 // Remove any empty root nodes
1426 foreach ($this->rootnodes as $node) {
1427 // Dont remove the home node
1428 /** @var navigation_node $node */
1429 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1434 if (!$this->contains_active_node()) {
1435 $this->search_for_active_node();
1438 // If the user is not logged in modify the navigation structure as detailed
1439 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1440 if (!isloggedin()) {
1441 $activities = clone($this->rootnodes['site']->children);
1442 $this->rootnodes['site']->remove();
1443 $children = clone($this->children);
1444 $this->children = new navigation_node_collection();
1445 foreach ($activities as $child) {
1446 $this->children->add($child);
1448 foreach ($children as $child) {
1449 $this->children->add($child);
1456 * Returns true if the current user is a parent of the user being currently viewed.
1458 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1459 * other user being viewed this function returns false.
1460 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1465 protected function current_user_is_parent_role() {
1467 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1468 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1469 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1472 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1480 * Returns true if courses should be shown within categories on the navigation.
1482 * @param bool $ismycourse Set to true if you are calculating this for a course.
1485 protected function show_categories($ismycourse = false) {
1488 return $this->show_my_categories();
1490 if ($this->showcategories === null) {
1492 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1494 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1497 $this->showcategories = $show;
1499 return $this->showcategories;
1503 * Returns true if we should show categories in the My Courses branch.
1506 protected function show_my_categories() {
1508 if ($this->showmycategories === null) {
1509 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && core_course_category::count_all() > 1;
1511 return $this->showmycategories;
1515 * Loads the courses in Moodle into the navigation.
1517 * @global moodle_database $DB
1518 * @param string|array $categoryids An array containing categories to load courses
1519 * for, OR null to load courses for all categories.
1520 * @return array An array of navigation_nodes one for each course
1522 protected function load_all_courses($categoryids = null) {
1523 global $CFG, $DB, $SITE;
1525 // Work out the limit of courses.
1527 if (!empty($CFG->navcourselimit)) {
1528 $limit = $CFG->navcourselimit;
1531 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1533 // If we are going to show all courses AND we are showing categories then
1534 // to save us repeated DB calls load all of the categories now
1535 if ($this->show_categories()) {
1536 $this->load_all_categories($toload);
1539 // Will be the return of our efforts
1540 $coursenodes = array();
1542 // Check if we need to show categories.
1543 if ($this->show_categories()) {
1544 // Hmmm we need to show categories... this is going to be painful.
1545 // We now need to fetch up to $limit courses for each category to
1547 if ($categoryids !== null) {
1548 if (!is_array($categoryids)) {
1549 $categoryids = array($categoryids);
1551 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1552 $categorywhere = 'WHERE cc.id '.$categorywhere;
1553 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1554 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1555 $categoryparams = array();
1557 $categorywhere = '';
1558 $categoryparams = array();
1561 // First up we are going to get the categories that we are going to
1562 // need so that we can determine how best to load the courses from them.
1563 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1564 FROM {course_categories} cc
1565 LEFT JOIN {course} c ON c.category = cc.id
1568 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1569 $fullfetch = array();
1570 $partfetch = array();
1571 foreach ($categories as $category) {
1572 if (!$this->can_add_more_courses_to_category($category->id)) {
1575 if ($category->coursecount > $limit * 5) {
1576 $partfetch[] = $category->id;
1577 } else if ($category->coursecount > 0) {
1578 $fullfetch[] = $category->id;
1581 $categories->close();
1583 if (count($fullfetch)) {
1584 // First up fetch all of the courses in categories where we know that we are going to
1585 // need the majority of courses.
1586 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1587 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1588 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1589 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1590 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1593 WHERE c.category {$categoryids}
1594 ORDER BY c.sortorder ASC";
1595 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1596 foreach ($coursesrs as $course) {
1597 if ($course->id == $SITE->id) {
1598 // This should not be necessary, frontpage is not in any category.
1601 if (array_key_exists($course->id, $this->addedcourses)) {
1602 // It is probably better to not include the already loaded courses
1603 // directly in SQL because inequalities may confuse query optimisers
1604 // and may interfere with query caching.
1607 if (!$this->can_add_more_courses_to_category($course->category)) {
1610 context_helper::preload_from_record($course);
1611 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1614 $coursenodes[$course->id] = $this->add_course($course);
1616 $coursesrs->close();
1619 if (count($partfetch)) {
1620 // Next we will work our way through the categories where we will likely only need a small
1621 // proportion of the courses.
1622 foreach ($partfetch as $categoryid) {
1623 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1624 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1625 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1628 WHERE c.category = :categoryid
1629 ORDER BY c.sortorder ASC";
1630 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1631 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1632 foreach ($coursesrs as $course) {
1633 if ($course->id == $SITE->id) {
1634 // This should not be necessary, frontpage is not in any category.
1637 if (array_key_exists($course->id, $this->addedcourses)) {
1638 // It is probably better to not include the already loaded courses
1639 // directly in SQL because inequalities may confuse query optimisers
1640 // and may interfere with query caching.
1641 // This also helps to respect expected $limit on repeated executions.
1644 if (!$this->can_add_more_courses_to_category($course->category)) {
1647 context_helper::preload_from_record($course);
1648 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1651 $coursenodes[$course->id] = $this->add_course($course);
1653 $coursesrs->close();
1657 // Prepare the SQL to load the courses and their contexts
1658 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1659 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1660 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1661 $courseparams['contextlevel'] = CONTEXT_COURSE;
1662 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1665 WHERE c.id {$courseids}
1666 ORDER BY c.sortorder ASC";
1667 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1668 foreach ($coursesrs as $course) {
1669 if ($course->id == $SITE->id) {
1670 // frotpage is not wanted here
1673 if ($this->page->course && ($this->page->course->id == $course->id)) {
1674 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1677 context_helper::preload_from_record($course);
1678 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1681 $coursenodes[$course->id] = $this->add_course($course);
1682 if (count($coursenodes) >= $limit) {
1686 $coursesrs->close();
1689 return $coursenodes;
1693 * Returns true if more courses can be added to the provided category.
1695 * @param int|navigation_node|stdClass $category
1698 protected function can_add_more_courses_to_category($category) {
1701 if (!empty($CFG->navcourselimit)) {
1702 $limit = (int)$CFG->navcourselimit;
1704 if (is_numeric($category)) {
1705 if (!array_key_exists($category, $this->addedcategories)) {
1708 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1709 } else if ($category instanceof navigation_node) {
1710 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1713 $coursecount = count($category->children->type(self::TYPE_COURSE));
1714 } else if (is_object($category) && property_exists($category,'id')) {
1715 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1717 return ($coursecount <= $limit);
1721 * Loads all categories (top level or if an id is specified for that category)
1723 * @param int $categoryid The category id to load or null/0 to load all base level categories
1724 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1725 * as the requested category and any parent categories.
1726 * @return navigation_node|void returns a navigation node if a category has been loaded.
1728 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1731 // Check if this category has already been loaded
1732 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1736 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1737 $sqlselect = "SELECT cc.*, $catcontextsql
1738 FROM {course_categories} cc
1739 JOIN {context} ctx ON cc.id = ctx.instanceid";
1740 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1741 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1744 $categoriestoload = array();
1745 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1746 // We are going to load all categories regardless... prepare to fire
1747 // on the database server!
1748 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1749 // We are going to load all of the first level categories (categories without parents)
1750 $sqlwhere .= " AND cc.parent = 0";
1751 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1752 // The category itself has been loaded already so we just need to ensure its subcategories
1754 $addedcategories = $this->addedcategories;
1755 unset($addedcategories[$categoryid]);
1756 if (count($addedcategories) > 0) {
1757 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1758 if ($showbasecategories) {
1759 // We need to include categories with parent = 0 as well
1760 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1762 // All we need is categories that match the parent
1763 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1766 $params['categoryid'] = $categoryid;
1768 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1769 // and load this category plus all its parents and subcategories
1770 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1771 $categoriestoload = explode('/', trim($category->path, '/'));
1772 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1773 // We are going to use select twice so double the params
1774 $params = array_merge($params, $params);
1775 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1776 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1779 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1780 $categories = array();
1781 foreach ($categoriesrs as $category) {
1782 // Preload the context.. we'll need it when adding the category in order
1783 // to format the category name.
1784 context_helper::preload_from_record($category);
1785 if (array_key_exists($category->id, $this->addedcategories)) {
1786 // Do nothing, its already been added.
1787 } else if ($category->parent == '0') {
1788 // This is a root category lets add it immediately
1789 $this->add_category($category, $this->rootnodes['courses']);
1790 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1791 // This categories parent has already been added we can add this immediately
1792 $this->add_category($category, $this->addedcategories[$category->parent]);
1794 $categories[] = $category;
1797 $categoriesrs->close();
1799 // Now we have an array of categories we need to add them to the navigation.
1800 while (!empty($categories)) {
1801 $category = reset($categories);
1802 if (array_key_exists($category->id, $this->addedcategories)) {
1804 } else if ($category->parent == '0') {
1805 $this->add_category($category, $this->rootnodes['courses']);
1806 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1807 $this->add_category($category, $this->addedcategories[$category->parent]);
1809 // This category isn't in the navigation and niether is it's parent (yet).
1810 // We need to go through the category path and add all of its components in order.
1811 $path = explode('/', trim($category->path, '/'));
1812 foreach ($path as $catid) {
1813 if (!array_key_exists($catid, $this->addedcategories)) {
1814 // This category isn't in the navigation yet so add it.
1815 $subcategory = $categories[$catid];
1816 if ($subcategory->parent == '0') {
1817 // Yay we have a root category - this likely means we will now be able
1818 // to add categories without problems.
1819 $this->add_category($subcategory, $this->rootnodes['courses']);
1820 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1821 // The parent is in the category (as we'd expect) so add it now.
1822 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1823 // Remove the category from the categories array.
1824 unset($categories[$catid]);
1826 // We should never ever arrive here - if we have then there is a bigger
1828 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1833 // Remove the category from the categories array now that we know it has been added.
1834 unset($categories[$category->id]);
1836 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1837 $this->allcategoriesloaded = true;
1839 // Check if there are any categories to load.
1840 if (count($categoriestoload) > 0) {
1841 $readytoloadcourses = array();
1842 foreach ($categoriestoload as $category) {
1843 if ($this->can_add_more_courses_to_category($category)) {
1844 $readytoloadcourses[] = $category;
1847 if (count($readytoloadcourses)) {
1848 $this->load_all_courses($readytoloadcourses);
1852 // Look for all categories which have been loaded
1853 if (!empty($this->addedcategories)) {
1854 $categoryids = array();
1855 foreach ($this->addedcategories as $category) {
1856 if ($this->can_add_more_courses_to_category($category)) {
1857 $categoryids[] = $category->key;
1861 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1862 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1863 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1864 FROM {course_categories} cc
1865 JOIN {course} c ON c.category = cc.id
1866 WHERE cc.id {$categoriessql}
1868 HAVING COUNT(c.id) > :limit";
1869 $excessivecategories = $DB->get_records_sql($sql, $params);
1870 foreach ($categories as &$category) {
1871 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1872 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1873 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1881 * Adds a structured category to the navigation in the correct order/place
1883 * @param stdClass $category category to be added in navigation.
1884 * @param navigation_node $parent parent navigation node
1885 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1888 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1889 if (array_key_exists($category->id, $this->addedcategories)) {
1892 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1893 $context = context_coursecat::instance($category->id);
1894 $categoryname = format_string($category->name, true, array('context' => $context));
1895 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1896 if (empty($category->visible)) {
1897 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1898 $categorynode->hidden = true;
1900 $categorynode->display = false;
1903 $this->addedcategories[$category->id] = $categorynode;
1907 * Loads the given course into the navigation
1909 * @param stdClass $course
1910 * @return navigation_node
1912 protected function load_course(stdClass $course) {
1914 if ($course->id == $SITE->id) {
1915 // This is always loaded during initialisation
1916 return $this->rootnodes['site'];
1917 } else if (array_key_exists($course->id, $this->addedcourses)) {
1918 // The course has already been loaded so return a reference
1919 return $this->addedcourses[$course->id];
1922 return $this->add_course($course);
1927 * Loads all of the courses section into the navigation.
1929 * This function calls method from current course format, see
1930 * {@link format_base::extend_course_navigation()}
1931 * If course module ($cm) is specified but course format failed to create the node,
1932 * the activity node is created anyway.
1934 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1936 * @param stdClass $course Database record for the course
1937 * @param navigation_node $coursenode The course node within the navigation
1938 * @param null|int $sectionnum If specified load the contents of section with this relative number
1939 * @param null|cm_info $cm If specified make sure that activity node is created (either
1940 * in containg section or by calling load_stealth_activity() )
1942 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1944 require_once($CFG->dirroot.'/course/lib.php');
1945 if (isset($cm->sectionnum)) {
1946 $sectionnum = $cm->sectionnum;
1948 if ($sectionnum !== null) {
1949 $this->includesectionnum = $sectionnum;
1951 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1952 if (isset($cm->id)) {
1953 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1954 if (empty($activity)) {
1955 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1961 * Generates an array of sections and an array of activities for the given course.
1963 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1965 * @param stdClass $course
1966 * @return array Array($sections, $activities)
1968 protected function generate_sections_and_activities(stdClass $course) {
1970 require_once($CFG->dirroot.'/course/lib.php');
1972 $modinfo = get_fast_modinfo($course);
1973 $sections = $modinfo->get_section_info_all();
1975 // For course formats using 'numsections' trim the sections list
1976 $courseformatoptions = course_get_format($course)->get_format_options();
1977 if (isset($courseformatoptions['numsections'])) {
1978 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1981 $activities = array();
1983 foreach ($sections as $key => $section) {
1984 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1985 $sections[$key] = clone($section);
1986 unset($sections[$key]->summary);
1987 $sections[$key]->hasactivites = false;
1988 if (!array_key_exists($section->section, $modinfo->sections)) {
1991 foreach ($modinfo->sections[$section->section] as $cmid) {
1992 $cm = $modinfo->cms[$cmid];
1993 $activity = new stdClass;
1994 $activity->id = $cm->id;
1995 $activity->course = $course->id;
1996 $activity->section = $section->section;
1997 $activity->name = $cm->name;
1998 $activity->icon = $cm->icon;
1999 $activity->iconcomponent = $cm->iconcomponent;
2000 $activity->hidden = (!$cm->visible);
2001 $activity->modname = $cm->modname;
2002 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2003 $activity->onclick = $cm->onclick;
2006 $activity->url = null;
2007 $activity->display = false;
2009 $activity->url = $url->out();
2010 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2011 if (self::module_extends_navigation($cm->modname)) {
2012 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2015 $activities[$cmid] = $activity;
2016 if ($activity->display) {
2017 $sections[$key]->hasactivites = true;
2022 return array($sections, $activities);
2026 * Generically loads the course sections into the course's navigation.
2028 * @param stdClass $course
2029 * @param navigation_node $coursenode
2030 * @return array An array of course section nodes
2032 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2033 global $CFG, $DB, $USER, $SITE;
2034 require_once($CFG->dirroot.'/course/lib.php');
2036 list($sections, $activities) = $this->generate_sections_and_activities($course);
2038 $navigationsections = array();
2039 foreach ($sections as $sectionid => $section) {
2040 $section = clone($section);
2041 if ($course->id == $SITE->id) {
2042 $this->load_section_activities($coursenode, $section->section, $activities);
2044 if (!$section->uservisible || (!$this->showemptysections &&
2045 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2049 $sectionname = get_section_name($course, $section);
2050 $url = course_get_url($course, $section->section, array('navigation' => true));
2052 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2053 null, $section->id, new pix_icon('i/section', ''));
2054 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2055 $sectionnode->hidden = (!$section->visible || !$section->available);
2056 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2057 $this->load_section_activities($sectionnode, $section->section, $activities);
2059 $section->sectionnode = $sectionnode;
2060 $navigationsections[$sectionid] = $section;
2063 return $navigationsections;
2067 * Loads all of the activities for a section into the navigation structure.
2069 * @param navigation_node $sectionnode
2070 * @param int $sectionnumber
2071 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2072 * @param stdClass $course The course object the section and activities relate to.
2073 * @return array Array of activity nodes
2075 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2077 // A static counter for JS function naming
2078 static $legacyonclickcounter = 0;
2080 $activitynodes = array();
2081 if (empty($activities)) {
2082 return $activitynodes;
2085 if (!is_object($course)) {
2086 $activity = reset($activities);
2087 $courseid = $activity->course;
2089 $courseid = $course->id;
2091 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2093 foreach ($activities as $activity) {
2094 if ($activity->section != $sectionnumber) {
2097 if ($activity->icon) {
2098 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2100 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2103 // Prepare the default name and url for the node
2104 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2105 $action = new moodle_url($activity->url);
2107 // Check if the onclick property is set (puke!)
2108 if (!empty($activity->onclick)) {
2109 // Increment the counter so that we have a unique number.
2110 $legacyonclickcounter++;
2111 // Generate the function name we will use
2112 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2113 $propogrationhandler = '';
2114 // Check if we need to cancel propogation. Remember inline onclick
2115 // events would return false if they wanted to prevent propogation and the
2117 if (strpos($activity->onclick, 'return false')) {
2118 $propogrationhandler = 'e.halt();';
2120 // Decode the onclick - it has already been encoded for display (puke)
2121 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2122 // Build the JS function the click event will call
2123 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2124 $this->page->requires->js_amd_inline($jscode);
2125 // Override the default url with the new action link
2126 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2129 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2130 $activitynode->title(get_string('modulename', $activity->modname));
2131 $activitynode->hidden = $activity->hidden;
2132 $activitynode->display = $showactivities && $activity->display;
2133 $activitynode->nodetype = $activity->nodetype;
2134 $activitynodes[$activity->id] = $activitynode;
2137 return $activitynodes;
2140 * Loads a stealth module from unavailable section
2141 * @param navigation_node $coursenode
2142 * @param stdClass $modinfo
2143 * @return navigation_node or null if not accessible
2145 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2146 if (empty($modinfo->cms[$this->page->cm->id])) {
2149 $cm = $modinfo->cms[$this->page->cm->id];
2151 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2153 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2156 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2157 $activitynode->title(get_string('modulename', $cm->modname));
2158 $activitynode->hidden = (!$cm->visible);
2159 if (!$cm->is_visible_on_course_page()) {
2160 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2161 // Also there may be no exception at all in case when teacher is logged in as student.
2162 $activitynode->display = false;
2164 // Don't show activities that don't have links!
2165 $activitynode->display = false;
2166 } else if (self::module_extends_navigation($cm->modname)) {
2167 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2169 return $activitynode;
2172 * Loads the navigation structure for the given activity into the activities node.
2174 * This method utilises a callback within the modules lib.php file to load the
2175 * content specific to activity given.
2177 * The callback is a method: {modulename}_extend_navigation()
2179 * * {@link forum_extend_navigation()}
2180 * * {@link workshop_extend_navigation()}
2182 * @param cm_info|stdClass $cm
2183 * @param stdClass $course
2184 * @param navigation_node $activity
2187 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2190 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2191 if (!($cm instanceof cm_info)) {
2192 $modinfo = get_fast_modinfo($course);
2193 $cm = $modinfo->get_cm($cm->id);
2195 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2196 $activity->make_active();
2197 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2198 $function = $cm->modname.'_extend_navigation';
2200 if (file_exists($file)) {
2201 require_once($file);
2202 if (function_exists($function)) {
2203 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2204 $function($activity, $course, $activtyrecord, $cm);
2208 // Allow the active advanced grading method plugin to append module navigation
2209 $featuresfunc = $cm->modname.'_supports';
2210 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2211 require_once($CFG->dirroot.'/grade/grading/lib.php');
2212 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2213 $gradingman->extend_navigation($this, $activity);
2216 return $activity->has_children();
2219 * Loads user specific information into the navigation in the appropriate place.
2221 * If no user is provided the current user is assumed.
2223 * @param stdClass $user
2224 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2227 protected function load_for_user($user=null, $forceforcontext=false) {
2228 global $DB, $CFG, $USER, $SITE;
2230 require_once($CFG->dirroot . '/course/lib.php');
2232 if ($user === null) {
2233 // We can't require login here but if the user isn't logged in we don't
2234 // want to show anything
2235 if (!isloggedin() || isguestuser()) {
2239 } else if (!is_object($user)) {
2240 // If the user is not an object then get them from the database
2241 $select = context_helper::get_preload_record_columns_sql('ctx');
2242 $sql = "SELECT u.*, $select
2244 JOIN {context} ctx ON u.id = ctx.instanceid
2245 WHERE u.id = :userid AND
2246 ctx.contextlevel = :contextlevel";
2247 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2248 context_helper::preload_from_record($user);
2251 $iscurrentuser = ($user->id == $USER->id);
2253 $usercontext = context_user::instance($user->id);
2255 // Get the course set against the page, by default this will be the site
2256 $course = $this->page->course;
2257 $baseargs = array('id'=>$user->id);
2258 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2259 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2260 $baseargs['course'] = $course->id;
2261 $coursecontext = context_course::instance($course->id);
2262 $issitecourse = false;
2264 // Load all categories and get the context for the system
2265 $coursecontext = context_system::instance();
2266 $issitecourse = true;
2269 // Create a node to add user information under.
2271 if (!$issitecourse) {
2272 // Not the current user so add it to the participants node for the current course.
2273 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2274 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2275 } else if ($USER->id != $user->id) {
2276 // This is the site so add a users node to the root branch.
2277 $usersnode = $this->rootnodes['users'];
2278 if (course_can_view_participants($coursecontext)) {
2279 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2281 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2284 // We should NEVER get here, if the course hasn't been populated
2285 // with a participants node then the navigaiton either wasn't generated
2286 // for it (you are missing a require_login or set_context call) or
2287 // you don't have access.... in the interests of no leaking informatin
2288 // we simply quit...
2291 // Add a branch for the current user.
2292 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2293 $viewprofile = true;
2294 if (!$iscurrentuser) {
2295 require_once($CFG->dirroot . '/user/lib.php');
2296 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2297 $viewprofile = false;
2298 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2299 $viewprofile = false;
2301 if (!$viewprofile) {
2302 $viewprofile = user_can_view_profile($user, null, $usercontext);
2306 // Now, conditionally add the user node.
2308 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2309 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2311 $usernode = $usersnode->add(get_string('user'));
2314 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2315 $usernode->make_active();
2318 // Add user information to the participants or user node.
2319 if ($issitecourse) {
2321 // If the user is the current user or has permission to view the details of the requested
2322 // user than add a view profile link.
2323 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2324 has_capability('moodle/user:viewdetails', $usercontext)) {
2325 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2326 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2328 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2332 if (!empty($CFG->navadduserpostslinks)) {
2333 // Add nodes for forum posts and discussions if the user can view either or both
2334 // There are no capability checks here as the content of the page is based
2335 // purely on the forums the current user has access too.
2336 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2337 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2338 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2339 array_merge($baseargs, array('mode' => 'discussions'))));
2343 if (!empty($CFG->enableblogs)) {
2344 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2345 require_once($CFG->dirroot.'/blog/lib.php');
2346 // Get all options for the user.
2347 $options = blog_get_options_for_user($user);
2348 $this->cache->set('userblogoptions'.$user->id, $options);
2350 $options = $this->cache->{'userblogoptions'.$user->id};
2353 if (count($options) > 0) {
2354 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2355 foreach ($options as $type => $option) {
2356 if ($type == "rss") {
2357 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2358 new pix_icon('i/rss', ''));
2360 $blogs->add($option['string'], $option['link']);
2366 // Add the messages link.
2367 // It is context based so can appear in the user's profile and in course participants information.
2368 if (!empty($CFG->messaging)) {
2369 $messageargs = array('user1' => $USER->id);
2370 if ($USER->id != $user->id) {
2371 $messageargs['user2'] = $user->id;
2373 $url = new moodle_url('/message/index.php', $messageargs);
2374 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2377 // Add the "My private files" link.
2378 // This link doesn't have a unique display for course context so only display it under the user's profile.
2379 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2380 $url = new moodle_url('/user/files.php');
2381 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2384 // Add a node to view the users notes if permitted.
2385 if (!empty($CFG->enablenotes) &&
2386 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2387 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2388 if ($coursecontext->instanceid != SITEID) {
2389 $url->param('course', $coursecontext->instanceid);
2391 $usernode->add(get_string('notes', 'notes'), $url);
2394 // Show the grades node.
2395 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2396 require_once($CFG->dirroot . '/user/lib.php');
2397 // Set the grades node to link to the "Grades" page.
2398 if ($course->id == SITEID) {
2399 $url = user_mygrades_url($user->id, $course->id);
2400 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2401 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2403 if ($USER->id != $user->id) {
2404 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2406 $usernode->add(get_string('grades', 'grades'), $url);
2410 // If the user is the current user add the repositories for the current user.
2411 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2412 if (!$iscurrentuser &&
2413 $course->id == $SITE->id &&
2414 has_capability('moodle/user:viewdetails', $usercontext) &&
2415 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2417 // Add view grade report is permitted.
2418 $reports = core_component::get_plugin_list('gradereport');
2419 arsort($reports); // User is last, we want to test it first.
2421 $userscourses = enrol_get_users_courses($user->id, false, '*');
2422 $userscoursesnode = $usernode->add(get_string('courses'));
2425 foreach ($userscourses as $usercourse) {
2426 if ($count === (int)$CFG->navcourselimit) {
2427 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2428 $userscoursesnode->add(get_string('showallcourses'), $url);
2432 $usercoursecontext = context_course::instance($usercourse->id);
2433 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2434 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2435 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2437 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2438 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2439 foreach ($reports as $plugin => $plugindir) {
2440 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2441 // Stop when the first visible plugin is found.
2442 $gradeavailable = true;
2448 if ($gradeavailable) {
2449 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2450 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2451 new pix_icon('i/grades', ''));
2454 // Add a node to view the users notes if permitted.
2455 if (!empty($CFG->enablenotes) &&
2456 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2457 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2458 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2461 if (can_access_course($usercourse, $user->id, '', true)) {
2462 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2463 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2466 $reporttab = $usercoursenode->add(get_string('activityreports'));
2468 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2469 foreach ($reportfunctions as $reportfunction) {
2470 $reportfunction($reporttab, $user, $usercourse);
2473 $reporttab->trim_if_empty();
2477 // Let plugins hook into user navigation.
2478 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2479 foreach ($pluginsfunction as $plugintype => $plugins) {
2480 if ($plugintype != 'report') {
2481 foreach ($plugins as $pluginfunction) {
2482 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2491 * This method simply checks to see if a given module can extend the navigation.
2493 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2495 * @param string $modname
2498 public static function module_extends_navigation($modname) {
2500 static $extendingmodules = array();
2501 if (!array_key_exists($modname, $extendingmodules)) {
2502 $extendingmodules[$modname] = false;
2503 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2504 if (file_exists($file)) {
2505 $function = $modname.'_extend_navigation';
2506 require_once($file);
2507 $extendingmodules[$modname] = (function_exists($function));
2510 return $extendingmodules[$modname];
2513 * Extends the navigation for the given user.
2515 * @param stdClass $user A user from the database
2517 public function extend_for_user($user) {
2518 $this->extendforuser[] = $user;
2522 * Returns all of the users the navigation is being extended for
2524 * @return array An array of extending users.
2526 public function get_extending_users() {
2527 return $this->extendforuser;
2530 * Adds the given course to the navigation structure.
2532 * @param stdClass $course
2533 * @param bool $forcegeneric
2534 * @param bool $ismycourse
2535 * @return navigation_node
2537 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2540 // We found the course... we can return it now :)
2541 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2542 return $this->addedcourses[$course->id];
2545 $coursecontext = context_course::instance($course->id);
2547 if ($course->id != $SITE->id && !$course->visible) {
2548 if (is_role_switched($course->id)) {
2549 // user has to be able to access course in order to switch, let's skip the visibility test here
2550 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2555 $issite = ($course->id == $SITE->id);
2556 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2557 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2558 // This is the name that will be shown for the course.
2559 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2561 if ($coursetype == self::COURSE_CURRENT) {
2562 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2565 $coursetype = self::COURSE_OTHER;
2569 // Can the user expand the course to see its content.
2570 $canexpandcourse = true;
2574 if (empty($CFG->usesitenameforsitepages)) {
2575 $coursename = get_string('sitepages');
2577 } else if ($coursetype == self::COURSE_CURRENT) {
2578 $parent = $this->rootnodes['currentcourse'];
2579 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2580 $canexpandcourse = $this->can_expand_course($course);
2581 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2582 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2583 // Nothing to do here the above statement set $parent to the category within mycourses.
2585 $parent = $this->rootnodes['mycourses'];
2587 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2589 $parent = $this->rootnodes['courses'];
2590 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2591 // They can only expand the course if they can access it.
2592 $canexpandcourse = $this->can_expand_course($course);
2593 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2594 if (!$this->is_category_fully_loaded($course->category)) {
2595 // We need to load the category structure for this course
2596 $this->load_all_categories($course->category, false);
2598 if (array_key_exists($course->category, $this->addedcategories)) {
2599 $parent = $this->addedcategories[$course->category];
2600 // This could lead to the course being created so we should check whether it is the case again
2601 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2602 return $this->addedcourses[$course->id];
2608 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2609 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2611 $coursenode->hidden = (!$course->visible);
2612 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2613 if ($canexpandcourse) {
2614 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2615 $coursenode->nodetype = self::NODETYPE_BRANCH;
2616 $coursenode->isexpandable = true;
2618 $coursenode->nodetype = self::NODETYPE_LEAF;
2619 $coursenode->isexpandable = false;
2621 if (!$forcegeneric) {
2622 $this->addedcourses[$course->id] = $coursenode;
2629 * Returns a cache instance to use for the expand course cache.
2630 * @return cache_session
2632 protected function get_expand_course_cache() {
2633 if ($this->cacheexpandcourse === null) {
2634 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2636 return $this->cacheexpandcourse;
2640 * Checks if a user can expand a course in the navigation.
2642 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2643 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2644 * permits stale data.
2645 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2647 * It is brought up to date in only one of two ways.
2648 * 1. The user logs out and in again.
2649 * 2. The user browses to the course they've just being given access to.
2651 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2653 * @param stdClass $course
2656 protected function can_expand_course($course) {
2657 $cache = $this->get_expand_course_cache();
2658 $canexpand = $cache->get($course->id);
2659 if ($canexpand === false) {
2660 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2661 $canexpand = (int)$canexpand;
2662 $cache->set($course->id, $canexpand);
2664 return ($canexpand === 1);
2668 * Returns true if the category has already been loaded as have any child categories
2670 * @param int $categoryid
2673 protected function is_category_fully_loaded($categoryid) {
2674 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2678 * Adds essential course nodes to the navigation for the given course.
2680 * This method adds nodes such as reports, blogs and participants
2682 * @param navigation_node $coursenode
2683 * @param stdClass $course
2684 * @return bool returns true on successful addition of a node.
2686 public function add_course_essentials($coursenode, stdClass $course) {
2688 require_once($CFG->dirroot . '/course/lib.php');
2690 if ($course->id == $SITE->id) {
2691 return $this->add_front_page_course_essentials($coursenode, $course);
2694 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2698 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2701 if ($navoptions->participants) {
2702 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2703 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2705 if ($navoptions->blogs) {
2706 $blogsurls = new moodle_url('/blog/index.php');
2707 if ($currentgroup = groups_get_course_group($course, true)) {
2708 $blogsurls->param('groupid', $currentgroup);
2710 $blogsurls->param('courseid', $course->id);
2712 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2715 if ($navoptions->notes) {
2716 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2718 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2719 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2723 if ($navoptions->badges) {
2724 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2726 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2727 navigation_node::TYPE_SETTING, null, 'badgesview',
2728 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2731 // Check access to the course and competencies page.
2732 if ($navoptions->competencies) {
2733 // Just a link to course competency.
2734 $title = get_string('competencies', 'core_competency');
2735 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2736 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2737 new pix_icon('i/competencies', ''));
2739 if ($navoptions->grades) {
2740 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2741 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2742 'grades', new pix_icon('i/grades', ''));
2743 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2744 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2745 $gradenode->make_active();
2752 * This generates the structure of the course that won't be generated when
2753 * the modules and sections are added.
2755 * Things such as the reports branch, the participants branch, blogs... get
2756 * added to the course node by this method.
2758 * @param navigation_node $coursenode
2759 * @param stdClass $course
2760 * @return bool True for successfull generation
2762 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2763 global $CFG, $USER, $COURSE, $SITE;
2764 require_once($CFG->dirroot . '/course/lib.php');
2766 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2770 $sitecontext = context_system::instance();
2771 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2773 // Hidden node that we use to determine if the front page navigation is loaded.
2774 // This required as there are not other guaranteed nodes that may be loaded.
2775 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2778 if ($navoptions->participants) {
2779 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2783 if ($navoptions->blogs) {
2784 $blogsurls = new moodle_url('/blog/index.php');
2785 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2791 if ($navoptions->badges) {
2792 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2793 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2797 if ($navoptions->notes) {
2798 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2799 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2803 if ($navoptions->tags) {
2804 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2805 self::TYPE_SETTING, null, 'tags');
2809 if ($navoptions->search) {
2810 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2811 self::TYPE_SETTING, null, 'search');
2814 if ($navoptions->calendar) {
2815 $courseid = $COURSE->id;
2816 $params = array('view' => 'month');
2817 if ($courseid != $SITE->id) {
2818 $params['course'] = $courseid;
2822 $calendarurl = new moodle_url('/calendar/view.php', $params);
2823 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2824 self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
2825 $node->showinflatnavigation = true;
2829 $usercontext = context_user::instance($USER->id);
2830 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2831 $url = new moodle_url('/user/files.php');
2832 $node = $coursenode->add(get_string('privatefiles'), $url,
2833 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2834 $node->display = false;
2835 $node->showinflatnavigation = true;
2843 * Clears the navigation cache
2845 public function clear_cache() {
2846 $this->cache->clear();
2850 * Sets an expansion limit for the navigation
2852 * The expansion limit is used to prevent the display of content that has a type
2853 * greater than the provided $type.
2855 * Can be used to ensure things such as activities or activity content don't get
2856 * shown on the navigation.
2857 * They are still generated in order to ensure the navbar still makes sense.
2859 * @param int $type One of navigation_node::TYPE_*
2860 * @return bool true when complete.
2862 public function set_expansion_limit($type) {
2864 $nodes = $this->find_all_of_type($type);
2866 // We only want to hide specific types of nodes.
2867 // Only nodes that represent "structure" in the navigation tree should be hidden.
2868 // If we hide all nodes then we risk hiding vital information.
2869 $typestohide = array(
2870 self::TYPE_CATEGORY,
2876 foreach ($nodes as $node) {
2877 // We need to generate the full site node
2878 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2881 foreach ($node->children as $child) {
2882 $child->hide($typestohide);
2888 * Attempts to get the navigation with the given key from this nodes children.
2890 * This function only looks at this nodes children, it does NOT look recursivily.
2891 * If the node can't be found then false is returned.
2893 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2895 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2896 * may be of more use to you.
2898 * @param string|int $key The key of the node you wish to receive.
2899 * @param int $type One of navigation_node::TYPE_*
2900 * @return navigation_node|false
2902 public function get($key, $type = null) {
2903 if (!$this->initialised) {
2904 $this->initialise();
2906 return parent::get($key, $type);
2910 * Searches this nodes children and their children to find a navigation node
2911 * with the matching key and type.
2913 * This method is recursive and searches children so until either a node is
2914 * found or there are no more nodes to search.
2916 * If you know that the node being searched for is a child of this node
2917 * then use the {@link global_navigation::get()} method instead.
2919 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2920 * may be of more use to you.
2922 * @param string|int $key The key of the node you wish to receive.
2923 * @param int $type One of navigation_node::TYPE_*
2924 * @return navigation_node|false
2926 public function find($key, $type) {
2927 if (!$this->initialised) {
2928 $this->initialise();
2930 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2931 return $this->rootnodes[$key];
2933 return parent::find($key, $type);
2937 * They've expanded the 'my courses' branch.
2939 protected function load_courses_enrolled() {
2942 $limit = (int) $CFG->navcourselimit;
2944 $courses = enrol_get_my_courses('*');
2945 $flatnavcourses = [];
2947 // Go through the courses and see which ones we want to display in the flatnav.
2948 foreach ($courses as $course) {
2949 $classify = course_classify_for_timeline($course);
2951 if ($classify == COURSE_TIMELINE_INPROGRESS) {
2952 $flatnavcourses[$course->id] = $course;
2956 // Get the number of courses that can be displayed in the nav block and in the flatnav.
2957 $numtotalcourses = count($courses);
2958 $numtotalflatnavcourses = count($flatnavcourses);
2960 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
2961 $courses = array_slice($courses, 0, $limit, true);
2962 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
2964 // Get the number of courses we are going to show for each.
2965 $numshowncourses = count($courses);
2966 $numshownflatnavcourses = count($flatnavcourses);
2967 if ($numshowncourses && $this->show_my_categories()) {
2968 // Generate an array containing unique values of all the courses' categories.
2969 $categoryids = array();
2970 foreach ($courses as $course) {
2971 if (in_array($course->category, $categoryids)) {
2974 $categoryids[] = $course->category;
2977 // Array of category IDs that include the categories of the user's courses and the related course categories.
2978 $fullpathcategoryids = [];
2979 // Get the course categories for the enrolled courses' category IDs.
2980 $mycoursecategories = core_course_category::get_many($categoryids);
2981 // Loop over each of these categories and build the category tree using each category's path.
2982 foreach ($mycoursecategories as $mycoursecat) {
2983 $pathcategoryids = explode('/', $mycoursecat->path);
2984 // First element of the exploded path is empty since paths begin with '/'.
2985 array_shift($pathcategoryids);
2986 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
2987 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
2990 // Fetch all of the categories related to the user's courses.
2991 $pathcategories = core_course_category::get_many($fullpathcategoryids);
2992 // Loop over each of these categories and build the category tree.
2993 foreach ($pathcategories as $coursecat) {
2994 // No need to process categories that have already been added.
2995 if (isset($this->addedcategories[$coursecat->id])) {
2999 // Get this course category's parent node.
3001 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3002 $parent = $this->addedcategories[$coursecat->parent];
3005 // If it has no parent, then it should be right under the My courses node.
3006 $parent = $this->rootnodes['mycourses'];
3009 // Build the category object based from the coursecat object.
3010 $mycategory = new stdClass();
3011 $mycategory->id = $coursecat->id;
3012 $mycategory->name = $coursecat->name;
3013 $mycategory->visible = $coursecat->visible;
3015 // Add this category to the nav tree.
3016 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3020 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3021 foreach ($courses as $course) {
3022 $node = $this->add_course($course, false, self::COURSE_MY);
3024 $node->showinflatnavigation = false;
3025 // Check if we should also add this to the flat nav as well.
3026 if (isset($flatnavcourses[$course->id])) {
3027 $node->showinflatnavigation = true;
3032 // Go through each course in the flatnav now.
3033 foreach ($flatnavcourses as $course) {
3034 // Check if we haven't already added it.
3035 if (!isset($courses[$course->id])) {
3036 // Ok, add it to the flatnav only.
3037 $node = $this->add_course($course, false, self::COURSE_MY);
3038 $node->display = false;
3039 $node->showinflatnavigation = true;
3043 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3044 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3045 // Show a link to the course page if there are more courses the user is enrolled in.
3046 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3047 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3048 $url = new moodle_url('/my/');
3049 $parent = $this->rootnodes['mycourses'];
3050 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3052 if ($showmorelinkinnav) {
3053 $coursenode->display = true;
3056 if ($showmorelinkinflatnav) {
3057 $coursenode->showinflatnavigation = true;
3064 * The global navigation class used especially for AJAX requests.
3066 * The primary methods that are used in the global navigation class have been overriden
3067 * to ensure that only the relevant branch is generated at the root of the tree.
3068 * This can be done because AJAX is only used when the backwards structure for the
3069 * requested branch exists.
3070 * This has been done only because it shortens the amounts of information that is generated
3071 * which of course will speed up the response time.. because no one likes laggy AJAX.
3074 * @category navigation
3075 * @copyright 2009 Sam Hemelryk
3076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3078 class global_navigation_for_ajax extends global_navigation {
3080 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3081 protected $branchtype;
3083 /** @var int the instance id */
3084 protected $instanceid;
3086 /** @var array Holds an array of expandable nodes */
3087 protected $expandable = array();
3090 * Constructs the navigation for use in an AJAX request
3092 * @param moodle_page $page moodle_page object
3093 * @param int $branchtype
3096 public function __construct($page, $branchtype, $id) {
3097 $this->page = $page;
3098 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3099 $this->children = new navigation_node_collection();
3100 $this->branchtype = $branchtype;
3101 $this->instanceid = $id;
3102 $this->initialise();
3105 * Initialise the navigation given the type and id for the branch to expand.
3107 * @return array An array of the expandable nodes
3109 public function initialise() {
3112 if ($this->initialised || during_initial_install()) {
3113 return $this->expandable;
3115 $this->initialised = true;
3117 $this->rootnodes = array();
3118 $this->rootnodes['site'] = $this->add_course($SITE);
3119 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3120 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3121 // The courses branch is always displayed, and is always expandable (although may be empty).
3122 // This mimicks what is done during {@link global_navigation::initialise()}.
3123 $this->rootnodes['courses']->isexpandable = true;
3125 // Branchtype will be one of navigation_node::TYPE_*
3126 switch ($this->branchtype) {
3128 if ($this->instanceid === 'mycourses') {
3129 $this->load_courses_enrolled();
3130 } else if ($this->instanceid === 'courses') {
3131 $this->load_courses_other();
3134 case self::TYPE_CATEGORY :
3135 $this->load_category($this->instanceid);
3137 case self::TYPE_MY_CATEGORY :
3138 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3140 case self::TYPE_COURSE :
3141 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3142 if (!can_access_course($course, null, '', true)) {
3143 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3144 // add the course node and break. This leads to an empty node.
3145 $this->add_course($course);
3148 require_course_login($course, true, null, false, true);
3149 $this->page->set_context(context_course::instance($course->id));
3150 $coursenode = $this->add_course($course);
3151 $this->add_course_essentials($coursenode, $course);
3152 $this->load_course_sections($course, $coursenode);
3154 case self::TYPE_SECTION :
3155 $sql = 'SELECT c.*, cs.section AS sectionnumber
3157 LEFT JOIN {course_sections} cs ON cs.course = c.id
3159 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3160 require_course_login($course, true, null, false, true);
3161 $this->page->set_context(context_course::instance($course->id));
3162 $coursenode = $this->add_course($course);
3163 $this->add_course_essentials($coursenode, $course);
3164 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3166 case self::TYPE_ACTIVITY :
3169 JOIN {course_modules} cm ON cm.course = c.id
3170 WHERE cm.id = :cmid";
3171 $params = array('cmid' => $this->instanceid);
3172 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3173 $modinfo = get_fast_modinfo($course);
3174 $cm = $modinfo->get_cm($this->instanceid);
3175 require_course_login($course, true, $cm, false, true);
3176 $this->page->set_context(context_module::instance($cm->id));
3177 $coursenode = $this->load_course($course);
3178 $this->load_course_sections($course, $coursenode, null, $cm);
3179 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3180 if ($activitynode) {
3181 $modulenode = $this->load_activity($cm, $course, $activitynode);
3185 throw new Exception('Unknown type');
3186 return $this->expandable;
3189 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3190 $this->load_for_user(null, true);
3193 $this->find_expandable($this->expandable);
3194 return $this->expandable;
3198 * They've expanded the general 'courses' branch.
3200 protected function load_courses_other() {
3201 $this->load_all_courses();
3205 * Loads a single category into the AJAX navigation.
3207 * This function is special in that it doesn't concern itself with the parent of
3208 * the requested category or its siblings.
3209 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3212 * @global moodle_database $DB
3213 * @param int $categoryid id of category to load in navigation.
3214 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3217 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3221 if (!empty($CFG->navcourselimit)) {
3222 $limit = (int)$CFG->navcourselimit;
3225 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3226 $sql = "SELECT cc.*, $catcontextsql
3227 FROM {course_categories} cc
3228 JOIN {context} ctx ON cc.id = ctx.instanceid
3229 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3230 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3231 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3232 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3233 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3234 $categorylist = array();
3235 $subcategories = array();
3236 $basecategory = null;
3237 foreach ($categories as $category) {
3238 $categorylist[] = $category->id;
3239 context_helper::preload_from_record($category);
3240 if ($category->id == $categoryid) {
3241 $this->add_category($category, $this, $nodetype);
3242 $basecategory = $this->addedcategories[$category->id];
3244 $subcategories[$category->id] = $category;
3247 $categories->close();
3250 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3251 // else show all courses.
3252 if ($nodetype === self::TYPE_MY_CATEGORY) {
3253 $courses = enrol_get_my_courses('*');
3254 $categoryids = array();
3256 // Only search for categories if basecategory was found.
3257 if (!is_null($basecategory)) {
3258 // Get course parent category ids.
3259 foreach ($courses as $course) {
3260 $categoryids[] = $course->category;
3263 // Get a unique list of category ids which a part of the path
3264 // to user's courses.
3265 $coursesubcategories = array();
3266 $addedsubcategories = array();
3268 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3269 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3271 foreach ($categories as $category){
3272 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3274 $categories->close();