MDL-65799 enrol: Final deprecations
[moodle.git] / lib / navigationlib.php
blob45c324eb39913f8af88b6eb4ea0d2c5e389a4bb0
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since Moodle 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
34 /**
35 * This class is used to represent a node in a navigation tree
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
43 * @package core
44 * @category navigation
45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF = 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH = 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN = null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY = 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
77 /** @var int Setting node type, used only within settings nav 80 */
78 const TYPE_USER = 80;
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
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] */
91 public $id = null;
92 /** @var string|int The identifier for the node, used to retrieve the node */
93 public $key = null;
94 /** @var string The text to use for the node */
95 public $text = null;
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 */
99 public $title = null;
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 */
105 public $icon = null;
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;
136 /** @var array */
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',
139 90 => 'container');
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;
152 /** @var bool If set to true this node will be forced into a "more" menu whenever possible */
153 public $forceintomoremenu = false;
154 /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */
155 public $showinsecondarynavigation = true;
158 * Constructs a new navigation_node
160 * @param array|string $properties Either an array of properties or a string to use
161 * as the text for the node
163 public function __construct($properties) {
164 if (is_array($properties)) {
165 // Check the array for each property that we allow to set at construction.
166 // text - The main content for the node
167 // shorttext - A short text if required for the node
168 // icon - The icon to display for the node
169 // type - The type of the node
170 // key - The key to use to identify the node
171 // parent - A reference to the nodes parent
172 // action - The action to attribute to this node, usually a URL to link to
173 if (array_key_exists('text', $properties)) {
174 $this->text = $properties['text'];
176 if (array_key_exists('shorttext', $properties)) {
177 $this->shorttext = $properties['shorttext'];
179 if (!array_key_exists('icon', $properties)) {
180 $properties['icon'] = new pix_icon('i/navigationitem', '');
182 $this->icon = $properties['icon'];
183 if ($this->icon instanceof pix_icon) {
184 if (empty($this->icon->attributes['class'])) {
185 $this->icon->attributes['class'] = 'navicon';
186 } else {
187 $this->icon->attributes['class'] .= ' navicon';
190 if (array_key_exists('type', $properties)) {
191 $this->type = $properties['type'];
192 } else {
193 $this->type = self::TYPE_CUSTOM;
195 if (array_key_exists('key', $properties)) {
196 $this->key = $properties['key'];
198 // This needs to happen last because of the check_if_active call that occurs
199 if (array_key_exists('action', $properties)) {
200 $this->action = $properties['action'];
201 if (is_string($this->action)) {
202 $this->action = new moodle_url($this->action);
204 if (self::$autofindactive) {
205 $this->check_if_active();
208 if (array_key_exists('parent', $properties)) {
209 $this->set_parent($properties['parent']);
211 } else if (is_string($properties)) {
212 $this->text = $properties;
214 if ($this->text === null) {
215 throw new coding_exception('You must set the text for the node when you create it.');
217 // Instantiate a new navigation node collection for this nodes children
218 $this->children = new navigation_node_collection();
222 * Checks if this node is the active node.
224 * This is determined by comparing the action for the node against the
225 * defined URL for the page. A match will see this node marked as active.
227 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
228 * @return bool
230 public function check_if_active($strength=URL_MATCH_EXACT) {
231 global $FULLME, $PAGE;
232 // Set fullmeurl if it hasn't already been set
233 if (self::$fullmeurl == null) {
234 if ($PAGE->has_set_url()) {
235 self::override_active_url(new moodle_url($PAGE->url));
236 } else {
237 self::override_active_url(new moodle_url($FULLME));
241 // Compare the action of this node against the fullmeurl
242 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
243 $this->make_active();
244 return true;
246 return false;
250 * True if this nav node has siblings in the tree.
252 * @return bool
254 public function has_siblings() {
255 if (empty($this->parent) || empty($this->parent->children)) {
256 return false;
258 if ($this->parent->children instanceof navigation_node_collection) {
259 $count = $this->parent->children->count();
260 } else {
261 $count = count($this->parent->children);
263 return ($count > 1);
267 * Get a list of sibling navigation nodes at the same level as this one.
269 * @return bool|array of navigation_node
271 public function get_siblings() {
272 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
273 // the in-page links or the breadcrumb links.
274 $siblings = false;
276 if ($this->has_siblings()) {
277 $siblings = [];
278 foreach ($this->parent->children as $child) {
279 if ($child->display) {
280 $siblings[] = $child;
284 return $siblings;
288 * This sets the URL that the URL of new nodes get compared to when locating
289 * the active node.
291 * The active node is the node that matches the URL set here. By default this
292 * is either $PAGE->url or if that hasn't been set $FULLME.
294 * @param moodle_url $url The url to use for the fullmeurl.
295 * @param bool $loadadmintree use true if the URL point to administration tree
297 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
298 // Clone the URL, in case the calling script changes their URL later.
299 self::$fullmeurl = new moodle_url($url);
300 // True means we do not want AJAX loaded admin tree, required for all admin pages.
301 if ($loadadmintree) {
302 // Do not change back to false if already set.
303 self::$loadadmintree = true;
308 * Use when page is linked from the admin tree,
309 * if not used navigation could not find the page using current URL
310 * because the tree is not fully loaded.
312 public static function require_admin_tree() {
313 self::$loadadmintree = true;
317 * Creates a navigation node, ready to add it as a child using add_node
318 * function. (The created node needs to be added before you can use it.)
319 * @param string $text
320 * @param moodle_url|action_link $action
321 * @param int $type
322 * @param string $shorttext
323 * @param string|int $key
324 * @param pix_icon $icon
325 * @return navigation_node
327 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
328 $shorttext=null, $key=null, pix_icon $icon=null) {
329 // Properties array used when creating the new navigation node
330 $itemarray = array(
331 'text' => $text,
332 'type' => $type
334 // Set the action if one was provided
335 if ($action!==null) {
336 $itemarray['action'] = $action;
338 // Set the shorttext if one was provided
339 if ($shorttext!==null) {
340 $itemarray['shorttext'] = $shorttext;
342 // Set the icon if one was provided
343 if ($icon!==null) {
344 $itemarray['icon'] = $icon;
346 // Set the key
347 $itemarray['key'] = $key;
348 // Construct and return
349 return new navigation_node($itemarray);
353 * Adds a navigation node as a child of this node.
355 * @param string $text
356 * @param moodle_url|action_link $action
357 * @param int $type
358 * @param string $shorttext
359 * @param string|int $key
360 * @param pix_icon $icon
361 * @return navigation_node
363 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
364 // Create child node
365 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
367 // Add the child to end and return
368 return $this->add_node($childnode);
372 * Adds a navigation node as a child of this one, given a $node object
373 * created using the create function.
374 * @param navigation_node $childnode Node to add
375 * @param string $beforekey
376 * @return navigation_node The added node
378 public function add_node(navigation_node $childnode, $beforekey=null) {
379 // First convert the nodetype for this node to a branch as it will now have children
380 if ($this->nodetype !== self::NODETYPE_BRANCH) {
381 $this->nodetype = self::NODETYPE_BRANCH;
383 // Set the parent to this node
384 $childnode->set_parent($this);
386 // Default the key to the number of children if not provided
387 if ($childnode->key === null) {
388 $childnode->key = $this->children->count();
391 // Add the child using the navigation_node_collections add method
392 $node = $this->children->add($childnode, $beforekey);
394 // If added node is a category node or the user is logged in and it's a course
395 // then mark added node as a branch (makes it expandable by AJAX)
396 $type = $childnode->type;
397 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
398 ($type === self::TYPE_SITE_ADMIN)) {
399 $node->nodetype = self::NODETYPE_BRANCH;
401 // If this node is hidden mark it's children as hidden also
402 if ($this->hidden) {
403 $node->hidden = true;
405 // Return added node (reference returned by $this->children->add()
406 return $node;
410 * Return a list of all the keys of all the child nodes.
411 * @return array the keys.
413 public function get_children_key_list() {
414 return $this->children->get_key_list();
418 * Searches for a node of the given type with the given key.
420 * This searches this node plus all of its children, and their children....
421 * If you know the node you are looking for is a child of this node then please
422 * use the get method instead.
424 * @param int|string $key The key of the node we are looking for
425 * @param int $type One of navigation_node::TYPE_*
426 * @return navigation_node|false
428 public function find($key, $type) {
429 return $this->children->find($key, $type);
433 * Walk the tree building up a list of all the flat navigation nodes.
435 * @param flat_navigation $nodes List of the found flat navigation nodes.
436 * @param boolean $showdivider Show a divider before the first node.
437 * @param string $label A label for the collection of navigation links.
439 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
440 if ($this->showinflatnavigation) {
441 $indent = 0;
442 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
443 $indent = 1;
445 $flat = new flat_navigation_node($this, $indent);
446 $flat->set_showdivider($showdivider, $label);
447 $nodes->add($flat);
449 foreach ($this->children as $child) {
450 $child->build_flat_navigation_list($nodes, false);
455 * Get the child of this node that has the given key + (optional) type.
457 * If you are looking for a node and want to search all children + their children
458 * then please use the find method instead.
460 * @param int|string $key The key of the node we are looking for
461 * @param int $type One of navigation_node::TYPE_*
462 * @return navigation_node|false
464 public function get($key, $type=null) {
465 return $this->children->get($key, $type);
469 * Removes this node.
471 * @return bool
473 public function remove() {
474 return $this->parent->children->remove($this->key, $this->type);
478 * Checks if this node has or could have any children
480 * @return bool Returns true if it has children or could have (by AJAX expansion)
482 public function has_children() {
483 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
487 * Marks this node as active and forces it open.
489 * Important: If you are here because you need to mark a node active to get
490 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
491 * You can use it to specify a different URL to match the active navigation node on
492 * rather than having to locate and manually mark a node active.
494 public function make_active() {
495 $this->isactive = true;
496 $this->add_class('active_tree_node');
497 $this->force_open();
498 if ($this->parent !== null) {
499 $this->parent->make_inactive();
504 * Marks a node as inactive and recusised back to the base of the tree
505 * doing the same to all parents.
507 public function make_inactive() {
508 $this->isactive = false;
509 $this->remove_class('active_tree_node');
510 if ($this->parent !== null) {
511 $this->parent->make_inactive();
516 * Forces this node to be open and at the same time forces open all
517 * parents until the root node.
519 * Recursive.
521 public function force_open() {
522 $this->forceopen = true;
523 if ($this->parent !== null) {
524 $this->parent->force_open();
529 * Adds a CSS class to this node.
531 * @param string $class
532 * @return bool
534 public function add_class($class) {
535 if (!in_array($class, $this->classes)) {
536 $this->classes[] = $class;
538 return true;
542 * Removes a CSS class from this node.
544 * @param string $class
545 * @return bool True if the class was successfully removed.
547 public function remove_class($class) {
548 if (in_array($class, $this->classes)) {
549 $key = array_search($class,$this->classes);
550 if ($key!==false) {
551 // Remove the class' array element.
552 unset($this->classes[$key]);
553 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
554 $this->classes = array_values($this->classes);
556 return true;
559 return false;
563 * Sets the title for this node and forces Moodle to utilise it.
564 * @param string $title
566 public function title($title) {
567 $this->title = $title;
568 $this->forcetitle = true;
572 * Resets the page specific information on this node if it is being unserialised.
574 public function __wakeup(){
575 $this->forceopen = false;
576 $this->isactive = false;
577 $this->remove_class('active_tree_node');
581 * Checks if this node or any of its children contain the active node.
583 * Recursive.
585 * @return bool
587 public function contains_active_node() {
588 if ($this->isactive) {
589 return true;
590 } else {
591 foreach ($this->children as $child) {
592 if ($child->isactive || $child->contains_active_node()) {
593 return true;
597 return false;
601 * To better balance the admin tree, we want to group all the short top branches together.
603 * This means < 8 nodes and no subtrees.
605 * @return bool
607 public function is_short_branch() {
608 $limit = 8;
609 if ($this->children->count() >= $limit) {
610 return false;
612 foreach ($this->children as $child) {
613 if ($child->has_children()) {
614 return false;
617 return true;
621 * Finds the active node.
623 * Searches this nodes children plus all of the children for the active node
624 * and returns it if found.
626 * Recursive.
628 * @return navigation_node|false
630 public function find_active_node() {
631 if ($this->isactive) {
632 return $this;
633 } else {
634 foreach ($this->children as &$child) {
635 $outcome = $child->find_active_node();
636 if ($outcome !== false) {
637 return $outcome;
641 return false;
645 * Searches all children for the best matching active node
646 * @return navigation_node|false
648 public function search_for_active_node() {
649 if ($this->check_if_active(URL_MATCH_BASE)) {
650 return $this;
651 } else {
652 foreach ($this->children as &$child) {
653 $outcome = $child->search_for_active_node();
654 if ($outcome !== false) {
655 return $outcome;
659 return false;
663 * Gets the content for this node.
665 * @param bool $shorttext If true shorttext is used rather than the normal text
666 * @return string
668 public function get_content($shorttext=false) {
669 if ($shorttext && $this->shorttext!==null) {
670 return format_string($this->shorttext);
671 } else {
672 return format_string($this->text);
677 * Gets the title to use for this node.
679 * @return string
681 public function get_title() {
682 if ($this->forcetitle || $this->action != null){
683 return $this->title;
684 } else {
685 return '';
690 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
692 * @return boolean
694 public function has_action() {
695 return !empty($this->action);
699 * Used to easily determine if this link in the breadcrumbs is hidden.
701 * @return boolean
703 public function is_hidden() {
704 return $this->hidden;
708 * Gets the CSS class to add to this node to describe its type
710 * @return string
712 public function get_css_type() {
713 if (array_key_exists($this->type, $this->namedtypes)) {
714 return 'type_'.$this->namedtypes[$this->type];
716 return 'type_unknown';
720 * Finds all nodes that are expandable by AJAX
722 * @param array $expandable An array by reference to populate with expandable nodes.
724 public function find_expandable(array &$expandable) {
725 foreach ($this->children as &$child) {
726 if ($child->display && $child->has_children() && $child->children->count() == 0) {
727 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
728 $this->add_class('canexpand');
729 $child->requiresajaxloading = true;
730 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
732 $child->find_expandable($expandable);
737 * Finds all nodes of a given type (recursive)
739 * @param int $type One of navigation_node::TYPE_*
740 * @return array
742 public function find_all_of_type($type) {
743 $nodes = $this->children->type($type);
744 foreach ($this->children as &$node) {
745 $childnodes = $node->find_all_of_type($type);
746 $nodes = array_merge($nodes, $childnodes);
748 return $nodes;
752 * Removes this node if it is empty
754 public function trim_if_empty() {
755 if ($this->children->count() == 0) {
756 $this->remove();
761 * Creates a tab representation of this nodes children that can be used
762 * with print_tabs to produce the tabs on a page.
764 * call_user_func_array('print_tabs', $node->get_tabs_array());
766 * @param array $inactive
767 * @param bool $return
768 * @return array Array (tabs, selected, inactive, activated, return)
770 public function get_tabs_array(array $inactive=array(), $return=false) {
771 $tabs = array();
772 $rows = array();
773 $selected = null;
774 $activated = array();
775 foreach ($this->children as $node) {
776 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
777 if ($node->contains_active_node()) {
778 if ($node->children->count() > 0) {
779 $activated[] = $node->key;
780 foreach ($node->children as $child) {
781 if ($child->contains_active_node()) {
782 $selected = $child->key;
784 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
786 } else {
787 $selected = $node->key;
791 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
795 * Sets the parent for this node and if this node is active ensures that the tree is properly
796 * adjusted as well.
798 * @param navigation_node $parent
800 public function set_parent(navigation_node $parent) {
801 // Set the parent (thats the easy part)
802 $this->parent = $parent;
803 // Check if this node is active (this is checked during construction)
804 if ($this->isactive) {
805 // Force all of the parent nodes open so you can see this node
806 $this->parent->force_open();
807 // Make all parents inactive so that its clear where we are.
808 $this->parent->make_inactive();
813 * Hides the node and any children it has.
815 * @since Moodle 2.5
816 * @param array $typestohide Optional. An array of node types that should be hidden.
817 * If null all nodes will be hidden.
818 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
819 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
821 public function hide(array $typestohide = null) {
822 if ($typestohide === null || in_array($this->type, $typestohide)) {
823 $this->display = false;
824 if ($this->has_children()) {
825 foreach ($this->children as $child) {
826 $child->hide($typestohide);
833 * Get the action url for this navigation node.
834 * Called from templates.
836 * @since Moodle 3.2
838 public function action() {
839 if ($this->action instanceof moodle_url) {
840 return $this->action;
841 } else if ($this->action instanceof action_link) {
842 return $this->action->url;
844 return $this->action;
848 * Sets whether the node and its children should be added into a "more" menu whenever possible.
850 * @param bool $forceintomoremenu
852 public function set_force_into_more_menu(bool $forceintomoremenu = false) {
853 $this->forceintomoremenu = $forceintomoremenu;
854 foreach ($this->children as $child) {
855 $child->set_force_into_more_menu($forceintomoremenu);
860 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable.
862 * @param bool $show
864 public function set_show_in_secondary_navigation(bool $show = true) {
865 $this->showinsecondarynavigation = $show;
866 foreach ($this->children as $child) {
867 $child->set_show_in_secondary_navigation($show);
872 * Add the menu item to handle locking and unlocking of a conext.
874 * @param \navigation_node $node Node to add
875 * @param \context $context The context to be locked
877 protected function add_context_locking_node(\navigation_node $node, \context $context) {
878 global $CFG;
879 // Manage context locking.
880 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
881 $parentcontext = $context->get_parent_context();
882 if (empty($parentcontext) || !$parentcontext->locked) {
883 if ($context->locked) {
884 $lockicon = 'i/unlock';
885 $lockstring = get_string('managecontextunlock', 'admin');
886 } else {
887 $lockicon = 'i/lock';
888 $lockstring = get_string('managecontextlock', 'admin');
890 $node->add(
891 $lockstring,
892 new moodle_url(
893 '/admin/lock.php',
895 'id' => $context->id,
898 self::TYPE_SETTING,
899 null,
900 'contextlocking',
901 new pix_icon($lockicon, '')
910 * Navigation node collection
912 * This class is responsible for managing a collection of navigation nodes.
913 * It is required because a node's unique identifier is a combination of both its
914 * key and its type.
916 * Originally an array was used with a string key that was a combination of the two
917 * however it was decided that a better solution would be to use a class that
918 * implements the standard IteratorAggregate interface.
920 * @package core
921 * @category navigation
922 * @copyright 2010 Sam Hemelryk
923 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
925 class navigation_node_collection implements IteratorAggregate, Countable {
927 * A multidimensional array to where the first key is the type and the second
928 * key is the nodes key.
929 * @var array
931 protected $collection = array();
933 * An array that contains references to nodes in the same order they were added.
934 * This is maintained as a progressive array.
935 * @var array
937 protected $orderedcollection = array();
939 * A reference to the last node that was added to the collection
940 * @var navigation_node
942 protected $last = null;
944 * The total number of items added to this array.
945 * @var int
947 protected $count = 0;
950 * Label for collection of nodes.
951 * @var string
953 protected $collectionlabel = '';
956 * Adds a navigation node to the collection
958 * @param navigation_node $node Node to add
959 * @param string $beforekey If specified, adds before a node with this key,
960 * otherwise adds at end
961 * @return navigation_node Added node
963 public function add(navigation_node $node, $beforekey=null) {
964 global $CFG;
965 $key = $node->key;
966 $type = $node->type;
968 // First check we have a 2nd dimension for this type
969 if (!array_key_exists($type, $this->orderedcollection)) {
970 $this->orderedcollection[$type] = array();
972 // Check for a collision and report if debugging is turned on
973 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
974 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
977 // Find the key to add before
978 $newindex = $this->count;
979 $last = true;
980 if ($beforekey !== null) {
981 foreach ($this->collection as $index => $othernode) {
982 if ($othernode->key === $beforekey) {
983 $newindex = $index;
984 $last = false;
985 break;
988 if ($newindex === $this->count) {
989 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
990 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
994 // Add the node to the appropriate place in the by-type structure (which
995 // is not ordered, despite the variable name)
996 $this->orderedcollection[$type][$key] = $node;
997 if (!$last) {
998 // Update existing references in the ordered collection (which is the
999 // one that isn't called 'ordered') to shuffle them along if required
1000 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
1001 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
1004 // Add a reference to the node to the progressive collection.
1005 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
1006 // Update the last property to a reference to this new node.
1007 $this->last = $this->orderedcollection[$type][$key];
1009 // Reorder the array by index if needed
1010 if (!$last) {
1011 ksort($this->collection);
1013 $this->count++;
1014 // Return the reference to the now added node
1015 return $node;
1019 * Return a list of all the keys of all the nodes.
1020 * @return array the keys.
1022 public function get_key_list() {
1023 $keys = array();
1024 foreach ($this->collection as $node) {
1025 $keys[] = $node->key;
1027 return $keys;
1031 * Set a label for this collection.
1033 * @param string $label
1035 public function set_collectionlabel($label) {
1036 $this->collectionlabel = $label;
1040 * Return a label for this collection.
1042 * @return string
1044 public function get_collectionlabel() {
1045 return $this->collectionlabel;
1049 * Fetches a node from this collection.
1051 * @param string|int $key The key of the node we want to find.
1052 * @param int $type One of navigation_node::TYPE_*.
1053 * @return navigation_node|null
1055 public function get($key, $type=null) {
1056 if ($type !== null) {
1057 // If the type is known then we can simply check and fetch
1058 if (!empty($this->orderedcollection[$type][$key])) {
1059 return $this->orderedcollection[$type][$key];
1061 } else {
1062 // Because we don't know the type we look in the progressive array
1063 foreach ($this->collection as $node) {
1064 if ($node->key === $key) {
1065 return $node;
1069 return false;
1073 * Searches for a node with matching key and type.
1075 * This function searches both the nodes in this collection and all of
1076 * the nodes in each collection belonging to the nodes in this collection.
1078 * Recursive.
1080 * @param string|int $key The key of the node we want to find.
1081 * @param int $type One of navigation_node::TYPE_*.
1082 * @return navigation_node|null
1084 public function find($key, $type=null) {
1085 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1086 return $this->orderedcollection[$type][$key];
1087 } else {
1088 $nodes = $this->getIterator();
1089 // Search immediate children first
1090 foreach ($nodes as &$node) {
1091 if ($node->key === $key && ($type === null || $type === $node->type)) {
1092 return $node;
1095 // Now search each childs children
1096 foreach ($nodes as &$node) {
1097 $result = $node->children->find($key, $type);
1098 if ($result !== false) {
1099 return $result;
1103 return false;
1107 * Fetches the last node that was added to this collection
1109 * @return navigation_node
1111 public function last() {
1112 return $this->last;
1116 * Fetches all nodes of a given type from this collection
1118 * @param string|int $type node type being searched for.
1119 * @return array ordered collection
1121 public function type($type) {
1122 if (!array_key_exists($type, $this->orderedcollection)) {
1123 $this->orderedcollection[$type] = array();
1125 return $this->orderedcollection[$type];
1128 * Removes the node with the given key and type from the collection
1130 * @param string|int $key The key of the node we want to find.
1131 * @param int $type
1132 * @return bool
1134 public function remove($key, $type=null) {
1135 $child = $this->get($key, $type);
1136 if ($child !== false) {
1137 foreach ($this->collection as $colkey => $node) {
1138 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1139 unset($this->collection[$colkey]);
1140 $this->collection = array_values($this->collection);
1141 break;
1144 unset($this->orderedcollection[$child->type][$child->key]);
1145 $this->count--;
1146 return true;
1148 return false;
1152 * Gets the number of nodes in this collection
1154 * This option uses an internal count rather than counting the actual options to avoid
1155 * a performance hit through the count function.
1157 * @return int
1159 public function count() {
1160 return $this->count;
1163 * Gets an array iterator for the collection.
1165 * This is required by the IteratorAggregator interface and is used by routines
1166 * such as the foreach loop.
1168 * @return ArrayIterator
1170 public function getIterator() {
1171 return new ArrayIterator($this->collection);
1176 * The global navigation class used for... the global navigation
1178 * This class is used by PAGE to store the global navigation for the site
1179 * and is then used by the settings nav and navbar to save on processing and DB calls
1181 * See
1182 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1183 * {@link lib/ajax/getnavbranch.php} Called by ajax
1185 * @package core
1186 * @category navigation
1187 * @copyright 2009 Sam Hemelryk
1188 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1190 class global_navigation extends navigation_node {
1191 /** @var moodle_page The Moodle page this navigation object belongs to. */
1192 protected $page;
1193 /** @var bool switch to let us know if the navigation object is initialised*/
1194 protected $initialised = false;
1195 /** @var array An array of course information */
1196 protected $mycourses = array();
1197 /** @var navigation_node[] An array for containing root navigation nodes */
1198 protected $rootnodes = array();
1199 /** @var bool A switch for whether to show empty sections in the navigation */
1200 protected $showemptysections = true;
1201 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1202 protected $showcategories = null;
1203 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1204 protected $showmycategories = null;
1205 /** @var array An array of stdClasses for users that the navigation is extended for */
1206 protected $extendforuser = array();
1207 /** @var navigation_cache */
1208 protected $cache;
1209 /** @var array An array of course ids that are present in the navigation */
1210 protected $addedcourses = array();
1211 /** @var bool */
1212 protected $allcategoriesloaded = false;
1213 /** @var array An array of category ids that are included in the navigation */
1214 protected $addedcategories = array();
1215 /** @var int expansion limit */
1216 protected $expansionlimit = 0;
1217 /** @var int userid to allow parent to see child's profile page navigation */
1218 protected $useridtouseforparentchecks = 0;
1219 /** @var cache_session A cache that stores information on expanded courses */
1220 protected $cacheexpandcourse = null;
1222 /** Used when loading categories to load all top level categories [parent = 0] **/
1223 const LOAD_ROOT_CATEGORIES = 0;
1224 /** Used when loading categories to load all categories **/
1225 const LOAD_ALL_CATEGORIES = -1;
1228 * Constructs a new global navigation
1230 * @param moodle_page $page The page this navigation object belongs to
1232 public function __construct(moodle_page $page) {
1233 global $CFG, $SITE, $USER;
1235 if (during_initial_install()) {
1236 return;
1239 if (get_home_page() == HOMEPAGE_SITE) {
1240 // We are using the site home for the root element
1241 $properties = array(
1242 'key' => 'home',
1243 'type' => navigation_node::TYPE_SYSTEM,
1244 'text' => get_string('home'),
1245 'action' => new moodle_url('/'),
1246 'icon' => new pix_icon('i/home', '')
1248 } else {
1249 // We are using the users my moodle for the root element
1250 $properties = array(
1251 'key' => 'myhome',
1252 'type' => navigation_node::TYPE_SYSTEM,
1253 'text' => get_string('myhome'),
1254 'action' => new moodle_url('/my/'),
1255 'icon' => new pix_icon('i/dashboard', '')
1259 // Use the parents constructor.... good good reuse
1260 parent::__construct($properties);
1261 $this->showinflatnavigation = true;
1263 // Initalise and set defaults
1264 $this->page = $page;
1265 $this->forceopen = true;
1266 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1270 * Mutator to set userid to allow parent to see child's profile
1271 * page navigation. See MDL-25805 for initial issue. Linked to it
1272 * is an issue explaining why this is a REALLY UGLY HACK thats not
1273 * for you to use!
1275 * @param int $userid userid of profile page that parent wants to navigate around.
1277 public function set_userid_for_parent_checks($userid) {
1278 $this->useridtouseforparentchecks = $userid;
1283 * Initialises the navigation object.
1285 * This causes the navigation object to look at the current state of the page
1286 * that it is associated with and then load the appropriate content.
1288 * This should only occur the first time that the navigation structure is utilised
1289 * which will normally be either when the navbar is called to be displayed or
1290 * when a block makes use of it.
1292 * @return bool
1294 public function initialise() {
1295 global $CFG, $SITE, $USER;
1296 // Check if it has already been initialised
1297 if ($this->initialised || during_initial_install()) {
1298 return true;
1300 $this->initialised = true;
1302 // Set up the five base root nodes. These are nodes where we will put our
1303 // content and are as follows:
1304 // site: Navigation for the front page.
1305 // myprofile: User profile information goes here.
1306 // currentcourse: The course being currently viewed.
1307 // mycourses: The users courses get added here.
1308 // courses: Additional courses are added here.
1309 // users: Other users information loaded here.
1310 $this->rootnodes = array();
1311 if (get_home_page() == HOMEPAGE_SITE) {
1312 // The home element should be my moodle because the root element is the site
1313 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1314 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1315 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
1316 $this->rootnodes['home']->showinflatnavigation = true;
1318 } else {
1319 // The home element should be the site because the root node is my moodle
1320 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1321 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1322 $this->rootnodes['home']->showinflatnavigation = true;
1323 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1324 // We need to stop automatic redirection
1325 $this->rootnodes['home']->action->param('redirect', '0');
1328 $this->rootnodes['site'] = $this->add_course($SITE);
1329 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1330 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1331 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
1332 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1333 if (!core_course_category::user_top()) {
1334 $this->rootnodes['courses']->hide();
1336 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1338 // We always load the frontpage course to ensure it is available without
1339 // JavaScript enabled.
1340 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1341 $this->load_course_sections($SITE, $this->rootnodes['site']);
1343 $course = $this->page->course;
1344 $this->load_courses_enrolled();
1346 // $issite gets set to true if the current pages course is the sites frontpage course
1347 $issite = ($this->page->course->id == $SITE->id);
1349 // Determine if the user is enrolled in any course.
1350 $enrolledinanycourse = enrol_user_sees_own_courses();
1352 $this->rootnodes['currentcourse']->mainnavonly = true;
1353 if ($enrolledinanycourse) {
1354 $this->rootnodes['mycourses']->isexpandable = true;
1355 $this->rootnodes['mycourses']->showinflatnavigation = true;
1356 if ($CFG->navshowallcourses) {
1357 // When we show all courses we need to show both the my courses and the regular courses branch.
1358 $this->rootnodes['courses']->isexpandable = true;
1360 } else {
1361 $this->rootnodes['courses']->isexpandable = true;
1363 $this->rootnodes['mycourses']->forceopen = true;
1365 $canviewcourseprofile = true;
1367 // Next load context specific content into the navigation
1368 switch ($this->page->context->contextlevel) {
1369 case CONTEXT_SYSTEM :
1370 // Nothing left to do here I feel.
1371 break;
1372 case CONTEXT_COURSECAT :
1373 // This is essential, we must load categories.
1374 $this->load_all_categories($this->page->context->instanceid, true);
1375 break;
1376 case CONTEXT_BLOCK :
1377 case CONTEXT_COURSE :
1378 if ($issite) {
1379 // Nothing left to do here.
1380 break;
1383 // Load the course associated with the current page into the navigation.
1384 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1385 // If the course wasn't added then don't try going any further.
1386 if (!$coursenode) {
1387 $canviewcourseprofile = false;
1388 break;
1391 // If the user is not enrolled then we only want to show the
1392 // course node and not populate it.
1394 // Not enrolled, can't view, and hasn't switched roles
1395 if (!can_access_course($course, null, '', true)) {
1396 if ($coursenode->isexpandable === true) {
1397 // Obviously the situation has changed, update the cache and adjust the node.
1398 // This occurs if the user access to a course has been revoked (one way or another) after
1399 // initially logging in for this session.
1400 $this->get_expand_course_cache()->set($course->id, 1);
1401 $coursenode->isexpandable = true;
1402 $coursenode->nodetype = self::NODETYPE_BRANCH;
1404 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1405 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1406 if (!$this->current_user_is_parent_role()) {
1407 $coursenode->make_active();
1408 $canviewcourseprofile = false;
1409 break;
1411 } else if ($coursenode->isexpandable === false) {
1412 // Obviously the situation has changed, update the cache and adjust the node.
1413 // This occurs if the user has been granted access to a course (one way or another) after initially
1414 // logging in for this session.
1415 $this->get_expand_course_cache()->set($course->id, 1);
1416 $coursenode->isexpandable = true;
1417 $coursenode->nodetype = self::NODETYPE_BRANCH;
1420 // Add the essentials such as reports etc...
1421 $this->add_course_essentials($coursenode, $course);
1422 // Extend course navigation with it's sections/activities
1423 $this->load_course_sections($course, $coursenode);
1424 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1425 $coursenode->make_active();
1428 break;
1429 case CONTEXT_MODULE :
1430 if ($issite) {
1431 // If this is the site course then most information will have
1432 // already been loaded.
1433 // However we need to check if there is more content that can
1434 // yet be loaded for the specific module instance.
1435 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1436 if ($activitynode) {
1437 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1439 break;
1442 $course = $this->page->course;
1443 $cm = $this->page->cm;
1445 // Load the course associated with the page into the navigation
1446 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1448 // If the course wasn't added then don't try going any further.
1449 if (!$coursenode) {
1450 $canviewcourseprofile = false;
1451 break;
1454 // If the user is not enrolled then we only want to show the
1455 // course node and not populate it.
1456 if (!can_access_course($course, null, '', true)) {
1457 $coursenode->make_active();
1458 $canviewcourseprofile = false;
1459 break;
1462 $this->add_course_essentials($coursenode, $course);
1464 // Load the course sections into the page
1465 $this->load_course_sections($course, $coursenode, null, $cm);
1466 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1467 if (!empty($activity)) {
1468 // Finally load the cm specific navigaton information
1469 $this->load_activity($cm, $course, $activity);
1470 // Check if we have an active ndoe
1471 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1472 // And make the activity node active.
1473 $activity->make_active();
1476 break;
1477 case CONTEXT_USER :
1478 if ($issite) {
1479 // The users profile information etc is already loaded
1480 // for the front page.
1481 break;
1483 $course = $this->page->course;
1484 // Load the course associated with the user into the navigation
1485 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1487 // If the course wasn't added then don't try going any further.
1488 if (!$coursenode) {
1489 $canviewcourseprofile = false;
1490 break;
1493 // If the user is not enrolled then we only want to show the
1494 // course node and not populate it.
1495 if (!can_access_course($course, null, '', true)) {
1496 $coursenode->make_active();
1497 $canviewcourseprofile = false;
1498 break;
1500 $this->add_course_essentials($coursenode, $course);
1501 $this->load_course_sections($course, $coursenode);
1502 break;
1505 // Load for the current user
1506 $this->load_for_user();
1507 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1508 $this->load_for_user(null, true);
1510 // Load each extending user into the navigation.
1511 foreach ($this->extendforuser as $user) {
1512 if ($user->id != $USER->id) {
1513 $this->load_for_user($user);
1517 // Give the local plugins a chance to include some navigation if they want.
1518 $this->load_local_plugin_navigation();
1520 // Remove any empty root nodes
1521 foreach ($this->rootnodes as $node) {
1522 // Dont remove the home node
1523 /** @var navigation_node $node */
1524 if (!in_array($node->key, ['home', 'myhome']) && !$node->has_children() && !$node->isactive) {
1525 $node->remove();
1529 if (!$this->contains_active_node()) {
1530 $this->search_for_active_node();
1533 // If the user is not logged in modify the navigation structure as detailed
1534 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1535 if (!isloggedin()) {
1536 $activities = clone($this->rootnodes['site']->children);
1537 $this->rootnodes['site']->remove();
1538 $children = clone($this->children);
1539 $this->children = new navigation_node_collection();
1540 foreach ($activities as $child) {
1541 $this->children->add($child);
1543 foreach ($children as $child) {
1544 $this->children->add($child);
1547 return true;
1551 * This function gives local plugins an opportunity to modify navigation.
1553 protected function load_local_plugin_navigation() {
1554 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1555 $function($this);
1560 * Returns true if the current user is a parent of the user being currently viewed.
1562 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1563 * other user being viewed this function returns false.
1564 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1566 * @since Moodle 2.4
1567 * @return bool
1569 protected function current_user_is_parent_role() {
1570 global $USER, $DB;
1571 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1572 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1573 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1574 return false;
1576 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1577 return true;
1580 return false;
1584 * Returns true if courses should be shown within categories on the navigation.
1586 * @param bool $ismycourse Set to true if you are calculating this for a course.
1587 * @return bool
1589 protected function show_categories($ismycourse = false) {
1590 global $CFG, $DB;
1591 if ($ismycourse) {
1592 return $this->show_my_categories();
1594 if ($this->showcategories === null) {
1595 $show = false;
1596 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1597 $show = true;
1598 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1599 $show = true;
1601 $this->showcategories = $show;
1603 return $this->showcategories;
1607 * Returns true if we should show categories in the My Courses branch.
1608 * @return bool
1610 protected function show_my_categories() {
1611 global $CFG;
1612 if ($this->showmycategories === null) {
1613 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
1615 return $this->showmycategories;
1619 * Loads the courses in Moodle into the navigation.
1621 * @global moodle_database $DB
1622 * @param string|array $categoryids An array containing categories to load courses
1623 * for, OR null to load courses for all categories.
1624 * @return array An array of navigation_nodes one for each course
1626 protected function load_all_courses($categoryids = null) {
1627 global $CFG, $DB, $SITE;
1629 // Work out the limit of courses.
1630 $limit = 20;
1631 if (!empty($CFG->navcourselimit)) {
1632 $limit = $CFG->navcourselimit;
1635 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1637 // If we are going to show all courses AND we are showing categories then
1638 // to save us repeated DB calls load all of the categories now
1639 if ($this->show_categories()) {
1640 $this->load_all_categories($toload);
1643 // Will be the return of our efforts
1644 $coursenodes = array();
1646 // Check if we need to show categories.
1647 if ($this->show_categories()) {
1648 // Hmmm we need to show categories... this is going to be painful.
1649 // We now need to fetch up to $limit courses for each category to
1650 // be displayed.
1651 if ($categoryids !== null) {
1652 if (!is_array($categoryids)) {
1653 $categoryids = array($categoryids);
1655 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1656 $categorywhere = 'WHERE cc.id '.$categorywhere;
1657 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1658 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1659 $categoryparams = array();
1660 } else {
1661 $categorywhere = '';
1662 $categoryparams = array();
1665 // First up we are going to get the categories that we are going to
1666 // need so that we can determine how best to load the courses from them.
1667 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1668 FROM {course_categories} cc
1669 LEFT JOIN {course} c ON c.category = cc.id
1670 {$categorywhere}
1671 GROUP BY cc.id";
1672 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1673 $fullfetch = array();
1674 $partfetch = array();
1675 foreach ($categories as $category) {
1676 if (!$this->can_add_more_courses_to_category($category->id)) {
1677 continue;
1679 if ($category->coursecount > $limit * 5) {
1680 $partfetch[] = $category->id;
1681 } else if ($category->coursecount > 0) {
1682 $fullfetch[] = $category->id;
1685 $categories->close();
1687 if (count($fullfetch)) {
1688 // First up fetch all of the courses in categories where we know that we are going to
1689 // need the majority of courses.
1690 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1691 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1692 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1693 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1694 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1695 FROM {course} c
1696 $ccjoin
1697 WHERE c.category {$categoryids}
1698 ORDER BY c.sortorder ASC";
1699 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1700 foreach ($coursesrs as $course) {
1701 if ($course->id == $SITE->id) {
1702 // This should not be necessary, frontpage is not in any category.
1703 continue;
1705 if (array_key_exists($course->id, $this->addedcourses)) {
1706 // It is probably better to not include the already loaded courses
1707 // directly in SQL because inequalities may confuse query optimisers
1708 // and may interfere with query caching.
1709 continue;
1711 if (!$this->can_add_more_courses_to_category($course->category)) {
1712 continue;
1714 context_helper::preload_from_record($course);
1715 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1716 continue;
1718 $coursenodes[$course->id] = $this->add_course($course);
1720 $coursesrs->close();
1723 if (count($partfetch)) {
1724 // Next we will work our way through the categories where we will likely only need a small
1725 // proportion of the courses.
1726 foreach ($partfetch as $categoryid) {
1727 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1728 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1729 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1730 FROM {course} c
1731 $ccjoin
1732 WHERE c.category = :categoryid
1733 ORDER BY c.sortorder ASC";
1734 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1735 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1736 foreach ($coursesrs as $course) {
1737 if ($course->id == $SITE->id) {
1738 // This should not be necessary, frontpage is not in any category.
1739 continue;
1741 if (array_key_exists($course->id, $this->addedcourses)) {
1742 // It is probably better to not include the already loaded courses
1743 // directly in SQL because inequalities may confuse query optimisers
1744 // and may interfere with query caching.
1745 // This also helps to respect expected $limit on repeated executions.
1746 continue;
1748 if (!$this->can_add_more_courses_to_category($course->category)) {
1749 break;
1751 context_helper::preload_from_record($course);
1752 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1753 continue;
1755 $coursenodes[$course->id] = $this->add_course($course);
1757 $coursesrs->close();
1760 } else {
1761 // Prepare the SQL to load the courses and their contexts
1762 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1763 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1764 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1765 $courseparams['contextlevel'] = CONTEXT_COURSE;
1766 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1767 FROM {course} c
1768 $ccjoin
1769 WHERE c.id {$courseids}
1770 ORDER BY c.sortorder ASC";
1771 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1772 foreach ($coursesrs as $course) {
1773 if ($course->id == $SITE->id) {
1774 // frotpage is not wanted here
1775 continue;
1777 if ($this->page->course && ($this->page->course->id == $course->id)) {
1778 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1779 continue;
1781 context_helper::preload_from_record($course);
1782 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1783 continue;
1785 $coursenodes[$course->id] = $this->add_course($course);
1786 if (count($coursenodes) >= $limit) {
1787 break;
1790 $coursesrs->close();
1793 return $coursenodes;
1797 * Returns true if more courses can be added to the provided category.
1799 * @param int|navigation_node|stdClass $category
1800 * @return bool
1802 protected function can_add_more_courses_to_category($category) {
1803 global $CFG;
1804 $limit = 20;
1805 if (!empty($CFG->navcourselimit)) {
1806 $limit = (int)$CFG->navcourselimit;
1808 if (is_numeric($category)) {
1809 if (!array_key_exists($category, $this->addedcategories)) {
1810 return true;
1812 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1813 } else if ($category instanceof navigation_node) {
1814 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1815 return false;
1817 $coursecount = count($category->children->type(self::TYPE_COURSE));
1818 } else if (is_object($category) && property_exists($category,'id')) {
1819 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1821 return ($coursecount <= $limit);
1825 * Loads all categories (top level or if an id is specified for that category)
1827 * @param int $categoryid The category id to load or null/0 to load all base level categories
1828 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1829 * as the requested category and any parent categories.
1830 * @return navigation_node|void returns a navigation node if a category has been loaded.
1832 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1833 global $CFG, $DB;
1835 // Check if this category has already been loaded
1836 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1837 return true;
1840 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1841 $sqlselect = "SELECT cc.*, $catcontextsql
1842 FROM {course_categories} cc
1843 JOIN {context} ctx ON cc.id = ctx.instanceid";
1844 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1845 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1846 $params = array();
1848 $categoriestoload = array();
1849 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1850 // We are going to load all categories regardless... prepare to fire
1851 // on the database server!
1852 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1853 // We are going to load all of the first level categories (categories without parents)
1854 $sqlwhere .= " AND cc.parent = 0";
1855 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1856 // The category itself has been loaded already so we just need to ensure its subcategories
1857 // have been loaded
1858 $addedcategories = $this->addedcategories;
1859 unset($addedcategories[$categoryid]);
1860 if (count($addedcategories) > 0) {
1861 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1862 if ($showbasecategories) {
1863 // We need to include categories with parent = 0 as well
1864 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1865 } else {
1866 // All we need is categories that match the parent
1867 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1870 $params['categoryid'] = $categoryid;
1871 } else {
1872 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1873 // and load this category plus all its parents and subcategories
1874 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1875 $categoriestoload = explode('/', trim($category->path, '/'));
1876 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1877 // We are going to use select twice so double the params
1878 $params = array_merge($params, $params);
1879 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1880 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1883 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1884 $categories = array();
1885 foreach ($categoriesrs as $category) {
1886 // Preload the context.. we'll need it when adding the category in order
1887 // to format the category name.
1888 context_helper::preload_from_record($category);
1889 if (array_key_exists($category->id, $this->addedcategories)) {
1890 // Do nothing, its already been added.
1891 } else if ($category->parent == '0') {
1892 // This is a root category lets add it immediately
1893 $this->add_category($category, $this->rootnodes['courses']);
1894 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1895 // This categories parent has already been added we can add this immediately
1896 $this->add_category($category, $this->addedcategories[$category->parent]);
1897 } else {
1898 $categories[] = $category;
1901 $categoriesrs->close();
1903 // Now we have an array of categories we need to add them to the navigation.
1904 while (!empty($categories)) {
1905 $category = reset($categories);
1906 if (array_key_exists($category->id, $this->addedcategories)) {
1907 // Do nothing
1908 } else if ($category->parent == '0') {
1909 $this->add_category($category, $this->rootnodes['courses']);
1910 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1911 $this->add_category($category, $this->addedcategories[$category->parent]);
1912 } else {
1913 // This category isn't in the navigation and niether is it's parent (yet).
1914 // We need to go through the category path and add all of its components in order.
1915 $path = explode('/', trim($category->path, '/'));
1916 foreach ($path as $catid) {
1917 if (!array_key_exists($catid, $this->addedcategories)) {
1918 // This category isn't in the navigation yet so add it.
1919 $subcategory = $categories[$catid];
1920 if ($subcategory->parent == '0') {
1921 // Yay we have a root category - this likely means we will now be able
1922 // to add categories without problems.
1923 $this->add_category($subcategory, $this->rootnodes['courses']);
1924 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1925 // The parent is in the category (as we'd expect) so add it now.
1926 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1927 // Remove the category from the categories array.
1928 unset($categories[$catid]);
1929 } else {
1930 // We should never ever arrive here - if we have then there is a bigger
1931 // problem at hand.
1932 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1937 // Remove the category from the categories array now that we know it has been added.
1938 unset($categories[$category->id]);
1940 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1941 $this->allcategoriesloaded = true;
1943 // Check if there are any categories to load.
1944 if (count($categoriestoload) > 0) {
1945 $readytoloadcourses = array();
1946 foreach ($categoriestoload as $category) {
1947 if ($this->can_add_more_courses_to_category($category)) {
1948 $readytoloadcourses[] = $category;
1951 if (count($readytoloadcourses)) {
1952 $this->load_all_courses($readytoloadcourses);
1956 // Look for all categories which have been loaded
1957 if (!empty($this->addedcategories)) {
1958 $categoryids = array();
1959 foreach ($this->addedcategories as $category) {
1960 if ($this->can_add_more_courses_to_category($category)) {
1961 $categoryids[] = $category->key;
1964 if ($categoryids) {
1965 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1966 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1967 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1968 FROM {course_categories} cc
1969 JOIN {course} c ON c.category = cc.id
1970 WHERE cc.id {$categoriessql}
1971 GROUP BY cc.id
1972 HAVING COUNT(c.id) > :limit";
1973 $excessivecategories = $DB->get_records_sql($sql, $params);
1974 foreach ($categories as &$category) {
1975 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1976 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1977 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1985 * Adds a structured category to the navigation in the correct order/place
1987 * @param stdClass $category category to be added in navigation.
1988 * @param navigation_node $parent parent navigation node
1989 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1990 * @return void.
1992 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1993 if (array_key_exists($category->id, $this->addedcategories)) {
1994 return;
1996 $canview = core_course_category::can_view_category($category);
1997 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
1998 $context = context_coursecat::instance($category->id);
1999 $categoryname = $canview ? format_string($category->name, true, array('context' => $context)) :
2000 get_string('categoryhidden');
2001 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
2002 if (!$canview) {
2003 // User does not have required capabilities to view category.
2004 $categorynode->display = false;
2005 } else if (!$category->visible) {
2006 // Category is hidden but user has capability to view hidden categories.
2007 $categorynode->hidden = true;
2009 $this->addedcategories[$category->id] = $categorynode;
2013 * Loads the given course into the navigation
2015 * @param stdClass $course
2016 * @return navigation_node
2018 protected function load_course(stdClass $course) {
2019 global $SITE;
2020 if ($course->id == $SITE->id) {
2021 // This is always loaded during initialisation
2022 return $this->rootnodes['site'];
2023 } else if (array_key_exists($course->id, $this->addedcourses)) {
2024 // The course has already been loaded so return a reference
2025 return $this->addedcourses[$course->id];
2026 } else {
2027 // Add the course
2028 return $this->add_course($course);
2033 * Loads all of the courses section into the navigation.
2035 * This function calls method from current course format, see
2036 * core_courseformat\base::extend_course_navigation()
2037 * If course module ($cm) is specified but course format failed to create the node,
2038 * the activity node is created anyway.
2040 * By default course formats call the method global_navigation::load_generic_course_sections()
2042 * @param stdClass $course Database record for the course
2043 * @param navigation_node $coursenode The course node within the navigation
2044 * @param null|int $sectionnum If specified load the contents of section with this relative number
2045 * @param null|cm_info $cm If specified make sure that activity node is created (either
2046 * in containg section or by calling load_stealth_activity() )
2048 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2049 global $CFG, $SITE;
2050 require_once($CFG->dirroot.'/course/lib.php');
2051 if (isset($cm->sectionnum)) {
2052 $sectionnum = $cm->sectionnum;
2054 if ($sectionnum !== null) {
2055 $this->includesectionnum = $sectionnum;
2057 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2058 if (isset($cm->id)) {
2059 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2060 if (empty($activity)) {
2061 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2067 * Generates an array of sections and an array of activities for the given course.
2069 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2071 * @param stdClass $course
2072 * @return array Array($sections, $activities)
2074 protected function generate_sections_and_activities(stdClass $course) {
2075 global $CFG;
2076 require_once($CFG->dirroot.'/course/lib.php');
2078 $modinfo = get_fast_modinfo($course);
2079 $sections = $modinfo->get_section_info_all();
2081 // For course formats using 'numsections' trim the sections list
2082 $courseformatoptions = course_get_format($course)->get_format_options();
2083 if (isset($courseformatoptions['numsections'])) {
2084 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2087 $activities = array();
2089 foreach ($sections as $key => $section) {
2090 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2091 $sections[$key] = clone($section);
2092 unset($sections[$key]->summary);
2093 $sections[$key]->hasactivites = false;
2094 if (!array_key_exists($section->section, $modinfo->sections)) {
2095 continue;
2097 foreach ($modinfo->sections[$section->section] as $cmid) {
2098 $cm = $modinfo->cms[$cmid];
2099 $activity = new stdClass;
2100 $activity->id = $cm->id;
2101 $activity->course = $course->id;
2102 $activity->section = $section->section;
2103 $activity->name = $cm->name;
2104 $activity->icon = $cm->icon;
2105 $activity->iconcomponent = $cm->iconcomponent;
2106 $activity->hidden = (!$cm->visible);
2107 $activity->modname = $cm->modname;
2108 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2109 $activity->onclick = $cm->onclick;
2110 $url = $cm->url;
2111 if (!$url) {
2112 $activity->url = null;
2113 $activity->display = false;
2114 } else {
2115 $activity->url = $url->out();
2116 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2117 if (self::module_extends_navigation($cm->modname)) {
2118 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2121 $activities[$cmid] = $activity;
2122 if ($activity->display) {
2123 $sections[$key]->hasactivites = true;
2128 return array($sections, $activities);
2132 * Generically loads the course sections into the course's navigation.
2134 * @param stdClass $course
2135 * @param navigation_node $coursenode
2136 * @return array An array of course section nodes
2138 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2139 global $CFG, $DB, $USER, $SITE;
2140 require_once($CFG->dirroot.'/course/lib.php');
2142 list($sections, $activities) = $this->generate_sections_and_activities($course);
2144 $navigationsections = array();
2145 foreach ($sections as $sectionid => $section) {
2146 $section = clone($section);
2147 if ($course->id == $SITE->id) {
2148 $this->load_section_activities($coursenode, $section->section, $activities);
2149 } else {
2150 if (!$section->uservisible || (!$this->showemptysections &&
2151 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2152 continue;
2155 $sectionname = get_section_name($course, $section);
2156 $url = course_get_url($course, $section->section, array('navigation' => true));
2158 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2159 null, $section->id, new pix_icon('i/section', ''));
2160 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2161 $sectionnode->hidden = (!$section->visible || !$section->available);
2162 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2163 $this->load_section_activities($sectionnode, $section->section, $activities);
2165 $section->sectionnode = $sectionnode;
2166 $navigationsections[$sectionid] = $section;
2169 return $navigationsections;
2173 * Loads all of the activities for a section into the navigation structure.
2175 * @param navigation_node $sectionnode
2176 * @param int $sectionnumber
2177 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2178 * @param stdClass $course The course object the section and activities relate to.
2179 * @return array Array of activity nodes
2181 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2182 global $CFG, $SITE;
2183 // A static counter for JS function naming
2184 static $legacyonclickcounter = 0;
2186 $activitynodes = array();
2187 if (empty($activities)) {
2188 return $activitynodes;
2191 if (!is_object($course)) {
2192 $activity = reset($activities);
2193 $courseid = $activity->course;
2194 } else {
2195 $courseid = $course->id;
2197 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2199 foreach ($activities as $activity) {
2200 if ($activity->section != $sectionnumber) {
2201 continue;
2203 if ($activity->icon) {
2204 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2205 } else {
2206 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2209 // Prepare the default name and url for the node
2210 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2211 $action = new moodle_url($activity->url);
2213 // Check if the onclick property is set (puke!)
2214 if (!empty($activity->onclick)) {
2215 // Increment the counter so that we have a unique number.
2216 $legacyonclickcounter++;
2217 // Generate the function name we will use
2218 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2219 $propogrationhandler = '';
2220 // Check if we need to cancel propogation. Remember inline onclick
2221 // events would return false if they wanted to prevent propogation and the
2222 // default action.
2223 if (strpos($activity->onclick, 'return false')) {
2224 $propogrationhandler = 'e.halt();';
2226 // Decode the onclick - it has already been encoded for display (puke)
2227 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2228 // Build the JS function the click event will call
2229 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2230 $this->page->requires->js_amd_inline($jscode);
2231 // Override the default url with the new action link
2232 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2235 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2236 $activitynode->title(get_string('modulename', $activity->modname));
2237 $activitynode->hidden = $activity->hidden;
2238 $activitynode->display = $showactivities && $activity->display;
2239 $activitynode->nodetype = $activity->nodetype;
2240 $activitynodes[$activity->id] = $activitynode;
2243 return $activitynodes;
2246 * Loads a stealth module from unavailable section
2247 * @param navigation_node $coursenode
2248 * @param stdClass $modinfo
2249 * @return navigation_node or null if not accessible
2251 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2252 if (empty($modinfo->cms[$this->page->cm->id])) {
2253 return null;
2255 $cm = $modinfo->cms[$this->page->cm->id];
2256 if ($cm->icon) {
2257 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2258 } else {
2259 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2261 $url = $cm->url;
2262 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2263 $activitynode->title(get_string('modulename', $cm->modname));
2264 $activitynode->hidden = (!$cm->visible);
2265 if (!$cm->is_visible_on_course_page()) {
2266 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2267 // Also there may be no exception at all in case when teacher is logged in as student.
2268 $activitynode->display = false;
2269 } else if (!$url) {
2270 // Don't show activities that don't have links!
2271 $activitynode->display = false;
2272 } else if (self::module_extends_navigation($cm->modname)) {
2273 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2275 return $activitynode;
2278 * Loads the navigation structure for the given activity into the activities node.
2280 * This method utilises a callback within the modules lib.php file to load the
2281 * content specific to activity given.
2283 * The callback is a method: {modulename}_extend_navigation()
2284 * Examples:
2285 * * {@link forum_extend_navigation()}
2286 * * {@link workshop_extend_navigation()}
2288 * @param cm_info|stdClass $cm
2289 * @param stdClass $course
2290 * @param navigation_node $activity
2291 * @return bool
2293 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2294 global $CFG, $DB;
2296 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2297 if (!($cm instanceof cm_info)) {
2298 $modinfo = get_fast_modinfo($course);
2299 $cm = $modinfo->get_cm($cm->id);
2301 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2302 $activity->make_active();
2303 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2304 $function = $cm->modname.'_extend_navigation';
2306 if (file_exists($file)) {
2307 require_once($file);
2308 if (function_exists($function)) {
2309 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2310 $function($activity, $course, $activtyrecord, $cm);
2314 // Allow the active advanced grading method plugin to append module navigation
2315 $featuresfunc = $cm->modname.'_supports';
2316 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2317 require_once($CFG->dirroot.'/grade/grading/lib.php');
2318 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2319 $gradingman->extend_navigation($this, $activity);
2322 return $activity->has_children();
2325 * Loads user specific information into the navigation in the appropriate place.
2327 * If no user is provided the current user is assumed.
2329 * @param stdClass $user
2330 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2331 * @return bool
2333 protected function load_for_user($user=null, $forceforcontext=false) {
2334 global $DB, $CFG, $USER, $SITE;
2336 require_once($CFG->dirroot . '/course/lib.php');
2338 if ($user === null) {
2339 // We can't require login here but if the user isn't logged in we don't
2340 // want to show anything
2341 if (!isloggedin() || isguestuser()) {
2342 return false;
2344 $user = $USER;
2345 } else if (!is_object($user)) {
2346 // If the user is not an object then get them from the database
2347 $select = context_helper::get_preload_record_columns_sql('ctx');
2348 $sql = "SELECT u.*, $select
2349 FROM {user} u
2350 JOIN {context} ctx ON u.id = ctx.instanceid
2351 WHERE u.id = :userid AND
2352 ctx.contextlevel = :contextlevel";
2353 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2354 context_helper::preload_from_record($user);
2357 $iscurrentuser = ($user->id == $USER->id);
2359 $usercontext = context_user::instance($user->id);
2361 // Get the course set against the page, by default this will be the site
2362 $course = $this->page->course;
2363 $baseargs = array('id'=>$user->id);
2364 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2365 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2366 $baseargs['course'] = $course->id;
2367 $coursecontext = context_course::instance($course->id);
2368 $issitecourse = false;
2369 } else {
2370 // Load all categories and get the context for the system
2371 $coursecontext = context_system::instance();
2372 $issitecourse = true;
2375 // Create a node to add user information under.
2376 $usersnode = null;
2377 if (!$issitecourse) {
2378 // Not the current user so add it to the participants node for the current course.
2379 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2380 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2381 } else if ($USER->id != $user->id) {
2382 // This is the site so add a users node to the root branch.
2383 $usersnode = $this->rootnodes['users'];
2384 if (course_can_view_participants($coursecontext)) {
2385 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2387 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2389 if (!$usersnode) {
2390 // We should NEVER get here, if the course hasn't been populated
2391 // with a participants node then the navigaiton either wasn't generated
2392 // for it (you are missing a require_login or set_context call) or
2393 // you don't have access.... in the interests of no leaking informatin
2394 // we simply quit...
2395 return false;
2397 // Add a branch for the current user.
2398 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2399 $viewprofile = true;
2400 if (!$iscurrentuser) {
2401 require_once($CFG->dirroot . '/user/lib.php');
2402 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2403 $viewprofile = false;
2404 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2405 $viewprofile = false;
2407 if (!$viewprofile) {
2408 $viewprofile = user_can_view_profile($user, null, $usercontext);
2412 // Now, conditionally add the user node.
2413 if ($viewprofile) {
2414 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2415 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2416 } else {
2417 $usernode = $usersnode->add(get_string('user'));
2420 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2421 $usernode->make_active();
2424 // Add user information to the participants or user node.
2425 if ($issitecourse) {
2427 // If the user is the current user or has permission to view the details of the requested
2428 // user than add a view profile link.
2429 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2430 has_capability('moodle/user:viewdetails', $usercontext)) {
2431 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2432 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2433 } else {
2434 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2438 if (!empty($CFG->navadduserpostslinks)) {
2439 // Add nodes for forum posts and discussions if the user can view either or both
2440 // There are no capability checks here as the content of the page is based
2441 // purely on the forums the current user has access too.
2442 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2443 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2444 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2445 array_merge($baseargs, array('mode' => 'discussions'))));
2448 // Add blog nodes.
2449 if (!empty($CFG->enableblogs)) {
2450 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2451 require_once($CFG->dirroot.'/blog/lib.php');
2452 // Get all options for the user.
2453 $options = blog_get_options_for_user($user);
2454 $this->cache->set('userblogoptions'.$user->id, $options);
2455 } else {
2456 $options = $this->cache->{'userblogoptions'.$user->id};
2459 if (count($options) > 0) {
2460 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2461 foreach ($options as $type => $option) {
2462 if ($type == "rss") {
2463 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2464 new pix_icon('i/rss', ''));
2465 } else {
2466 $blogs->add($option['string'], $option['link']);
2472 // Add the messages link.
2473 // It is context based so can appear in the user's profile and in course participants information.
2474 if (!empty($CFG->messaging)) {
2475 $messageargs = array('user1' => $USER->id);
2476 if ($USER->id != $user->id) {
2477 $messageargs['user2'] = $user->id;
2479 $url = new moodle_url('/message/index.php', $messageargs);
2480 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2483 // Add the "My private files" link.
2484 // This link doesn't have a unique display for course context so only display it under the user's profile.
2485 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2486 $url = new moodle_url('/user/files.php');
2487 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2490 // Add a node to view the users notes if permitted.
2491 if (!empty($CFG->enablenotes) &&
2492 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2493 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2494 if ($coursecontext->instanceid != SITEID) {
2495 $url->param('course', $coursecontext->instanceid);
2497 $usernode->add(get_string('notes', 'notes'), $url);
2500 // Show the grades node.
2501 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2502 require_once($CFG->dirroot . '/user/lib.php');
2503 // Set the grades node to link to the "Grades" page.
2504 if ($course->id == SITEID) {
2505 $url = user_mygrades_url($user->id, $course->id);
2506 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2507 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2509 if ($USER->id != $user->id) {
2510 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2511 } else {
2512 $usernode->add(get_string('grades', 'grades'), $url);
2516 // If the user is the current user add the repositories for the current user.
2517 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2518 if (!$iscurrentuser &&
2519 $course->id == $SITE->id &&
2520 has_capability('moodle/user:viewdetails', $usercontext) &&
2521 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2523 // Add view grade report is permitted.
2524 $reports = core_component::get_plugin_list('gradereport');
2525 arsort($reports); // User is last, we want to test it first.
2527 $userscourses = enrol_get_users_courses($user->id, false, '*');
2528 $userscoursesnode = $usernode->add(get_string('courses'));
2530 $count = 0;
2531 foreach ($userscourses as $usercourse) {
2532 if ($count === (int)$CFG->navcourselimit) {
2533 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2534 $userscoursesnode->add(get_string('showallcourses'), $url);
2535 break;
2537 $count++;
2538 $usercoursecontext = context_course::instance($usercourse->id);
2539 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2540 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2541 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2543 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2544 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2545 foreach ($reports as $plugin => $plugindir) {
2546 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2547 // Stop when the first visible plugin is found.
2548 $gradeavailable = true;
2549 break;
2554 if ($gradeavailable) {
2555 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2556 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2557 new pix_icon('i/grades', ''));
2560 // Add a node to view the users notes if permitted.
2561 if (!empty($CFG->enablenotes) &&
2562 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2563 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2564 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2567 if (can_access_course($usercourse, $user->id, '', true)) {
2568 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2569 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2572 $reporttab = $usercoursenode->add(get_string('activityreports'));
2574 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2575 foreach ($reportfunctions as $reportfunction) {
2576 $reportfunction($reporttab, $user, $usercourse);
2579 $reporttab->trim_if_empty();
2583 // Let plugins hook into user navigation.
2584 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2585 foreach ($pluginsfunction as $plugintype => $plugins) {
2586 if ($plugintype != 'report') {
2587 foreach ($plugins as $pluginfunction) {
2588 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2593 return true;
2597 * This method simply checks to see if a given module can extend the navigation.
2599 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2601 * @param string $modname
2602 * @return bool
2604 public static function module_extends_navigation($modname) {
2605 global $CFG;
2606 static $extendingmodules = array();
2607 if (!array_key_exists($modname, $extendingmodules)) {
2608 $extendingmodules[$modname] = false;
2609 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2610 if (file_exists($file)) {
2611 $function = $modname.'_extend_navigation';
2612 require_once($file);
2613 $extendingmodules[$modname] = (function_exists($function));
2616 return $extendingmodules[$modname];
2619 * Extends the navigation for the given user.
2621 * @param stdClass $user A user from the database
2623 public function extend_for_user($user) {
2624 $this->extendforuser[] = $user;
2628 * Returns all of the users the navigation is being extended for
2630 * @return array An array of extending users.
2632 public function get_extending_users() {
2633 return $this->extendforuser;
2636 * Adds the given course to the navigation structure.
2638 * @param stdClass $course
2639 * @param bool $forcegeneric
2640 * @param bool $ismycourse
2641 * @return navigation_node
2643 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2644 global $CFG, $SITE;
2646 // We found the course... we can return it now :)
2647 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2648 return $this->addedcourses[$course->id];
2651 $coursecontext = context_course::instance($course->id);
2653 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
2654 if (is_role_switched($course->id)) {
2655 // user has to be able to access course in order to switch, let's skip the visibility test here
2656 } else if (!core_course_category::can_view_course_info($course)) {
2657 return false;
2661 $issite = ($course->id == $SITE->id);
2662 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2663 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2664 // This is the name that will be shown for the course.
2665 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2667 if ($coursetype == self::COURSE_CURRENT) {
2668 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2669 return $coursenode;
2670 } else {
2671 $coursetype = self::COURSE_OTHER;
2675 // Can the user expand the course to see its content.
2676 $canexpandcourse = true;
2677 if ($issite) {
2678 $parent = $this;
2679 $url = null;
2680 if (empty($CFG->usesitenameforsitepages)) {
2681 $coursename = get_string('sitepages');
2683 } else if ($coursetype == self::COURSE_CURRENT) {
2684 $parent = $this->rootnodes['currentcourse'];
2685 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2686 $canexpandcourse = $this->can_expand_course($course);
2687 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2688 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2689 // Nothing to do here the above statement set $parent to the category within mycourses.
2690 } else {
2691 $parent = $this->rootnodes['mycourses'];
2693 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2694 } else {
2695 $parent = $this->rootnodes['courses'];
2696 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2697 // They can only expand the course if they can access it.
2698 $canexpandcourse = $this->can_expand_course($course);
2699 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2700 if (!$this->is_category_fully_loaded($course->category)) {
2701 // We need to load the category structure for this course
2702 $this->load_all_categories($course->category, false);
2704 if (array_key_exists($course->category, $this->addedcategories)) {
2705 $parent = $this->addedcategories[$course->category];
2706 // This could lead to the course being created so we should check whether it is the case again
2707 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2708 return $this->addedcourses[$course->id];
2714 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2715 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2717 $coursenode->hidden = (!$course->visible);
2718 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2719 if ($canexpandcourse) {
2720 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2721 $coursenode->nodetype = self::NODETYPE_BRANCH;
2722 $coursenode->isexpandable = true;
2723 } else {
2724 $coursenode->nodetype = self::NODETYPE_LEAF;
2725 $coursenode->isexpandable = false;
2727 if (!$forcegeneric) {
2728 $this->addedcourses[$course->id] = $coursenode;
2731 return $coursenode;
2735 * Returns a cache instance to use for the expand course cache.
2736 * @return cache_session
2738 protected function get_expand_course_cache() {
2739 if ($this->cacheexpandcourse === null) {
2740 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2742 return $this->cacheexpandcourse;
2746 * Checks if a user can expand a course in the navigation.
2748 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2749 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2750 * permits stale data.
2751 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2752 * will be stale.
2753 * It is brought up to date in only one of two ways.
2754 * 1. The user logs out and in again.
2755 * 2. The user browses to the course they've just being given access to.
2757 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2759 * @param stdClass $course
2760 * @return bool
2762 protected function can_expand_course($course) {
2763 $cache = $this->get_expand_course_cache();
2764 $canexpand = $cache->get($course->id);
2765 if ($canexpand === false) {
2766 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2767 $canexpand = (int)$canexpand;
2768 $cache->set($course->id, $canexpand);
2770 return ($canexpand === 1);
2774 * Returns true if the category has already been loaded as have any child categories
2776 * @param int $categoryid
2777 * @return bool
2779 protected function is_category_fully_loaded($categoryid) {
2780 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2784 * Adds essential course nodes to the navigation for the given course.
2786 * This method adds nodes such as reports, blogs and participants
2788 * @param navigation_node $coursenode
2789 * @param stdClass $course
2790 * @return bool returns true on successful addition of a node.
2792 public function add_course_essentials($coursenode, stdClass $course) {
2793 global $CFG, $SITE;
2794 require_once($CFG->dirroot . '/course/lib.php');
2796 if ($course->id == $SITE->id) {
2797 return $this->add_front_page_course_essentials($coursenode, $course);
2800 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2801 return true;
2804 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2806 //Participants
2807 if ($navoptions->participants) {
2808 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2809 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2811 if ($navoptions->blogs) {
2812 $blogsurls = new moodle_url('/blog/index.php');
2813 if ($currentgroup = groups_get_course_group($course, true)) {
2814 $blogsurls->param('groupid', $currentgroup);
2815 } else {
2816 $blogsurls->param('courseid', $course->id);
2818 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2821 if ($navoptions->notes) {
2822 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2824 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2825 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2828 // Badges.
2829 if ($navoptions->badges) {
2830 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2832 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2833 navigation_node::TYPE_SETTING, null, 'badgesview',
2834 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2837 // Check access to the course and competencies page.
2838 if ($navoptions->competencies) {
2839 // Just a link to course competency.
2840 $title = get_string('competencies', 'core_competency');
2841 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2842 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2843 new pix_icon('i/competencies', ''));
2845 if ($navoptions->grades) {
2846 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2847 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2848 'grades', new pix_icon('i/grades', ''));
2849 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2850 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2851 $gradenode->make_active();
2855 return true;
2858 * This generates the structure of the course that won't be generated when
2859 * the modules and sections are added.
2861 * Things such as the reports branch, the participants branch, blogs... get
2862 * added to the course node by this method.
2864 * @param navigation_node $coursenode
2865 * @param stdClass $course
2866 * @return bool True for successfull generation
2868 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2869 global $CFG, $USER, $COURSE, $SITE;
2870 require_once($CFG->dirroot . '/course/lib.php');
2872 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2873 return true;
2876 $systemcontext = context_system::instance();
2877 $navoptions = course_get_user_navigation_options($systemcontext, $course);
2879 // Hidden node that we use to determine if the front page navigation is loaded.
2880 // This required as there are not other guaranteed nodes that may be loaded.
2881 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2883 // Participants.
2884 if ($navoptions->participants) {
2885 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2888 // Blogs.
2889 if ($navoptions->blogs) {
2890 $blogsurls = new moodle_url('/blog/index.php');
2891 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2894 $filterselect = 0;
2896 // Badges.
2897 if ($navoptions->badges) {
2898 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2899 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2902 // Notes.
2903 if ($navoptions->notes) {
2904 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2905 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2908 // Tags
2909 if ($navoptions->tags) {
2910 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2911 self::TYPE_SETTING, null, 'tags');
2914 // Search.
2915 if ($navoptions->search) {
2916 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2917 self::TYPE_SETTING, null, 'search');
2920 if ($navoptions->calendar) {
2921 $courseid = $COURSE->id;
2922 $params = array('view' => 'month');
2923 if ($courseid != $SITE->id) {
2924 $params['course'] = $courseid;
2927 // Calendar
2928 $calendarurl = new moodle_url('/calendar/view.php', $params);
2929 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2930 self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
2931 $node->showinflatnavigation = true;
2934 if (isloggedin()) {
2935 $usercontext = context_user::instance($USER->id);
2936 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2937 $url = new moodle_url('/user/files.php');
2938 $node = $coursenode->add(get_string('privatefiles'), $url,
2939 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2940 $node->display = false;
2941 $node->showinflatnavigation = true;
2945 if (isloggedin()) {
2946 $context = $this->page->context;
2947 switch ($context->contextlevel) {
2948 case CONTEXT_COURSECAT:
2949 // OK, expected context level.
2950 break;
2951 case CONTEXT_COURSE:
2952 // OK, expected context level if not on frontpage.
2953 if ($COURSE->id != $SITE->id) {
2954 break;
2956 default:
2957 // If this context is part of a course (excluding frontpage), use the course context.
2958 // Otherwise, use the system context.
2959 $coursecontext = $context->get_course_context(false);
2960 if ($coursecontext && $coursecontext->instanceid !== $SITE->id) {
2961 $context = $coursecontext;
2962 } else {
2963 $context = $systemcontext;
2967 $params = ['contextid' => $context->id];
2968 if (has_capability('moodle/contentbank:access', $context)) {
2969 $url = new moodle_url('/contentbank/index.php', $params);
2970 $node = $coursenode->add(get_string('contentbank'), $url,
2971 self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', ''));
2972 $node->showinflatnavigation = true;
2976 return true;
2980 * Clears the navigation cache
2982 public function clear_cache() {
2983 $this->cache->clear();
2987 * Sets an expansion limit for the navigation
2989 * The expansion limit is used to prevent the display of content that has a type
2990 * greater than the provided $type.
2992 * Can be used to ensure things such as activities or activity content don't get
2993 * shown on the navigation.
2994 * They are still generated in order to ensure the navbar still makes sense.
2996 * @param int $type One of navigation_node::TYPE_*
2997 * @return bool true when complete.
2999 public function set_expansion_limit($type) {
3000 global $SITE;
3001 $nodes = $this->find_all_of_type($type);
3003 // We only want to hide specific types of nodes.
3004 // Only nodes that represent "structure" in the navigation tree should be hidden.
3005 // If we hide all nodes then we risk hiding vital information.
3006 $typestohide = array(
3007 self::TYPE_CATEGORY,
3008 self::TYPE_COURSE,
3009 self::TYPE_SECTION,
3010 self::TYPE_ACTIVITY
3013 foreach ($nodes as $node) {
3014 // We need to generate the full site node
3015 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
3016 continue;
3018 foreach ($node->children as $child) {
3019 $child->hide($typestohide);
3022 return true;
3025 * Attempts to get the navigation with the given key from this nodes children.
3027 * This function only looks at this nodes children, it does NOT look recursivily.
3028 * If the node can't be found then false is returned.
3030 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3032 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3033 * may be of more use to you.
3035 * @param string|int $key The key of the node you wish to receive.
3036 * @param int $type One of navigation_node::TYPE_*
3037 * @return navigation_node|false
3039 public function get($key, $type = null) {
3040 if (!$this->initialised) {
3041 $this->initialise();
3043 return parent::get($key, $type);
3047 * Searches this nodes children and their children to find a navigation node
3048 * with the matching key and type.
3050 * This method is recursive and searches children so until either a node is
3051 * found or there are no more nodes to search.
3053 * If you know that the node being searched for is a child of this node
3054 * then use the {@link global_navigation::get()} method instead.
3056 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3057 * may be of more use to you.
3059 * @param string|int $key The key of the node you wish to receive.
3060 * @param int $type One of navigation_node::TYPE_*
3061 * @return navigation_node|false
3063 public function find($key, $type) {
3064 if (!$this->initialised) {
3065 $this->initialise();
3067 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
3068 return $this->rootnodes[$key];
3070 return parent::find($key, $type);
3074 * They've expanded the 'my courses' branch.
3076 protected function load_courses_enrolled() {
3077 global $CFG;
3079 $limit = (int) $CFG->navcourselimit;
3081 $courses = enrol_get_my_courses('*');
3082 $flatnavcourses = [];
3084 // Go through the courses and see which ones we want to display in the flatnav.
3085 foreach ($courses as $course) {
3086 $classify = course_classify_for_timeline($course);
3088 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3089 $flatnavcourses[$course->id] = $course;
3093 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3094 $numtotalcourses = count($courses);
3095 $numtotalflatnavcourses = count($flatnavcourses);
3097 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3098 $courses = array_slice($courses, 0, $limit, true);
3099 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3101 // Get the number of courses we are going to show for each.
3102 $numshowncourses = count($courses);
3103 $numshownflatnavcourses = count($flatnavcourses);
3104 if ($numshowncourses && $this->show_my_categories()) {
3105 // Generate an array containing unique values of all the courses' categories.
3106 $categoryids = array();
3107 foreach ($courses as $course) {
3108 if (in_array($course->category, $categoryids)) {
3109 continue;
3111 $categoryids[] = $course->category;
3114 // Array of category IDs that include the categories of the user's courses and the related course categories.
3115 $fullpathcategoryids = [];
3116 // Get the course categories for the enrolled courses' category IDs.
3117 $mycoursecategories = core_course_category::get_many($categoryids);
3118 // Loop over each of these categories and build the category tree using each category's path.
3119 foreach ($mycoursecategories as $mycoursecat) {
3120 $pathcategoryids = explode('/', $mycoursecat->path);
3121 // First element of the exploded path is empty since paths begin with '/'.
3122 array_shift($pathcategoryids);
3123 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3124 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3127 // Fetch all of the categories related to the user's courses.
3128 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3129 // Loop over each of these categories and build the category tree.
3130 foreach ($pathcategories as $coursecat) {
3131 // No need to process categories that have already been added.
3132 if (isset($this->addedcategories[$coursecat->id])) {
3133 continue;
3135 // Skip categories that are not visible.
3136 if (!$coursecat->is_uservisible()) {
3137 continue;
3140 // Get this course category's parent node.
3141 $parent = null;
3142 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3143 $parent = $this->addedcategories[$coursecat->parent];
3145 if (!$parent) {
3146 // If it has no parent, then it should be right under the My courses node.
3147 $parent = $this->rootnodes['mycourses'];
3150 // Build the category object based from the coursecat object.
3151 $mycategory = new stdClass();
3152 $mycategory->id = $coursecat->id;
3153 $mycategory->name = $coursecat->name;
3154 $mycategory->visible = $coursecat->visible;
3156 // Add this category to the nav tree.
3157 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3161 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3162 foreach ($courses as $course) {
3163 $node = $this->add_course($course, false, self::COURSE_MY);
3164 if ($node) {
3165 $node->showinflatnavigation = false;
3166 // Check if we should also add this to the flat nav as well.
3167 if (isset($flatnavcourses[$course->id])) {
3168 $node->showinflatnavigation = true;
3173 // Go through each course in the flatnav now.
3174 foreach ($flatnavcourses as $course) {
3175 // Check if we haven't already added it.
3176 if (!isset($courses[$course->id])) {
3177 // Ok, add it to the flatnav only.
3178 $node = $this->add_course($course, false, self::COURSE_MY);
3179 $node->display = false;
3180 $node->showinflatnavigation = true;
3184 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3185 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3186 // Show a link to the course page if there are more courses the user is enrolled in.
3187 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3188 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3189 $url = new moodle_url('/my/');
3190 $parent = $this->rootnodes['mycourses'];
3191 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3193 if ($showmorelinkinnav) {
3194 $coursenode->display = true;
3197 if ($showmorelinkinflatnav) {
3198 $coursenode->showinflatnavigation = true;
3205 * The global navigation class used especially for AJAX requests.
3207 * The primary methods that are used in the global navigation class have been overriden
3208 * to ensure that only the relevant branch is generated at the root of the tree.
3209 * This can be done because AJAX is only used when the backwards structure for the
3210 * requested branch exists.
3211 * This has been done only because it shortens the amounts of information that is generated
3212 * which of course will speed up the response time.. because no one likes laggy AJAX.
3214 * @package core
3215 * @category navigation
3216 * @copyright 2009 Sam Hemelryk
3217 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3219 class global_navigation_for_ajax extends global_navigation {
3221 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3222 protected $branchtype;
3224 /** @var int the instance id */
3225 protected $instanceid;
3227 /** @var array Holds an array of expandable nodes */
3228 protected $expandable = array();
3231 * Constructs the navigation for use in an AJAX request
3233 * @param moodle_page $page moodle_page object
3234 * @param int $branchtype
3235 * @param int $id
3237 public function __construct($page, $branchtype, $id) {
3238 $this->page = $page;
3239 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3240 $this->children = new navigation_node_collection();
3241 $this->branchtype = $branchtype;
3242 $this->instanceid = $id;
3243 $this->initialise();
3246 * Initialise the navigation given the type and id for the branch to expand.
3248 * @return array An array of the expandable nodes
3250 public function initialise() {
3251 global $DB, $SITE;
3253 if ($this->initialised || during_initial_install()) {
3254 return $this->expandable;
3256 $this->initialised = true;
3258 $this->rootnodes = array();
3259 $this->rootnodes['site'] = $this->add_course($SITE);
3260 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3261 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3262 // The courses branch is always displayed, and is always expandable (although may be empty).
3263 // This mimicks what is done during {@link global_navigation::initialise()}.
3264 $this->rootnodes['courses']->isexpandable = true;
3266 // Branchtype will be one of navigation_node::TYPE_*
3267 switch ($this->branchtype) {
3268 case 0:
3269 if ($this->instanceid === 'mycourses') {
3270 $this->load_courses_enrolled();
3271 } else if ($this->instanceid === 'courses') {
3272 $this->load_courses_other();
3274 break;
3275 case self::TYPE_CATEGORY :
3276 $this->load_category($this->instanceid);
3277 break;
3278 case self::TYPE_MY_CATEGORY :
3279 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3280 break;
3281 case self::TYPE_COURSE :
3282 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3283 if (!can_access_course($course, null, '', true)) {
3284 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3285 // add the course node and break. This leads to an empty node.
3286 $this->add_course($course);
3287 break;
3289 require_course_login($course, true, null, false, true);
3290 $this->page->set_context(context_course::instance($course->id));
3291 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3292 $this->add_course_essentials($coursenode, $course);
3293 $this->load_course_sections($course, $coursenode);
3294 break;
3295 case self::TYPE_SECTION :
3296 $sql = 'SELECT c.*, cs.section AS sectionnumber
3297 FROM {course} c
3298 LEFT JOIN {course_sections} cs ON cs.course = c.id
3299 WHERE cs.id = ?';
3300 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3301 require_course_login($course, true, null, false, true);
3302 $this->page->set_context(context_course::instance($course->id));
3303 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3304 $this->add_course_essentials($coursenode, $course);
3305 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3306 break;
3307 case self::TYPE_ACTIVITY :
3308 $sql = "SELECT c.*
3309 FROM {course} c
3310 JOIN {course_modules} cm ON cm.course = c.id
3311 WHERE cm.id = :cmid";
3312 $params = array('cmid' => $this->instanceid);
3313 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3314 $modinfo = get_fast_modinfo($course);
3315 $cm = $modinfo->get_cm($this->instanceid);
3316 require_course_login($course, true, $cm, false, true);
3317 $this->page->set_context(context_module::instance($cm->id));
3318 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3319 $this->load_course_sections($course, $coursenode, null, $cm);
3320 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3321 if ($activitynode) {
3322 $modulenode = $this->load_activity($cm, $course, $activitynode);
3324 break;
3325 default:
3326 throw new Exception('Unknown type');
3327 return $this->expandable;
3330 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3331 $this->load_for_user(null, true);
3334 // Give the local plugins a chance to include some navigation if they want.
3335 $this->load_local_plugin_navigation();
3337 $this->find_expandable($this->expandable);
3338 return $this->expandable;
3342 * They've expanded the general 'courses' branch.
3344 protected function load_courses_other() {
3345 $this->load_all_courses();
3349 * Loads a single category into the AJAX navigation.
3351 * This function is special in that it doesn't concern itself with the parent of
3352 * the requested category or its siblings.
3353 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3354 * request that.
3356 * @global moodle_database $DB
3357 * @param int $categoryid id of category to load in navigation.
3358 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3359 * @return void.
3361 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3362 global $CFG, $DB;
3364 $limit = 20;
3365 if (!empty($CFG->navcourselimit)) {
3366 $limit = (int)$CFG->navcourselimit;
3369 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3370 $sql = "SELECT cc.*, $catcontextsql
3371 FROM {course_categories} cc
3372 JOIN {context} ctx ON cc.id = ctx.instanceid
3373 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3374 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3375 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3376 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3377 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3378 $categorylist = array();
3379 $subcategories = array();
3380 $basecategory = null;
3381 foreach ($categories as $category) {
3382 $categorylist[] = $category->id;
3383 context_helper::preload_from_record($category);
3384 if ($category->id == $categoryid) {
3385 $this->add_category($category, $this, $nodetype);
3386 $basecategory = $this->addedcategories[$category->id];
3387 } else {
3388 $subcategories[$category->id] = $category;
3391 $categories->close();
3394 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3395 // else show all courses.
3396 if ($nodetype === self::TYPE_MY_CATEGORY) {
3397 $courses = enrol_get_my_courses('*');
3398 $categoryids = array();
3400 // Only search for categories if basecategory was found.
3401 if (!is_null($basecategory)) {
3402 // Get course parent category ids.
3403 foreach ($courses as $course) {
3404 $categoryids[] = $course->category;
3407 // Get a unique list of category ids which a part of the path
3408 // to user's courses.
3409 $coursesubcategories = array();
3410 $addedsubcategories = array();
3412 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3413 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3415 foreach ($categories as $category){
3416 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3418 $categories->close();
3419 $coursesubcategories = array_unique($coursesubcategories);
3421 // Only add a subcategory if it is part of the path to user's course and
3422 // wasn't already added.
3423 foreach ($subcategories as $subid => $subcategory) {
3424 if (in_array($subid, $coursesubcategories) &&
3425 !in_array($subid, $addedsubcategories)) {
3426 $this->add_category($subcategory, $basecategory, $nodetype);
3427 $addedsubcategories[] = $subid;
3432 foreach ($courses as $course) {
3433 // Add course if it's in category.
3434 if (in_array($course->category, $categorylist)) {
3435 $this->add_course($course, true, self::COURSE_MY);
3438 } else {
3439 if (!is_null($basecategory)) {
3440 foreach ($subcategories as $key=>$category) {
3441 $this->add_category($category, $basecategory, $nodetype);
3444 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3445 foreach ($courses as $course) {
3446 $this->add_course($course);
3448 $courses->close();
3453 * Returns an array of expandable nodes
3454 * @return array
3456 public function get_expandable() {
3457 return $this->expandable;
3462 * Navbar class
3464 * This class is used to manage the navbar, which is initialised from the navigation
3465 * object held by PAGE
3467 * @package core
3468 * @category navigation
3469 * @copyright 2009 Sam Hemelryk
3470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3472 class navbar extends navigation_node {
3473 /** @var bool A switch for whether the navbar is initialised or not */
3474 protected $initialised = false;
3475 /** @var mixed keys used to reference the nodes on the navbar */
3476 protected $keys = array();
3477 /** @var null|string content of the navbar */
3478 protected $content = null;
3479 /** @var moodle_page object the moodle page that this navbar belongs to */
3480 protected $page;
3481 /** @var bool A switch for whether to ignore the active navigation information */
3482 protected $ignoreactive = false;
3483 /** @var bool A switch to let us know if we are in the middle of an install */
3484 protected $duringinstall = false;
3485 /** @var bool A switch for whether the navbar has items */
3486 protected $hasitems = false;
3487 /** @var array An array of navigation nodes for the navbar */
3488 protected $items;
3489 /** @var array An array of child node objects */
3490 public $children = array();
3491 /** @var bool A switch for whether we want to include the root node in the navbar */
3492 public $includesettingsbase = false;
3493 /** @var breadcrumb_navigation_node[] $prependchildren */
3494 protected $prependchildren = array();
3497 * The almighty constructor
3499 * @param moodle_page $page
3501 public function __construct(moodle_page $page) {
3502 global $CFG;
3503 if (during_initial_install()) {
3504 $this->duringinstall = true;
3505 return false;
3507 $this->page = $page;
3508 $this->text = get_string('home');
3509 $this->shorttext = get_string('home');
3510 $this->action = new moodle_url($CFG->wwwroot);
3511 $this->nodetype = self::NODETYPE_BRANCH;
3512 $this->type = self::TYPE_SYSTEM;
3516 * Quick check to see if the navbar will have items in.
3518 * @return bool Returns true if the navbar will have items, false otherwise
3520 public function has_items() {
3521 if ($this->duringinstall) {
3522 return false;
3523 } else if ($this->hasitems !== false) {
3524 return true;
3526 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3527 // There have been manually added items - there are definitely items.
3528 $outcome = true;
3529 } else if (!$this->ignoreactive) {
3530 // We will need to initialise the navigation structure to check if there are active items.
3531 $this->page->navigation->initialise($this->page);
3532 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3534 $this->hasitems = $outcome;
3535 return $outcome;
3539 * Turn on/off ignore active
3541 * @param bool $setting
3543 public function ignore_active($setting=true) {
3544 $this->ignoreactive = ($setting);
3548 * Gets a navigation node
3550 * @param string|int $key for referencing the navbar nodes
3551 * @param int $type breadcrumb_navigation_node::TYPE_*
3552 * @return breadcrumb_navigation_node|bool
3554 public function get($key, $type = null) {
3555 foreach ($this->children as &$child) {
3556 if ($child->key === $key && ($type == null || $type == $child->type)) {
3557 return $child;
3560 foreach ($this->prependchildren as &$child) {
3561 if ($child->key === $key && ($type == null || $type == $child->type)) {
3562 return $child;
3565 return false;
3568 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3570 * @return array
3572 public function get_items() {
3573 global $CFG;
3574 $items = array();
3575 // Make sure that navigation is initialised
3576 if (!$this->has_items()) {
3577 return $items;
3579 if ($this->items !== null) {
3580 return $this->items;
3583 if (count($this->children) > 0) {
3584 // Add the custom children.
3585 $items = array_reverse($this->children);
3588 // Check if navigation contains the active node
3589 if (!$this->ignoreactive) {
3590 // We will need to ensure the navigation has been initialised.
3591 $this->page->navigation->initialise($this->page);
3592 // Now find the active nodes on both the navigation and settings.
3593 $navigationactivenode = $this->page->navigation->find_active_node();
3594 $settingsactivenode = $this->page->settingsnav->find_active_node();
3596 if ($navigationactivenode && $settingsactivenode) {
3597 // Parse a combined navigation tree
3598 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3599 if (!$settingsactivenode->mainnavonly) {
3600 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3602 $settingsactivenode = $settingsactivenode->parent;
3604 if (!$this->includesettingsbase) {
3605 // Removes the first node from the settings (root node) from the list
3606 array_pop($items);
3608 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3609 if (!$navigationactivenode->mainnavonly) {
3610 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3612 if (!empty($CFG->navshowcategories) &&
3613 $navigationactivenode->type === self::TYPE_COURSE &&
3614 $navigationactivenode->parent->key === 'currentcourse') {
3615 foreach ($this->get_course_categories() as $item) {
3616 $items[] = new breadcrumb_navigation_node($item);
3619 $navigationactivenode = $navigationactivenode->parent;
3621 } else if ($navigationactivenode) {
3622 // Parse the navigation tree to get the active node
3623 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3624 if (!$navigationactivenode->mainnavonly) {
3625 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3627 if (!empty($CFG->navshowcategories) &&
3628 $navigationactivenode->type === self::TYPE_COURSE &&
3629 $navigationactivenode->parent->key === 'currentcourse') {
3630 foreach ($this->get_course_categories() as $item) {
3631 $items[] = new breadcrumb_navigation_node($item);
3634 $navigationactivenode = $navigationactivenode->parent;
3636 } else if ($settingsactivenode) {
3637 // Parse the settings navigation to get the active node
3638 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3639 if (!$settingsactivenode->mainnavonly) {
3640 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3642 $settingsactivenode = $settingsactivenode->parent;
3647 $items[] = new breadcrumb_navigation_node(array(
3648 'text' => $this->page->navigation->text,
3649 'shorttext' => $this->page->navigation->shorttext,
3650 'key' => $this->page->navigation->key,
3651 'action' => $this->page->navigation->action
3654 if (count($this->prependchildren) > 0) {
3655 // Add the custom children
3656 $items = array_merge($items, array_reverse($this->prependchildren));
3659 $last = reset($items);
3660 if ($last) {
3661 $last->set_last(true);
3663 $this->items = array_reverse($items);
3664 return $this->items;
3668 * Get the list of categories leading to this course.
3670 * This function is used by {@link navbar::get_items()} to add back the "courses"
3671 * node and category chain leading to the current course. Note that this is only ever
3672 * called for the current course, so we don't need to bother taking in any parameters.
3674 * @return array
3676 private function get_course_categories() {
3677 global $CFG;
3678 require_once($CFG->dirroot.'/course/lib.php');
3680 $categories = array();
3681 $cap = 'moodle/category:viewhiddencategories';
3682 $showcategories = !core_course_category::is_simple_site();
3684 if ($showcategories) {
3685 foreach ($this->page->categories as $category) {
3686 $context = context_coursecat::instance($category->id);
3687 if (!core_course_category::can_view_category($category)) {
3688 continue;
3690 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3691 $name = format_string($category->name, true, array('context' => $context));
3692 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3693 if (!$category->visible) {
3694 $categorynode->hidden = true;
3696 $categories[] = $categorynode;
3700 // Don't show the 'course' node if enrolled in this course.
3701 $coursecontext = context_course::instance($this->page->course->id);
3702 if (!is_enrolled($coursecontext, null, '', true)) {
3703 $courses = $this->page->navigation->get('courses');
3704 if (!$courses) {
3705 // Courses node may not be present.
3706 $courses = breadcrumb_navigation_node::create(
3707 get_string('courses'),
3708 new moodle_url('/course/index.php'),
3709 self::TYPE_CONTAINER
3712 $categories[] = $courses;
3715 return $categories;
3719 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3721 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3722 * the way nodes get added to allow us to simply call add and have the node added to the
3723 * end of the navbar
3725 * @param string $text
3726 * @param string|moodle_url|action_link $action An action to associate with this node.
3727 * @param int $type One of navigation_node::TYPE_*
3728 * @param string $shorttext
3729 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3730 * @param pix_icon $icon An optional icon to use for this node.
3731 * @return navigation_node
3733 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3734 if ($this->content !== null) {
3735 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3738 // Properties array used when creating the new navigation node
3739 $itemarray = array(
3740 'text' => $text,
3741 'type' => $type
3743 // Set the action if one was provided
3744 if ($action!==null) {
3745 $itemarray['action'] = $action;
3747 // Set the shorttext if one was provided
3748 if ($shorttext!==null) {
3749 $itemarray['shorttext'] = $shorttext;
3751 // Set the icon if one was provided
3752 if ($icon!==null) {
3753 $itemarray['icon'] = $icon;
3755 // Default the key to the number of children if not provided
3756 if ($key === null) {
3757 $key = count($this->children);
3759 // Set the key
3760 $itemarray['key'] = $key;
3761 // Set the parent to this node
3762 $itemarray['parent'] = $this;
3763 // Add the child using the navigation_node_collections add method
3764 $this->children[] = new breadcrumb_navigation_node($itemarray);
3765 return $this;
3769 * Prepends a new navigation_node to the start of the navbar
3771 * @param string $text
3772 * @param string|moodle_url|action_link $action An action to associate with this node.
3773 * @param int $type One of navigation_node::TYPE_*
3774 * @param string $shorttext
3775 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3776 * @param pix_icon $icon An optional icon to use for this node.
3777 * @return navigation_node
3779 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3780 if ($this->content !== null) {
3781 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3783 // Properties array used when creating the new navigation node.
3784 $itemarray = array(
3785 'text' => $text,
3786 'type' => $type
3788 // Set the action if one was provided.
3789 if ($action!==null) {
3790 $itemarray['action'] = $action;
3792 // Set the shorttext if one was provided.
3793 if ($shorttext!==null) {
3794 $itemarray['shorttext'] = $shorttext;
3796 // Set the icon if one was provided.
3797 if ($icon!==null) {
3798 $itemarray['icon'] = $icon;
3800 // Default the key to the number of children if not provided.
3801 if ($key === null) {
3802 $key = count($this->children);
3804 // Set the key.
3805 $itemarray['key'] = $key;
3806 // Set the parent to this node.
3807 $itemarray['parent'] = $this;
3808 // Add the child node to the prepend list.
3809 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3810 return $this;
3815 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3816 * in particular adding extra metadata for search engine robots to leverage.
3818 * @package core
3819 * @category navigation
3820 * @copyright 2015 Brendan Heywood
3821 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3823 class breadcrumb_navigation_node extends navigation_node {
3825 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3826 private $last = false;
3829 * A proxy constructor
3831 * @param mixed $navnode A navigation_node or an array
3833 public function __construct($navnode) {
3834 if (is_array($navnode)) {
3835 parent::__construct($navnode);
3836 } else if ($navnode instanceof navigation_node) {
3838 // Just clone everything.
3839 $objvalues = get_object_vars($navnode);
3840 foreach ($objvalues as $key => $value) {
3841 $this->$key = $value;
3843 } else {
3844 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3849 * Getter for "last"
3850 * @return boolean
3852 public function is_last() {
3853 return $this->last;
3857 * Setter for "last"
3858 * @param $val boolean
3860 public function set_last($val) {
3861 $this->last = $val;
3866 * Subclass of navigation_node allowing different rendering for the flat navigation
3867 * in particular allowing dividers and indents.
3869 * @package core
3870 * @category navigation
3871 * @copyright 2016 Damyon Wiese
3872 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3874 class flat_navigation_node extends navigation_node {
3876 /** @var $indent integer The indent level */
3877 private $indent = 0;
3879 /** @var $showdivider bool Show a divider before this element */
3880 private $showdivider = false;
3882 /** @var $collectionlabel string Label for a group of nodes */
3883 private $collectionlabel = '';
3886 * A proxy constructor
3888 * @param mixed $navnode A navigation_node or an array
3890 public function __construct($navnode, $indent) {
3891 if (is_array($navnode)) {
3892 parent::__construct($navnode);
3893 } else if ($navnode instanceof navigation_node) {
3895 // Just clone everything.
3896 $objvalues = get_object_vars($navnode);
3897 foreach ($objvalues as $key => $value) {
3898 $this->$key = $value;
3900 } else {
3901 throw new coding_exception('Not a valid flat_navigation_node');
3903 $this->indent = $indent;
3907 * Setter, a label is required for a flat navigation node that shows a divider.
3909 * @param string $label
3911 public function set_collectionlabel($label) {
3912 $this->collectionlabel = $label;
3916 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
3918 * @return string
3920 public function get_collectionlabel() {
3921 if (!empty($this->collectionlabel)) {
3922 return $this->collectionlabel;
3924 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) {
3925 return $this->parent->get_collectionlabel();
3927 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3928 return '';
3932 * Does this node represent a course section link.
3933 * @return boolean
3935 public function is_section() {
3936 return $this->type == navigation_node::TYPE_SECTION;
3940 * In flat navigation - sections are active if we are looking at activities in the section.
3941 * @return boolean
3943 public function isactive() {
3944 global $PAGE;
3946 if ($this->is_section()) {
3947 $active = $PAGE->navigation->find_active_node();
3948 while ($active = $active->parent) {
3949 if ($active->key == $this->key && $active->type == $this->type) {
3950 return true;
3954 return $this->isactive;
3958 * Getter for "showdivider"
3959 * @return boolean
3961 public function showdivider() {
3962 return $this->showdivider;
3966 * Setter for "showdivider"
3967 * @param $val boolean
3968 * @param $label string Label for the group of nodes
3970 public function set_showdivider($val, $label = '') {
3971 $this->showdivider = $val;
3972 if ($this->showdivider && empty($label)) {
3973 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3974 } else {
3975 $this->set_collectionlabel($label);
3980 * Getter for "indent"
3981 * @return boolean
3983 public function get_indent() {
3984 return $this->indent;
3988 * Setter for "indent"
3989 * @param $val boolean
3991 public function set_indent($val) {
3992 $this->indent = $val;
3997 * Class used to generate a collection of navigation nodes most closely related
3998 * to the current page.
4000 * @package core
4001 * @copyright 2016 Damyon Wiese
4002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4004 class flat_navigation extends navigation_node_collection {
4005 /** @var moodle_page the moodle page that the navigation belongs to */
4006 protected $page;
4009 * Constructor.
4011 * @param moodle_page $page
4013 public function __construct(moodle_page &$page) {
4014 if (during_initial_install()) {
4015 return false;
4017 $this->page = $page;
4021 * Build the list of navigation nodes based on the current navigation and settings trees.
4024 public function initialise() {
4025 global $PAGE, $USER, $OUTPUT, $CFG;
4026 if (during_initial_install()) {
4027 return;
4030 $current = false;
4032 $course = $PAGE->course;
4034 $this->page->navigation->initialise();
4036 // First walk the nav tree looking for "flat_navigation" nodes.
4037 if ($course->id > 1) {
4038 // It's a real course.
4039 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4041 $coursecontext = context_course::instance($course->id, MUST_EXIST);
4042 // This is the name that will be shown for the course.
4043 $coursename = empty($CFG->navshowfullcoursenames) ?
4044 format_string($course->shortname, true, array('context' => $coursecontext)) :
4045 format_string($course->fullname, true, array('context' => $coursecontext));
4047 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
4048 $flat->set_collectionlabel($coursename);
4049 $flat->key = 'coursehome';
4050 $flat->icon = new pix_icon('i/course', '');
4052 $courseformat = course_get_format($course);
4053 $coursenode = $PAGE->navigation->find_active_node();
4054 $targettype = navigation_node::TYPE_COURSE;
4056 // Single activity format has no course node - the course node is swapped for the activity node.
4057 if (!$courseformat->has_view_page()) {
4058 $targettype = navigation_node::TYPE_ACTIVITY;
4061 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
4062 $coursenode = $coursenode->parent;
4064 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4065 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4066 if ($coursenode && $coursenode->key != SITEID) {
4067 $this->add($flat);
4068 foreach ($coursenode->children as $child) {
4069 if ($child->action) {
4070 $flat = new flat_navigation_node($child, 0);
4071 $this->add($flat);
4076 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
4077 } else {
4078 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
4081 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
4082 if (!$admin) {
4083 // Try again - crazy nav tree!
4084 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
4086 if ($admin) {
4087 $flat = new flat_navigation_node($admin, 0);
4088 $flat->set_showdivider(true, get_string('sitesettings'));
4089 $flat->key = 'sitesettings';
4090 $flat->icon = new pix_icon('t/preferences', '');
4091 $this->add($flat);
4094 // Add-a-block in editing mode.
4095 if (isset($this->page->theme->addblockposition) &&
4096 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
4097 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) {
4098 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
4099 $addablock = navigation_node::create(get_string('addblock'), $url);
4100 $flat = new flat_navigation_node($addablock, 0);
4101 $flat->set_showdivider(true, get_string('blocksaddedit'));
4102 $flat->key = 'addblock';
4103 $flat->icon = new pix_icon('i/addblock', '');
4104 $this->add($flat);
4106 $addblockurl = "?{$url->get_query_string(false)}";
4108 $PAGE->requires->js_call_amd('core/addblockmodal', 'init',
4109 [$PAGE->pagetype, $PAGE->pagelayout, $addblockurl]);
4115 * Override the parent so we can set a label for this collection if it has not been set yet.
4117 * @param navigation_node $node Node to add
4118 * @param string $beforekey If specified, adds before a node with this key,
4119 * otherwise adds at end
4120 * @return navigation_node Added node
4122 public function add(navigation_node $node, $beforekey=null) {
4123 $result = parent::add($node, $beforekey);
4124 // Extend the parent to get a name for the collection of nodes if required.
4125 if (empty($this->collectionlabel)) {
4126 if ($node instanceof flat_navigation_node) {
4127 $this->set_collectionlabel($node->get_collectionlabel());
4131 return $result;
4136 * Class used to manage the settings option for the current page
4138 * This class is used to manage the settings options in a tree format (recursively)
4139 * and was created initially for use with the settings blocks.
4141 * @package core
4142 * @category navigation
4143 * @copyright 2009 Sam Hemelryk
4144 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4146 class settings_navigation extends navigation_node {
4147 /** @var stdClass the current context */
4148 protected $context;
4149 /** @var moodle_page the moodle page that the navigation belongs to */
4150 protected $page;
4151 /** @var string contains administration section navigation_nodes */
4152 protected $adminsection;
4153 /** @var bool A switch to see if the navigation node is initialised */
4154 protected $initialised = false;
4155 /** @var array An array of users that the nodes can extend for. */
4156 protected $userstoextendfor = array();
4157 /** @var navigation_cache **/
4158 protected $cache;
4161 * Sets up the object with basic settings and preparse it for use
4163 * @param moodle_page $page
4165 public function __construct(moodle_page &$page) {
4166 if (during_initial_install()) {
4167 return false;
4169 $this->page = $page;
4170 // Initialise the main navigation. It is most important that this is done
4171 // before we try anything
4172 $this->page->navigation->initialise();
4173 // Initialise the navigation cache
4174 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4175 $this->children = new navigation_node_collection();
4179 * Initialise the settings navigation based on the current context
4181 * This function initialises the settings navigation tree for a given context
4182 * by calling supporting functions to generate major parts of the tree.
4185 public function initialise() {
4186 global $DB, $SESSION, $SITE;
4188 if (during_initial_install()) {
4189 return false;
4190 } else if ($this->initialised) {
4191 return true;
4193 $this->id = 'settingsnav';
4194 $this->context = $this->page->context;
4196 $context = $this->context;
4197 if ($context->contextlevel == CONTEXT_BLOCK) {
4198 $this->load_block_settings();
4199 $context = $context->get_parent_context();
4200 $this->context = $context;
4202 switch ($context->contextlevel) {
4203 case CONTEXT_SYSTEM:
4204 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4205 $this->load_front_page_settings(($context->id == $this->context->id));
4207 break;
4208 case CONTEXT_COURSECAT:
4209 $this->load_category_settings();
4210 break;
4211 case CONTEXT_COURSE:
4212 if ($this->page->course->id != $SITE->id) {
4213 $this->load_course_settings(($context->id == $this->context->id));
4214 } else {
4215 $this->load_front_page_settings(($context->id == $this->context->id));
4217 break;
4218 case CONTEXT_MODULE:
4219 $this->load_module_settings();
4220 $this->load_course_settings();
4221 break;
4222 case CONTEXT_USER:
4223 if ($this->page->course->id != $SITE->id) {
4224 $this->load_course_settings();
4226 break;
4229 $usersettings = $this->load_user_settings($this->page->course->id);
4231 $adminsettings = false;
4232 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4233 $isadminpage = $this->is_admin_tree_needed();
4235 if (has_capability('moodle/site:configview', context_system::instance())) {
4236 if (has_capability('moodle/site:config', context_system::instance())) {
4237 // Make sure this works even if config capability changes on the fly
4238 // and also make it fast for admin right after login.
4239 $SESSION->load_navigation_admin = 1;
4240 if ($isadminpage) {
4241 $adminsettings = $this->load_administration_settings();
4244 } else if (!isset($SESSION->load_navigation_admin)) {
4245 $adminsettings = $this->load_administration_settings();
4246 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4248 } else if ($SESSION->load_navigation_admin) {
4249 if ($isadminpage) {
4250 $adminsettings = $this->load_administration_settings();
4254 // Print empty navigation node, if needed.
4255 if ($SESSION->load_navigation_admin && !$isadminpage) {
4256 if ($adminsettings) {
4257 // Do not print settings tree on pages that do not need it, this helps with performance.
4258 $adminsettings->remove();
4259 $adminsettings = false;
4261 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4262 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4263 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4264 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4265 $siteadminnode->requiresajaxloading = 'true';
4270 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4271 $adminsettings->force_open();
4272 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4273 $usersettings->force_open();
4276 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4277 $this->load_local_plugin_settings();
4279 foreach ($this->children as $key=>$node) {
4280 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4281 // Site administration is shown as link.
4282 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4283 continue;
4285 $node->remove();
4288 $this->initialised = true;
4291 * Override the parent function so that we can add preceeding hr's and set a
4292 * root node class against all first level element
4294 * It does this by first calling the parent's add method {@link navigation_node::add()}
4295 * and then proceeds to use the key to set class and hr
4297 * @param string $text text to be used for the link.
4298 * @param string|moodle_url $url url for the new node
4299 * @param int $type the type of node navigation_node::TYPE_*
4300 * @param string $shorttext
4301 * @param string|int $key a key to access the node by.
4302 * @param pix_icon $icon An icon that appears next to the node.
4303 * @return navigation_node with the new node added to it.
4305 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4306 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4307 $node->add_class('root_node');
4308 return $node;
4312 * This function allows the user to add something to the start of the settings
4313 * navigation, which means it will be at the top of the settings navigation block
4315 * @param string $text text to be used for the link.
4316 * @param string|moodle_url $url url for the new node
4317 * @param int $type the type of node navigation_node::TYPE_*
4318 * @param string $shorttext
4319 * @param string|int $key a key to access the node by.
4320 * @param pix_icon $icon An icon that appears next to the node.
4321 * @return navigation_node $node with the new node added to it.
4323 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4324 $children = $this->children;
4325 $childrenclass = get_class($children);
4326 $this->children = new $childrenclass;
4327 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4328 foreach ($children as $child) {
4329 $this->children->add($child);
4331 return $node;
4335 * Does this page require loading of full admin tree or is
4336 * it enough rely on AJAX?
4338 * @return bool
4340 protected function is_admin_tree_needed() {
4341 if (self::$loadadmintree) {
4342 // Usually external admin page or settings page.
4343 return true;
4346 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4347 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4348 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4349 return false;
4351 return true;
4354 return false;
4358 * Load the site administration tree
4360 * This function loads the site administration tree by using the lib/adminlib library functions
4362 * @param navigation_node $referencebranch A reference to a branch in the settings
4363 * navigation tree
4364 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4365 * tree and start at the beginning
4366 * @return mixed A key to access the admin tree by
4368 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4369 global $CFG;
4371 // Check if we are just starting to generate this navigation.
4372 if ($referencebranch === null) {
4374 // Require the admin lib then get an admin structure
4375 if (!function_exists('admin_get_root')) {
4376 require_once($CFG->dirroot.'/lib/adminlib.php');
4378 $adminroot = admin_get_root(false, false);
4379 // This is the active section identifier
4380 $this->adminsection = $this->page->url->param('section');
4382 // Disable the navigation from automatically finding the active node
4383 navigation_node::$autofindactive = false;
4384 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4385 foreach ($adminroot->children as $adminbranch) {
4386 $this->load_administration_settings($referencebranch, $adminbranch);
4388 navigation_node::$autofindactive = true;
4390 // Use the admin structure to locate the active page
4391 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4392 $currentnode = $this;
4393 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4394 $currentnode = $currentnode->get($pathkey);
4396 if ($currentnode) {
4397 $currentnode->make_active();
4399 } else {
4400 $this->scan_for_active_node($referencebranch);
4402 return $referencebranch;
4403 } else if ($adminbranch->check_access()) {
4404 // We have a reference branch that we can access and is not hidden `hurrah`
4405 // Now we need to display it and any children it may have
4406 $url = null;
4407 $icon = null;
4409 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) {
4410 if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4411 $url = null;
4412 } else {
4413 $url = $adminbranch->get_settings_page_url();
4417 // Add the branch
4418 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4420 if ($adminbranch->is_hidden()) {
4421 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4422 $reference->add_class('hidden');
4423 } else {
4424 $reference->display = false;
4428 // Check if we are generating the admin notifications and whether notificiations exist
4429 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4430 $reference->add_class('criticalnotification');
4432 // Check if this branch has children
4433 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4434 foreach ($adminbranch->children as $branch) {
4435 // Generate the child branches as well now using this branch as the reference
4436 $this->load_administration_settings($reference, $branch);
4438 } else {
4439 $reference->icon = new pix_icon('i/settings', '');
4445 * This function recursivily scans nodes until it finds the active node or there
4446 * are no more nodes.
4447 * @param navigation_node $node
4449 protected function scan_for_active_node(navigation_node $node) {
4450 if (!$node->check_if_active() && $node->children->count()>0) {
4451 foreach ($node->children as &$child) {
4452 $this->scan_for_active_node($child);
4458 * Gets a navigation node given an array of keys that represent the path to
4459 * the desired node.
4461 * @param array $path
4462 * @return navigation_node|false
4464 protected function get_by_path(array $path) {
4465 $node = $this->get(array_shift($path));
4466 foreach ($path as $key) {
4467 $node->get($key);
4469 return $node;
4473 * This function loads the course settings that are available for the user
4475 * @param bool $forceopen If set to true the course node will be forced open
4476 * @return navigation_node|false
4478 protected function load_course_settings($forceopen = false) {
4479 global $CFG, $USER;
4480 require_once($CFG->dirroot . '/course/lib.php');
4482 $course = $this->page->course;
4483 $coursecontext = context_course::instance($course->id);
4484 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4486 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4488 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4489 if ($forceopen) {
4490 $coursenode->force_open();
4494 if ($adminoptions->update) {
4495 // Add the course settings link
4496 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4497 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null,
4498 'editsettings', new pix_icon('i/settings', ''));
4501 if ($adminoptions->editcompletion) {
4502 // Add the course completion settings link
4503 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4504 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion',
4505 new pix_icon('i/settings', ''));
4508 if (!$adminoptions->update && $adminoptions->tags) {
4509 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4510 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4513 // add enrol nodes
4514 enrol_add_course_navigation($coursenode, $course);
4516 // Manage filters
4517 if ($adminoptions->filters) {
4518 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4519 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
4520 null, 'filtermanagement', new pix_icon('i/filter', ''));
4523 // View course reports.
4524 if ($adminoptions->reports) {
4525 $reportnav = $coursenode->add(get_string('reports'),
4526 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]),
4527 self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', ''));
4528 $coursereports = core_component::get_plugin_list('coursereport');
4529 foreach ($coursereports as $report => $dir) {
4530 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4531 if (file_exists($libfile)) {
4532 require_once($libfile);
4533 $reportfunction = $report.'_report_extend_navigation';
4534 if (function_exists($report.'_report_extend_navigation')) {
4535 $reportfunction($reportnav, $course, $coursecontext);
4540 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4541 foreach ($reports as $reportfunction) {
4542 $reportfunction($reportnav, $course, $coursecontext);
4546 // Check if we can view the gradebook's setup page.
4547 if ($adminoptions->gradebook) {
4548 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4549 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4550 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4553 // Add the context locking node.
4554 $this->add_context_locking_node($coursenode, $coursecontext);
4556 // Add outcome if permitted
4557 if ($adminoptions->outcomes) {
4558 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4559 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4562 //Add badges navigation
4563 if ($adminoptions->badges) {
4564 require_once($CFG->libdir .'/badgeslib.php');
4565 badges_add_course_navigation($coursenode, $course);
4568 // Backup this course
4569 if ($adminoptions->backup) {
4570 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4571 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4574 // Restore to this course
4575 if ($adminoptions->restore) {
4576 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4577 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4580 // Import data from other courses
4581 if ($adminoptions->import) {
4582 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
4583 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4586 // Copy this course.
4587 if ($adminoptions->copy) {
4588 $url = new moodle_url('/backup/copy.php', array('id' => $course->id));
4589 $coursenode->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', ''));
4592 // Reset this course
4593 if ($adminoptions->reset) {
4594 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4595 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4598 // Questions
4599 require_once($CFG->libdir . '/questionlib.php');
4600 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4602 if ($adminoptions->update) {
4603 // Repository Instances
4604 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4605 require_once($CFG->dirroot . '/repository/lib.php');
4606 $editabletypes = repository::get_editable_types($coursecontext);
4607 $haseditabletypes = !empty($editabletypes);
4608 unset($editabletypes);
4609 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4610 } else {
4611 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4613 if ($haseditabletypes) {
4614 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4615 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4619 // Manage files
4620 if ($adminoptions->files) {
4621 // hidden in new courses and courses where legacy files were turned off
4622 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4623 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4627 // Let plugins hook into course navigation.
4628 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4629 foreach ($pluginsfunction as $plugintype => $plugins) {
4630 // Ignore the report plugin as it was already loaded above.
4631 if ($plugintype == 'report') {
4632 continue;
4634 foreach ($plugins as $pluginfunction) {
4635 $pluginfunction($coursenode, $course, $coursecontext);
4639 // Prepare data for course content download functionality if it is enabled.
4640 // Will only be included here if the action menu is already in use, otherwise a button will be added to the UI elsewhere.
4641 if (\core\content::can_export_context($coursecontext, $USER) && !empty($coursenode->get_children_key_list())) {
4642 $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext);
4643 $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes);
4645 $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download',
4646 new pix_icon('t/download', ''));
4649 // Return we are done
4650 return $coursenode;
4654 * This function calls the module function to inject module settings into the
4655 * settings navigation tree.
4657 * This only gets called if there is a corrosponding function in the modules
4658 * lib file.
4660 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4662 * @return navigation_node|false
4664 protected function load_module_settings() {
4665 global $CFG;
4667 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4668 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4669 $this->page->set_cm($cm, $this->page->course);
4672 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4673 if (file_exists($file)) {
4674 require_once($file);
4677 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4678 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4679 $modulenode->force_open();
4681 // Settings for the module
4682 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4683 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4684 $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
4686 // Assign local roles
4687 if (count(get_assignable_roles($this->page->cm->context))>0) {
4688 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4689 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
4691 // Override roles
4692 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4693 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4694 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
4696 // Check role permissions
4697 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4698 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4699 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
4702 // Add the context locking node.
4703 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4705 // Manage filters
4706 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4707 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4708 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
4710 // Add reports
4711 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4712 foreach ($reports as $reportfunction) {
4713 $reportfunction($modulenode, $this->page->cm);
4715 // Add a backup link
4716 $featuresfunc = $this->page->activityname.'_supports';
4717 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4718 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4719 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4722 // Restore this activity
4723 $featuresfunc = $this->page->activityname.'_supports';
4724 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4725 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4726 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4729 // Allow the active advanced grading method plugin to append its settings
4730 $featuresfunc = $this->page->activityname.'_supports';
4731 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4732 require_once($CFG->dirroot.'/grade/grading/lib.php');
4733 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4734 $gradingman->extend_settings_navigation($this, $modulenode);
4737 $function = $this->page->activityname.'_extend_settings_navigation';
4738 if (function_exists($function)) {
4739 $function($this, $modulenode);
4742 // Remove the module node if there are no children.
4743 if ($modulenode->children->count() <= 0) {
4744 $modulenode->remove();
4747 return $modulenode;
4751 * Loads the user settings block of the settings nav
4753 * This function is simply works out the userid and whether we need to load
4754 * just the current users profile settings, or the current user and the user the
4755 * current user is viewing.
4757 * This function has some very ugly code to work out the user, if anyone has
4758 * any bright ideas please feel free to intervene.
4760 * @param int $courseid The course id of the current course
4761 * @return navigation_node|false
4763 protected function load_user_settings($courseid = SITEID) {
4764 global $USER, $CFG;
4766 if (isguestuser() || !isloggedin()) {
4767 return false;
4770 $navusers = $this->page->navigation->get_extending_users();
4772 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4773 $usernode = null;
4774 foreach ($this->userstoextendfor as $userid) {
4775 if ($userid == $USER->id) {
4776 continue;
4778 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4779 if (is_null($usernode)) {
4780 $usernode = $node;
4783 foreach ($navusers as $user) {
4784 if ($user->id == $USER->id) {
4785 continue;
4787 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4788 if (is_null($usernode)) {
4789 $usernode = $node;
4792 $this->generate_user_settings($courseid, $USER->id);
4793 } else {
4794 $usernode = $this->generate_user_settings($courseid, $USER->id);
4796 return $usernode;
4800 * Extends the settings navigation for the given user.
4802 * Note: This method gets called automatically if you call
4803 * $PAGE->navigation->extend_for_user($userid)
4805 * @param int $userid
4807 public function extend_for_user($userid) {
4808 global $CFG;
4810 if (!in_array($userid, $this->userstoextendfor)) {
4811 $this->userstoextendfor[] = $userid;
4812 if ($this->initialised) {
4813 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4814 $children = array();
4815 foreach ($this->children as $child) {
4816 $children[] = $child;
4818 array_unshift($children, array_pop($children));
4819 $this->children = new navigation_node_collection();
4820 foreach ($children as $child) {
4821 $this->children->add($child);
4828 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4829 * what can be shown/done
4831 * @param int $courseid The current course' id
4832 * @param int $userid The user id to load for
4833 * @param string $gstitle The string to pass to get_string for the branch title
4834 * @return navigation_node|false
4836 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4837 global $DB, $CFG, $USER, $SITE;
4839 if ($courseid != $SITE->id) {
4840 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4841 $course = $this->page->course;
4842 } else {
4843 $select = context_helper::get_preload_record_columns_sql('ctx');
4844 $sql = "SELECT c.*, $select
4845 FROM {course} c
4846 JOIN {context} ctx ON c.id = ctx.instanceid
4847 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4848 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4849 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4850 context_helper::preload_from_record($course);
4852 } else {
4853 $course = $SITE;
4856 $coursecontext = context_course::instance($course->id); // Course context
4857 $systemcontext = context_system::instance();
4858 $currentuser = ($USER->id == $userid);
4860 if ($currentuser) {
4861 $user = $USER;
4862 $usercontext = context_user::instance($user->id); // User context
4863 } else {
4864 $select = context_helper::get_preload_record_columns_sql('ctx');
4865 $sql = "SELECT u.*, $select
4866 FROM {user} u
4867 JOIN {context} ctx ON u.id = ctx.instanceid
4868 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4869 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4870 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4871 if (!$user) {
4872 return false;
4874 context_helper::preload_from_record($user);
4876 // Check that the user can view the profile
4877 $usercontext = context_user::instance($user->id); // User context
4878 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4880 if ($course->id == $SITE->id) {
4881 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4882 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4883 return false;
4885 } else {
4886 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4887 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4888 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4889 return false;
4891 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4892 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4893 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4894 if ($courseid == $this->page->course->id) {
4895 $mygroups = get_fast_modinfo($this->page->course)->groups;
4896 } else {
4897 $mygroups = groups_get_user_groups($courseid);
4899 $usergroups = groups_get_user_groups($courseid, $userid);
4900 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4901 return false;
4907 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4909 $key = $gstitle;
4910 $prefurl = new moodle_url('/user/preferences.php');
4911 if ($gstitle != 'usercurrentsettings') {
4912 $key .= $userid;
4913 $prefurl->param('userid', $userid);
4916 // Add a user setting branch.
4917 if ($gstitle == 'usercurrentsettings') {
4918 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4919 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4920 // breadcrumb.
4921 $dashboard->display = false;
4922 if (get_home_page() == HOMEPAGE_MY) {
4923 $dashboard->mainnavonly = true;
4926 $iscurrentuser = ($user->id == $USER->id);
4928 $baseargs = array('id' => $user->id);
4929 if ($course->id != $SITE->id && !$iscurrentuser) {
4930 $baseargs['course'] = $course->id;
4931 $issitecourse = false;
4932 } else {
4933 // Load all categories and get the context for the system.
4934 $issitecourse = true;
4937 // Add the user profile to the dashboard.
4938 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4939 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4941 if (!empty($CFG->navadduserpostslinks)) {
4942 // Add nodes for forum posts and discussions if the user can view either or both
4943 // There are no capability checks here as the content of the page is based
4944 // purely on the forums the current user has access too.
4945 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4946 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4947 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4948 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4951 // Add blog nodes.
4952 if (!empty($CFG->enableblogs)) {
4953 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4954 require_once($CFG->dirroot.'/blog/lib.php');
4955 // Get all options for the user.
4956 $options = blog_get_options_for_user($user);
4957 $this->cache->set('userblogoptions'.$user->id, $options);
4958 } else {
4959 $options = $this->cache->{'userblogoptions'.$user->id};
4962 if (count($options) > 0) {
4963 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4964 foreach ($options as $type => $option) {
4965 if ($type == "rss") {
4966 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4967 new pix_icon('i/rss', ''));
4968 } else {
4969 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4975 // Add the messages link.
4976 // It is context based so can appear in the user's profile and in course participants information.
4977 if (!empty($CFG->messaging)) {
4978 $messageargs = array('user1' => $USER->id);
4979 if ($USER->id != $user->id) {
4980 $messageargs['user2'] = $user->id;
4982 $url = new moodle_url('/message/index.php', $messageargs);
4983 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4986 // Add the "My private files" link.
4987 // This link doesn't have a unique display for course context so only display it under the user's profile.
4988 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4989 $url = new moodle_url('/user/files.php');
4990 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
4993 // Add a node to view the users notes if permitted.
4994 if (!empty($CFG->enablenotes) &&
4995 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4996 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4997 if ($coursecontext->instanceid != SITEID) {
4998 $url->param('course', $coursecontext->instanceid);
5000 $profilenode->add(get_string('notes', 'notes'), $url);
5003 // Show the grades node.
5004 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
5005 require_once($CFG->dirroot . '/user/lib.php');
5006 // Set the grades node to link to the "Grades" page.
5007 if ($course->id == SITEID) {
5008 $url = user_mygrades_url($user->id, $course->id);
5009 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
5010 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
5012 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
5015 // Let plugins hook into user navigation.
5016 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5017 foreach ($pluginsfunction as $plugintype => $plugins) {
5018 if ($plugintype != 'report') {
5019 foreach ($plugins as $pluginfunction) {
5020 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5025 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5026 $dashboard->add_node($usersetting);
5027 } else {
5028 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5029 $usersetting->display = false;
5031 $usersetting->id = 'usersettings';
5033 // Check if the user has been deleted.
5034 if ($user->deleted) {
5035 if (!has_capability('moodle/user:update', $coursecontext)) {
5036 // We can't edit the user so just show the user deleted message.
5037 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
5038 } else {
5039 // We can edit the user so show the user deleted message and link it to the profile.
5040 if ($course->id == $SITE->id) {
5041 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
5042 } else {
5043 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
5045 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
5047 return true;
5050 $userauthplugin = false;
5051 if (!empty($user->auth)) {
5052 $userauthplugin = get_auth_plugin($user->auth);
5055 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
5057 // Add the profile edit link.
5058 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5059 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
5060 has_capability('moodle/user:update', $systemcontext)) {
5061 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
5062 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5063 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5064 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5065 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5066 $url = $userauthplugin->edit_profile_url();
5067 if (empty($url)) {
5068 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
5070 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5075 // Change password link.
5076 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
5077 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5078 $passwordchangeurl = $userauthplugin->change_password_url();
5079 if (empty($passwordchangeurl)) {
5080 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
5082 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
5085 // Default homepage.
5086 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER));
5087 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5088 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5089 has_capability('moodle/user:editprofile', $usercontext)) {
5090 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]);
5091 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser');
5095 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5096 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5097 has_capability('moodle/user:editprofile', $usercontext)) {
5098 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
5099 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
5102 $pluginmanager = core_plugin_manager::instance();
5103 $enabled = $pluginmanager->get_enabled_plugins('mod');
5104 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5105 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5106 has_capability('moodle/user:editprofile', $usercontext)) {
5107 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
5108 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
5111 $editors = editors_get_enabled();
5112 if (count($editors) > 1) {
5113 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5114 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5115 has_capability('moodle/user:editprofile', $usercontext)) {
5116 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
5117 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
5122 // Add "Calendar preferences" link.
5123 if (isloggedin() && !isguestuser($user)) {
5124 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5125 has_capability('moodle/user:editprofile', $usercontext)) {
5126 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
5127 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
5131 // Add "Content bank preferences" link.
5132 if (isloggedin() && !isguestuser($user)) {
5133 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5134 has_capability('moodle/user:editprofile', $usercontext)) {
5135 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]);
5136 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING,
5137 null, 'contentbankpreferences');
5141 // View the roles settings.
5142 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5143 'moodle/role:manage'], $usercontext)) {
5144 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
5146 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]);
5147 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
5149 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
5151 if (!empty($assignableroles)) {
5152 $url = new moodle_url('/admin/roles/assign.php',
5153 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5154 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
5157 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
5158 $url = new moodle_url('/admin/roles/permissions.php',
5159 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5160 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5163 $url = new moodle_url('/admin/roles/check.php',
5164 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5165 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5168 // Repositories.
5169 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5170 require_once($CFG->dirroot . '/repository/lib.php');
5171 $editabletypes = repository::get_editable_types($usercontext);
5172 $haseditabletypes = !empty($editabletypes);
5173 unset($editabletypes);
5174 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5175 } else {
5176 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5178 if ($haseditabletypes) {
5179 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5180 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5181 array('contextid' => $usercontext->id)));
5184 // Portfolio.
5185 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5186 require_once($CFG->libdir . '/portfoliolib.php');
5187 if (portfolio_has_visible_instances()) {
5188 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5190 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5191 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5193 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5194 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5198 $enablemanagetokens = false;
5199 if (!empty($CFG->enablerssfeeds)) {
5200 $enablemanagetokens = true;
5201 } else if (!is_siteadmin($USER->id)
5202 && !empty($CFG->enablewebservices)
5203 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5204 $enablemanagetokens = true;
5206 // Security keys.
5207 if ($currentuser && $enablemanagetokens) {
5208 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
5209 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5212 // Messaging.
5213 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5214 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5215 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5216 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5217 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5218 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5221 // Blogs.
5222 if ($currentuser && !empty($CFG->enableblogs)) {
5223 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5224 if (has_capability('moodle/blog:view', $systemcontext)) {
5225 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5226 navigation_node::TYPE_SETTING);
5228 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5229 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5230 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5231 navigation_node::TYPE_SETTING);
5232 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5233 navigation_node::TYPE_SETTING);
5235 // Remove the blog node if empty.
5236 $blog->trim_if_empty();
5239 // Badges.
5240 if ($currentuser && !empty($CFG->enablebadges)) {
5241 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5242 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5243 $url = new moodle_url('/badges/mybadges.php');
5244 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5246 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5247 navigation_node::TYPE_SETTING);
5248 if (!empty($CFG->badges_allowexternalbackpack)) {
5249 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5250 navigation_node::TYPE_SETTING);
5254 // Let plugins hook into user settings navigation.
5255 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5256 foreach ($pluginsfunction as $plugintype => $plugins) {
5257 foreach ($plugins as $pluginfunction) {
5258 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5262 return $usersetting;
5266 * Loads block specific settings in the navigation
5268 * @return navigation_node
5270 protected function load_block_settings() {
5271 global $CFG;
5273 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5274 $blocknode->force_open();
5276 // Assign local roles
5277 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5278 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5279 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5280 'roles', new pix_icon('i/assignroles', ''));
5283 // Override roles
5284 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5285 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5286 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5287 'permissions', new pix_icon('i/permissions', ''));
5289 // Check role permissions
5290 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5291 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5292 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5293 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5296 // Add the context locking node.
5297 $this->add_context_locking_node($blocknode, $this->context);
5299 return $blocknode;
5303 * Loads category specific settings in the navigation
5305 * @return navigation_node
5307 protected function load_category_settings() {
5308 global $CFG;
5310 // We can land here while being in the context of a block, in which case we
5311 // should get the parent context which should be the category one. See self::initialise().
5312 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5313 $catcontext = $this->context->get_parent_context();
5314 } else {
5315 $catcontext = $this->context;
5318 // Let's make sure that we always have the right context when getting here.
5319 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5320 throw new coding_exception('Unexpected context while loading category settings.');
5323 $categorynodetype = navigation_node::TYPE_CONTAINER;
5324 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5325 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5326 $categorynode->force_open();
5328 if (can_edit_in_category($catcontext->instanceid)) {
5329 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5330 $editstring = get_string('managecategorythis');
5331 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', ''));
5334 if (has_capability('moodle/category:manage', $catcontext)) {
5335 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5336 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5338 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5339 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5342 // Assign local roles
5343 $assignableroles = get_assignable_roles($catcontext);
5344 if (!empty($assignableroles)) {
5345 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5346 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5349 // Override roles
5350 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5351 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5352 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5354 // Check role permissions
5355 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5356 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5357 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5358 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5361 // Add the context locking node.
5362 $this->add_context_locking_node($categorynode, $catcontext);
5364 // Cohorts
5365 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5366 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5367 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5370 // Manage filters
5371 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5372 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5373 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5376 // Restore.
5377 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5378 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5379 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5382 // Let plugins hook into category settings navigation.
5383 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5384 foreach ($pluginsfunction as $plugintype => $plugins) {
5385 foreach ($plugins as $pluginfunction) {
5386 $pluginfunction($categorynode, $catcontext);
5390 return $categorynode;
5394 * Determine whether the user is assuming another role
5396 * This function checks to see if the user is assuming another role by means of
5397 * role switching. In doing this we compare each RSW key (context path) against
5398 * the current context path. This ensures that we can provide the switching
5399 * options against both the course and any page shown under the course.
5401 * @return bool|int The role(int) if the user is in another role, false otherwise
5403 protected function in_alternative_role() {
5404 global $USER;
5405 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5406 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5407 return $USER->access['rsw'][$this->page->context->path];
5409 foreach ($USER->access['rsw'] as $key=>$role) {
5410 if (strpos($this->context->path,$key)===0) {
5411 return $role;
5415 return false;
5419 * This function loads all of the front page settings into the settings navigation.
5420 * This function is called when the user is on the front page, or $COURSE==$SITE
5421 * @param bool $forceopen (optional)
5422 * @return navigation_node
5424 protected function load_front_page_settings($forceopen = false) {
5425 global $SITE, $CFG;
5426 require_once($CFG->dirroot . '/course/lib.php');
5428 $course = clone($SITE);
5429 $coursecontext = context_course::instance($course->id); // Course context
5430 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5432 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5433 if ($forceopen) {
5434 $frontpage->force_open();
5436 $frontpage->id = 'frontpagesettings';
5438 if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) {
5440 // Add the turn on/off settings
5441 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5442 if ($this->page->user_is_editing()) {
5443 $url->param('edit', 'off');
5444 $editstring = get_string('turneditingoff');
5445 } else {
5446 $url->param('edit', 'on');
5447 $editstring = get_string('turneditingon');
5449 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5452 if ($adminoptions->update) {
5453 // Add the course settings link
5454 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5455 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5458 // add enrol nodes
5459 enrol_add_course_navigation($frontpage, $course);
5461 // Manage filters
5462 if ($adminoptions->filters) {
5463 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5464 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5467 // View course reports.
5468 if ($adminoptions->reports) {
5469 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5470 new pix_icon('i/stats', ''));
5471 $coursereports = core_component::get_plugin_list('coursereport');
5472 foreach ($coursereports as $report=>$dir) {
5473 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5474 if (file_exists($libfile)) {
5475 require_once($libfile);
5476 $reportfunction = $report.'_report_extend_navigation';
5477 if (function_exists($report.'_report_extend_navigation')) {
5478 $reportfunction($frontpagenav, $course, $coursecontext);
5483 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5484 foreach ($reports as $reportfunction) {
5485 $reportfunction($frontpagenav, $course, $coursecontext);
5489 // Backup this course
5490 if ($adminoptions->backup) {
5491 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5492 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5495 // Restore to this course
5496 if ($adminoptions->restore) {
5497 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5498 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5501 // Questions
5502 require_once($CFG->libdir . '/questionlib.php');
5503 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5505 // Manage files
5506 if ($adminoptions->files) {
5507 //hiden in new installs
5508 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5509 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5512 // Let plugins hook into frontpage navigation.
5513 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5514 foreach ($pluginsfunction as $plugintype => $plugins) {
5515 foreach ($plugins as $pluginfunction) {
5516 $pluginfunction($frontpage, $course, $coursecontext);
5520 return $frontpage;
5524 * This function gives local plugins an opportunity to modify the settings navigation.
5526 protected function load_local_plugin_settings() {
5528 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5529 $function($this, $this->context);
5534 * This function marks the cache as volatile so it is cleared during shutdown
5536 public function clear_cache() {
5537 $this->cache->volatile();
5541 * Checks to see if there are child nodes available in the specific user's preference node.
5542 * If so, then they have the appropriate permissions view this user's preferences.
5544 * @since Moodle 2.9.3
5545 * @param int $userid The user's ID.
5546 * @return bool True if child nodes exist to view, otherwise false.
5548 public function can_view_user_preferences($userid) {
5549 if (is_siteadmin()) {
5550 return true;
5552 // See if any nodes are present in the preferences section for this user.
5553 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5554 if ($preferencenode && $preferencenode->has_children()) {
5555 // Run through each child node.
5556 foreach ($preferencenode->children as $childnode) {
5557 // If the child node has children then this user has access to a link in the preferences page.
5558 if ($childnode->has_children()) {
5559 return true;
5563 // No links found for the user to access on the preferences page.
5564 return false;
5569 * Class used to populate site admin navigation for ajax.
5571 * @package core
5572 * @category navigation
5573 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5574 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5576 class settings_navigation_ajax extends settings_navigation {
5578 * Constructs the navigation for use in an AJAX request
5580 * @param moodle_page $page
5582 public function __construct(moodle_page &$page) {
5583 $this->page = $page;
5584 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5585 $this->children = new navigation_node_collection();
5586 $this->initialise();
5590 * Initialise the site admin navigation.
5592 * @return array An array of the expandable nodes
5594 public function initialise() {
5595 if ($this->initialised || during_initial_install()) {
5596 return false;
5598 $this->context = $this->page->context;
5599 $this->load_administration_settings();
5601 // Check if local plugins is adding node to site admin.
5602 $this->load_local_plugin_settings();
5604 $this->initialised = true;
5609 * Simple class used to output a navigation branch in XML
5611 * @package core
5612 * @category navigation
5613 * @copyright 2009 Sam Hemelryk
5614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5616 class navigation_json {
5617 /** @var array An array of different node types */
5618 protected $nodetype = array('node','branch');
5619 /** @var array An array of node keys and types */
5620 protected $expandable = array();
5622 * Turns a branch and all of its children into XML
5624 * @param navigation_node $branch
5625 * @return string XML string
5627 public function convert($branch) {
5628 $xml = $this->convert_child($branch);
5629 return $xml;
5632 * Set the expandable items in the array so that we have enough information
5633 * to attach AJAX events
5634 * @param array $expandable
5636 public function set_expandable($expandable) {
5637 foreach ($expandable as $node) {
5638 $this->expandable[$node['key'].':'.$node['type']] = $node;
5642 * Recusively converts a child node and its children to XML for output
5644 * @param navigation_node $child The child to convert
5645 * @param int $depth Pointlessly used to track the depth of the XML structure
5646 * @return string JSON
5648 protected function convert_child($child, $depth=1) {
5649 if (!$child->display) {
5650 return '';
5652 $attributes = array();
5653 $attributes['id'] = $child->id;
5654 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5655 $attributes['type'] = $child->type;
5656 $attributes['key'] = $child->key;
5657 $attributes['class'] = $child->get_css_type();
5658 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5660 if ($child->icon instanceof pix_icon) {
5661 $attributes['icon'] = array(
5662 'component' => $child->icon->component,
5663 'pix' => $child->icon->pix,
5665 foreach ($child->icon->attributes as $key=>$value) {
5666 if ($key == 'class') {
5667 $attributes['icon']['classes'] = explode(' ', $value);
5668 } else if (!array_key_exists($key, $attributes['icon'])) {
5669 $attributes['icon'][$key] = $value;
5673 } else if (!empty($child->icon)) {
5674 $attributes['icon'] = (string)$child->icon;
5677 if ($child->forcetitle || $child->title !== $child->text) {
5678 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5680 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5681 $attributes['expandable'] = $child->key;
5682 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5685 if (count($child->classes)>0) {
5686 $attributes['class'] .= ' '.join(' ',$child->classes);
5688 if (is_string($child->action)) {
5689 $attributes['link'] = $child->action;
5690 } else if ($child->action instanceof moodle_url) {
5691 $attributes['link'] = $child->action->out();
5692 } else if ($child->action instanceof action_link) {
5693 $attributes['link'] = $child->action->url->out();
5695 $attributes['hidden'] = ($child->hidden);
5696 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5697 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5699 if ($child->children->count() > 0) {
5700 $attributes['children'] = array();
5701 foreach ($child->children as $subchild) {
5702 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5706 if ($depth > 1) {
5707 return $attributes;
5708 } else {
5709 return json_encode($attributes);
5715 * The cache class used by global navigation and settings navigation.
5717 * It is basically an easy access point to session with a bit of smarts to make
5718 * sure that the information that is cached is valid still.
5720 * Example use:
5721 * <code php>
5722 * if (!$cache->viewdiscussion()) {
5723 * // Code to do stuff and produce cachable content
5724 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5726 * $content = $cache->viewdiscussion;
5727 * </code>
5729 * @package core
5730 * @category navigation
5731 * @copyright 2009 Sam Hemelryk
5732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5734 class navigation_cache {
5735 /** @var int represents the time created */
5736 protected $creation;
5737 /** @var array An array of session keys */
5738 protected $session;
5740 * The string to use to segregate this particular cache. It can either be
5741 * unique to start a fresh cache or if you want to share a cache then make
5742 * it the string used in the original cache.
5743 * @var string
5745 protected $area;
5746 /** @var int a time that the information will time out */
5747 protected $timeout;
5748 /** @var stdClass The current context */
5749 protected $currentcontext;
5750 /** @var int cache time information */
5751 const CACHETIME = 0;
5752 /** @var int cache user id */
5753 const CACHEUSERID = 1;
5754 /** @var int cache value */
5755 const CACHEVALUE = 2;
5756 /** @var null|array An array of navigation cache areas to expire on shutdown */
5757 public static $volatilecaches;
5760 * Contructor for the cache. Requires two arguments
5762 * @param string $area The string to use to segregate this particular cache
5763 * it can either be unique to start a fresh cache or if you want
5764 * to share a cache then make it the string used in the original
5765 * cache
5766 * @param int $timeout The number of seconds to time the information out after
5768 public function __construct($area, $timeout=1800) {
5769 $this->creation = time();
5770 $this->area = $area;
5771 $this->timeout = time() - $timeout;
5772 if (rand(0,100) === 0) {
5773 $this->garbage_collection();
5778 * Used to set up the cache within the SESSION.
5780 * This is called for each access and ensure that we don't put anything into the session before
5781 * it is required.
5783 protected function ensure_session_cache_initialised() {
5784 global $SESSION;
5785 if (empty($this->session)) {
5786 if (!isset($SESSION->navcache)) {
5787 $SESSION->navcache = new stdClass;
5789 if (!isset($SESSION->navcache->{$this->area})) {
5790 $SESSION->navcache->{$this->area} = array();
5792 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5797 * Magic Method to retrieve something by simply calling using = cache->key
5799 * @param mixed $key The identifier for the information you want out again
5800 * @return void|mixed Either void or what ever was put in
5802 public function __get($key) {
5803 if (!$this->cached($key)) {
5804 return;
5806 $information = $this->session[$key][self::CACHEVALUE];
5807 return unserialize($information);
5811 * Magic method that simply uses {@link set();} to store something in the cache
5813 * @param string|int $key
5814 * @param mixed $information
5816 public function __set($key, $information) {
5817 $this->set($key, $information);
5821 * Sets some information against the cache (session) for later retrieval
5823 * @param string|int $key
5824 * @param mixed $information
5826 public function set($key, $information) {
5827 global $USER;
5828 $this->ensure_session_cache_initialised();
5829 $information = serialize($information);
5830 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5833 * Check the existence of the identifier in the cache
5835 * @param string|int $key
5836 * @return bool
5838 public function cached($key) {
5839 global $USER;
5840 $this->ensure_session_cache_initialised();
5841 if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) {
5842 return false;
5844 return true;
5847 * Compare something to it's equivilant in the cache
5849 * @param string $key
5850 * @param mixed $value
5851 * @param bool $serialise Whether to serialise the value before comparison
5852 * this should only be set to false if the value is already
5853 * serialised
5854 * @return bool If the value is the same false if it is not set or doesn't match
5856 public function compare($key, $value, $serialise = true) {
5857 if ($this->cached($key)) {
5858 if ($serialise) {
5859 $value = serialize($value);
5861 if ($this->session[$key][self::CACHEVALUE] === $value) {
5862 return true;
5865 return false;
5868 * Wipes the entire cache, good to force regeneration
5870 public function clear() {
5871 global $SESSION;
5872 unset($SESSION->navcache);
5873 $this->session = null;
5876 * Checks all cache entries and removes any that have expired, good ole cleanup
5878 protected function garbage_collection() {
5879 if (empty($this->session)) {
5880 return true;
5882 foreach ($this->session as $key=>$cachedinfo) {
5883 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5884 unset($this->session[$key]);
5890 * Marks the cache as being volatile (likely to change)
5892 * Any caches marked as volatile will be destroyed at the on shutdown by
5893 * {@link navigation_node::destroy_volatile_caches()} which is registered
5894 * as a shutdown function if any caches are marked as volatile.
5896 * @param bool $setting True to destroy the cache false not too
5898 public function volatile($setting = true) {
5899 if (self::$volatilecaches===null) {
5900 self::$volatilecaches = array();
5901 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5904 if ($setting) {
5905 self::$volatilecaches[$this->area] = $this->area;
5906 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5907 unset(self::$volatilecaches[$this->area]);
5912 * Destroys all caches marked as volatile
5914 * This function is static and works in conjunction with the static volatilecaches
5915 * property of navigation cache.
5916 * Because this function is static it manually resets the cached areas back to an
5917 * empty array.
5919 public static function destroy_volatile_caches() {
5920 global $SESSION;
5921 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5922 foreach (self::$volatilecaches as $area) {
5923 $SESSION->navcache->{$area} = array();
5925 } else {
5926 $SESSION->navcache = new stdClass;