Automatically generated installer lang files
[moodle.git] / lib / navigationlib.php
blobf3547a6b9402951d618f0e8c7ecbabcb8e4652c4
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 use core_contentbank\contentbank;
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * The name that will be used to separate the navigation cache within SESSION
33 define('NAVIGATION_CACHE_NAME', 'navigation');
34 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
36 /**
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
45 * @package core
46 * @category navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node implements renderable {
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF = 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH = 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN = null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE = 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM = 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY = 10;
63 /** var int Category displayed in MyHome navigation node */
64 const TYPE_MY_CATEGORY = 11;
65 /** @var int Course node type 20 */
66 const TYPE_COURSE = 20;
67 /** @var int Course Structure node type 30 */
68 const TYPE_SECTION = 30;
69 /** @var int Activity node type, e.g. Forum, Quiz 40 */
70 const TYPE_ACTIVITY = 40;
71 /** @var int Resource node type, e.g. Link to a file, or label 50 */
72 const TYPE_RESOURCE = 50;
73 /** @var int A custom node type, default when adding without specifing type 60 */
74 const TYPE_CUSTOM = 60;
75 /** @var int Setting node type, used only within settings nav 70 */
76 const TYPE_SETTING = 70;
77 /** @var int site admin branch node type, used only within settings nav 71 */
78 const TYPE_SITE_ADMIN = 71;
79 /** @var int Setting node type, used only within settings nav 80 */
80 const TYPE_USER = 80;
81 /** @var int Setting node type, used for containers of no importance 90 */
82 const TYPE_CONTAINER = 90;
83 /** var int Course the current user is not enrolled in */
84 const COURSE_OTHER = 0;
85 /** var int Course the current user is enrolled in but not viewing */
86 const COURSE_MY = 1;
87 /** var int Course the current user is currently viewing */
88 const COURSE_CURRENT = 2;
89 /** var string The course index page navigation node */
90 const COURSE_INDEX_PAGE = 'courseindexpage';
92 /** @var int Parameter to aid the coder in tracking [optional] */
93 public $id = null;
94 /** @var string|int The identifier for the node, used to retrieve the node */
95 public $key = null;
96 /** @var string The text to use for the node */
97 public $text = null;
98 /** @var string Short text to use if requested [optional] */
99 public $shorttext = null;
100 /** @var string The title attribute for an action if one is defined */
101 public $title = null;
102 /** @var string A string that can be used to build a help button */
103 public $helpbutton = null;
104 /** @var moodle_url|action_link|null An action for the node (link) */
105 public $action = null;
106 /** @var pix_icon The path to an icon to use for this node */
107 public $icon = null;
108 /** @var int See TYPE_* constants defined for this class */
109 public $type = self::TYPE_UNKNOWN;
110 /** @var int See NODETYPE_* constants defined for this class */
111 public $nodetype = self::NODETYPE_LEAF;
112 /** @var bool If set to true the node will be collapsed by default */
113 public $collapse = false;
114 /** @var bool If set to true the node will be expanded by default */
115 public $forceopen = false;
116 /** @var array An array of CSS classes for the node */
117 public $classes = array();
118 /** @var navigation_node_collection An array of child nodes */
119 public $children = array();
120 /** @var bool If set to true the node will be recognised as active */
121 public $isactive = false;
122 /** @var bool If set to true the node will be dimmed */
123 public $hidden = false;
124 /** @var bool If set to false the node will not be displayed */
125 public $display = true;
126 /** @var bool If set to true then an HR will be printed before the node */
127 public $preceedwithhr = false;
128 /** @var bool If set to true the the navigation bar should ignore this node */
129 public $mainnavonly = false;
130 /** @var bool If set to true a title will be added to the action no matter what */
131 public $forcetitle = false;
132 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
133 public $parent = null;
134 /** @var bool Override to not display the icon even if one is provided **/
135 public $hideicon = false;
136 /** @var bool Set to true if we KNOW that this node can be expanded. */
137 public $isexpandable = false;
138 /** @var array */
139 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
140 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
141 90 => 'container');
142 /** @var moodle_url */
143 protected static $fullmeurl = null;
144 /** @var bool toogles auto matching of active node */
145 public static $autofindactive = true;
146 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
147 protected static $loadadmintree = false;
148 /** @var mixed If set to an int, that section will be included even if it has no activities */
149 public $includesectionnum = false;
150 /** @var bool does the node need to be loaded via ajax */
151 public $requiresajaxloading = false;
152 /** @var bool If set to true this node will be added to the "flat" navigation */
153 public $showinflatnavigation = false;
154 /** @var bool If set to true this node will be forced into a "more" menu whenever possible */
155 public $forceintomoremenu = false;
156 /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */
157 public $showinsecondarynavigation = true;
158 /** @var bool If set to true the children of this node will be displayed within a submenu when applicable */
159 public $showchildreninsubmenu = false;
162 * Constructs a new navigation_node
164 * @param array|string $properties Either an array of properties or a string to use
165 * as the text for the node
167 public function __construct($properties) {
168 if (is_array($properties)) {
169 // Check the array for each property that we allow to set at construction.
170 // text - The main content for the node
171 // shorttext - A short text if required for the node
172 // icon - The icon to display for the node
173 // type - The type of the node
174 // key - The key to use to identify the node
175 // parent - A reference to the nodes parent
176 // action - The action to attribute to this node, usually a URL to link to
177 if (array_key_exists('text', $properties)) {
178 $this->text = $properties['text'];
180 if (array_key_exists('shorttext', $properties)) {
181 $this->shorttext = $properties['shorttext'];
183 if (!array_key_exists('icon', $properties)) {
184 $properties['icon'] = new pix_icon('i/navigationitem', '');
186 $this->icon = $properties['icon'];
187 if ($this->icon instanceof pix_icon) {
188 if (empty($this->icon->attributes['class'])) {
189 $this->icon->attributes['class'] = 'navicon';
190 } else {
191 $this->icon->attributes['class'] .= ' navicon';
194 if (array_key_exists('type', $properties)) {
195 $this->type = $properties['type'];
196 } else {
197 $this->type = self::TYPE_CUSTOM;
199 if (array_key_exists('key', $properties)) {
200 $this->key = $properties['key'];
202 // This needs to happen last because of the check_if_active call that occurs
203 if (array_key_exists('action', $properties)) {
204 $this->action = $properties['action'];
205 if (is_string($this->action)) {
206 $this->action = new moodle_url($this->action);
208 if (self::$autofindactive) {
209 $this->check_if_active();
212 if (array_key_exists('parent', $properties)) {
213 $this->set_parent($properties['parent']);
215 } else if (is_string($properties)) {
216 $this->text = $properties;
218 if ($this->text === null) {
219 throw new coding_exception('You must set the text for the node when you create it.');
221 // Instantiate a new navigation node collection for this nodes children
222 $this->children = new navigation_node_collection();
226 * Checks if this node is the active node.
228 * This is determined by comparing the action for the node against the
229 * defined URL for the page. A match will see this node marked as active.
231 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
232 * @return bool
234 public function check_if_active($strength=URL_MATCH_EXACT) {
235 global $FULLME, $PAGE;
236 // Set fullmeurl if it hasn't already been set
237 if (self::$fullmeurl == null) {
238 if ($PAGE->has_set_url()) {
239 self::override_active_url(new moodle_url($PAGE->url));
240 } else {
241 self::override_active_url(new moodle_url($FULLME));
245 // Compare the action of this node against the fullmeurl
246 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
247 $this->make_active();
248 return true;
250 return false;
254 * True if this nav node has siblings in the tree.
256 * @return bool
258 public function has_siblings() {
259 if (empty($this->parent) || empty($this->parent->children)) {
260 return false;
262 if ($this->parent->children instanceof navigation_node_collection) {
263 $count = $this->parent->children->count();
264 } else {
265 $count = count($this->parent->children);
267 return ($count > 1);
271 * Get a list of sibling navigation nodes at the same level as this one.
273 * @return bool|array of navigation_node
275 public function get_siblings() {
276 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
277 // the in-page links or the breadcrumb links.
278 $siblings = false;
280 if ($this->has_siblings()) {
281 $siblings = [];
282 foreach ($this->parent->children as $child) {
283 if ($child->display) {
284 $siblings[] = $child;
288 return $siblings;
292 * This sets the URL that the URL of new nodes get compared to when locating
293 * the active node.
295 * The active node is the node that matches the URL set here. By default this
296 * is either $PAGE->url or if that hasn't been set $FULLME.
298 * @param moodle_url $url The url to use for the fullmeurl.
299 * @param bool $loadadmintree use true if the URL point to administration tree
301 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
302 // Clone the URL, in case the calling script changes their URL later.
303 self::$fullmeurl = new moodle_url($url);
304 // True means we do not want AJAX loaded admin tree, required for all admin pages.
305 if ($loadadmintree) {
306 // Do not change back to false if already set.
307 self::$loadadmintree = true;
312 * Use when page is linked from the admin tree,
313 * if not used navigation could not find the page using current URL
314 * because the tree is not fully loaded.
316 public static function require_admin_tree() {
317 self::$loadadmintree = true;
321 * Creates a navigation node, ready to add it as a child using add_node
322 * function. (The created node needs to be added before you can use it.)
323 * @param string $text
324 * @param moodle_url|action_link $action
325 * @param int $type
326 * @param string $shorttext
327 * @param string|int $key
328 * @param pix_icon $icon
329 * @return navigation_node
331 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
332 $shorttext=null, $key=null, pix_icon $icon=null) {
333 if ($action && !($action instanceof moodle_url || $action instanceof action_link)) {
334 debugging(
335 "It is required that the action provided be either an action_url|moodle_url." .
336 " Please update your definition.", E_NOTICE);
338 // Properties array used when creating the new navigation node
339 $itemarray = array(
340 'text' => $text,
341 'type' => $type
343 // Set the action if one was provided
344 if ($action!==null) {
345 $itemarray['action'] = $action;
347 // Set the shorttext if one was provided
348 if ($shorttext!==null) {
349 $itemarray['shorttext'] = $shorttext;
351 // Set the icon if one was provided
352 if ($icon!==null) {
353 $itemarray['icon'] = $icon;
355 // Set the key
356 $itemarray['key'] = $key;
357 // Construct and return
358 return new navigation_node($itemarray);
362 * Adds a navigation node as a child of this node.
364 * @param string $text
365 * @param moodle_url|action_link $action
366 * @param int $type
367 * @param string $shorttext
368 * @param string|int $key
369 * @param pix_icon $icon
370 * @return navigation_node
372 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
373 if ($action && is_string($action)) {
374 $action = new moodle_url($action);
376 // Create child node
377 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
379 // Add the child to end and return
380 return $this->add_node($childnode);
384 * Adds a navigation node as a child of this one, given a $node object
385 * created using the create function.
386 * @param navigation_node $childnode Node to add
387 * @param string $beforekey
388 * @return navigation_node The added node
390 public function add_node(navigation_node $childnode, $beforekey=null) {
391 // First convert the nodetype for this node to a branch as it will now have children
392 if ($this->nodetype !== self::NODETYPE_BRANCH) {
393 $this->nodetype = self::NODETYPE_BRANCH;
395 // Set the parent to this node
396 $childnode->set_parent($this);
398 // Default the key to the number of children if not provided
399 if ($childnode->key === null) {
400 $childnode->key = $this->children->count();
403 // Add the child using the navigation_node_collections add method
404 $node = $this->children->add($childnode, $beforekey);
406 // If added node is a category node or the user is logged in and it's a course
407 // then mark added node as a branch (makes it expandable by AJAX)
408 $type = $childnode->type;
409 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
410 ($type === self::TYPE_SITE_ADMIN)) {
411 $node->nodetype = self::NODETYPE_BRANCH;
413 // If this node is hidden mark it's children as hidden also
414 if ($this->hidden) {
415 $node->hidden = true;
417 // Return added node (reference returned by $this->children->add()
418 return $node;
422 * Return a list of all the keys of all the child nodes.
423 * @return array the keys.
425 public function get_children_key_list() {
426 return $this->children->get_key_list();
430 * Searches for a node of the given type with the given key.
432 * This searches this node plus all of its children, and their children....
433 * If you know the node you are looking for is a child of this node then please
434 * use the get method instead.
436 * @param int|string $key The key of the node we are looking for
437 * @param int $type One of navigation_node::TYPE_*
438 * @return navigation_node|false
440 public function find($key, $type) {
441 return $this->children->find($key, $type);
445 * Walk the tree building up a list of all the flat navigation nodes.
447 * @deprecated since Moodle 4.0
448 * @param flat_navigation $nodes List of the found flat navigation nodes.
449 * @param boolean $showdivider Show a divider before the first node.
450 * @param string $label A label for the collection of navigation links.
452 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
453 debugging("Function has been deprecated with the deprecation of the flat_navigation class.");
454 if ($this->showinflatnavigation) {
455 $indent = 0;
456 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
457 $indent = 1;
459 $flat = new flat_navigation_node($this, $indent);
460 $flat->set_showdivider($showdivider, $label);
461 $nodes->add($flat);
463 foreach ($this->children as $child) {
464 $child->build_flat_navigation_list($nodes, false);
469 * Get the child of this node that has the given key + (optional) type.
471 * If you are looking for a node and want to search all children + their children
472 * then please use the find method instead.
474 * @param int|string $key The key of the node we are looking for
475 * @param int $type One of navigation_node::TYPE_*
476 * @return navigation_node|false
478 public function get($key, $type=null) {
479 return $this->children->get($key, $type);
483 * Removes this node.
485 * @return bool
487 public function remove() {
488 return $this->parent->children->remove($this->key, $this->type);
492 * Checks if this node has or could have any children
494 * @return bool Returns true if it has children or could have (by AJAX expansion)
496 public function has_children() {
497 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
501 * Marks this node as active and forces it open.
503 * Important: If you are here because you need to mark a node active to get
504 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
505 * You can use it to specify a different URL to match the active navigation node on
506 * rather than having to locate and manually mark a node active.
508 public function make_active() {
509 $this->isactive = true;
510 $this->add_class('active_tree_node');
511 $this->force_open();
512 if ($this->parent !== null) {
513 $this->parent->make_inactive();
518 * Marks a node as inactive and recusised back to the base of the tree
519 * doing the same to all parents.
521 public function make_inactive() {
522 $this->isactive = false;
523 $this->remove_class('active_tree_node');
524 if ($this->parent !== null) {
525 $this->parent->make_inactive();
530 * Forces this node to be open and at the same time forces open all
531 * parents until the root node.
533 * Recursive.
535 public function force_open() {
536 $this->forceopen = true;
537 if ($this->parent !== null) {
538 $this->parent->force_open();
543 * Adds a CSS class to this node.
545 * @param string $class
546 * @return bool
548 public function add_class($class) {
549 if (!in_array($class, $this->classes)) {
550 $this->classes[] = $class;
552 return true;
556 * Removes a CSS class from this node.
558 * @param string $class
559 * @return bool True if the class was successfully removed.
561 public function remove_class($class) {
562 if (in_array($class, $this->classes)) {
563 $key = array_search($class,$this->classes);
564 if ($key!==false) {
565 // Remove the class' array element.
566 unset($this->classes[$key]);
567 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
568 $this->classes = array_values($this->classes);
570 return true;
573 return false;
577 * Sets the title for this node and forces Moodle to utilise it.
578 * @param string $title
580 public function title($title) {
581 $this->title = $title;
582 $this->forcetitle = true;
586 * Resets the page specific information on this node if it is being unserialised.
588 public function __wakeup(){
589 $this->forceopen = false;
590 $this->isactive = false;
591 $this->remove_class('active_tree_node');
595 * Checks if this node or any of its children contain the active node.
597 * Recursive.
599 * @return bool
601 public function contains_active_node() {
602 if ($this->isactive) {
603 return true;
604 } else {
605 foreach ($this->children as $child) {
606 if ($child->isactive || $child->contains_active_node()) {
607 return true;
611 return false;
615 * To better balance the admin tree, we want to group all the short top branches together.
617 * This means < 8 nodes and no subtrees.
619 * @return bool
621 public function is_short_branch() {
622 $limit = 8;
623 if ($this->children->count() >= $limit) {
624 return false;
626 foreach ($this->children as $child) {
627 if ($child->has_children()) {
628 return false;
631 return true;
635 * Finds the active node.
637 * Searches this nodes children plus all of the children for the active node
638 * and returns it if found.
640 * Recursive.
642 * @return navigation_node|false
644 public function find_active_node() {
645 if ($this->isactive) {
646 return $this;
647 } else {
648 foreach ($this->children as &$child) {
649 $outcome = $child->find_active_node();
650 if ($outcome !== false) {
651 return $outcome;
655 return false;
659 * Searches all children for the best matching active node
660 * @param int $strength The url match to be made.
661 * @return navigation_node|false
663 public function search_for_active_node($strength = URL_MATCH_BASE) {
664 if ($this->check_if_active($strength)) {
665 return $this;
666 } else {
667 foreach ($this->children as &$child) {
668 $outcome = $child->search_for_active_node($strength);
669 if ($outcome !== false) {
670 return $outcome;
674 return false;
678 * Gets the content for this node.
680 * @param bool $shorttext If true shorttext is used rather than the normal text
681 * @return string
683 public function get_content($shorttext=false) {
684 $navcontext = \context_helper::get_navigation_filter_context(null);
685 $options = !empty($navcontext) ? ['context' => $navcontext] : null;
687 if ($shorttext && $this->shorttext!==null) {
688 return format_string($this->shorttext, null, $options);
689 } else {
690 return format_string($this->text, null, $options);
695 * Gets the title to use for this node.
697 * @return string
699 public function get_title() {
700 if ($this->forcetitle || $this->action != null){
701 return $this->title;
702 } else {
703 return '';
708 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
710 * @return boolean
712 public function has_action() {
713 return !empty($this->action);
717 * Used to easily determine if the action is an internal link.
719 * @return bool
721 public function has_internal_action(): bool {
722 global $CFG;
723 if ($this->has_action()) {
724 $url = $this->action();
725 if ($this->action() instanceof \action_link) {
726 $url = $this->action()->url;
729 if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) {
730 return true;
733 return false;
737 * Used to easily determine if this link in the breadcrumbs is hidden.
739 * @return boolean
741 public function is_hidden() {
742 return $this->hidden;
746 * Gets the CSS class to add to this node to describe its type
748 * @return string
750 public function get_css_type() {
751 if (array_key_exists($this->type, $this->namedtypes)) {
752 return 'type_'.$this->namedtypes[$this->type];
754 return 'type_unknown';
758 * Finds all nodes that are expandable by AJAX
760 * @param array $expandable An array by reference to populate with expandable nodes.
762 public function find_expandable(array &$expandable) {
763 foreach ($this->children as &$child) {
764 if ($child->display && $child->has_children() && $child->children->count() == 0) {
765 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
766 $this->add_class('canexpand');
767 $child->requiresajaxloading = true;
768 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
770 $child->find_expandable($expandable);
775 * Finds all nodes of a given type (recursive)
777 * @param int $type One of navigation_node::TYPE_*
778 * @return array
780 public function find_all_of_type($type) {
781 $nodes = $this->children->type($type);
782 foreach ($this->children as &$node) {
783 $childnodes = $node->find_all_of_type($type);
784 $nodes = array_merge($nodes, $childnodes);
786 return $nodes;
790 * Removes this node if it is empty
792 public function trim_if_empty() {
793 if ($this->children->count() == 0) {
794 $this->remove();
799 * Creates a tab representation of this nodes children that can be used
800 * with print_tabs to produce the tabs on a page.
802 * call_user_func_array('print_tabs', $node->get_tabs_array());
804 * @param array $inactive
805 * @param bool $return
806 * @return array Array (tabs, selected, inactive, activated, return)
808 public function get_tabs_array(array $inactive=array(), $return=false) {
809 $tabs = array();
810 $rows = array();
811 $selected = null;
812 $activated = array();
813 foreach ($this->children as $node) {
814 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
815 if ($node->contains_active_node()) {
816 if ($node->children->count() > 0) {
817 $activated[] = $node->key;
818 foreach ($node->children as $child) {
819 if ($child->contains_active_node()) {
820 $selected = $child->key;
822 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
824 } else {
825 $selected = $node->key;
829 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
833 * Sets the parent for this node and if this node is active ensures that the tree is properly
834 * adjusted as well.
836 * @param navigation_node $parent
838 public function set_parent(navigation_node $parent) {
839 // Set the parent (thats the easy part)
840 $this->parent = $parent;
841 // Check if this node is active (this is checked during construction)
842 if ($this->isactive) {
843 // Force all of the parent nodes open so you can see this node
844 $this->parent->force_open();
845 // Make all parents inactive so that its clear where we are.
846 $this->parent->make_inactive();
851 * Hides the node and any children it has.
853 * @since Moodle 2.5
854 * @param array $typestohide Optional. An array of node types that should be hidden.
855 * If null all nodes will be hidden.
856 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
857 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
859 public function hide(array $typestohide = null) {
860 if ($typestohide === null || in_array($this->type, $typestohide)) {
861 $this->display = false;
862 if ($this->has_children()) {
863 foreach ($this->children as $child) {
864 $child->hide($typestohide);
871 * Get the action url for this navigation node.
872 * Called from templates.
874 * @since Moodle 3.2
876 public function action() {
877 if ($this->action instanceof moodle_url) {
878 return $this->action;
879 } else if ($this->action instanceof action_link) {
880 return $this->action->url;
882 return $this->action;
886 * Return an array consisting of the additional attributes for the action url.
888 * @return array Formatted array to parse in a template
890 public function actionattributes() {
891 if ($this->action instanceof action_link) {
892 return array_map(function($key, $value) {
893 return [
894 'name' => $key,
895 'value' => $value
897 }, array_keys($this->action->attributes), $this->action->attributes);
900 return [];
904 * Check whether the node's action is of type action_link.
906 * @return bool
908 public function is_action_link() {
909 return $this->action instanceof action_link;
913 * Return an array consisting of the actions for the action link.
915 * @return array Formatted array to parse in a template
917 public function action_link_actions() {
918 global $PAGE;
920 if (!$this->is_action_link()) {
921 return [];
924 $actionid = $this->action->attributes['id'];
925 $actionsdata = array_map(function($action) use ($PAGE, $actionid) {
926 $data = $action->export_for_template($PAGE->get_renderer('core'));
927 $data->id = $actionid;
928 return $data;
929 }, !empty($this->action->actions) ? $this->action->actions : []);
931 return ['actions' => $actionsdata];
935 * Sets whether the node and its children should be added into a "more" menu whenever possible.
937 * @param bool $forceintomoremenu
939 public function set_force_into_more_menu(bool $forceintomoremenu = false) {
940 $this->forceintomoremenu = $forceintomoremenu;
941 foreach ($this->children as $child) {
942 $child->set_force_into_more_menu($forceintomoremenu);
947 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable.
949 * @param bool $show
951 public function set_show_in_secondary_navigation(bool $show = true) {
952 $this->showinsecondarynavigation = $show;
953 foreach ($this->children as $child) {
954 $child->set_show_in_secondary_navigation($show);
959 * Add the menu item to handle locking and unlocking of a conext.
961 * @param \navigation_node $node Node to add
962 * @param \context $context The context to be locked
964 protected function add_context_locking_node(\navigation_node $node, \context $context) {
965 global $CFG;
966 // Manage context locking.
967 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
968 $parentcontext = $context->get_parent_context();
969 if (empty($parentcontext) || !$parentcontext->locked) {
970 if ($context->locked) {
971 $lockicon = 'i/unlock';
972 $lockstring = get_string('managecontextunlock', 'admin');
973 } else {
974 $lockicon = 'i/lock';
975 $lockstring = get_string('managecontextlock', 'admin');
977 $node->add(
978 $lockstring,
979 new moodle_url(
980 '/admin/lock.php',
982 'id' => $context->id,
985 self::TYPE_SETTING,
986 null,
987 'contextlocking',
988 new pix_icon($lockicon, '')
997 * Navigation node collection
999 * This class is responsible for managing a collection of navigation nodes.
1000 * It is required because a node's unique identifier is a combination of both its
1001 * key and its type.
1003 * Originally an array was used with a string key that was a combination of the two
1004 * however it was decided that a better solution would be to use a class that
1005 * implements the standard IteratorAggregate interface.
1007 * @package core
1008 * @category navigation
1009 * @copyright 2010 Sam Hemelryk
1010 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1012 class navigation_node_collection implements IteratorAggregate, Countable {
1014 * A multidimensional array to where the first key is the type and the second
1015 * key is the nodes key.
1016 * @var array
1018 protected $collection = array();
1020 * An array that contains references to nodes in the same order they were added.
1021 * This is maintained as a progressive array.
1022 * @var array
1024 protected $orderedcollection = array();
1026 * A reference to the last node that was added to the collection
1027 * @var navigation_node
1029 protected $last = null;
1031 * The total number of items added to this array.
1032 * @var int
1034 protected $count = 0;
1037 * Label for collection of nodes.
1038 * @var string
1040 protected $collectionlabel = '';
1043 * Adds a navigation node to the collection
1045 * @param navigation_node $node Node to add
1046 * @param string $beforekey If specified, adds before a node with this key,
1047 * otherwise adds at end
1048 * @return navigation_node Added node
1050 public function add(navigation_node $node, $beforekey=null) {
1051 global $CFG;
1052 $key = $node->key;
1053 $type = $node->type;
1055 // First check we have a 2nd dimension for this type
1056 if (!array_key_exists($type, $this->orderedcollection)) {
1057 $this->orderedcollection[$type] = array();
1059 // Check for a collision and report if debugging is turned on
1060 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
1061 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
1064 // Find the key to add before
1065 $newindex = $this->count;
1066 $last = true;
1067 if ($beforekey !== null) {
1068 foreach ($this->collection as $index => $othernode) {
1069 if ($othernode->key === $beforekey) {
1070 $newindex = $index;
1071 $last = false;
1072 break;
1075 if ($newindex === $this->count) {
1076 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
1077 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
1081 // Add the node to the appropriate place in the by-type structure (which
1082 // is not ordered, despite the variable name)
1083 $this->orderedcollection[$type][$key] = $node;
1084 if (!$last) {
1085 // Update existing references in the ordered collection (which is the
1086 // one that isn't called 'ordered') to shuffle them along if required
1087 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
1088 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
1091 // Add a reference to the node to the progressive collection.
1092 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
1093 // Update the last property to a reference to this new node.
1094 $this->last = $this->orderedcollection[$type][$key];
1096 // Reorder the array by index if needed
1097 if (!$last) {
1098 ksort($this->collection);
1100 $this->count++;
1101 // Return the reference to the now added node
1102 return $node;
1106 * Return a list of all the keys of all the nodes.
1107 * @return array the keys.
1109 public function get_key_list() {
1110 $keys = array();
1111 foreach ($this->collection as $node) {
1112 $keys[] = $node->key;
1114 return $keys;
1118 * Set a label for this collection.
1120 * @param string $label
1122 public function set_collectionlabel($label) {
1123 $this->collectionlabel = $label;
1127 * Return a label for this collection.
1129 * @return string
1131 public function get_collectionlabel() {
1132 return $this->collectionlabel;
1136 * Fetches a node from this collection.
1138 * @param string|int $key The key of the node we want to find.
1139 * @param int $type One of navigation_node::TYPE_*.
1140 * @return navigation_node|null
1142 public function get($key, $type=null) {
1143 if ($type !== null) {
1144 // If the type is known then we can simply check and fetch
1145 if (!empty($this->orderedcollection[$type][$key])) {
1146 return $this->orderedcollection[$type][$key];
1148 } else {
1149 // Because we don't know the type we look in the progressive array
1150 foreach ($this->collection as $node) {
1151 if ($node->key === $key) {
1152 return $node;
1156 return false;
1160 * Searches for a node with matching key and type.
1162 * This function searches both the nodes in this collection and all of
1163 * the nodes in each collection belonging to the nodes in this collection.
1165 * Recursive.
1167 * @param string|int $key The key of the node we want to find.
1168 * @param int $type One of navigation_node::TYPE_*.
1169 * @return navigation_node|null
1171 public function find($key, $type=null) {
1172 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1173 return $this->orderedcollection[$type][$key];
1174 } else {
1175 $nodes = $this->getIterator();
1176 // Search immediate children first
1177 foreach ($nodes as &$node) {
1178 if ($node->key === $key && ($type === null || $type === $node->type)) {
1179 return $node;
1182 // Now search each childs children
1183 foreach ($nodes as &$node) {
1184 $result = $node->children->find($key, $type);
1185 if ($result !== false) {
1186 return $result;
1190 return false;
1194 * Fetches the last node that was added to this collection
1196 * @return navigation_node
1198 public function last() {
1199 return $this->last;
1203 * Fetches all nodes of a given type from this collection
1205 * @param string|int $type node type being searched for.
1206 * @return array ordered collection
1208 public function type($type) {
1209 if (!array_key_exists($type, $this->orderedcollection)) {
1210 $this->orderedcollection[$type] = array();
1212 return $this->orderedcollection[$type];
1215 * Removes the node with the given key and type from the collection
1217 * @param string|int $key The key of the node we want to find.
1218 * @param int $type
1219 * @return bool
1221 public function remove($key, $type=null) {
1222 $child = $this->get($key, $type);
1223 if ($child !== false) {
1224 foreach ($this->collection as $colkey => $node) {
1225 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1226 unset($this->collection[$colkey]);
1227 $this->collection = array_values($this->collection);
1228 break;
1231 unset($this->orderedcollection[$child->type][$child->key]);
1232 $this->count--;
1233 return true;
1235 return false;
1239 * Gets the number of nodes in this collection
1241 * This option uses an internal count rather than counting the actual options to avoid
1242 * a performance hit through the count function.
1244 * @return int
1246 public function count(): int {
1247 return $this->count;
1250 * Gets an array iterator for the collection.
1252 * This is required by the IteratorAggregator interface and is used by routines
1253 * such as the foreach loop.
1255 * @return ArrayIterator
1257 public function getIterator(): Traversable {
1258 return new ArrayIterator($this->collection);
1263 * The global navigation class used for... the global navigation
1265 * This class is used by PAGE to store the global navigation for the site
1266 * and is then used by the settings nav and navbar to save on processing and DB calls
1268 * See
1269 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1270 * {@link lib/ajax/getnavbranch.php} Called by ajax
1272 * @package core
1273 * @category navigation
1274 * @copyright 2009 Sam Hemelryk
1275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1277 class global_navigation extends navigation_node {
1278 /** @var moodle_page The Moodle page this navigation object belongs to. */
1279 protected $page;
1280 /** @var bool switch to let us know if the navigation object is initialised*/
1281 protected $initialised = false;
1282 /** @var array An array of course information */
1283 protected $mycourses = array();
1284 /** @var navigation_node[] An array for containing root navigation nodes */
1285 protected $rootnodes = array();
1286 /** @var bool A switch for whether to show empty sections in the navigation */
1287 protected $showemptysections = true;
1288 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1289 protected $showcategories = null;
1290 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1291 protected $showmycategories = null;
1292 /** @var array An array of stdClasses for users that the navigation is extended for */
1293 protected $extendforuser = array();
1294 /** @var navigation_cache */
1295 protected $cache;
1296 /** @var array An array of course ids that are present in the navigation */
1297 protected $addedcourses = array();
1298 /** @var bool */
1299 protected $allcategoriesloaded = false;
1300 /** @var array An array of category ids that are included in the navigation */
1301 protected $addedcategories = array();
1302 /** @var int expansion limit */
1303 protected $expansionlimit = 0;
1304 /** @var int userid to allow parent to see child's profile page navigation */
1305 protected $useridtouseforparentchecks = 0;
1306 /** @var cache_session A cache that stores information on expanded courses */
1307 protected $cacheexpandcourse = null;
1309 /** Used when loading categories to load all top level categories [parent = 0] **/
1310 const LOAD_ROOT_CATEGORIES = 0;
1311 /** Used when loading categories to load all categories **/
1312 const LOAD_ALL_CATEGORIES = -1;
1315 * Constructs a new global navigation
1317 * @param moodle_page $page The page this navigation object belongs to
1319 public function __construct(moodle_page $page) {
1320 global $CFG, $SITE, $USER;
1322 if (during_initial_install()) {
1323 return;
1326 $homepage = get_home_page();
1327 if ($homepage == HOMEPAGE_SITE) {
1328 // We are using the site home for the root element.
1329 $properties = array(
1330 'key' => 'home',
1331 'type' => navigation_node::TYPE_SYSTEM,
1332 'text' => get_string('home'),
1333 'action' => new moodle_url('/'),
1334 'icon' => new pix_icon('i/home', '')
1336 } else if ($homepage == HOMEPAGE_MYCOURSES) {
1337 // We are using the user's course summary page for the root element.
1338 $properties = array(
1339 'key' => 'mycourses',
1340 'type' => navigation_node::TYPE_SYSTEM,
1341 'text' => get_string('mycourses'),
1342 'action' => new moodle_url('/my/courses.php'),
1343 'icon' => new pix_icon('i/course', '')
1345 } else {
1346 // We are using the users my moodle for the root element.
1347 $properties = array(
1348 'key' => 'myhome',
1349 'type' => navigation_node::TYPE_SYSTEM,
1350 'text' => get_string('myhome'),
1351 'action' => new moodle_url('/my/'),
1352 'icon' => new pix_icon('i/dashboard', '')
1356 // Use the parents constructor.... good good reuse
1357 parent::__construct($properties);
1358 $this->showinflatnavigation = true;
1360 // Initalise and set defaults
1361 $this->page = $page;
1362 $this->forceopen = true;
1363 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1367 * Mutator to set userid to allow parent to see child's profile
1368 * page navigation. See MDL-25805 for initial issue. Linked to it
1369 * is an issue explaining why this is a REALLY UGLY HACK thats not
1370 * for you to use!
1372 * @param int $userid userid of profile page that parent wants to navigate around.
1374 public function set_userid_for_parent_checks($userid) {
1375 $this->useridtouseforparentchecks = $userid;
1380 * Initialises the navigation object.
1382 * This causes the navigation object to look at the current state of the page
1383 * that it is associated with and then load the appropriate content.
1385 * This should only occur the first time that the navigation structure is utilised
1386 * which will normally be either when the navbar is called to be displayed or
1387 * when a block makes use of it.
1389 * @return bool
1391 public function initialise() {
1392 global $CFG, $SITE, $USER;
1393 // Check if it has already been initialised
1394 if ($this->initialised || during_initial_install()) {
1395 return true;
1397 $this->initialised = true;
1399 // Set up the five base root nodes. These are nodes where we will put our
1400 // content and are as follows:
1401 // site: Navigation for the front page.
1402 // myprofile: User profile information goes here.
1403 // currentcourse: The course being currently viewed.
1404 // mycourses: The users courses get added here.
1405 // courses: Additional courses are added here.
1406 // users: Other users information loaded here.
1407 $this->rootnodes = array();
1408 $defaulthomepage = get_home_page();
1409 if ($defaulthomepage == HOMEPAGE_SITE) {
1410 // The home element should be my moodle because the root element is the site
1411 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1412 if (!empty($CFG->enabledashboard)) {
1413 // Only add dashboard to home if it's enabled.
1414 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1415 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
1416 $this->rootnodes['home']->showinflatnavigation = true;
1419 } else {
1420 // The home element should be the site because the root node is my moodle
1421 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1422 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1423 $this->rootnodes['home']->showinflatnavigation = true;
1424 if (!empty($CFG->defaulthomepage) &&
1425 ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) {
1426 // We need to stop automatic redirection
1427 $this->rootnodes['home']->action->param('redirect', '0');
1430 $this->rootnodes['site'] = $this->add_course($SITE);
1431 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1432 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1433 $this->rootnodes['mycourses'] = $this->add(
1434 get_string('mycourses'),
1435 new moodle_url('/my/courses.php'),
1436 self::TYPE_ROOTNODE,
1437 null,
1438 'mycourses',
1439 new pix_icon('i/course', '')
1441 // We do not need to show this node in the breadcrumbs if the default homepage is mycourses.
1442 // It will be automatically handled by the breadcrumb generator.
1443 if ($defaulthomepage == HOMEPAGE_MYCOURSES) {
1444 $this->rootnodes['mycourses']->mainnavonly = true;
1447 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1448 if (!core_course_category::user_top()) {
1449 $this->rootnodes['courses']->hide();
1451 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1453 // We always load the frontpage course to ensure it is available without
1454 // JavaScript enabled.
1455 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1456 $this->load_course_sections($SITE, $this->rootnodes['site']);
1458 $course = $this->page->course;
1459 $this->load_courses_enrolled();
1461 // $issite gets set to true if the current pages course is the sites frontpage course
1462 $issite = ($this->page->course->id == $SITE->id);
1464 // Determine if the user is enrolled in any course.
1465 $enrolledinanycourse = enrol_user_sees_own_courses();
1467 $this->rootnodes['currentcourse']->mainnavonly = true;
1468 if ($enrolledinanycourse) {
1469 $this->rootnodes['mycourses']->isexpandable = true;
1470 $this->rootnodes['mycourses']->showinflatnavigation = true;
1471 if ($CFG->navshowallcourses) {
1472 // When we show all courses we need to show both the my courses and the regular courses branch.
1473 $this->rootnodes['courses']->isexpandable = true;
1475 } else {
1476 $this->rootnodes['courses']->isexpandable = true;
1478 $this->rootnodes['mycourses']->forceopen = true;
1480 $canviewcourseprofile = true;
1482 // Next load context specific content into the navigation
1483 switch ($this->page->context->contextlevel) {
1484 case CONTEXT_SYSTEM :
1485 // Nothing left to do here I feel.
1486 break;
1487 case CONTEXT_COURSECAT :
1488 // This is essential, we must load categories.
1489 $this->load_all_categories($this->page->context->instanceid, true);
1490 break;
1491 case CONTEXT_BLOCK :
1492 case CONTEXT_COURSE :
1493 if ($issite) {
1494 // Nothing left to do here.
1495 break;
1498 // Load the course associated with the current page into the navigation.
1499 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1500 // If the course wasn't added then don't try going any further.
1501 if (!$coursenode) {
1502 $canviewcourseprofile = false;
1503 break;
1506 // If the user is not enrolled then we only want to show the
1507 // course node and not populate it.
1509 // Not enrolled, can't view, and hasn't switched roles
1510 if (!can_access_course($course, null, '', true)) {
1511 if ($coursenode->isexpandable === true) {
1512 // Obviously the situation has changed, update the cache and adjust the node.
1513 // This occurs if the user access to a course has been revoked (one way or another) after
1514 // initially logging in for this session.
1515 $this->get_expand_course_cache()->set($course->id, 1);
1516 $coursenode->isexpandable = true;
1517 $coursenode->nodetype = self::NODETYPE_BRANCH;
1519 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1520 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1521 if (!$this->current_user_is_parent_role()) {
1522 $coursenode->make_active();
1523 $canviewcourseprofile = false;
1524 break;
1526 } else if ($coursenode->isexpandable === false) {
1527 // Obviously the situation has changed, update the cache and adjust the node.
1528 // This occurs if the user has been granted access to a course (one way or another) after initially
1529 // logging in for this session.
1530 $this->get_expand_course_cache()->set($course->id, 1);
1531 $coursenode->isexpandable = true;
1532 $coursenode->nodetype = self::NODETYPE_BRANCH;
1535 // Add the essentials such as reports etc...
1536 $this->add_course_essentials($coursenode, $course);
1537 // Extend course navigation with it's sections/activities
1538 $this->load_course_sections($course, $coursenode);
1539 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1540 $coursenode->make_active();
1543 break;
1544 case CONTEXT_MODULE :
1545 if ($issite) {
1546 // If this is the site course then most information will have
1547 // already been loaded.
1548 // However we need to check if there is more content that can
1549 // yet be loaded for the specific module instance.
1550 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1551 if ($activitynode) {
1552 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1554 break;
1557 $course = $this->page->course;
1558 $cm = $this->page->cm;
1560 // Load the course associated with the page into the navigation
1561 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1563 // If the course wasn't added then don't try going any further.
1564 if (!$coursenode) {
1565 $canviewcourseprofile = false;
1566 break;
1569 // If the user is not enrolled then we only want to show the
1570 // course node and not populate it.
1571 if (!can_access_course($course, null, '', true)) {
1572 $coursenode->make_active();
1573 $canviewcourseprofile = false;
1574 break;
1577 $this->add_course_essentials($coursenode, $course);
1579 // Load the course sections into the page
1580 $this->load_course_sections($course, $coursenode, null, $cm);
1581 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1582 if (!empty($activity)) {
1583 // Finally load the cm specific navigaton information
1584 $this->load_activity($cm, $course, $activity);
1585 // Check if we have an active ndoe
1586 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1587 // And make the activity node active.
1588 $activity->make_active();
1591 break;
1592 case CONTEXT_USER :
1593 if ($issite) {
1594 // The users profile information etc is already loaded
1595 // for the front page.
1596 break;
1598 $course = $this->page->course;
1599 // Load the course associated with the user into the navigation
1600 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1602 // If the course wasn't added then don't try going any further.
1603 if (!$coursenode) {
1604 $canviewcourseprofile = false;
1605 break;
1608 // If the user is not enrolled then we only want to show the
1609 // course node and not populate it.
1610 if (!can_access_course($course, null, '', true)) {
1611 $coursenode->make_active();
1612 $canviewcourseprofile = false;
1613 break;
1615 $this->add_course_essentials($coursenode, $course);
1616 $this->load_course_sections($course, $coursenode);
1617 break;
1620 // Load for the current user
1621 $this->load_for_user();
1622 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1623 $this->load_for_user(null, true);
1625 // Load each extending user into the navigation.
1626 foreach ($this->extendforuser as $user) {
1627 if ($user->id != $USER->id) {
1628 $this->load_for_user($user);
1632 // Give the local plugins a chance to include some navigation if they want.
1633 $this->load_local_plugin_navigation();
1635 // Remove any empty root nodes
1636 foreach ($this->rootnodes as $node) {
1637 // Dont remove the home node
1638 /** @var navigation_node $node */
1639 if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) {
1640 $node->remove();
1644 if (!$this->contains_active_node()) {
1645 $this->search_for_active_node();
1648 // If the user is not logged in modify the navigation structure as detailed
1649 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1650 if (!isloggedin()) {
1651 $activities = clone($this->rootnodes['site']->children);
1652 $this->rootnodes['site']->remove();
1653 $children = clone($this->children);
1654 $this->children = new navigation_node_collection();
1655 foreach ($activities as $child) {
1656 $this->children->add($child);
1658 foreach ($children as $child) {
1659 $this->children->add($child);
1662 return true;
1666 * This function gives local plugins an opportunity to modify navigation.
1668 protected function load_local_plugin_navigation() {
1669 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1670 $function($this);
1675 * Returns true if the current user is a parent of the user being currently viewed.
1677 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1678 * other user being viewed this function returns false.
1679 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1681 * @since Moodle 2.4
1682 * @return bool
1684 protected function current_user_is_parent_role() {
1685 global $USER, $DB;
1686 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1687 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1688 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1689 return false;
1691 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1692 return true;
1695 return false;
1699 * Returns true if courses should be shown within categories on the navigation.
1701 * @param bool $ismycourse Set to true if you are calculating this for a course.
1702 * @return bool
1704 protected function show_categories($ismycourse = false) {
1705 global $CFG, $DB;
1706 if ($ismycourse) {
1707 return $this->show_my_categories();
1709 if ($this->showcategories === null) {
1710 $show = false;
1711 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1712 $show = true;
1713 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1714 $show = true;
1716 $this->showcategories = $show;
1718 return $this->showcategories;
1722 * Returns true if we should show categories in the My Courses branch.
1723 * @return bool
1725 protected function show_my_categories() {
1726 global $CFG;
1727 if ($this->showmycategories === null) {
1728 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
1730 return $this->showmycategories;
1734 * Loads the courses in Moodle into the navigation.
1736 * @global moodle_database $DB
1737 * @param string|array $categoryids An array containing categories to load courses
1738 * for, OR null to load courses for all categories.
1739 * @return array An array of navigation_nodes one for each course
1741 protected function load_all_courses($categoryids = null) {
1742 global $CFG, $DB, $SITE;
1744 // Work out the limit of courses.
1745 $limit = 20;
1746 if (!empty($CFG->navcourselimit)) {
1747 $limit = $CFG->navcourselimit;
1750 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1752 // If we are going to show all courses AND we are showing categories then
1753 // to save us repeated DB calls load all of the categories now
1754 if ($this->show_categories()) {
1755 $this->load_all_categories($toload);
1758 // Will be the return of our efforts
1759 $coursenodes = array();
1761 // Check if we need to show categories.
1762 if ($this->show_categories()) {
1763 // Hmmm we need to show categories... this is going to be painful.
1764 // We now need to fetch up to $limit courses for each category to
1765 // be displayed.
1766 if ($categoryids !== null) {
1767 if (!is_array($categoryids)) {
1768 $categoryids = array($categoryids);
1770 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1771 $categorywhere = 'WHERE cc.id '.$categorywhere;
1772 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1773 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1774 $categoryparams = array();
1775 } else {
1776 $categorywhere = '';
1777 $categoryparams = array();
1780 // First up we are going to get the categories that we are going to
1781 // need so that we can determine how best to load the courses from them.
1782 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1783 FROM {course_categories} cc
1784 LEFT JOIN {course} c ON c.category = cc.id
1785 {$categorywhere}
1786 GROUP BY cc.id";
1787 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1788 $fullfetch = array();
1789 $partfetch = array();
1790 foreach ($categories as $category) {
1791 if (!$this->can_add_more_courses_to_category($category->id)) {
1792 continue;
1794 if ($category->coursecount > $limit * 5) {
1795 $partfetch[] = $category->id;
1796 } else if ($category->coursecount > 0) {
1797 $fullfetch[] = $category->id;
1800 $categories->close();
1802 if (count($fullfetch)) {
1803 // First up fetch all of the courses in categories where we know that we are going to
1804 // need the majority of courses.
1805 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1806 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1807 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1808 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1809 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1810 FROM {course} c
1811 $ccjoin
1812 WHERE c.category {$categoryids}
1813 ORDER BY c.sortorder ASC";
1814 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1815 foreach ($coursesrs as $course) {
1816 if ($course->id == $SITE->id) {
1817 // This should not be necessary, frontpage is not in any category.
1818 continue;
1820 if (array_key_exists($course->id, $this->addedcourses)) {
1821 // It is probably better to not include the already loaded courses
1822 // directly in SQL because inequalities may confuse query optimisers
1823 // and may interfere with query caching.
1824 continue;
1826 if (!$this->can_add_more_courses_to_category($course->category)) {
1827 continue;
1829 context_helper::preload_from_record($course);
1830 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1831 continue;
1833 $coursenodes[$course->id] = $this->add_course($course);
1835 $coursesrs->close();
1838 if (count($partfetch)) {
1839 // Next we will work our way through the categories where we will likely only need a small
1840 // proportion of the courses.
1841 foreach ($partfetch as $categoryid) {
1842 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1843 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1844 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1845 FROM {course} c
1846 $ccjoin
1847 WHERE c.category = :categoryid
1848 ORDER BY c.sortorder ASC";
1849 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1850 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1851 foreach ($coursesrs as $course) {
1852 if ($course->id == $SITE->id) {
1853 // This should not be necessary, frontpage is not in any category.
1854 continue;
1856 if (array_key_exists($course->id, $this->addedcourses)) {
1857 // It is probably better to not include the already loaded courses
1858 // directly in SQL because inequalities may confuse query optimisers
1859 // and may interfere with query caching.
1860 // This also helps to respect expected $limit on repeated executions.
1861 continue;
1863 if (!$this->can_add_more_courses_to_category($course->category)) {
1864 break;
1866 context_helper::preload_from_record($course);
1867 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1868 continue;
1870 $coursenodes[$course->id] = $this->add_course($course);
1872 $coursesrs->close();
1875 } else {
1876 // Prepare the SQL to load the courses and their contexts
1877 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1878 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1879 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1880 $courseparams['contextlevel'] = CONTEXT_COURSE;
1881 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1882 FROM {course} c
1883 $ccjoin
1884 WHERE c.id {$courseids}
1885 ORDER BY c.sortorder ASC";
1886 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1887 foreach ($coursesrs as $course) {
1888 if ($course->id == $SITE->id) {
1889 // frotpage is not wanted here
1890 continue;
1892 if ($this->page->course && ($this->page->course->id == $course->id)) {
1893 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1894 continue;
1896 context_helper::preload_from_record($course);
1897 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1898 continue;
1900 $coursenodes[$course->id] = $this->add_course($course);
1901 if (count($coursenodes) >= $limit) {
1902 break;
1905 $coursesrs->close();
1908 return $coursenodes;
1912 * Returns true if more courses can be added to the provided category.
1914 * @param int|navigation_node|stdClass $category
1915 * @return bool
1917 protected function can_add_more_courses_to_category($category) {
1918 global $CFG;
1919 $limit = 20;
1920 if (!empty($CFG->navcourselimit)) {
1921 $limit = (int)$CFG->navcourselimit;
1923 if (is_numeric($category)) {
1924 if (!array_key_exists($category, $this->addedcategories)) {
1925 return true;
1927 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1928 } else if ($category instanceof navigation_node) {
1929 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1930 return false;
1932 $coursecount = count($category->children->type(self::TYPE_COURSE));
1933 } else if (is_object($category) && property_exists($category,'id')) {
1934 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1936 return ($coursecount <= $limit);
1940 * Loads all categories (top level or if an id is specified for that category)
1942 * @param int $categoryid The category id to load or null/0 to load all base level categories
1943 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1944 * as the requested category and any parent categories.
1945 * @return navigation_node|void returns a navigation node if a category has been loaded.
1947 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1948 global $CFG, $DB;
1950 // Check if this category has already been loaded
1951 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1952 return true;
1955 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1956 $sqlselect = "SELECT cc.*, $catcontextsql
1957 FROM {course_categories} cc
1958 JOIN {context} ctx ON cc.id = ctx.instanceid";
1959 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1960 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1961 $params = array();
1963 $categoriestoload = array();
1964 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1965 // We are going to load all categories regardless... prepare to fire
1966 // on the database server!
1967 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1968 // We are going to load all of the first level categories (categories without parents)
1969 $sqlwhere .= " AND cc.parent = 0";
1970 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1971 // The category itself has been loaded already so we just need to ensure its subcategories
1972 // have been loaded
1973 $addedcategories = $this->addedcategories;
1974 unset($addedcategories[$categoryid]);
1975 if (count($addedcategories) > 0) {
1976 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1977 if ($showbasecategories) {
1978 // We need to include categories with parent = 0 as well
1979 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1980 } else {
1981 // All we need is categories that match the parent
1982 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1985 $params['categoryid'] = $categoryid;
1986 } else {
1987 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1988 // and load this category plus all its parents and subcategories
1989 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1990 $categoriestoload = explode('/', trim($category->path, '/'));
1991 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1992 // We are going to use select twice so double the params
1993 $params = array_merge($params, $params);
1994 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1995 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1998 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1999 $categories = array();
2000 foreach ($categoriesrs as $category) {
2001 // Preload the context.. we'll need it when adding the category in order
2002 // to format the category name.
2003 context_helper::preload_from_record($category);
2004 if (array_key_exists($category->id, $this->addedcategories)) {
2005 // Do nothing, its already been added.
2006 } else if ($category->parent == '0') {
2007 // This is a root category lets add it immediately
2008 $this->add_category($category, $this->rootnodes['courses']);
2009 } else if (array_key_exists($category->parent, $this->addedcategories)) {
2010 // This categories parent has already been added we can add this immediately
2011 $this->add_category($category, $this->addedcategories[$category->parent]);
2012 } else {
2013 $categories[] = $category;
2016 $categoriesrs->close();
2018 // Now we have an array of categories we need to add them to the navigation.
2019 while (!empty($categories)) {
2020 $category = reset($categories);
2021 if (array_key_exists($category->id, $this->addedcategories)) {
2022 // Do nothing
2023 } else if ($category->parent == '0') {
2024 $this->add_category($category, $this->rootnodes['courses']);
2025 } else if (array_key_exists($category->parent, $this->addedcategories)) {
2026 $this->add_category($category, $this->addedcategories[$category->parent]);
2027 } else {
2028 // This category isn't in the navigation and niether is it's parent (yet).
2029 // We need to go through the category path and add all of its components in order.
2030 $path = explode('/', trim($category->path, '/'));
2031 foreach ($path as $catid) {
2032 if (!array_key_exists($catid, $this->addedcategories)) {
2033 // This category isn't in the navigation yet so add it.
2034 $subcategory = $categories[$catid];
2035 if ($subcategory->parent == '0') {
2036 // Yay we have a root category - this likely means we will now be able
2037 // to add categories without problems.
2038 $this->add_category($subcategory, $this->rootnodes['courses']);
2039 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
2040 // The parent is in the category (as we'd expect) so add it now.
2041 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
2042 // Remove the category from the categories array.
2043 unset($categories[$catid]);
2044 } else {
2045 // We should never ever arrive here - if we have then there is a bigger
2046 // problem at hand.
2047 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
2052 // Remove the category from the categories array now that we know it has been added.
2053 unset($categories[$category->id]);
2055 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
2056 $this->allcategoriesloaded = true;
2058 // Check if there are any categories to load.
2059 if (count($categoriestoload) > 0) {
2060 $readytoloadcourses = array();
2061 foreach ($categoriestoload as $category) {
2062 if ($this->can_add_more_courses_to_category($category)) {
2063 $readytoloadcourses[] = $category;
2066 if (count($readytoloadcourses)) {
2067 $this->load_all_courses($readytoloadcourses);
2071 // Look for all categories which have been loaded
2072 if (!empty($this->addedcategories)) {
2073 $categoryids = array();
2074 foreach ($this->addedcategories as $category) {
2075 if ($this->can_add_more_courses_to_category($category)) {
2076 $categoryids[] = $category->key;
2079 if ($categoryids) {
2080 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
2081 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
2082 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
2083 FROM {course_categories} cc
2084 JOIN {course} c ON c.category = cc.id
2085 WHERE cc.id {$categoriessql}
2086 GROUP BY cc.id
2087 HAVING COUNT(c.id) > :limit";
2088 $excessivecategories = $DB->get_records_sql($sql, $params);
2089 foreach ($categories as &$category) {
2090 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
2091 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
2092 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
2100 * Adds a structured category to the navigation in the correct order/place
2102 * @param stdClass $category category to be added in navigation.
2103 * @param navigation_node $parent parent navigation node
2104 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2105 * @return void.
2107 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
2108 global $CFG;
2109 if (array_key_exists($category->id, $this->addedcategories)) {
2110 return;
2112 $canview = core_course_category::can_view_category($category);
2113 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
2114 $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id));
2115 $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) :
2116 get_string('categoryhidden');
2117 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
2118 if (!$canview) {
2119 // User does not have required capabilities to view category.
2120 $categorynode->display = false;
2121 } else if (!$category->visible) {
2122 // Category is hidden but user has capability to view hidden categories.
2123 $categorynode->hidden = true;
2125 $this->addedcategories[$category->id] = $categorynode;
2129 * Loads the given course into the navigation
2131 * @param stdClass $course
2132 * @return navigation_node
2134 protected function load_course(stdClass $course) {
2135 global $SITE;
2136 if ($course->id == $SITE->id) {
2137 // This is always loaded during initialisation
2138 return $this->rootnodes['site'];
2139 } else if (array_key_exists($course->id, $this->addedcourses)) {
2140 // The course has already been loaded so return a reference
2141 return $this->addedcourses[$course->id];
2142 } else {
2143 // Add the course
2144 return $this->add_course($course);
2149 * Loads all of the courses section into the navigation.
2151 * This function calls method from current course format, see
2152 * core_courseformat\base::extend_course_navigation()
2153 * If course module ($cm) is specified but course format failed to create the node,
2154 * the activity node is created anyway.
2156 * By default course formats call the method global_navigation::load_generic_course_sections()
2158 * @param stdClass $course Database record for the course
2159 * @param navigation_node $coursenode The course node within the navigation
2160 * @param null|int $sectionnum If specified load the contents of section with this relative number
2161 * @param null|cm_info $cm If specified make sure that activity node is created (either
2162 * in containg section or by calling load_stealth_activity() )
2164 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2165 global $CFG, $SITE;
2166 require_once($CFG->dirroot.'/course/lib.php');
2167 if (isset($cm->sectionnum)) {
2168 $sectionnum = $cm->sectionnum;
2170 if ($sectionnum !== null) {
2171 $this->includesectionnum = $sectionnum;
2173 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2174 if (isset($cm->id)) {
2175 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2176 if (empty($activity)) {
2177 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2183 * Generates an array of sections and an array of activities for the given course.
2185 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2187 * @param stdClass $course
2188 * @return array Array($sections, $activities)
2190 protected function generate_sections_and_activities(stdClass $course) {
2191 global $CFG;
2192 require_once($CFG->dirroot.'/course/lib.php');
2194 $modinfo = get_fast_modinfo($course);
2195 $sections = $modinfo->get_section_info_all();
2197 // For course formats using 'numsections' trim the sections list
2198 $courseformatoptions = course_get_format($course)->get_format_options();
2199 if (isset($courseformatoptions['numsections'])) {
2200 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2203 $activities = array();
2205 foreach ($sections as $key => $section) {
2206 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2207 $sections[$key] = clone($section);
2208 unset($sections[$key]->summary);
2209 $sections[$key]->hasactivites = false;
2210 if (!array_key_exists($section->section, $modinfo->sections)) {
2211 continue;
2213 foreach ($modinfo->sections[$section->section] as $cmid) {
2214 $cm = $modinfo->cms[$cmid];
2215 $activity = new stdClass;
2216 $activity->id = $cm->id;
2217 $activity->course = $course->id;
2218 $activity->section = $section->section;
2219 $activity->name = $cm->name;
2220 $activity->icon = $cm->icon;
2221 $activity->iconcomponent = $cm->iconcomponent;
2222 $activity->hidden = (!$cm->visible);
2223 $activity->modname = $cm->modname;
2224 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2225 $activity->onclick = $cm->onclick;
2226 $url = $cm->url;
2227 if (!$url) {
2228 $activity->url = null;
2229 $activity->display = false;
2230 } else {
2231 $activity->url = $url->out();
2232 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2233 if (self::module_extends_navigation($cm->modname)) {
2234 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2237 $activities[$cmid] = $activity;
2238 if ($activity->display) {
2239 $sections[$key]->hasactivites = true;
2244 return array($sections, $activities);
2248 * Generically loads the course sections into the course's navigation.
2250 * @param stdClass $course
2251 * @param navigation_node $coursenode
2252 * @return array An array of course section nodes
2254 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2255 global $CFG, $DB, $USER, $SITE;
2256 require_once($CFG->dirroot.'/course/lib.php');
2258 list($sections, $activities) = $this->generate_sections_and_activities($course);
2260 $navigationsections = array();
2261 foreach ($sections as $sectionid => $section) {
2262 $section = clone($section);
2263 if ($course->id == $SITE->id) {
2264 $this->load_section_activities($coursenode, $section->section, $activities);
2265 } else {
2266 if (!$section->uservisible || (!$this->showemptysections &&
2267 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2268 continue;
2271 $sectionname = get_section_name($course, $section);
2272 $url = course_get_url($course, $section->section, array('navigation' => true));
2274 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2275 null, $section->id, new pix_icon('i/section', ''));
2276 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2277 $sectionnode->hidden = (!$section->visible || !$section->available);
2278 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2279 $this->load_section_activities($sectionnode, $section->section, $activities);
2281 $section->sectionnode = $sectionnode;
2282 $navigationsections[$sectionid] = $section;
2285 return $navigationsections;
2289 * Loads all of the activities for a section into the navigation structure.
2291 * @param navigation_node $sectionnode
2292 * @param int $sectionnumber
2293 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2294 * @param stdClass $course The course object the section and activities relate to.
2295 * @return array Array of activity nodes
2297 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2298 global $CFG, $SITE;
2299 // A static counter for JS function naming
2300 static $legacyonclickcounter = 0;
2302 $activitynodes = array();
2303 if (empty($activities)) {
2304 return $activitynodes;
2307 if (!is_object($course)) {
2308 $activity = reset($activities);
2309 $courseid = $activity->course;
2310 } else {
2311 $courseid = $course->id;
2313 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2315 foreach ($activities as $activity) {
2316 if ($activity->section != $sectionnumber) {
2317 continue;
2319 if ($activity->icon) {
2320 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2321 } else {
2322 $icon = new pix_icon('monologo', get_string('modulename', $activity->modname), $activity->modname);
2325 // Prepare the default name and url for the node
2326 $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activity->id));
2327 $activityname = format_string($activity->name, true, ['context' => $displaycontext]);
2328 $action = new moodle_url($activity->url);
2330 // Check if the onclick property is set (puke!)
2331 if (!empty($activity->onclick)) {
2332 // Increment the counter so that we have a unique number.
2333 $legacyonclickcounter++;
2334 // Generate the function name we will use
2335 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2336 $propogrationhandler = '';
2337 // Check if we need to cancel propogation. Remember inline onclick
2338 // events would return false if they wanted to prevent propogation and the
2339 // default action.
2340 if (strpos($activity->onclick, 'return false')) {
2341 $propogrationhandler = 'e.halt();';
2343 // Decode the onclick - it has already been encoded for display (puke)
2344 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2345 // Build the JS function the click event will call
2346 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2347 $this->page->requires->js_amd_inline($jscode);
2348 // Override the default url with the new action link
2349 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2352 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2353 $activitynode->title(get_string('modulename', $activity->modname));
2354 $activitynode->hidden = $activity->hidden;
2355 $activitynode->display = $showactivities && $activity->display;
2356 $activitynode->nodetype = $activity->nodetype;
2357 $activitynodes[$activity->id] = $activitynode;
2360 return $activitynodes;
2363 * Loads a stealth module from unavailable section
2364 * @param navigation_node $coursenode
2365 * @param stdClass $modinfo
2366 * @return navigation_node or null if not accessible
2368 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2369 if (empty($modinfo->cms[$this->page->cm->id])) {
2370 return null;
2372 $cm = $modinfo->cms[$this->page->cm->id];
2373 if ($cm->icon) {
2374 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2375 } else {
2376 $icon = new pix_icon('monologo', get_string('modulename', $cm->modname), $cm->modname);
2378 $url = $cm->url;
2379 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2380 $activitynode->title(get_string('modulename', $cm->modname));
2381 $activitynode->hidden = (!$cm->visible);
2382 if (!$cm->is_visible_on_course_page()) {
2383 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2384 // Also there may be no exception at all in case when teacher is logged in as student.
2385 $activitynode->display = false;
2386 } else if (!$url) {
2387 // Don't show activities that don't have links!
2388 $activitynode->display = false;
2389 } else if (self::module_extends_navigation($cm->modname)) {
2390 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2392 return $activitynode;
2395 * Loads the navigation structure for the given activity into the activities node.
2397 * This method utilises a callback within the modules lib.php file to load the
2398 * content specific to activity given.
2400 * The callback is a method: {modulename}_extend_navigation()
2401 * Examples:
2402 * * {@link forum_extend_navigation()}
2403 * * {@link workshop_extend_navigation()}
2405 * @param cm_info|stdClass $cm
2406 * @param stdClass $course
2407 * @param navigation_node $activity
2408 * @return bool
2410 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2411 global $CFG, $DB;
2413 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2414 if (!($cm instanceof cm_info)) {
2415 $modinfo = get_fast_modinfo($course);
2416 $cm = $modinfo->get_cm($cm->id);
2418 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2419 $activity->make_active();
2420 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2421 $function = $cm->modname.'_extend_navigation';
2423 if (file_exists($file)) {
2424 require_once($file);
2425 if (function_exists($function)) {
2426 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2427 $function($activity, $course, $activtyrecord, $cm);
2431 // Allow the active advanced grading method plugin to append module navigation
2432 $featuresfunc = $cm->modname.'_supports';
2433 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2434 require_once($CFG->dirroot.'/grade/grading/lib.php');
2435 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2436 $gradingman->extend_navigation($this, $activity);
2439 return $activity->has_children();
2442 * Loads user specific information into the navigation in the appropriate place.
2444 * If no user is provided the current user is assumed.
2446 * @param stdClass $user
2447 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2448 * @return bool
2450 protected function load_for_user($user=null, $forceforcontext=false) {
2451 global $DB, $CFG, $USER, $SITE;
2453 require_once($CFG->dirroot . '/course/lib.php');
2455 if ($user === null) {
2456 // We can't require login here but if the user isn't logged in we don't
2457 // want to show anything
2458 if (!isloggedin() || isguestuser()) {
2459 return false;
2461 $user = $USER;
2462 } else if (!is_object($user)) {
2463 // If the user is not an object then get them from the database
2464 $select = context_helper::get_preload_record_columns_sql('ctx');
2465 $sql = "SELECT u.*, $select
2466 FROM {user} u
2467 JOIN {context} ctx ON u.id = ctx.instanceid
2468 WHERE u.id = :userid AND
2469 ctx.contextlevel = :contextlevel";
2470 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2471 context_helper::preload_from_record($user);
2474 $iscurrentuser = ($user->id == $USER->id);
2476 $usercontext = context_user::instance($user->id);
2478 // Get the course set against the page, by default this will be the site
2479 $course = $this->page->course;
2480 $baseargs = array('id'=>$user->id);
2481 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2482 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2483 $baseargs['course'] = $course->id;
2484 $coursecontext = context_course::instance($course->id);
2485 $issitecourse = false;
2486 } else {
2487 // Load all categories and get the context for the system
2488 $coursecontext = context_system::instance();
2489 $issitecourse = true;
2492 // Create a node to add user information under.
2493 $usersnode = null;
2494 if (!$issitecourse) {
2495 // Not the current user so add it to the participants node for the current course.
2496 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2497 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2498 } else if ($USER->id != $user->id) {
2499 // This is the site so add a users node to the root branch.
2500 $usersnode = $this->rootnodes['users'];
2501 if (course_can_view_participants($coursecontext)) {
2502 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2504 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2506 if (!$usersnode) {
2507 // We should NEVER get here, if the course hasn't been populated
2508 // with a participants node then the navigaiton either wasn't generated
2509 // for it (you are missing a require_login or set_context call) or
2510 // you don't have access.... in the interests of no leaking informatin
2511 // we simply quit...
2512 return false;
2514 // Add a branch for the current user.
2515 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2516 $viewprofile = true;
2517 if (!$iscurrentuser) {
2518 require_once($CFG->dirroot . '/user/lib.php');
2519 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2520 $viewprofile = false;
2521 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2522 $viewprofile = false;
2524 if (!$viewprofile) {
2525 $viewprofile = user_can_view_profile($user, null, $usercontext);
2529 // Now, conditionally add the user node.
2530 if ($viewprofile) {
2531 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2532 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2533 } else {
2534 $usernode = $usersnode->add(get_string('user'));
2537 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2538 $usernode->make_active();
2541 // Add user information to the participants or user node.
2542 if ($issitecourse) {
2544 // If the user is the current user or has permission to view the details of the requested
2545 // user than add a view profile link.
2546 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2547 has_capability('moodle/user:viewdetails', $usercontext)) {
2548 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2549 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2550 } else {
2551 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2555 if (!empty($CFG->navadduserpostslinks)) {
2556 // Add nodes for forum posts and discussions if the user can view either or both
2557 // There are no capability checks here as the content of the page is based
2558 // purely on the forums the current user has access too.
2559 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2560 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2561 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2562 array_merge($baseargs, array('mode' => 'discussions'))));
2565 // Add blog nodes.
2566 if (!empty($CFG->enableblogs)) {
2567 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2568 require_once($CFG->dirroot.'/blog/lib.php');
2569 // Get all options for the user.
2570 $options = blog_get_options_for_user($user);
2571 $this->cache->set('userblogoptions'.$user->id, $options);
2572 } else {
2573 $options = $this->cache->{'userblogoptions'.$user->id};
2576 if (count($options) > 0) {
2577 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2578 foreach ($options as $type => $option) {
2579 if ($type == "rss") {
2580 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2581 new pix_icon('i/rss', ''));
2582 } else {
2583 $blogs->add($option['string'], $option['link']);
2589 // Add the messages link.
2590 // It is context based so can appear in the user's profile and in course participants information.
2591 if (!empty($CFG->messaging)) {
2592 $messageargs = array('user1' => $USER->id);
2593 if ($USER->id != $user->id) {
2594 $messageargs['user2'] = $user->id;
2596 $url = new moodle_url('/message/index.php', $messageargs);
2597 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2600 // Add the "My private files" link.
2601 // This link doesn't have a unique display for course context so only display it under the user's profile.
2602 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2603 $url = new moodle_url('/user/files.php');
2604 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2607 // Add a node to view the users notes if permitted.
2608 if (!empty($CFG->enablenotes) &&
2609 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2610 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2611 if ($coursecontext->instanceid != SITEID) {
2612 $url->param('course', $coursecontext->instanceid);
2614 $usernode->add(get_string('notes', 'notes'), $url);
2617 // Show the grades node.
2618 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2619 require_once($CFG->dirroot . '/user/lib.php');
2620 // Set the grades node to link to the "Grades" page.
2621 if ($course->id == SITEID) {
2622 $url = user_mygrades_url($user->id, $course->id);
2623 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2624 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2626 if ($USER->id != $user->id) {
2627 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2628 } else {
2629 $usernode->add(get_string('grades', 'grades'), $url);
2633 // If the user is the current user add the repositories for the current user.
2634 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2635 if (!$iscurrentuser &&
2636 $course->id == $SITE->id &&
2637 has_capability('moodle/user:viewdetails', $usercontext) &&
2638 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2640 // Add view grade report is permitted.
2641 $reports = core_component::get_plugin_list('gradereport');
2642 arsort($reports); // User is last, we want to test it first.
2644 $userscourses = enrol_get_users_courses($user->id, false, '*');
2645 $userscoursesnode = $usernode->add(get_string('courses'));
2647 $count = 0;
2648 foreach ($userscourses as $usercourse) {
2649 if ($count === (int)$CFG->navcourselimit) {
2650 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2651 $userscoursesnode->add(get_string('showallcourses'), $url);
2652 break;
2654 $count++;
2655 $usercoursecontext = context_course::instance($usercourse->id);
2656 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2657 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2658 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2660 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2661 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2662 foreach ($reports as $plugin => $plugindir) {
2663 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2664 // Stop when the first visible plugin is found.
2665 $gradeavailable = true;
2666 break;
2671 if ($gradeavailable) {
2672 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2673 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2674 new pix_icon('i/grades', ''));
2677 // Add a node to view the users notes if permitted.
2678 if (!empty($CFG->enablenotes) &&
2679 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2680 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2681 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2684 if (can_access_course($usercourse, $user->id, '', true)) {
2685 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2686 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2689 $reporttab = $usercoursenode->add(get_string('activityreports'));
2691 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2692 foreach ($reportfunctions as $reportfunction) {
2693 $reportfunction($reporttab, $user, $usercourse);
2696 $reporttab->trim_if_empty();
2700 // Let plugins hook into user navigation.
2701 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2702 foreach ($pluginsfunction as $plugintype => $plugins) {
2703 if ($plugintype != 'report') {
2704 foreach ($plugins as $pluginfunction) {
2705 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2710 return true;
2714 * This method simply checks to see if a given module can extend the navigation.
2716 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2718 * @param string $modname
2719 * @return bool
2721 public static function module_extends_navigation($modname) {
2722 global $CFG;
2723 static $extendingmodules = array();
2724 if (!array_key_exists($modname, $extendingmodules)) {
2725 $extendingmodules[$modname] = false;
2726 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2727 if (file_exists($file)) {
2728 $function = $modname.'_extend_navigation';
2729 require_once($file);
2730 $extendingmodules[$modname] = (function_exists($function));
2733 return $extendingmodules[$modname];
2736 * Extends the navigation for the given user.
2738 * @param stdClass $user A user from the database
2740 public function extend_for_user($user) {
2741 $this->extendforuser[] = $user;
2745 * Returns all of the users the navigation is being extended for
2747 * @return array An array of extending users.
2749 public function get_extending_users() {
2750 return $this->extendforuser;
2753 * Adds the given course to the navigation structure.
2755 * @param stdClass $course
2756 * @param bool $forcegeneric
2757 * @param bool $ismycourse
2758 * @return navigation_node
2760 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2761 global $CFG, $SITE;
2763 // We found the course... we can return it now :)
2764 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2765 return $this->addedcourses[$course->id];
2768 $coursecontext = context_course::instance($course->id);
2770 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
2771 if (is_role_switched($course->id)) {
2772 // user has to be able to access course in order to switch, let's skip the visibility test here
2773 } else if (!core_course_category::can_view_course_info($course)) {
2774 return false;
2778 $issite = ($course->id == $SITE->id);
2779 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
2780 $shortname = format_string($course->shortname, true, ['context' => $displaycontext]);
2781 $fullname = format_string($course->fullname, true, ['context' => $displaycontext]);
2782 // This is the name that will be shown for the course.
2783 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2785 if ($coursetype == self::COURSE_CURRENT) {
2786 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2787 return $coursenode;
2788 } else {
2789 $coursetype = self::COURSE_OTHER;
2793 // Can the user expand the course to see its content.
2794 $canexpandcourse = true;
2795 if ($issite) {
2796 $parent = $this;
2797 $url = null;
2798 if (empty($CFG->usesitenameforsitepages)) {
2799 $coursename = get_string('sitepages');
2801 } else if ($coursetype == self::COURSE_CURRENT) {
2802 $parent = $this->rootnodes['currentcourse'];
2803 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2804 $canexpandcourse = $this->can_expand_course($course);
2805 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2806 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2807 // Nothing to do here the above statement set $parent to the category within mycourses.
2808 } else {
2809 $parent = $this->rootnodes['mycourses'];
2811 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2812 } else {
2813 $parent = $this->rootnodes['courses'];
2814 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2815 // They can only expand the course if they can access it.
2816 $canexpandcourse = $this->can_expand_course($course);
2817 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2818 if (!$this->is_category_fully_loaded($course->category)) {
2819 // We need to load the category structure for this course
2820 $this->load_all_categories($course->category, false);
2822 if (array_key_exists($course->category, $this->addedcategories)) {
2823 $parent = $this->addedcategories[$course->category];
2824 // This could lead to the course being created so we should check whether it is the case again
2825 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2826 return $this->addedcourses[$course->id];
2832 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2833 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2835 $coursenode->hidden = (!$course->visible);
2836 $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false]));
2837 if ($canexpandcourse) {
2838 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2839 $coursenode->nodetype = self::NODETYPE_BRANCH;
2840 $coursenode->isexpandable = true;
2841 } else {
2842 $coursenode->nodetype = self::NODETYPE_LEAF;
2843 $coursenode->isexpandable = false;
2845 if (!$forcegeneric) {
2846 $this->addedcourses[$course->id] = $coursenode;
2849 return $coursenode;
2853 * Returns a cache instance to use for the expand course cache.
2854 * @return cache_session
2856 protected function get_expand_course_cache() {
2857 if ($this->cacheexpandcourse === null) {
2858 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2860 return $this->cacheexpandcourse;
2864 * Checks if a user can expand a course in the navigation.
2866 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2867 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2868 * permits stale data.
2869 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2870 * will be stale.
2871 * It is brought up to date in only one of two ways.
2872 * 1. The user logs out and in again.
2873 * 2. The user browses to the course they've just being given access to.
2875 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2877 * @param stdClass $course
2878 * @return bool
2880 protected function can_expand_course($course) {
2881 $cache = $this->get_expand_course_cache();
2882 $canexpand = $cache->get($course->id);
2883 if ($canexpand === false) {
2884 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2885 $canexpand = (int)$canexpand;
2886 $cache->set($course->id, $canexpand);
2888 return ($canexpand === 1);
2892 * Returns true if the category has already been loaded as have any child categories
2894 * @param int $categoryid
2895 * @return bool
2897 protected function is_category_fully_loaded($categoryid) {
2898 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2902 * Adds essential course nodes to the navigation for the given course.
2904 * This method adds nodes such as reports, blogs and participants
2906 * @param navigation_node $coursenode
2907 * @param stdClass $course
2908 * @return bool returns true on successful addition of a node.
2910 public function add_course_essentials($coursenode, stdClass $course) {
2911 global $CFG, $SITE;
2912 require_once($CFG->dirroot . '/course/lib.php');
2914 if ($course->id == $SITE->id) {
2915 return $this->add_front_page_course_essentials($coursenode, $course);
2918 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2919 return true;
2922 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2924 //Participants
2925 if ($navoptions->participants) {
2926 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2927 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2929 if ($navoptions->blogs) {
2930 $blogsurls = new moodle_url('/blog/index.php');
2931 if ($currentgroup = groups_get_course_group($course, true)) {
2932 $blogsurls->param('groupid', $currentgroup);
2933 } else {
2934 $blogsurls->param('courseid', $course->id);
2936 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2939 if ($navoptions->notes) {
2940 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2942 } else if (count($this->extendforuser) > 0) {
2943 $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2946 // Badges.
2947 if ($navoptions->badges) {
2948 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2950 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2951 navigation_node::TYPE_SETTING, null, 'badgesview',
2952 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2955 // Check access to the course and competencies page.
2956 if ($navoptions->competencies) {
2957 // Just a link to course competency.
2958 $title = get_string('competencies', 'core_competency');
2959 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2960 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2961 new pix_icon('i/competencies', ''));
2963 if ($navoptions->grades) {
2964 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2965 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2966 'grades', new pix_icon('i/grades', ''));
2967 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2968 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2969 $gradenode->make_active();
2973 return true;
2976 * This generates the structure of the course that won't be generated when
2977 * the modules and sections are added.
2979 * Things such as the reports branch, the participants branch, blogs... get
2980 * added to the course node by this method.
2982 * @param navigation_node $coursenode
2983 * @param stdClass $course
2984 * @return bool True for successfull generation
2986 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2987 global $CFG, $USER, $COURSE, $SITE;
2988 require_once($CFG->dirroot . '/course/lib.php');
2990 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2991 return true;
2994 $systemcontext = context_system::instance();
2995 $navoptions = course_get_user_navigation_options($systemcontext, $course);
2997 // Hidden node that we use to determine if the front page navigation is loaded.
2998 // This required as there are not other guaranteed nodes that may be loaded.
2999 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
3001 // Add My courses to the site pages within the navigation structure so the block can read it.
3002 $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses');
3004 // Participants.
3005 if ($navoptions->participants) {
3006 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
3007 self::TYPE_CUSTOM, get_string('participants'), 'participants');
3010 // Blogs.
3011 if ($navoptions->blogs) {
3012 $blogsurls = new moodle_url('/blog/index.php');
3013 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
3016 $filterselect = 0;
3018 // Badges.
3019 if ($navoptions->badges) {
3020 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
3021 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
3024 // Notes.
3025 if ($navoptions->notes) {
3026 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
3027 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
3030 // Tags
3031 if ($navoptions->tags) {
3032 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
3033 self::TYPE_SETTING, null, 'tags');
3036 // Search.
3037 if ($navoptions->search) {
3038 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
3039 self::TYPE_SETTING, null, 'search');
3042 if (isloggedin()) {
3043 $usercontext = context_user::instance($USER->id);
3044 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
3045 $url = new moodle_url('/user/files.php');
3046 $node = $coursenode->add(get_string('privatefiles'), $url,
3047 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
3048 $node->display = false;
3049 $node->showinflatnavigation = true;
3050 $node->mainnavonly = true;
3054 if (isloggedin()) {
3055 $context = $this->page->context;
3056 switch ($context->contextlevel) {
3057 case CONTEXT_COURSECAT:
3058 // OK, expected context level.
3059 break;
3060 case CONTEXT_COURSE:
3061 // OK, expected context level if not on frontpage.
3062 if ($COURSE->id != $SITE->id) {
3063 break;
3065 default:
3066 // If this context is part of a course (excluding frontpage), use the course context.
3067 // Otherwise, use the system context.
3068 $coursecontext = $context->get_course_context(false);
3069 if ($coursecontext && $coursecontext->instanceid !== $SITE->id) {
3070 $context = $coursecontext;
3071 } else {
3072 $context = $systemcontext;
3076 $params = ['contextid' => $context->id];
3077 if (has_capability('moodle/contentbank:access', $context)) {
3078 $url = new moodle_url('/contentbank/index.php', $params);
3079 $node = $coursenode->add(get_string('contentbank'), $url,
3080 self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', ''));
3081 $node->showinflatnavigation = true;
3085 return true;
3089 * Clears the navigation cache
3091 public function clear_cache() {
3092 $this->cache->clear();
3096 * Sets an expansion limit for the navigation
3098 * The expansion limit is used to prevent the display of content that has a type
3099 * greater than the provided $type.
3101 * Can be used to ensure things such as activities or activity content don't get
3102 * shown on the navigation.
3103 * They are still generated in order to ensure the navbar still makes sense.
3105 * @param int $type One of navigation_node::TYPE_*
3106 * @return bool true when complete.
3108 public function set_expansion_limit($type) {
3109 global $SITE;
3110 $nodes = $this->find_all_of_type($type);
3112 // We only want to hide specific types of nodes.
3113 // Only nodes that represent "structure" in the navigation tree should be hidden.
3114 // If we hide all nodes then we risk hiding vital information.
3115 $typestohide = array(
3116 self::TYPE_CATEGORY,
3117 self::TYPE_COURSE,
3118 self::TYPE_SECTION,
3119 self::TYPE_ACTIVITY
3122 foreach ($nodes as $node) {
3123 // We need to generate the full site node
3124 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
3125 continue;
3127 foreach ($node->children as $child) {
3128 $child->hide($typestohide);
3131 return true;
3134 * Attempts to get the navigation with the given key from this nodes children.
3136 * This function only looks at this nodes children, it does NOT look recursivily.
3137 * If the node can't be found then false is returned.
3139 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3141 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3142 * may be of more use to you.
3144 * @param string|int $key The key of the node you wish to receive.
3145 * @param int $type One of navigation_node::TYPE_*
3146 * @return navigation_node|false
3148 public function get($key, $type = null) {
3149 if (!$this->initialised) {
3150 $this->initialise();
3152 return parent::get($key, $type);
3156 * Searches this nodes children and their children to find a navigation node
3157 * with the matching key and type.
3159 * This method is recursive and searches children so until either a node is
3160 * found or there are no more nodes to search.
3162 * If you know that the node being searched for is a child of this node
3163 * then use the {@link global_navigation::get()} method instead.
3165 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3166 * may be of more use to you.
3168 * @param string|int $key The key of the node you wish to receive.
3169 * @param int $type One of navigation_node::TYPE_*
3170 * @return navigation_node|false
3172 public function find($key, $type) {
3173 if (!$this->initialised) {
3174 $this->initialise();
3176 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
3177 return $this->rootnodes[$key];
3179 return parent::find($key, $type);
3183 * They've expanded the 'my courses' branch.
3185 protected function load_courses_enrolled() {
3186 global $CFG;
3188 $limit = (int) $CFG->navcourselimit;
3190 $courses = enrol_get_my_courses('*');
3191 $flatnavcourses = [];
3193 // Go through the courses and see which ones we want to display in the flatnav.
3194 foreach ($courses as $course) {
3195 $classify = course_classify_for_timeline($course);
3197 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3198 $flatnavcourses[$course->id] = $course;
3202 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3203 $numtotalcourses = count($courses);
3204 $numtotalflatnavcourses = count($flatnavcourses);
3206 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3207 $courses = array_slice($courses, 0, $limit, true);
3208 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3210 // Get the number of courses we are going to show for each.
3211 $numshowncourses = count($courses);
3212 $numshownflatnavcourses = count($flatnavcourses);
3213 if ($numshowncourses && $this->show_my_categories()) {
3214 // Generate an array containing unique values of all the courses' categories.
3215 $categoryids = array();
3216 foreach ($courses as $course) {
3217 if (in_array($course->category, $categoryids)) {
3218 continue;
3220 $categoryids[] = $course->category;
3223 // Array of category IDs that include the categories of the user's courses and the related course categories.
3224 $fullpathcategoryids = [];
3225 // Get the course categories for the enrolled courses' category IDs.
3226 $mycoursecategories = core_course_category::get_many($categoryids);
3227 // Loop over each of these categories and build the category tree using each category's path.
3228 foreach ($mycoursecategories as $mycoursecat) {
3229 $pathcategoryids = explode('/', $mycoursecat->path);
3230 // First element of the exploded path is empty since paths begin with '/'.
3231 array_shift($pathcategoryids);
3232 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3233 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3236 // Fetch all of the categories related to the user's courses.
3237 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3238 // Loop over each of these categories and build the category tree.
3239 foreach ($pathcategories as $coursecat) {
3240 // No need to process categories that have already been added.
3241 if (isset($this->addedcategories[$coursecat->id])) {
3242 continue;
3244 // Skip categories that are not visible.
3245 if (!$coursecat->is_uservisible()) {
3246 continue;
3249 // Get this course category's parent node.
3250 $parent = null;
3251 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3252 $parent = $this->addedcategories[$coursecat->parent];
3254 if (!$parent) {
3255 // If it has no parent, then it should be right under the My courses node.
3256 $parent = $this->rootnodes['mycourses'];
3259 // Build the category object based from the coursecat object.
3260 $mycategory = new stdClass();
3261 $mycategory->id = $coursecat->id;
3262 $mycategory->name = $coursecat->name;
3263 $mycategory->visible = $coursecat->visible;
3265 // Add this category to the nav tree.
3266 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3270 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3271 foreach ($courses as $course) {
3272 $node = $this->add_course($course, false, self::COURSE_MY);
3273 if ($node) {
3274 $node->showinflatnavigation = false;
3275 // Check if we should also add this to the flat nav as well.
3276 if (isset($flatnavcourses[$course->id])) {
3277 $node->showinflatnavigation = true;
3282 // Go through each course in the flatnav now.
3283 foreach ($flatnavcourses as $course) {
3284 // Check if we haven't already added it.
3285 if (!isset($courses[$course->id])) {
3286 // Ok, add it to the flatnav only.
3287 $node = $this->add_course($course, false, self::COURSE_MY);
3288 $node->display = false;
3289 $node->showinflatnavigation = true;
3293 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3294 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3295 // Show a link to the course page if there are more courses the user is enrolled in.
3296 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3297 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3298 $url = new moodle_url('/my/courses.php');
3299 $parent = $this->rootnodes['mycourses'];
3300 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3302 if ($showmorelinkinnav) {
3303 $coursenode->display = true;
3306 if ($showmorelinkinflatnav) {
3307 $coursenode->showinflatnavigation = true;
3314 * The global navigation class used especially for AJAX requests.
3316 * The primary methods that are used in the global navigation class have been overriden
3317 * to ensure that only the relevant branch is generated at the root of the tree.
3318 * This can be done because AJAX is only used when the backwards structure for the
3319 * requested branch exists.
3320 * This has been done only because it shortens the amounts of information that is generated
3321 * which of course will speed up the response time.. because no one likes laggy AJAX.
3323 * @package core
3324 * @category navigation
3325 * @copyright 2009 Sam Hemelryk
3326 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3328 class global_navigation_for_ajax extends global_navigation {
3330 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3331 protected $branchtype;
3333 /** @var int the instance id */
3334 protected $instanceid;
3336 /** @var array Holds an array of expandable nodes */
3337 protected $expandable = array();
3340 * Constructs the navigation for use in an AJAX request
3342 * @param moodle_page $page moodle_page object
3343 * @param int $branchtype
3344 * @param int $id
3346 public function __construct($page, $branchtype, $id) {
3347 $this->page = $page;
3348 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3349 $this->children = new navigation_node_collection();
3350 $this->branchtype = $branchtype;
3351 $this->instanceid = $id;
3352 $this->initialise();
3355 * Initialise the navigation given the type and id for the branch to expand.
3357 * @return array An array of the expandable nodes
3359 public function initialise() {
3360 global $DB, $SITE;
3362 if ($this->initialised || during_initial_install()) {
3363 return $this->expandable;
3365 $this->initialised = true;
3367 $this->rootnodes = array();
3368 $this->rootnodes['site'] = $this->add_course($SITE);
3369 $this->rootnodes['mycourses'] = $this->add(
3370 get_string('mycourses'),
3371 new moodle_url('/my/courses.php'),
3372 self::TYPE_ROOTNODE,
3373 null,
3374 'mycourses'
3376 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3377 // The courses branch is always displayed, and is always expandable (although may be empty).
3378 // This mimicks what is done during {@link global_navigation::initialise()}.
3379 $this->rootnodes['courses']->isexpandable = true;
3381 // Branchtype will be one of navigation_node::TYPE_*
3382 switch ($this->branchtype) {
3383 case 0:
3384 if ($this->instanceid === 'mycourses') {
3385 $this->load_courses_enrolled();
3386 } else if ($this->instanceid === 'courses') {
3387 $this->load_courses_other();
3389 break;
3390 case self::TYPE_CATEGORY :
3391 $this->load_category($this->instanceid);
3392 break;
3393 case self::TYPE_MY_CATEGORY :
3394 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3395 break;
3396 case self::TYPE_COURSE :
3397 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3398 if (!can_access_course($course, null, '', true)) {
3399 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3400 // add the course node and break. This leads to an empty node.
3401 $this->add_course($course);
3402 break;
3404 require_course_login($course, true, null, false, true);
3405 $this->page->set_context(context_course::instance($course->id));
3406 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3407 $this->add_course_essentials($coursenode, $course);
3408 $this->load_course_sections($course, $coursenode);
3409 break;
3410 case self::TYPE_SECTION :
3411 $sql = 'SELECT c.*, cs.section AS sectionnumber
3412 FROM {course} c
3413 LEFT JOIN {course_sections} cs ON cs.course = c.id
3414 WHERE cs.id = ?';
3415 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3416 require_course_login($course, true, null, false, true);
3417 $this->page->set_context(context_course::instance($course->id));
3418 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3419 $this->add_course_essentials($coursenode, $course);
3420 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3421 break;
3422 case self::TYPE_ACTIVITY :
3423 $sql = "SELECT c.*
3424 FROM {course} c
3425 JOIN {course_modules} cm ON cm.course = c.id
3426 WHERE cm.id = :cmid";
3427 $params = array('cmid' => $this->instanceid);
3428 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3429 $modinfo = get_fast_modinfo($course);
3430 $cm = $modinfo->get_cm($this->instanceid);
3431 require_course_login($course, true, $cm, false, true);
3432 $this->page->set_context(context_module::instance($cm->id));
3433 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3434 $this->load_course_sections($course, $coursenode, null, $cm);
3435 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3436 if ($activitynode) {
3437 $modulenode = $this->load_activity($cm, $course, $activitynode);
3439 break;
3440 default:
3441 throw new Exception('Unknown type');
3442 return $this->expandable;
3445 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3446 $this->load_for_user(null, true);
3449 // Give the local plugins a chance to include some navigation if they want.
3450 $this->load_local_plugin_navigation();
3452 $this->find_expandable($this->expandable);
3453 return $this->expandable;
3457 * They've expanded the general 'courses' branch.
3459 protected function load_courses_other() {
3460 $this->load_all_courses();
3464 * Loads a single category into the AJAX navigation.
3466 * This function is special in that it doesn't concern itself with the parent of
3467 * the requested category or its siblings.
3468 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3469 * request that.
3471 * @global moodle_database $DB
3472 * @param int $categoryid id of category to load in navigation.
3473 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3474 * @return void.
3476 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3477 global $CFG, $DB;
3479 $limit = 20;
3480 if (!empty($CFG->navcourselimit)) {
3481 $limit = (int)$CFG->navcourselimit;
3484 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3485 $sql = "SELECT cc.*, $catcontextsql
3486 FROM {course_categories} cc
3487 JOIN {context} ctx ON cc.id = ctx.instanceid
3488 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3489 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3490 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3491 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3492 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3493 $categorylist = array();
3494 $subcategories = array();
3495 $basecategory = null;
3496 foreach ($categories as $category) {
3497 $categorylist[] = $category->id;
3498 context_helper::preload_from_record($category);
3499 if ($category->id == $categoryid) {
3500 $this->add_category($category, $this, $nodetype);
3501 $basecategory = $this->addedcategories[$category->id];
3502 } else {
3503 $subcategories[$category->id] = $category;
3506 $categories->close();
3509 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3510 // else show all courses.
3511 if ($nodetype === self::TYPE_MY_CATEGORY) {
3512 $courses = enrol_get_my_courses('*');
3513 $categoryids = array();
3515 // Only search for categories if basecategory was found.
3516 if (!is_null($basecategory)) {
3517 // Get course parent category ids.
3518 foreach ($courses as $course) {
3519 $categoryids[] = $course->category;
3522 // Get a unique list of category ids which a part of the path
3523 // to user's courses.
3524 $coursesubcategories = array();
3525 $addedsubcategories = array();
3527 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3528 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3530 foreach ($categories as $category){
3531 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3533 $categories->close();
3534 $coursesubcategories = array_unique($coursesubcategories);
3536 // Only add a subcategory if it is part of the path to user's course and
3537 // wasn't already added.
3538 foreach ($subcategories as $subid => $subcategory) {
3539 if (in_array($subid, $coursesubcategories) &&
3540 !in_array($subid, $addedsubcategories)) {
3541 $this->add_category($subcategory, $basecategory, $nodetype);
3542 $addedsubcategories[] = $subid;
3547 foreach ($courses as $course) {
3548 // Add course if it's in category.
3549 if (in_array($course->category, $categorylist)) {
3550 $this->add_course($course, true, self::COURSE_MY);
3553 } else {
3554 if (!is_null($basecategory)) {
3555 foreach ($subcategories as $key=>$category) {
3556 $this->add_category($category, $basecategory, $nodetype);
3559 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3560 foreach ($courses as $course) {
3561 $this->add_course($course);
3563 $courses->close();
3568 * Returns an array of expandable nodes
3569 * @return array
3571 public function get_expandable() {
3572 return $this->expandable;
3577 * Navbar class
3579 * This class is used to manage the navbar, which is initialised from the navigation
3580 * object held by PAGE
3582 * @package core
3583 * @category navigation
3584 * @copyright 2009 Sam Hemelryk
3585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3587 class navbar extends navigation_node {
3588 /** @var bool A switch for whether the navbar is initialised or not */
3589 protected $initialised = false;
3590 /** @var mixed keys used to reference the nodes on the navbar */
3591 protected $keys = array();
3592 /** @var null|string content of the navbar */
3593 protected $content = null;
3594 /** @var moodle_page object the moodle page that this navbar belongs to */
3595 protected $page;
3596 /** @var bool A switch for whether to ignore the active navigation information */
3597 protected $ignoreactive = false;
3598 /** @var bool A switch to let us know if we are in the middle of an install */
3599 protected $duringinstall = false;
3600 /** @var bool A switch for whether the navbar has items */
3601 protected $hasitems = false;
3602 /** @var array An array of navigation nodes for the navbar */
3603 protected $items;
3604 /** @var array An array of child node objects */
3605 public $children = array();
3606 /** @var bool A switch for whether we want to include the root node in the navbar */
3607 public $includesettingsbase = false;
3608 /** @var breadcrumb_navigation_node[] $prependchildren */
3609 protected $prependchildren = array();
3612 * The almighty constructor
3614 * @param moodle_page $page
3616 public function __construct(moodle_page $page) {
3617 global $CFG;
3618 if (during_initial_install()) {
3619 $this->duringinstall = true;
3620 return false;
3622 $this->page = $page;
3623 $this->text = get_string('home');
3624 $this->shorttext = get_string('home');
3625 $this->action = new moodle_url($CFG->wwwroot);
3626 $this->nodetype = self::NODETYPE_BRANCH;
3627 $this->type = self::TYPE_SYSTEM;
3631 * Quick check to see if the navbar will have items in.
3633 * @return bool Returns true if the navbar will have items, false otherwise
3635 public function has_items() {
3636 if ($this->duringinstall) {
3637 return false;
3638 } else if ($this->hasitems !== false) {
3639 return true;
3641 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3642 // There have been manually added items - there are definitely items.
3643 $outcome = true;
3644 } else if (!$this->ignoreactive) {
3645 // We will need to initialise the navigation structure to check if there are active items.
3646 $this->page->navigation->initialise($this->page);
3647 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3649 $this->hasitems = $outcome;
3650 return $outcome;
3654 * Turn on/off ignore active
3656 * @param bool $setting
3658 public function ignore_active($setting=true) {
3659 $this->ignoreactive = ($setting);
3663 * Gets a navigation node
3665 * @param string|int $key for referencing the navbar nodes
3666 * @param int $type breadcrumb_navigation_node::TYPE_*
3667 * @return breadcrumb_navigation_node|bool
3669 public function get($key, $type = null) {
3670 foreach ($this->children as &$child) {
3671 if ($child->key === $key && ($type == null || $type == $child->type)) {
3672 return $child;
3675 foreach ($this->prependchildren as &$child) {
3676 if ($child->key === $key && ($type == null || $type == $child->type)) {
3677 return $child;
3680 return false;
3683 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3685 * @return array
3687 public function get_items() {
3688 global $CFG;
3689 $items = array();
3690 // Make sure that navigation is initialised
3691 if (!$this->has_items()) {
3692 return $items;
3694 if ($this->items !== null) {
3695 return $this->items;
3698 if (count($this->children) > 0) {
3699 // Add the custom children.
3700 $items = array_reverse($this->children);
3703 // Check if navigation contains the active node
3704 if (!$this->ignoreactive) {
3705 // We will need to ensure the navigation has been initialised.
3706 $this->page->navigation->initialise($this->page);
3707 // Now find the active nodes on both the navigation and settings.
3708 $navigationactivenode = $this->page->navigation->find_active_node();
3709 $settingsactivenode = $this->page->settingsnav->find_active_node();
3711 if ($navigationactivenode && $settingsactivenode) {
3712 // Parse a combined navigation tree
3713 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3714 if (!$settingsactivenode->mainnavonly) {
3715 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3717 $settingsactivenode = $settingsactivenode->parent;
3719 if (!$this->includesettingsbase) {
3720 // Removes the first node from the settings (root node) from the list
3721 array_pop($items);
3723 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3724 if (!$navigationactivenode->mainnavonly) {
3725 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3727 if (!empty($CFG->navshowcategories) &&
3728 $navigationactivenode->type === self::TYPE_COURSE &&
3729 $navigationactivenode->parent->key === 'currentcourse') {
3730 foreach ($this->get_course_categories() as $item) {
3731 $items[] = new breadcrumb_navigation_node($item);
3734 $navigationactivenode = $navigationactivenode->parent;
3736 } else if ($navigationactivenode) {
3737 // Parse the navigation tree to get the active node
3738 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3739 if (!$navigationactivenode->mainnavonly) {
3740 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3742 if (!empty($CFG->navshowcategories) &&
3743 $navigationactivenode->type === self::TYPE_COURSE &&
3744 $navigationactivenode->parent->key === 'currentcourse') {
3745 foreach ($this->get_course_categories() as $item) {
3746 $items[] = new breadcrumb_navigation_node($item);
3749 $navigationactivenode = $navigationactivenode->parent;
3751 } else if ($settingsactivenode) {
3752 // Parse the settings navigation to get the active node
3753 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3754 if (!$settingsactivenode->mainnavonly) {
3755 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3757 $settingsactivenode = $settingsactivenode->parent;
3762 $items[] = new breadcrumb_navigation_node(array(
3763 'text' => $this->page->navigation->text,
3764 'shorttext' => $this->page->navigation->shorttext,
3765 'key' => $this->page->navigation->key,
3766 'action' => $this->page->navigation->action
3769 if (count($this->prependchildren) > 0) {
3770 // Add the custom children
3771 $items = array_merge($items, array_reverse($this->prependchildren));
3774 $last = reset($items);
3775 if ($last) {
3776 $last->set_last(true);
3778 $this->items = array_reverse($items);
3779 return $this->items;
3783 * Get the list of categories leading to this course.
3785 * This function is used by {@link navbar::get_items()} to add back the "courses"
3786 * node and category chain leading to the current course. Note that this is only ever
3787 * called for the current course, so we don't need to bother taking in any parameters.
3789 * @return array
3791 private function get_course_categories() {
3792 global $CFG;
3793 require_once($CFG->dirroot.'/course/lib.php');
3795 $categories = array();
3796 $cap = 'moodle/category:viewhiddencategories';
3797 $showcategories = !core_course_category::is_simple_site();
3799 if ($showcategories) {
3800 foreach ($this->page->categories as $category) {
3801 $context = context_coursecat::instance($category->id);
3802 if (!core_course_category::can_view_category($category)) {
3803 continue;
3806 $displaycontext = \context_helper::get_navigation_filter_context($context);
3807 $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]);
3808 $name = format_string($category->name, true, ['context' => $displaycontext]);
3809 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3810 if (!$category->visible) {
3811 $categorynode->hidden = true;
3813 $categories[] = $categorynode;
3817 // Don't show the 'course' node if enrolled in this course.
3818 $coursecontext = context_course::instance($this->page->course->id);
3819 if (!is_enrolled($coursecontext, null, '', true)) {
3820 $courses = $this->page->navigation->get('courses');
3821 if (!$courses) {
3822 // Courses node may not be present.
3823 $courses = breadcrumb_navigation_node::create(
3824 get_string('courses'),
3825 new moodle_url('/course/index.php'),
3826 self::TYPE_CONTAINER
3829 $categories[] = $courses;
3832 return $categories;
3836 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3838 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3839 * the way nodes get added to allow us to simply call add and have the node added to the
3840 * end of the navbar
3842 * @param string $text
3843 * @param string|moodle_url|action_link $action An action to associate with this node.
3844 * @param int $type One of navigation_node::TYPE_*
3845 * @param string $shorttext
3846 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3847 * @param pix_icon $icon An optional icon to use for this node.
3848 * @return navigation_node
3850 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3851 if ($this->content !== null) {
3852 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3855 // Properties array used when creating the new navigation node
3856 $itemarray = array(
3857 'text' => $text,
3858 'type' => $type
3860 // Set the action if one was provided
3861 if ($action!==null) {
3862 $itemarray['action'] = $action;
3864 // Set the shorttext if one was provided
3865 if ($shorttext!==null) {
3866 $itemarray['shorttext'] = $shorttext;
3868 // Set the icon if one was provided
3869 if ($icon!==null) {
3870 $itemarray['icon'] = $icon;
3872 // Default the key to the number of children if not provided
3873 if ($key === null) {
3874 $key = count($this->children);
3876 // Set the key
3877 $itemarray['key'] = $key;
3878 // Set the parent to this node
3879 $itemarray['parent'] = $this;
3880 // Add the child using the navigation_node_collections add method
3881 $this->children[] = new breadcrumb_navigation_node($itemarray);
3882 return $this;
3886 * Prepends a new navigation_node to the start of the navbar
3888 * @param string $text
3889 * @param string|moodle_url|action_link $action An action to associate with this node.
3890 * @param int $type One of navigation_node::TYPE_*
3891 * @param string $shorttext
3892 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3893 * @param pix_icon $icon An optional icon to use for this node.
3894 * @return navigation_node
3896 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3897 if ($this->content !== null) {
3898 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3900 // Properties array used when creating the new navigation node.
3901 $itemarray = array(
3902 'text' => $text,
3903 'type' => $type
3905 // Set the action if one was provided.
3906 if ($action!==null) {
3907 $itemarray['action'] = $action;
3909 // Set the shorttext if one was provided.
3910 if ($shorttext!==null) {
3911 $itemarray['shorttext'] = $shorttext;
3913 // Set the icon if one was provided.
3914 if ($icon!==null) {
3915 $itemarray['icon'] = $icon;
3917 // Default the key to the number of children if not provided.
3918 if ($key === null) {
3919 $key = count($this->children);
3921 // Set the key.
3922 $itemarray['key'] = $key;
3923 // Set the parent to this node.
3924 $itemarray['parent'] = $this;
3925 // Add the child node to the prepend list.
3926 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3927 return $this;
3932 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3933 * in particular adding extra metadata for search engine robots to leverage.
3935 * @package core
3936 * @category navigation
3937 * @copyright 2015 Brendan Heywood
3938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3940 class breadcrumb_navigation_node extends navigation_node {
3942 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3943 private $last = false;
3946 * A proxy constructor
3948 * @param mixed $navnode A navigation_node or an array
3950 public function __construct($navnode) {
3951 if (is_array($navnode)) {
3952 parent::__construct($navnode);
3953 } else if ($navnode instanceof navigation_node) {
3955 // Just clone everything.
3956 $objvalues = get_object_vars($navnode);
3957 foreach ($objvalues as $key => $value) {
3958 $this->$key = $value;
3960 } else {
3961 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3966 * Getter for "last"
3967 * @return boolean
3969 public function is_last() {
3970 return $this->last;
3974 * Setter for "last"
3975 * @param $val boolean
3977 public function set_last($val) {
3978 $this->last = $val;
3983 * Subclass of navigation_node allowing different rendering for the flat navigation
3984 * in particular allowing dividers and indents.
3986 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts
3987 * @package core
3988 * @category navigation
3989 * @copyright 2016 Damyon Wiese
3990 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3992 class flat_navigation_node extends navigation_node {
3994 /** @var $indent integer The indent level */
3995 private $indent = 0;
3997 /** @var $showdivider bool Show a divider before this element */
3998 private $showdivider = false;
4000 /** @var $collectionlabel string Label for a group of nodes */
4001 private $collectionlabel = '';
4004 * A proxy constructor
4006 * @param mixed $navnode A navigation_node or an array
4008 public function __construct($navnode, $indent) {
4009 debugging("Flat nav has been deprecated in favour of primary/secondary navigation concepts");
4010 if (is_array($navnode)) {
4011 parent::__construct($navnode);
4012 } else if ($navnode instanceof navigation_node) {
4014 // Just clone everything.
4015 $objvalues = get_object_vars($navnode);
4016 foreach ($objvalues as $key => $value) {
4017 $this->$key = $value;
4019 } else {
4020 throw new coding_exception('Not a valid flat_navigation_node');
4022 $this->indent = $indent;
4026 * Setter, a label is required for a flat navigation node that shows a divider.
4028 * @param string $label
4030 public function set_collectionlabel($label) {
4031 $this->collectionlabel = $label;
4035 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
4037 * @return string
4039 public function get_collectionlabel() {
4040 if (!empty($this->collectionlabel)) {
4041 return $this->collectionlabel;
4043 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) {
4044 return $this->parent->get_collectionlabel();
4046 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
4047 return '';
4051 * Does this node represent a course section link.
4052 * @return boolean
4054 public function is_section() {
4055 return $this->type == navigation_node::TYPE_SECTION;
4059 * In flat navigation - sections are active if we are looking at activities in the section.
4060 * @return boolean
4062 public function isactive() {
4063 global $PAGE;
4065 if ($this->is_section()) {
4066 $active = $PAGE->navigation->find_active_node();
4067 if ($active) {
4068 while ($active = $active->parent) {
4069 if ($active->key == $this->key && $active->type == $this->type) {
4070 return true;
4075 return $this->isactive;
4079 * Getter for "showdivider"
4080 * @return boolean
4082 public function showdivider() {
4083 return $this->showdivider;
4087 * Setter for "showdivider"
4088 * @param $val boolean
4089 * @param $label string Label for the group of nodes
4091 public function set_showdivider($val, $label = '') {
4092 $this->showdivider = $val;
4093 if ($this->showdivider && empty($label)) {
4094 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
4095 } else {
4096 $this->set_collectionlabel($label);
4101 * Getter for "indent"
4102 * @return boolean
4104 public function get_indent() {
4105 return $this->indent;
4109 * Setter for "indent"
4110 * @param $val boolean
4112 public function set_indent($val) {
4113 $this->indent = $val;
4118 * Class used to generate a collection of navigation nodes most closely related
4119 * to the current page.
4121 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts
4122 * @package core
4123 * @copyright 2016 Damyon Wiese
4124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4126 class flat_navigation extends navigation_node_collection {
4127 /** @var moodle_page the moodle page that the navigation belongs to */
4128 protected $page;
4131 * Constructor.
4133 * @param moodle_page $page
4135 public function __construct(moodle_page &$page) {
4136 if (during_initial_install()) {
4137 return false;
4139 debugging("Flat navigation has been deprecated in favour of primary/secondary navigation concepts");
4140 $this->page = $page;
4144 * Build the list of navigation nodes based on the current navigation and settings trees.
4147 public function initialise() {
4148 global $PAGE, $USER, $OUTPUT, $CFG;
4149 if (during_initial_install()) {
4150 return;
4153 $current = false;
4155 $course = $PAGE->course;
4157 $this->page->navigation->initialise();
4159 // First walk the nav tree looking for "flat_navigation" nodes.
4160 if ($course->id > 1) {
4161 // It's a real course.
4162 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4164 $coursecontext = context_course::instance($course->id, MUST_EXIST);
4165 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
4166 // This is the name that will be shown for the course.
4167 $coursename = empty($CFG->navshowfullcoursenames) ?
4168 format_string($course->shortname, true, ['context' => $displaycontext]) :
4169 format_string($course->fullname, true, ['context' => $displaycontext]);
4171 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
4172 $flat->set_collectionlabel($coursename);
4173 $flat->key = 'coursehome';
4174 $flat->icon = new pix_icon('i/course', '');
4176 $courseformat = course_get_format($course);
4177 $coursenode = $PAGE->navigation->find_active_node();
4178 $targettype = navigation_node::TYPE_COURSE;
4180 // Single activity format has no course node - the course node is swapped for the activity node.
4181 if (!$courseformat->has_view_page()) {
4182 $targettype = navigation_node::TYPE_ACTIVITY;
4185 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
4186 $coursenode = $coursenode->parent;
4188 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4189 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4190 if ($coursenode && $coursenode->key != SITEID) {
4191 $this->add($flat);
4192 foreach ($coursenode->children as $child) {
4193 if ($child->action) {
4194 $flat = new flat_navigation_node($child, 0);
4195 $this->add($flat);
4200 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
4201 } else {
4202 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
4205 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
4206 if (!$admin) {
4207 // Try again - crazy nav tree!
4208 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
4210 if ($admin) {
4211 $flat = new flat_navigation_node($admin, 0);
4212 $flat->set_showdivider(true, get_string('sitesettings'));
4213 $flat->key = 'sitesettings';
4214 $flat->icon = new pix_icon('t/preferences', '');
4215 $this->add($flat);
4218 // Add-a-block in editing mode.
4219 if (isset($this->page->theme->addblockposition) &&
4220 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
4221 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) {
4222 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
4223 $addablock = navigation_node::create(get_string('addblock'), $url);
4224 $flat = new flat_navigation_node($addablock, 0);
4225 $flat->set_showdivider(true, get_string('blocksaddedit'));
4226 $flat->key = 'addblock';
4227 $flat->icon = new pix_icon('i/addblock', '');
4228 $this->add($flat);
4230 $addblockurl = "?{$url->get_query_string(false)}";
4232 $PAGE->requires->js_call_amd('core_block/add_modal', 'init',
4233 [$addblockurl, $this->page->get_edited_page_hash()]);
4238 * Override the parent so we can set a label for this collection if it has not been set yet.
4240 * @param navigation_node $node Node to add
4241 * @param string $beforekey If specified, adds before a node with this key,
4242 * otherwise adds at end
4243 * @return navigation_node Added node
4245 public function add(navigation_node $node, $beforekey=null) {
4246 $result = parent::add($node, $beforekey);
4247 // Extend the parent to get a name for the collection of nodes if required.
4248 if (empty($this->collectionlabel)) {
4249 if ($node instanceof flat_navigation_node) {
4250 $this->set_collectionlabel($node->get_collectionlabel());
4254 return $result;
4259 * Class used to manage the settings option for the current page
4261 * This class is used to manage the settings options in a tree format (recursively)
4262 * and was created initially for use with the settings blocks.
4264 * @package core
4265 * @category navigation
4266 * @copyright 2009 Sam Hemelryk
4267 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4269 class settings_navigation extends navigation_node {
4270 /** @var stdClass the current context */
4271 protected $context;
4272 /** @var moodle_page the moodle page that the navigation belongs to */
4273 protected $page;
4274 /** @var string contains administration section navigation_nodes */
4275 protected $adminsection;
4276 /** @var bool A switch to see if the navigation node is initialised */
4277 protected $initialised = false;
4278 /** @var array An array of users that the nodes can extend for. */
4279 protected $userstoextendfor = array();
4280 /** @var navigation_cache **/
4281 protected $cache;
4284 * Sets up the object with basic settings and preparse it for use
4286 * @param moodle_page $page
4288 public function __construct(moodle_page &$page) {
4289 if (during_initial_install()) {
4290 return false;
4292 $this->page = $page;
4293 // Initialise the main navigation. It is most important that this is done
4294 // before we try anything
4295 $this->page->navigation->initialise();
4296 // Initialise the navigation cache
4297 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4298 $this->children = new navigation_node_collection();
4302 * Initialise the settings navigation based on the current context
4304 * This function initialises the settings navigation tree for a given context
4305 * by calling supporting functions to generate major parts of the tree.
4308 public function initialise() {
4309 global $DB, $SESSION, $SITE;
4311 if (during_initial_install()) {
4312 return false;
4313 } else if ($this->initialised) {
4314 return true;
4316 $this->id = 'settingsnav';
4317 $this->context = $this->page->context;
4319 $context = $this->context;
4320 if ($context->contextlevel == CONTEXT_BLOCK) {
4321 $this->load_block_settings();
4322 $context = $context->get_parent_context();
4323 $this->context = $context;
4325 switch ($context->contextlevel) {
4326 case CONTEXT_SYSTEM:
4327 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4328 $this->load_front_page_settings(($context->id == $this->context->id));
4330 break;
4331 case CONTEXT_COURSECAT:
4332 $this->load_category_settings();
4333 break;
4334 case CONTEXT_COURSE:
4335 if ($this->page->course->id != $SITE->id) {
4336 $this->load_course_settings(($context->id == $this->context->id));
4337 } else {
4338 $this->load_front_page_settings(($context->id == $this->context->id));
4340 break;
4341 case CONTEXT_MODULE:
4342 $this->load_module_settings();
4343 $this->load_course_settings();
4344 break;
4345 case CONTEXT_USER:
4346 if ($this->page->course->id != $SITE->id) {
4347 $this->load_course_settings();
4349 break;
4352 $usersettings = $this->load_user_settings($this->page->course->id);
4354 $adminsettings = false;
4355 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4356 $isadminpage = $this->is_admin_tree_needed();
4358 if (has_capability('moodle/site:configview', context_system::instance())) {
4359 if (has_capability('moodle/site:config', context_system::instance())) {
4360 // Make sure this works even if config capability changes on the fly
4361 // and also make it fast for admin right after login.
4362 $SESSION->load_navigation_admin = 1;
4363 if ($isadminpage) {
4364 $adminsettings = $this->load_administration_settings();
4367 } else if (!isset($SESSION->load_navigation_admin)) {
4368 $adminsettings = $this->load_administration_settings();
4369 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4371 } else if ($SESSION->load_navigation_admin) {
4372 if ($isadminpage) {
4373 $adminsettings = $this->load_administration_settings();
4377 // Print empty navigation node, if needed.
4378 if ($SESSION->load_navigation_admin && !$isadminpage) {
4379 if ($adminsettings) {
4380 // Do not print settings tree on pages that do not need it, this helps with performance.
4381 $adminsettings->remove();
4382 $adminsettings = false;
4384 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4385 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4386 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4387 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4388 $siteadminnode->requiresajaxloading = 'true';
4393 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4394 $adminsettings->force_open();
4395 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4396 $usersettings->force_open();
4399 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4400 $this->load_local_plugin_settings();
4402 foreach ($this->children as $key=>$node) {
4403 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4404 // Site administration is shown as link.
4405 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4406 continue;
4408 $node->remove();
4411 $this->initialised = true;
4414 * Override the parent function so that we can add preceeding hr's and set a
4415 * root node class against all first level element
4417 * It does this by first calling the parent's add method {@link navigation_node::add()}
4418 * and then proceeds to use the key to set class and hr
4420 * @param string $text text to be used for the link.
4421 * @param string|moodle_url $url url for the new node
4422 * @param int $type the type of node navigation_node::TYPE_*
4423 * @param string $shorttext
4424 * @param string|int $key a key to access the node by.
4425 * @param pix_icon $icon An icon that appears next to the node.
4426 * @return navigation_node with the new node added to it.
4428 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4429 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4430 $node->add_class('root_node');
4431 return $node;
4435 * This function allows the user to add something to the start of the settings
4436 * navigation, which means it will be at the top of the settings navigation block
4438 * @param string $text text to be used for the link.
4439 * @param string|moodle_url $url url for the new node
4440 * @param int $type the type of node navigation_node::TYPE_*
4441 * @param string $shorttext
4442 * @param string|int $key a key to access the node by.
4443 * @param pix_icon $icon An icon that appears next to the node.
4444 * @return navigation_node $node with the new node added to it.
4446 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4447 $children = $this->children;
4448 $childrenclass = get_class($children);
4449 $this->children = new $childrenclass;
4450 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4451 foreach ($children as $child) {
4452 $this->children->add($child);
4454 return $node;
4458 * Does this page require loading of full admin tree or is
4459 * it enough rely on AJAX?
4461 * @return bool
4463 protected function is_admin_tree_needed() {
4464 if (self::$loadadmintree) {
4465 // Usually external admin page or settings page.
4466 return true;
4469 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4470 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4471 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4472 return false;
4474 return true;
4477 return false;
4481 * Load the site administration tree
4483 * This function loads the site administration tree by using the lib/adminlib library functions
4485 * @param navigation_node $referencebranch A reference to a branch in the settings
4486 * navigation tree
4487 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4488 * tree and start at the beginning
4489 * @return mixed A key to access the admin tree by
4491 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4492 global $CFG;
4494 // Check if we are just starting to generate this navigation.
4495 if ($referencebranch === null) {
4497 // Require the admin lib then get an admin structure
4498 if (!function_exists('admin_get_root')) {
4499 require_once($CFG->dirroot.'/lib/adminlib.php');
4501 $adminroot = admin_get_root(false, false);
4502 // This is the active section identifier
4503 $this->adminsection = $this->page->url->param('section');
4505 // Disable the navigation from automatically finding the active node
4506 navigation_node::$autofindactive = false;
4507 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4508 foreach ($adminroot->children as $adminbranch) {
4509 $this->load_administration_settings($referencebranch, $adminbranch);
4511 navigation_node::$autofindactive = true;
4513 // Use the admin structure to locate the active page
4514 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4515 $currentnode = $this;
4516 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4517 $currentnode = $currentnode->get($pathkey);
4519 if ($currentnode) {
4520 $currentnode->make_active();
4522 } else {
4523 $this->scan_for_active_node($referencebranch);
4525 return $referencebranch;
4526 } else if ($adminbranch->check_access()) {
4527 // We have a reference branch that we can access and is not hidden `hurrah`
4528 // Now we need to display it and any children it may have
4529 $url = null;
4530 $icon = null;
4532 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) {
4533 if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4534 $url = null;
4535 } else {
4536 $url = $adminbranch->get_settings_page_url();
4540 // Add the branch
4541 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4543 if ($adminbranch->is_hidden()) {
4544 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4545 $reference->add_class('hidden');
4546 } else {
4547 $reference->display = false;
4551 // Check if we are generating the admin notifications and whether notificiations exist
4552 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4553 $reference->add_class('criticalnotification');
4555 // Check if this branch has children
4556 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4557 foreach ($adminbranch->children as $branch) {
4558 // Generate the child branches as well now using this branch as the reference
4559 $this->load_administration_settings($reference, $branch);
4561 } else {
4562 $reference->icon = new pix_icon('i/settings', '');
4568 * This function recursivily scans nodes until it finds the active node or there
4569 * are no more nodes.
4570 * @param navigation_node $node
4572 protected function scan_for_active_node(navigation_node $node) {
4573 if (!$node->check_if_active() && $node->children->count()>0) {
4574 foreach ($node->children as &$child) {
4575 $this->scan_for_active_node($child);
4581 * Gets a navigation node given an array of keys that represent the path to
4582 * the desired node.
4584 * @param array $path
4585 * @return navigation_node|false
4587 protected function get_by_path(array $path) {
4588 $node = $this->get(array_shift($path));
4589 foreach ($path as $key) {
4590 $node->get($key);
4592 return $node;
4596 * This function loads the course settings that are available for the user
4598 * @param bool $forceopen If set to true the course node will be forced open
4599 * @return navigation_node|false
4601 protected function load_course_settings($forceopen = false) {
4602 global $CFG, $USER;
4603 require_once($CFG->dirroot . '/course/lib.php');
4605 $course = $this->page->course;
4606 $coursecontext = context_course::instance($course->id);
4607 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4609 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4611 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4612 if ($forceopen) {
4613 $coursenode->force_open();
4617 if ($adminoptions->update) {
4618 // Add the course settings link
4619 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4620 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null,
4621 'editsettings', new pix_icon('i/settings', ''));
4624 if ($adminoptions->editcompletion) {
4625 // Add the course completion settings link
4626 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4627 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion',
4628 new pix_icon('i/settings', ''));
4631 if (!$adminoptions->update && $adminoptions->tags) {
4632 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4633 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4634 $coursenode->get('coursetags')->set_force_into_more_menu();
4637 // add enrol nodes
4638 enrol_add_course_navigation($coursenode, $course);
4640 // Manage filters
4641 if ($adminoptions->filters) {
4642 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4643 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
4644 null, 'filtermanagement', new pix_icon('i/filter', ''));
4647 // View course reports.
4648 if ($adminoptions->reports) {
4649 $reportnav = $coursenode->add(get_string('reports'),
4650 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]),
4651 self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', ''));
4652 $coursereports = core_component::get_plugin_list('coursereport');
4653 foreach ($coursereports as $report => $dir) {
4654 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4655 if (file_exists($libfile)) {
4656 require_once($libfile);
4657 $reportfunction = $report.'_report_extend_navigation';
4658 if (function_exists($report.'_report_extend_navigation')) {
4659 $reportfunction($reportnav, $course, $coursecontext);
4664 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4665 foreach ($reports as $reportfunction) {
4666 $reportfunction($reportnav, $course, $coursecontext);
4669 if (!$reportnav->has_children()) {
4670 $reportnav->remove();
4674 // Check if we can view the gradebook's setup page.
4675 if ($adminoptions->gradebook) {
4676 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4677 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4678 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4681 // Add the context locking node.
4682 $this->add_context_locking_node($coursenode, $coursecontext);
4684 // Add outcome if permitted
4685 if ($adminoptions->outcomes) {
4686 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4687 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4690 //Add badges navigation
4691 if ($adminoptions->badges) {
4692 require_once($CFG->libdir .'/badgeslib.php');
4693 badges_add_course_navigation($coursenode, $course);
4696 // Import data from other courses.
4697 if ($adminoptions->import) {
4698 $url = new moodle_url('/backup/import.php', array('id' => $course->id));
4699 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4702 // Backup this course
4703 if ($adminoptions->backup) {
4704 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4705 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4708 // Restore to this course
4709 if ($adminoptions->restore) {
4710 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4711 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4714 // Copy this course.
4715 if ($adminoptions->copy) {
4716 $url = new moodle_url('/backup/copy.php', array('id' => $course->id));
4717 $coursenode->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', ''));
4720 // Reset this course
4721 if ($adminoptions->reset) {
4722 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4723 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4726 // Questions
4727 require_once($CFG->libdir . '/questionlib.php');
4728 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4730 if ($adminoptions->update) {
4731 // Repository Instances
4732 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4733 require_once($CFG->dirroot . '/repository/lib.php');
4734 $editabletypes = repository::get_editable_types($coursecontext);
4735 $haseditabletypes = !empty($editabletypes);
4736 unset($editabletypes);
4737 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4738 } else {
4739 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4741 if ($haseditabletypes) {
4742 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4743 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4747 // Manage files
4748 if ($adminoptions->files) {
4749 // hidden in new courses and courses where legacy files were turned off
4750 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4751 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4755 // Let plugins hook into course navigation.
4756 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4757 foreach ($pluginsfunction as $plugintype => $plugins) {
4758 // Ignore the report plugin as it was already loaded above.
4759 if ($plugintype == 'report') {
4760 continue;
4762 foreach ($plugins as $pluginfunction) {
4763 $pluginfunction($coursenode, $course, $coursecontext);
4767 // Prepare data for course content download functionality if it is enabled.
4768 if (\core\content::can_export_context($coursecontext, $USER)) {
4769 $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext);
4770 $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes);
4772 $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download',
4773 new pix_icon('t/download', ''));
4774 $coursenode->get('download')->set_force_into_more_menu(true);
4777 // Return we are done
4778 return $coursenode;
4782 * Get the moodle_page object associated to the current settings navigation.
4784 * @return moodle_page
4786 public function get_page(): moodle_page {
4787 return $this->page;
4791 * This function calls the module function to inject module settings into the
4792 * settings navigation tree.
4794 * This only gets called if there is a corrosponding function in the modules
4795 * lib file.
4797 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4799 * @return navigation_node|false
4801 protected function load_module_settings() {
4802 global $CFG;
4804 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4805 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4806 $this->page->set_cm($cm, $this->page->course);
4809 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4810 if (file_exists($file)) {
4811 require_once($file);
4814 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4815 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4816 $modulenode->force_open();
4818 // Settings for the module
4819 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4820 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4821 $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', ''));
4823 // Assign local roles
4824 if (count(get_assignable_roles($this->page->cm->context))>0) {
4825 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4826 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign',
4827 new pix_icon('i/role', ''));
4829 // Override roles
4830 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4831 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4832 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride',
4833 new pix_icon('i/permissions', ''));
4835 // Check role permissions
4836 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4837 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4838 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck',
4839 new pix_icon('i/checkpermissions', ''));
4842 // Add the context locking node.
4843 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4845 // Manage filters
4846 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4847 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4848 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage',
4849 new pix_icon('i/filter', ''));
4851 // Add reports
4852 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4853 foreach ($reports as $reportfunction) {
4854 $reportfunction($modulenode, $this->page->cm);
4856 // Add a backup link
4857 $featuresfunc = $this->page->activityname.'_supports';
4858 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4859 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4860 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4863 // Restore this activity
4864 $featuresfunc = $this->page->activityname.'_supports';
4865 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4866 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4867 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4870 // Allow the active advanced grading method plugin to append its settings
4871 $featuresfunc = $this->page->activityname.'_supports';
4872 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4873 require_once($CFG->dirroot.'/grade/grading/lib.php');
4874 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4875 $gradingman->extend_settings_navigation($this, $modulenode);
4878 $function = $this->page->activityname.'_extend_settings_navigation';
4879 if (function_exists($function)) {
4880 $function($this, $modulenode);
4883 // Remove the module node if there are no children.
4884 if ($modulenode->children->count() <= 0) {
4885 $modulenode->remove();
4888 return $modulenode;
4892 * Loads the user settings block of the settings nav
4894 * This function is simply works out the userid and whether we need to load
4895 * just the current users profile settings, or the current user and the user the
4896 * current user is viewing.
4898 * This function has some very ugly code to work out the user, if anyone has
4899 * any bright ideas please feel free to intervene.
4901 * @param int $courseid The course id of the current course
4902 * @return navigation_node|false
4904 protected function load_user_settings($courseid = SITEID) {
4905 global $USER, $CFG;
4907 if (isguestuser() || !isloggedin()) {
4908 return false;
4911 $navusers = $this->page->navigation->get_extending_users();
4913 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4914 $usernode = null;
4915 foreach ($this->userstoextendfor as $userid) {
4916 if ($userid == $USER->id) {
4917 continue;
4919 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4920 if (is_null($usernode)) {
4921 $usernode = $node;
4924 foreach ($navusers as $user) {
4925 if ($user->id == $USER->id) {
4926 continue;
4928 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4929 if (is_null($usernode)) {
4930 $usernode = $node;
4933 $this->generate_user_settings($courseid, $USER->id);
4934 } else {
4935 $usernode = $this->generate_user_settings($courseid, $USER->id);
4937 return $usernode;
4941 * Extends the settings navigation for the given user.
4943 * Note: This method gets called automatically if you call
4944 * $PAGE->navigation->extend_for_user($userid)
4946 * @param int $userid
4948 public function extend_for_user($userid) {
4949 global $CFG;
4951 if (!in_array($userid, $this->userstoextendfor)) {
4952 $this->userstoextendfor[] = $userid;
4953 if ($this->initialised) {
4954 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4955 $children = array();
4956 foreach ($this->children as $child) {
4957 $children[] = $child;
4959 array_unshift($children, array_pop($children));
4960 $this->children = new navigation_node_collection();
4961 foreach ($children as $child) {
4962 $this->children->add($child);
4969 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4970 * what can be shown/done
4972 * @param int $courseid The current course' id
4973 * @param int $userid The user id to load for
4974 * @param string $gstitle The string to pass to get_string for the branch title
4975 * @return navigation_node|false
4977 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4978 global $DB, $CFG, $USER, $SITE;
4980 if ($courseid != $SITE->id) {
4981 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4982 $course = $this->page->course;
4983 } else {
4984 $select = context_helper::get_preload_record_columns_sql('ctx');
4985 $sql = "SELECT c.*, $select
4986 FROM {course} c
4987 JOIN {context} ctx ON c.id = ctx.instanceid
4988 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4989 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4990 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4991 context_helper::preload_from_record($course);
4993 } else {
4994 $course = $SITE;
4997 $coursecontext = context_course::instance($course->id); // Course context
4998 $systemcontext = context_system::instance();
4999 $currentuser = ($USER->id == $userid);
5001 if ($currentuser) {
5002 $user = $USER;
5003 $usercontext = context_user::instance($user->id); // User context
5004 } else {
5005 $select = context_helper::get_preload_record_columns_sql('ctx');
5006 $sql = "SELECT u.*, $select
5007 FROM {user} u
5008 JOIN {context} ctx ON u.id = ctx.instanceid
5009 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
5010 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
5011 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
5012 if (!$user) {
5013 return false;
5015 context_helper::preload_from_record($user);
5017 // Check that the user can view the profile
5018 $usercontext = context_user::instance($user->id); // User context
5019 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
5021 if ($course->id == $SITE->id) {
5022 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
5023 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
5024 return false;
5026 } else {
5027 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
5028 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
5029 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
5030 return false;
5032 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
5033 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
5034 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
5035 if ($courseid == $this->page->course->id) {
5036 $mygroups = get_fast_modinfo($this->page->course)->groups;
5037 } else {
5038 $mygroups = groups_get_user_groups($courseid);
5040 $usergroups = groups_get_user_groups($courseid, $userid);
5041 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
5042 return false;
5048 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
5050 $key = $gstitle;
5051 $prefurl = new moodle_url('/user/preferences.php');
5052 if ($gstitle != 'usercurrentsettings') {
5053 $key .= $userid;
5054 $prefurl->param('userid', $userid);
5057 // Add a user setting branch.
5058 if ($gstitle == 'usercurrentsettings') {
5059 $mainpage = $this->add(get_string('home'), new moodle_url('/'), self::TYPE_CONTAINER, null, 'site');
5061 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
5062 // breadcrumb.
5063 $mainpage->display = false;
5064 $homepage = get_home_page();
5065 if (($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES)) {
5066 $mainpage->mainnavonly = true;
5069 $iscurrentuser = ($user->id == $USER->id);
5071 $baseargs = array('id' => $user->id);
5072 if ($course->id != $SITE->id && !$iscurrentuser) {
5073 $baseargs['course'] = $course->id;
5074 $issitecourse = false;
5075 } else {
5076 // Load all categories and get the context for the system.
5077 $issitecourse = true;
5080 // Add the user profile to the dashboard.
5081 $profilenode = $mainpage->add(get_string('profile'), new moodle_url('/user/profile.php',
5082 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
5084 if (!empty($CFG->navadduserpostslinks)) {
5085 // Add nodes for forum posts and discussions if the user can view either or both
5086 // There are no capability checks here as the content of the page is based
5087 // purely on the forums the current user has access too.
5088 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
5089 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
5090 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
5091 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
5094 // Add blog nodes.
5095 if (!empty($CFG->enableblogs)) {
5096 if (!$this->cache->cached('userblogoptions'.$user->id)) {
5097 require_once($CFG->dirroot.'/blog/lib.php');
5098 // Get all options for the user.
5099 $options = blog_get_options_for_user($user);
5100 $this->cache->set('userblogoptions'.$user->id, $options);
5101 } else {
5102 $options = $this->cache->{'userblogoptions'.$user->id};
5105 if (count($options) > 0) {
5106 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
5107 foreach ($options as $type => $option) {
5108 if ($type == "rss") {
5109 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
5110 new pix_icon('i/rss', ''));
5111 } else {
5112 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
5118 // Add the messages link.
5119 // It is context based so can appear in the user's profile and in course participants information.
5120 if (!empty($CFG->messaging)) {
5121 $messageargs = array('user1' => $USER->id);
5122 if ($USER->id != $user->id) {
5123 $messageargs['user2'] = $user->id;
5125 $url = new moodle_url('/message/index.php', $messageargs);
5126 $mainpage->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
5129 // Add the "My private files" link.
5130 // This link doesn't have a unique display for course context so only display it under the user's profile.
5131 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
5132 $url = new moodle_url('/user/files.php');
5133 $mainpage->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
5136 // Add a node to view the users notes if permitted.
5137 if (!empty($CFG->enablenotes) &&
5138 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
5139 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
5140 if ($coursecontext->instanceid != SITEID) {
5141 $url->param('course', $coursecontext->instanceid);
5143 $profilenode->add(get_string('notes', 'notes'), $url);
5146 // Show the grades node.
5147 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
5148 require_once($CFG->dirroot . '/user/lib.php');
5149 // Set the grades node to link to the "Grades" page.
5150 if ($course->id == SITEID) {
5151 $url = user_mygrades_url($user->id, $course->id);
5152 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
5153 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
5155 $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
5158 // Let plugins hook into user navigation.
5159 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5160 foreach ($pluginsfunction as $plugintype => $plugins) {
5161 if ($plugintype != 'report') {
5162 foreach ($plugins as $pluginfunction) {
5163 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5168 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5169 $mainpage->add_node($usersetting);
5170 } else {
5171 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5172 $usersetting->display = false;
5174 $usersetting->id = 'usersettings';
5176 // Check if the user has been deleted.
5177 if ($user->deleted) {
5178 if (!has_capability('moodle/user:update', $coursecontext)) {
5179 // We can't edit the user so just show the user deleted message.
5180 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
5181 } else {
5182 // We can edit the user so show the user deleted message and link it to the profile.
5183 if ($course->id == $SITE->id) {
5184 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
5185 } else {
5186 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
5188 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
5190 return true;
5193 $userauthplugin = false;
5194 if (!empty($user->auth)) {
5195 $userauthplugin = get_auth_plugin($user->auth);
5198 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
5200 // Add the profile edit link.
5201 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5202 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
5203 has_capability('moodle/user:update', $systemcontext)) {
5204 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
5205 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5206 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5207 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5208 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5209 $url = $userauthplugin->edit_profile_url();
5210 if (empty($url)) {
5211 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
5213 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5218 // Change password link.
5219 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
5220 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5221 $passwordchangeurl = $userauthplugin->change_password_url();
5222 if (empty($passwordchangeurl)) {
5223 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
5225 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
5228 // Default homepage.
5229 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER));
5230 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5231 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5232 has_capability('moodle/user:editprofile', $usercontext)) {
5233 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]);
5234 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser');
5238 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5239 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5240 has_capability('moodle/user:editprofile', $usercontext)) {
5241 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
5242 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
5245 $pluginmanager = core_plugin_manager::instance();
5246 $enabled = $pluginmanager->get_enabled_plugins('mod');
5247 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5248 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5249 has_capability('moodle/user:editprofile', $usercontext)) {
5250 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
5251 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
5254 $editors = editors_get_enabled();
5255 if (count($editors) > 1) {
5256 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5257 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5258 has_capability('moodle/user:editprofile', $usercontext)) {
5259 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
5260 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
5265 // Add "Calendar preferences" link.
5266 if (isloggedin() && !isguestuser($user)) {
5267 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5268 has_capability('moodle/user:editprofile', $usercontext)) {
5269 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
5270 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
5274 // Add "Content bank preferences" link.
5275 if (isloggedin() && !isguestuser($user)) {
5276 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5277 has_capability('moodle/user:editprofile', $usercontext)) {
5278 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]);
5279 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING,
5280 null, 'contentbankpreferences');
5284 // View the roles settings.
5285 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5286 'moodle/role:manage'], $usercontext)) {
5287 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
5289 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]);
5290 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
5292 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
5294 if (!empty($assignableroles)) {
5295 $url = new moodle_url('/admin/roles/assign.php',
5296 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5297 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
5300 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
5301 $url = new moodle_url('/admin/roles/permissions.php',
5302 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5303 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5306 $url = new moodle_url('/admin/roles/check.php',
5307 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5308 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5311 // Repositories.
5312 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5313 require_once($CFG->dirroot . '/repository/lib.php');
5314 $editabletypes = repository::get_editable_types($usercontext);
5315 $haseditabletypes = !empty($editabletypes);
5316 unset($editabletypes);
5317 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5318 } else {
5319 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5321 if ($haseditabletypes) {
5322 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5323 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5324 array('contextid' => $usercontext->id)));
5327 // Portfolio.
5328 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5329 require_once($CFG->libdir . '/portfoliolib.php');
5330 if (portfolio_has_visible_instances()) {
5331 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5333 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5334 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5336 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5337 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5341 $enablemanagetokens = false;
5342 if (!empty($CFG->enablerssfeeds)) {
5343 $enablemanagetokens = true;
5344 } else if (!is_siteadmin($USER->id)
5345 && !empty($CFG->enablewebservices)
5346 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5347 $enablemanagetokens = true;
5349 // Security keys.
5350 if ($currentuser && $enablemanagetokens) {
5351 $url = new moodle_url('/user/managetoken.php');
5352 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5355 // Messaging.
5356 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5357 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5358 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5359 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5360 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5361 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5364 // Blogs.
5365 if ($currentuser && !empty($CFG->enableblogs)) {
5366 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5367 if (has_capability('moodle/blog:view', $systemcontext)) {
5368 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5369 navigation_node::TYPE_SETTING);
5371 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5372 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5373 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5374 navigation_node::TYPE_SETTING);
5375 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5376 navigation_node::TYPE_SETTING);
5378 // Remove the blog node if empty.
5379 $blog->trim_if_empty();
5382 // Badges.
5383 if ($currentuser && !empty($CFG->enablebadges)) {
5384 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5385 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5386 $url = new moodle_url('/badges/mybadges.php');
5387 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5389 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5390 navigation_node::TYPE_SETTING);
5391 if (!empty($CFG->badges_allowexternalbackpack)) {
5392 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5393 navigation_node::TYPE_SETTING);
5397 // Let plugins hook into user settings navigation.
5398 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5399 foreach ($pluginsfunction as $plugintype => $plugins) {
5400 foreach ($plugins as $pluginfunction) {
5401 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5405 return $usersetting;
5409 * Loads block specific settings in the navigation
5411 * @return navigation_node
5413 protected function load_block_settings() {
5414 global $CFG;
5416 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5417 $blocknode->force_open();
5419 // Assign local roles
5420 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5421 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5422 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5423 'roles', new pix_icon('i/assignroles', ''));
5426 // Override roles
5427 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5428 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5429 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5430 'permissions', new pix_icon('i/permissions', ''));
5432 // Check role permissions
5433 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5434 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5435 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5436 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5439 // Add the context locking node.
5440 $this->add_context_locking_node($blocknode, $this->context);
5442 return $blocknode;
5446 * Loads category specific settings in the navigation
5448 * @return navigation_node
5450 protected function load_category_settings() {
5451 global $CFG;
5453 // We can land here while being in the context of a block, in which case we
5454 // should get the parent context which should be the category one. See self::initialise().
5455 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5456 $catcontext = $this->context->get_parent_context();
5457 } else {
5458 $catcontext = $this->context;
5461 // Let's make sure that we always have the right context when getting here.
5462 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5463 throw new coding_exception('Unexpected context while loading category settings.');
5466 $categorynodetype = navigation_node::TYPE_CONTAINER;
5467 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5468 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5469 $categorynode->force_open();
5471 if (can_edit_in_category($catcontext->instanceid)) {
5472 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5473 $editstring = get_string('managecategorythis');
5474 $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', ''));
5475 $node->set_show_in_secondary_navigation(false);
5478 if (has_capability('moodle/category:manage', $catcontext)) {
5479 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5480 $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5482 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5483 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null,
5484 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false);
5487 // Assign local roles
5488 $assignableroles = get_assignable_roles($catcontext);
5489 if (!empty($assignableroles)) {
5490 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5491 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5494 // Override roles
5495 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5496 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5497 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5499 // Check role permissions
5500 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5501 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5502 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5503 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', ''));
5506 // Add the context locking node.
5507 $this->add_context_locking_node($categorynode, $catcontext);
5509 // Cohorts
5510 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5511 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5512 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5515 // Manage filters
5516 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5517 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5518 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5521 // Restore.
5522 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5523 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5524 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5527 // Let plugins hook into category settings navigation.
5528 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5529 foreach ($pluginsfunction as $plugintype => $plugins) {
5530 foreach ($plugins as $pluginfunction) {
5531 $pluginfunction($categorynode, $catcontext);
5535 $cb = new contentbank();
5536 if ($cb->is_context_allowed($catcontext)
5537 && has_capability('moodle/contentbank:access', $catcontext)) {
5538 $url = new \moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id]);
5539 $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null,
5540 'contentbank', new \pix_icon('i/contentbank', ''));
5543 return $categorynode;
5547 * Determine whether the user is assuming another role
5549 * This function checks to see if the user is assuming another role by means of
5550 * role switching. In doing this we compare each RSW key (context path) against
5551 * the current context path. This ensures that we can provide the switching
5552 * options against both the course and any page shown under the course.
5554 * @return bool|int The role(int) if the user is in another role, false otherwise
5556 protected function in_alternative_role() {
5557 global $USER;
5558 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5559 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5560 return $USER->access['rsw'][$this->page->context->path];
5562 foreach ($USER->access['rsw'] as $key=>$role) {
5563 if (strpos($this->context->path,$key)===0) {
5564 return $role;
5568 return false;
5572 * This function loads all of the front page settings into the settings navigation.
5573 * This function is called when the user is on the front page, or $COURSE==$SITE
5574 * @param bool $forceopen (optional)
5575 * @return navigation_node
5577 protected function load_front_page_settings($forceopen = false) {
5578 global $SITE, $CFG;
5579 require_once($CFG->dirroot . '/course/lib.php');
5581 $course = clone($SITE);
5582 $coursecontext = context_course::instance($course->id); // Course context
5583 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5585 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5586 if ($forceopen) {
5587 $frontpage->force_open();
5589 $frontpage->id = 'frontpagesettings';
5591 if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) {
5593 // Add the turn on/off settings
5594 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5595 if ($this->page->user_is_editing()) {
5596 $url->param('edit', 'off');
5597 $editstring = get_string('turneditingoff');
5598 } else {
5599 $url->param('edit', 'on');
5600 $editstring = get_string('turneditingon');
5602 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5605 if ($adminoptions->update) {
5606 // Add the course settings link
5607 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5608 $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null,
5609 'editsettings', new pix_icon('i/settings', ''));
5612 // add enrol nodes
5613 enrol_add_course_navigation($frontpage, $course);
5615 // Manage filters
5616 if ($adminoptions->filters) {
5617 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5618 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
5619 null, 'filtermanagement', new pix_icon('i/filter', ''));
5622 // View course reports.
5623 if ($adminoptions->reports) {
5624 $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php',
5625 ['courseid' => $coursecontext->instanceid]),
5626 self::TYPE_CONTAINER, null, 'coursereports',
5627 new pix_icon('i/stats', ''));
5628 $coursereports = core_component::get_plugin_list('coursereport');
5629 foreach ($coursereports as $report=>$dir) {
5630 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5631 if (file_exists($libfile)) {
5632 require_once($libfile);
5633 $reportfunction = $report.'_report_extend_navigation';
5634 if (function_exists($report.'_report_extend_navigation')) {
5635 $reportfunction($frontpagenav, $course, $coursecontext);
5640 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5641 foreach ($reports as $reportfunction) {
5642 $reportfunction($frontpagenav, $course, $coursecontext);
5645 if (!$frontpagenav->has_children()) {
5646 $frontpagenav->remove();
5650 // Backup this course
5651 if ($adminoptions->backup) {
5652 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5653 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
5656 // Restore to this course
5657 if ($adminoptions->restore) {
5658 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5659 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
5662 // Questions
5663 require_once($CFG->libdir . '/questionlib.php');
5664 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5666 // Manage files
5667 if ($adminoptions->files) {
5668 //hiden in new installs
5669 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5670 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5673 // Let plugins hook into frontpage navigation.
5674 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5675 foreach ($pluginsfunction as $plugintype => $plugins) {
5676 foreach ($plugins as $pluginfunction) {
5677 $pluginfunction($frontpage, $course, $coursecontext);
5681 return $frontpage;
5685 * This function gives local plugins an opportunity to modify the settings navigation.
5687 protected function load_local_plugin_settings() {
5689 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5690 $function($this, $this->context);
5695 * This function marks the cache as volatile so it is cleared during shutdown
5697 public function clear_cache() {
5698 $this->cache->volatile();
5702 * Checks to see if there are child nodes available in the specific user's preference node.
5703 * If so, then they have the appropriate permissions view this user's preferences.
5705 * @since Moodle 2.9.3
5706 * @param int $userid The user's ID.
5707 * @return bool True if child nodes exist to view, otherwise false.
5709 public function can_view_user_preferences($userid) {
5710 if (is_siteadmin()) {
5711 return true;
5713 // See if any nodes are present in the preferences section for this user.
5714 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5715 if ($preferencenode && $preferencenode->has_children()) {
5716 // Run through each child node.
5717 foreach ($preferencenode->children as $childnode) {
5718 // If the child node has children then this user has access to a link in the preferences page.
5719 if ($childnode->has_children()) {
5720 return true;
5724 // No links found for the user to access on the preferences page.
5725 return false;
5730 * Class used to populate site admin navigation for ajax.
5732 * @package core
5733 * @category navigation
5734 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5737 class settings_navigation_ajax extends settings_navigation {
5739 * Constructs the navigation for use in an AJAX request
5741 * @param moodle_page $page
5743 public function __construct(moodle_page &$page) {
5744 $this->page = $page;
5745 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5746 $this->children = new navigation_node_collection();
5747 $this->initialise();
5751 * Initialise the site admin navigation.
5753 * @return array An array of the expandable nodes
5755 public function initialise() {
5756 if ($this->initialised || during_initial_install()) {
5757 return false;
5759 $this->context = $this->page->context;
5760 $this->load_administration_settings();
5762 // Check if local plugins is adding node to site admin.
5763 $this->load_local_plugin_settings();
5765 $this->initialised = true;
5770 * Simple class used to output a navigation branch in XML
5772 * @package core
5773 * @category navigation
5774 * @copyright 2009 Sam Hemelryk
5775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5777 class navigation_json {
5778 /** @var array An array of different node types */
5779 protected $nodetype = array('node','branch');
5780 /** @var array An array of node keys and types */
5781 protected $expandable = array();
5783 * Turns a branch and all of its children into XML
5785 * @param navigation_node $branch
5786 * @return string XML string
5788 public function convert($branch) {
5789 $xml = $this->convert_child($branch);
5790 return $xml;
5793 * Set the expandable items in the array so that we have enough information
5794 * to attach AJAX events
5795 * @param array $expandable
5797 public function set_expandable($expandable) {
5798 foreach ($expandable as $node) {
5799 $this->expandable[$node['key'].':'.$node['type']] = $node;
5803 * Recusively converts a child node and its children to XML for output
5805 * @param navigation_node $child The child to convert
5806 * @param int $depth Pointlessly used to track the depth of the XML structure
5807 * @return string JSON
5809 protected function convert_child($child, $depth=1) {
5810 if (!$child->display) {
5811 return '';
5813 $attributes = array();
5814 $attributes['id'] = $child->id;
5815 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5816 $attributes['type'] = $child->type;
5817 $attributes['key'] = $child->key;
5818 $attributes['class'] = $child->get_css_type();
5819 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5821 if ($child->icon instanceof pix_icon) {
5822 $attributes['icon'] = array(
5823 'component' => $child->icon->component,
5824 'pix' => $child->icon->pix,
5826 foreach ($child->icon->attributes as $key=>$value) {
5827 if ($key == 'class') {
5828 $attributes['icon']['classes'] = explode(' ', $value);
5829 } else if (!array_key_exists($key, $attributes['icon'])) {
5830 $attributes['icon'][$key] = $value;
5834 } else if (!empty($child->icon)) {
5835 $attributes['icon'] = (string)$child->icon;
5838 if ($child->forcetitle || $child->title !== $child->text) {
5839 $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8');
5841 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5842 $attributes['expandable'] = $child->key;
5843 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5846 if (count($child->classes)>0) {
5847 $attributes['class'] .= ' '.join(' ',$child->classes);
5849 if (is_string($child->action)) {
5850 $attributes['link'] = $child->action;
5851 } else if ($child->action instanceof moodle_url) {
5852 $attributes['link'] = $child->action->out();
5853 } else if ($child->action instanceof action_link) {
5854 $attributes['link'] = $child->action->url->out();
5856 $attributes['hidden'] = ($child->hidden);
5857 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5858 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5860 if ($child->children->count() > 0) {
5861 $attributes['children'] = array();
5862 foreach ($child->children as $subchild) {
5863 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5867 if ($depth > 1) {
5868 return $attributes;
5869 } else {
5870 return json_encode($attributes);
5876 * The cache class used by global navigation and settings navigation.
5878 * It is basically an easy access point to session with a bit of smarts to make
5879 * sure that the information that is cached is valid still.
5881 * Example use:
5882 * <code php>
5883 * if (!$cache->viewdiscussion()) {
5884 * // Code to do stuff and produce cachable content
5885 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5887 * $content = $cache->viewdiscussion;
5888 * </code>
5890 * @package core
5891 * @category navigation
5892 * @copyright 2009 Sam Hemelryk
5893 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5895 class navigation_cache {
5896 /** @var int represents the time created */
5897 protected $creation;
5898 /** @var array An array of session keys */
5899 protected $session;
5901 * The string to use to segregate this particular cache. It can either be
5902 * unique to start a fresh cache or if you want to share a cache then make
5903 * it the string used in the original cache.
5904 * @var string
5906 protected $area;
5907 /** @var int a time that the information will time out */
5908 protected $timeout;
5909 /** @var stdClass The current context */
5910 protected $currentcontext;
5911 /** @var int cache time information */
5912 const CACHETIME = 0;
5913 /** @var int cache user id */
5914 const CACHEUSERID = 1;
5915 /** @var int cache value */
5916 const CACHEVALUE = 2;
5917 /** @var null|array An array of navigation cache areas to expire on shutdown */
5918 public static $volatilecaches;
5921 * Contructor for the cache. Requires two arguments
5923 * @param string $area The string to use to segregate this particular cache
5924 * it can either be unique to start a fresh cache or if you want
5925 * to share a cache then make it the string used in the original
5926 * cache
5927 * @param int $timeout The number of seconds to time the information out after
5929 public function __construct($area, $timeout=1800) {
5930 $this->creation = time();
5931 $this->area = $area;
5932 $this->timeout = time() - $timeout;
5933 if (rand(0,100) === 0) {
5934 $this->garbage_collection();
5939 * Used to set up the cache within the SESSION.
5941 * This is called for each access and ensure that we don't put anything into the session before
5942 * it is required.
5944 protected function ensure_session_cache_initialised() {
5945 global $SESSION;
5946 if (empty($this->session)) {
5947 if (!isset($SESSION->navcache)) {
5948 $SESSION->navcache = new stdClass;
5950 if (!isset($SESSION->navcache->{$this->area})) {
5951 $SESSION->navcache->{$this->area} = array();
5953 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5958 * Magic Method to retrieve something by simply calling using = cache->key
5960 * @param mixed $key The identifier for the information you want out again
5961 * @return void|mixed Either void or what ever was put in
5963 public function __get($key) {
5964 if (!$this->cached($key)) {
5965 return;
5967 $information = $this->session[$key][self::CACHEVALUE];
5968 return unserialize($information);
5972 * Magic method that simply uses {@link set();} to store something in the cache
5974 * @param string|int $key
5975 * @param mixed $information
5977 public function __set($key, $information) {
5978 $this->set($key, $information);
5982 * Sets some information against the cache (session) for later retrieval
5984 * @param string|int $key
5985 * @param mixed $information
5987 public function set($key, $information) {
5988 global $USER;
5989 $this->ensure_session_cache_initialised();
5990 $information = serialize($information);
5991 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5994 * Check the existence of the identifier in the cache
5996 * @param string|int $key
5997 * @return bool
5999 public function cached($key) {
6000 global $USER;
6001 $this->ensure_session_cache_initialised();
6002 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) {
6003 return false;
6005 return true;
6008 * Compare something to it's equivilant in the cache
6010 * @param string $key
6011 * @param mixed $value
6012 * @param bool $serialise Whether to serialise the value before comparison
6013 * this should only be set to false if the value is already
6014 * serialised
6015 * @return bool If the value is the same false if it is not set or doesn't match
6017 public function compare($key, $value, $serialise = true) {
6018 if ($this->cached($key)) {
6019 if ($serialise) {
6020 $value = serialize($value);
6022 if ($this->session[$key][self::CACHEVALUE] === $value) {
6023 return true;
6026 return false;
6029 * Wipes the entire cache, good to force regeneration
6031 public function clear() {
6032 global $SESSION;
6033 unset($SESSION->navcache);
6034 $this->session = null;
6037 * Checks all cache entries and removes any that have expired, good ole cleanup
6039 protected function garbage_collection() {
6040 if (empty($this->session)) {
6041 return true;
6043 foreach ($this->session as $key=>$cachedinfo) {
6044 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
6045 unset($this->session[$key]);
6051 * Marks the cache as being volatile (likely to change)
6053 * Any caches marked as volatile will be destroyed at the on shutdown by
6054 * {@link navigation_node::destroy_volatile_caches()} which is registered
6055 * as a shutdown function if any caches are marked as volatile.
6057 * @param bool $setting True to destroy the cache false not too
6059 public function volatile($setting = true) {
6060 if (self::$volatilecaches===null) {
6061 self::$volatilecaches = array();
6062 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
6065 if ($setting) {
6066 self::$volatilecaches[$this->area] = $this->area;
6067 } else if (array_key_exists($this->area, self::$volatilecaches)) {
6068 unset(self::$volatilecaches[$this->area]);
6073 * Destroys all caches marked as volatile
6075 * This function is static and works in conjunction with the static volatilecaches
6076 * property of navigation cache.
6077 * Because this function is static it manually resets the cached areas back to an
6078 * empty array.
6080 public static function destroy_volatile_caches() {
6081 global $SESSION;
6082 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
6083 foreach (self::$volatilecaches as $area) {
6084 $SESSION->navcache->{$area} = array();
6086 } else {
6087 $SESSION->navcache = new stdClass;