MDL-74741 javascript: A11y fix for dialogues visible from beginning
[moodle.git] / lib / navigationlib.php
blob33ac8929718aa4b612ab95752f0b44fd5e3b43db
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since Moodle 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
34 /**
35 * This class is used to represent a node in a navigation tree
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
43 * @package core
44 * @category navigation
45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF = 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH = 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN = null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY = 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
77 /** @var int Setting node type, used only within settings nav 80 */
78 const TYPE_USER = 80;
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE = 'courseindexpage';
90 /** @var int Parameter to aid the coder in tracking [optional] */
91 public $id = null;
92 /** @var string|int The identifier for the node, used to retrieve the node */
93 public $key = null;
94 /** @var string The text to use for the node */
95 public $text = null;
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
99 public $title = null;
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
102 /** @var moodle_url|action_link|null An action for the node (link) */
103 public $action = null;
104 /** @var pix_icon The path to an icon to use for this node */
105 public $icon = null;
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self::TYPE_UNKNOWN;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self::NODETYPE_LEAF;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
114 /** @var array An array of CSS classes for the node */
115 public $classes = array();
116 /** @var navigation_node_collection An array of child nodes */
117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
120 /** @var bool If set to true the node will be dimmed */
121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
131 public $parent = null;
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
136 /** @var array */
137 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
138 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
139 90 => 'container');
140 /** @var moodle_url */
141 protected static $fullmeurl = null;
142 /** @var bool toogles auto matching of active node */
143 public static $autofindactive = true;
144 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
145 protected static $loadadmintree = false;
146 /** @var mixed If set to an int, that section will be included even if it has no activities */
147 public $includesectionnum = false;
148 /** @var bool does the node need to be loaded via ajax */
149 public $requiresajaxloading = false;
150 /** @var bool If set to true this node will be added to the "flat" navigation */
151 public $showinflatnavigation = false;
154 * Constructs a new navigation_node
156 * @param array|string $properties Either an array of properties or a string to use
157 * as the text for the node
159 public function __construct($properties) {
160 if (is_array($properties)) {
161 // Check the array for each property that we allow to set at construction.
162 // text - The main content for the node
163 // shorttext - A short text if required for the node
164 // icon - The icon to display for the node
165 // type - The type of the node
166 // key - The key to use to identify the node
167 // parent - A reference to the nodes parent
168 // action - The action to attribute to this node, usually a URL to link to
169 if (array_key_exists('text', $properties)) {
170 $this->text = $properties['text'];
172 if (array_key_exists('shorttext', $properties)) {
173 $this->shorttext = $properties['shorttext'];
175 if (!array_key_exists('icon', $properties)) {
176 $properties['icon'] = new pix_icon('i/navigationitem', '');
178 $this->icon = $properties['icon'];
179 if ($this->icon instanceof pix_icon) {
180 if (empty($this->icon->attributes['class'])) {
181 $this->icon->attributes['class'] = 'navicon';
182 } else {
183 $this->icon->attributes['class'] .= ' navicon';
186 if (array_key_exists('type', $properties)) {
187 $this->type = $properties['type'];
188 } else {
189 $this->type = self::TYPE_CUSTOM;
191 if (array_key_exists('key', $properties)) {
192 $this->key = $properties['key'];
194 // This needs to happen last because of the check_if_active call that occurs
195 if (array_key_exists('action', $properties)) {
196 $this->action = $properties['action'];
197 if (is_string($this->action)) {
198 $this->action = new moodle_url($this->action);
200 if (self::$autofindactive) {
201 $this->check_if_active();
204 if (array_key_exists('parent', $properties)) {
205 $this->set_parent($properties['parent']);
207 } else if (is_string($properties)) {
208 $this->text = $properties;
210 if ($this->text === null) {
211 throw new coding_exception('You must set the text for the node when you create it.');
213 // Instantiate a new navigation node collection for this nodes children
214 $this->children = new navigation_node_collection();
218 * Checks if this node is the active node.
220 * This is determined by comparing the action for the node against the
221 * defined URL for the page. A match will see this node marked as active.
223 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
224 * @return bool
226 public function check_if_active($strength=URL_MATCH_EXACT) {
227 global $FULLME, $PAGE;
228 // Set fullmeurl if it hasn't already been set
229 if (self::$fullmeurl == null) {
230 if ($PAGE->has_set_url()) {
231 self::override_active_url(new moodle_url($PAGE->url));
232 } else {
233 self::override_active_url(new moodle_url($FULLME));
237 // Compare the action of this node against the fullmeurl
238 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
239 $this->make_active();
240 return true;
242 return false;
246 * True if this nav node has siblings in the tree.
248 * @return bool
250 public function has_siblings() {
251 if (empty($this->parent) || empty($this->parent->children)) {
252 return false;
254 if ($this->parent->children instanceof navigation_node_collection) {
255 $count = $this->parent->children->count();
256 } else {
257 $count = count($this->parent->children);
259 return ($count > 1);
263 * Get a list of sibling navigation nodes at the same level as this one.
265 * @return bool|array of navigation_node
267 public function get_siblings() {
268 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
269 // the in-page links or the breadcrumb links.
270 $siblings = false;
272 if ($this->has_siblings()) {
273 $siblings = [];
274 foreach ($this->parent->children as $child) {
275 if ($child->display) {
276 $siblings[] = $child;
280 return $siblings;
284 * This sets the URL that the URL of new nodes get compared to when locating
285 * the active node.
287 * The active node is the node that matches the URL set here. By default this
288 * is either $PAGE->url or if that hasn't been set $FULLME.
290 * @param moodle_url $url The url to use for the fullmeurl.
291 * @param bool $loadadmintree use true if the URL point to administration tree
293 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
294 // Clone the URL, in case the calling script changes their URL later.
295 self::$fullmeurl = new moodle_url($url);
296 // True means we do not want AJAX loaded admin tree, required for all admin pages.
297 if ($loadadmintree) {
298 // Do not change back to false if already set.
299 self::$loadadmintree = true;
304 * Use when page is linked from the admin tree,
305 * if not used navigation could not find the page using current URL
306 * because the tree is not fully loaded.
308 public static function require_admin_tree() {
309 self::$loadadmintree = true;
313 * Creates a navigation node, ready to add it as a child using add_node
314 * function. (The created node needs to be added before you can use it.)
315 * @param string $text
316 * @param moodle_url|action_link $action
317 * @param int $type
318 * @param string $shorttext
319 * @param string|int $key
320 * @param pix_icon $icon
321 * @return navigation_node
323 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
324 $shorttext=null, $key=null, pix_icon $icon=null) {
325 // Properties array used when creating the new navigation node
326 $itemarray = array(
327 'text' => $text,
328 'type' => $type
330 // Set the action if one was provided
331 if ($action!==null) {
332 $itemarray['action'] = $action;
334 // Set the shorttext if one was provided
335 if ($shorttext!==null) {
336 $itemarray['shorttext'] = $shorttext;
338 // Set the icon if one was provided
339 if ($icon!==null) {
340 $itemarray['icon'] = $icon;
342 // Set the key
343 $itemarray['key'] = $key;
344 // Construct and return
345 return new navigation_node($itemarray);
349 * Adds a navigation node as a child of this node.
351 * @param string $text
352 * @param moodle_url|action_link $action
353 * @param int $type
354 * @param string $shorttext
355 * @param string|int $key
356 * @param pix_icon $icon
357 * @return navigation_node
359 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
360 // Create child node
361 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
363 // Add the child to end and return
364 return $this->add_node($childnode);
368 * Adds a navigation node as a child of this one, given a $node object
369 * created using the create function.
370 * @param navigation_node $childnode Node to add
371 * @param string $beforekey
372 * @return navigation_node The added node
374 public function add_node(navigation_node $childnode, $beforekey=null) {
375 // First convert the nodetype for this node to a branch as it will now have children
376 if ($this->nodetype !== self::NODETYPE_BRANCH) {
377 $this->nodetype = self::NODETYPE_BRANCH;
379 // Set the parent to this node
380 $childnode->set_parent($this);
382 // Default the key to the number of children if not provided
383 if ($childnode->key === null) {
384 $childnode->key = $this->children->count();
387 // Add the child using the navigation_node_collections add method
388 $node = $this->children->add($childnode, $beforekey);
390 // If added node is a category node or the user is logged in and it's a course
391 // then mark added node as a branch (makes it expandable by AJAX)
392 $type = $childnode->type;
393 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
394 ($type === self::TYPE_SITE_ADMIN)) {
395 $node->nodetype = self::NODETYPE_BRANCH;
397 // If this node is hidden mark it's children as hidden also
398 if ($this->hidden) {
399 $node->hidden = true;
401 // Return added node (reference returned by $this->children->add()
402 return $node;
406 * Return a list of all the keys of all the child nodes.
407 * @return array the keys.
409 public function get_children_key_list() {
410 return $this->children->get_key_list();
414 * Searches for a node of the given type with the given key.
416 * This searches this node plus all of its children, and their children....
417 * If you know the node you are looking for is a child of this node then please
418 * use the get method instead.
420 * @param int|string $key The key of the node we are looking for
421 * @param int $type One of navigation_node::TYPE_*
422 * @return navigation_node|false
424 public function find($key, $type) {
425 return $this->children->find($key, $type);
429 * Walk the tree building up a list of all the flat navigation nodes.
431 * @param flat_navigation $nodes List of the found flat navigation nodes.
432 * @param boolean $showdivider Show a divider before the first node.
433 * @param string $label A label for the collection of navigation links.
435 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
436 if ($this->showinflatnavigation) {
437 $indent = 0;
438 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
439 $indent = 1;
441 $flat = new flat_navigation_node($this, $indent);
442 $flat->set_showdivider($showdivider, $label);
443 $nodes->add($flat);
445 foreach ($this->children as $child) {
446 $child->build_flat_navigation_list($nodes, false);
451 * Get the child of this node that has the given key + (optional) type.
453 * If you are looking for a node and want to search all children + their children
454 * then please use the find method instead.
456 * @param int|string $key The key of the node we are looking for
457 * @param int $type One of navigation_node::TYPE_*
458 * @return navigation_node|false
460 public function get($key, $type=null) {
461 return $this->children->get($key, $type);
465 * Removes this node.
467 * @return bool
469 public function remove() {
470 return $this->parent->children->remove($this->key, $this->type);
474 * Checks if this node has or could have any children
476 * @return bool Returns true if it has children or could have (by AJAX expansion)
478 public function has_children() {
479 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
483 * Marks this node as active and forces it open.
485 * Important: If you are here because you need to mark a node active to get
486 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
487 * You can use it to specify a different URL to match the active navigation node on
488 * rather than having to locate and manually mark a node active.
490 public function make_active() {
491 $this->isactive = true;
492 $this->add_class('active_tree_node');
493 $this->force_open();
494 if ($this->parent !== null) {
495 $this->parent->make_inactive();
500 * Marks a node as inactive and recusised back to the base of the tree
501 * doing the same to all parents.
503 public function make_inactive() {
504 $this->isactive = false;
505 $this->remove_class('active_tree_node');
506 if ($this->parent !== null) {
507 $this->parent->make_inactive();
512 * Forces this node to be open and at the same time forces open all
513 * parents until the root node.
515 * Recursive.
517 public function force_open() {
518 $this->forceopen = true;
519 if ($this->parent !== null) {
520 $this->parent->force_open();
525 * Adds a CSS class to this node.
527 * @param string $class
528 * @return bool
530 public function add_class($class) {
531 if (!in_array($class, $this->classes)) {
532 $this->classes[] = $class;
534 return true;
538 * Removes a CSS class from this node.
540 * @param string $class
541 * @return bool True if the class was successfully removed.
543 public function remove_class($class) {
544 if (in_array($class, $this->classes)) {
545 $key = array_search($class,$this->classes);
546 if ($key!==false) {
547 // Remove the class' array element.
548 unset($this->classes[$key]);
549 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
550 $this->classes = array_values($this->classes);
552 return true;
555 return false;
559 * Sets the title for this node and forces Moodle to utilise it.
560 * @param string $title
562 public function title($title) {
563 $this->title = $title;
564 $this->forcetitle = true;
568 * Resets the page specific information on this node if it is being unserialised.
570 public function __wakeup(){
571 $this->forceopen = false;
572 $this->isactive = false;
573 $this->remove_class('active_tree_node');
577 * Checks if this node or any of its children contain the active node.
579 * Recursive.
581 * @return bool
583 public function contains_active_node() {
584 if ($this->isactive) {
585 return true;
586 } else {
587 foreach ($this->children as $child) {
588 if ($child->isactive || $child->contains_active_node()) {
589 return true;
593 return false;
597 * To better balance the admin tree, we want to group all the short top branches together.
599 * This means < 8 nodes and no subtrees.
601 * @return bool
603 public function is_short_branch() {
604 $limit = 8;
605 if ($this->children->count() >= $limit) {
606 return false;
608 foreach ($this->children as $child) {
609 if ($child->has_children()) {
610 return false;
613 return true;
617 * Finds the active node.
619 * Searches this nodes children plus all of the children for the active node
620 * and returns it if found.
622 * Recursive.
624 * @return navigation_node|false
626 public function find_active_node() {
627 if ($this->isactive) {
628 return $this;
629 } else {
630 foreach ($this->children as &$child) {
631 $outcome = $child->find_active_node();
632 if ($outcome !== false) {
633 return $outcome;
637 return false;
641 * Searches all children for the best matching active node
642 * @return navigation_node|false
644 public function search_for_active_node() {
645 if ($this->check_if_active(URL_MATCH_BASE)) {
646 return $this;
647 } else {
648 foreach ($this->children as &$child) {
649 $outcome = $child->search_for_active_node();
650 if ($outcome !== false) {
651 return $outcome;
655 return false;
659 * Gets the content for this node.
661 * @param bool $shorttext If true shorttext is used rather than the normal text
662 * @return string
664 public function get_content($shorttext=false) {
665 $navcontext = \context_helper::get_navigation_filter_context(null);
666 $options = !empty($navcontext) ? ['context' => $navcontext] : null;
668 if ($shorttext && $this->shorttext!==null) {
669 return format_string($this->shorttext, null, $options);
670 } else {
671 return format_string($this->text, null, $options);
676 * Gets the title to use for this node.
678 * @return string
680 public function get_title() {
681 if ($this->forcetitle || $this->action != null){
682 return $this->title;
683 } else {
684 return '';
689 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
691 * @return boolean
693 public function has_action() {
694 return !empty($this->action);
698 * Used to easily determine if this link in the breadcrumbs is hidden.
700 * @return boolean
702 public function is_hidden() {
703 return $this->hidden;
707 * Gets the CSS class to add to this node to describe its type
709 * @return string
711 public function get_css_type() {
712 if (array_key_exists($this->type, $this->namedtypes)) {
713 return 'type_'.$this->namedtypes[$this->type];
715 return 'type_unknown';
719 * Finds all nodes that are expandable by AJAX
721 * @param array $expandable An array by reference to populate with expandable nodes.
723 public function find_expandable(array &$expandable) {
724 foreach ($this->children as &$child) {
725 if ($child->display && $child->has_children() && $child->children->count() == 0) {
726 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
727 $this->add_class('canexpand');
728 $child->requiresajaxloading = true;
729 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
731 $child->find_expandable($expandable);
736 * Finds all nodes of a given type (recursive)
738 * @param int $type One of navigation_node::TYPE_*
739 * @return array
741 public function find_all_of_type($type) {
742 $nodes = $this->children->type($type);
743 foreach ($this->children as &$node) {
744 $childnodes = $node->find_all_of_type($type);
745 $nodes = array_merge($nodes, $childnodes);
747 return $nodes;
751 * Removes this node if it is empty
753 public function trim_if_empty() {
754 if ($this->children->count() == 0) {
755 $this->remove();
760 * Creates a tab representation of this nodes children that can be used
761 * with print_tabs to produce the tabs on a page.
763 * call_user_func_array('print_tabs', $node->get_tabs_array());
765 * @param array $inactive
766 * @param bool $return
767 * @return array Array (tabs, selected, inactive, activated, return)
769 public function get_tabs_array(array $inactive=array(), $return=false) {
770 $tabs = array();
771 $rows = array();
772 $selected = null;
773 $activated = array();
774 foreach ($this->children as $node) {
775 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
776 if ($node->contains_active_node()) {
777 if ($node->children->count() > 0) {
778 $activated[] = $node->key;
779 foreach ($node->children as $child) {
780 if ($child->contains_active_node()) {
781 $selected = $child->key;
783 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
785 } else {
786 $selected = $node->key;
790 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
794 * Sets the parent for this node and if this node is active ensures that the tree is properly
795 * adjusted as well.
797 * @param navigation_node $parent
799 public function set_parent(navigation_node $parent) {
800 // Set the parent (thats the easy part)
801 $this->parent = $parent;
802 // Check if this node is active (this is checked during construction)
803 if ($this->isactive) {
804 // Force all of the parent nodes open so you can see this node
805 $this->parent->force_open();
806 // Make all parents inactive so that its clear where we are.
807 $this->parent->make_inactive();
812 * Hides the node and any children it has.
814 * @since Moodle 2.5
815 * @param array $typestohide Optional. An array of node types that should be hidden.
816 * If null all nodes will be hidden.
817 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
818 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
820 public function hide(array $typestohide = null) {
821 if ($typestohide === null || in_array($this->type, $typestohide)) {
822 $this->display = false;
823 if ($this->has_children()) {
824 foreach ($this->children as $child) {
825 $child->hide($typestohide);
832 * Get the action url for this navigation node.
833 * Called from templates.
835 * @since Moodle 3.2
837 public function action() {
838 if ($this->action instanceof moodle_url) {
839 return $this->action;
840 } else if ($this->action instanceof action_link) {
841 return $this->action->url;
843 return $this->action;
847 * Add the menu item to handle locking and unlocking of a conext.
849 * @param \navigation_node $node Node to add
850 * @param \context $context The context to be locked
852 protected function add_context_locking_node(\navigation_node $node, \context $context) {
853 global $CFG;
854 // Manage context locking.
855 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
856 $parentcontext = $context->get_parent_context();
857 if (empty($parentcontext) || !$parentcontext->locked) {
858 if ($context->locked) {
859 $lockicon = 'i/unlock';
860 $lockstring = get_string('managecontextunlock', 'admin');
861 } else {
862 $lockicon = 'i/lock';
863 $lockstring = get_string('managecontextlock', 'admin');
865 $node->add(
866 $lockstring,
867 new moodle_url(
868 '/admin/lock.php',
870 'id' => $context->id,
873 self::TYPE_SETTING,
874 null,
875 'contextlocking',
876 new pix_icon($lockicon, '')
885 * Navigation node collection
887 * This class is responsible for managing a collection of navigation nodes.
888 * It is required because a node's unique identifier is a combination of both its
889 * key and its type.
891 * Originally an array was used with a string key that was a combination of the two
892 * however it was decided that a better solution would be to use a class that
893 * implements the standard IteratorAggregate interface.
895 * @package core
896 * @category navigation
897 * @copyright 2010 Sam Hemelryk
898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
900 class navigation_node_collection implements IteratorAggregate, Countable {
902 * A multidimensional array to where the first key is the type and the second
903 * key is the nodes key.
904 * @var array
906 protected $collection = array();
908 * An array that contains references to nodes in the same order they were added.
909 * This is maintained as a progressive array.
910 * @var array
912 protected $orderedcollection = array();
914 * A reference to the last node that was added to the collection
915 * @var navigation_node
917 protected $last = null;
919 * The total number of items added to this array.
920 * @var int
922 protected $count = 0;
925 * Label for collection of nodes.
926 * @var string
928 protected $collectionlabel = '';
931 * Adds a navigation node to the collection
933 * @param navigation_node $node Node to add
934 * @param string $beforekey If specified, adds before a node with this key,
935 * otherwise adds at end
936 * @return navigation_node Added node
938 public function add(navigation_node $node, $beforekey=null) {
939 global $CFG;
940 $key = $node->key;
941 $type = $node->type;
943 // First check we have a 2nd dimension for this type
944 if (!array_key_exists($type, $this->orderedcollection)) {
945 $this->orderedcollection[$type] = array();
947 // Check for a collision and report if debugging is turned on
948 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
949 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
952 // Find the key to add before
953 $newindex = $this->count;
954 $last = true;
955 if ($beforekey !== null) {
956 foreach ($this->collection as $index => $othernode) {
957 if ($othernode->key === $beforekey) {
958 $newindex = $index;
959 $last = false;
960 break;
963 if ($newindex === $this->count) {
964 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
965 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
969 // Add the node to the appropriate place in the by-type structure (which
970 // is not ordered, despite the variable name)
971 $this->orderedcollection[$type][$key] = $node;
972 if (!$last) {
973 // Update existing references in the ordered collection (which is the
974 // one that isn't called 'ordered') to shuffle them along if required
975 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
976 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
979 // Add a reference to the node to the progressive collection.
980 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
981 // Update the last property to a reference to this new node.
982 $this->last = $this->orderedcollection[$type][$key];
984 // Reorder the array by index if needed
985 if (!$last) {
986 ksort($this->collection);
988 $this->count++;
989 // Return the reference to the now added node
990 return $node;
994 * Return a list of all the keys of all the nodes.
995 * @return array the keys.
997 public function get_key_list() {
998 $keys = array();
999 foreach ($this->collection as $node) {
1000 $keys[] = $node->key;
1002 return $keys;
1006 * Set a label for this collection.
1008 * @param string $label
1010 public function set_collectionlabel($label) {
1011 $this->collectionlabel = $label;
1015 * Return a label for this collection.
1017 * @return string
1019 public function get_collectionlabel() {
1020 return $this->collectionlabel;
1024 * Fetches a node from this collection.
1026 * @param string|int $key The key of the node we want to find.
1027 * @param int $type One of navigation_node::TYPE_*.
1028 * @return navigation_node|null
1030 public function get($key, $type=null) {
1031 if ($type !== null) {
1032 // If the type is known then we can simply check and fetch
1033 if (!empty($this->orderedcollection[$type][$key])) {
1034 return $this->orderedcollection[$type][$key];
1036 } else {
1037 // Because we don't know the type we look in the progressive array
1038 foreach ($this->collection as $node) {
1039 if ($node->key === $key) {
1040 return $node;
1044 return false;
1048 * Searches for a node with matching key and type.
1050 * This function searches both the nodes in this collection and all of
1051 * the nodes in each collection belonging to the nodes in this collection.
1053 * Recursive.
1055 * @param string|int $key The key of the node we want to find.
1056 * @param int $type One of navigation_node::TYPE_*.
1057 * @return navigation_node|null
1059 public function find($key, $type=null) {
1060 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1061 return $this->orderedcollection[$type][$key];
1062 } else {
1063 $nodes = $this->getIterator();
1064 // Search immediate children first
1065 foreach ($nodes as &$node) {
1066 if ($node->key === $key && ($type === null || $type === $node->type)) {
1067 return $node;
1070 // Now search each childs children
1071 foreach ($nodes as &$node) {
1072 $result = $node->children->find($key, $type);
1073 if ($result !== false) {
1074 return $result;
1078 return false;
1082 * Fetches the last node that was added to this collection
1084 * @return navigation_node
1086 public function last() {
1087 return $this->last;
1091 * Fetches all nodes of a given type from this collection
1093 * @param string|int $type node type being searched for.
1094 * @return array ordered collection
1096 public function type($type) {
1097 if (!array_key_exists($type, $this->orderedcollection)) {
1098 $this->orderedcollection[$type] = array();
1100 return $this->orderedcollection[$type];
1103 * Removes the node with the given key and type from the collection
1105 * @param string|int $key The key of the node we want to find.
1106 * @param int $type
1107 * @return bool
1109 public function remove($key, $type=null) {
1110 $child = $this->get($key, $type);
1111 if ($child !== false) {
1112 foreach ($this->collection as $colkey => $node) {
1113 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1114 unset($this->collection[$colkey]);
1115 $this->collection = array_values($this->collection);
1116 break;
1119 unset($this->orderedcollection[$child->type][$child->key]);
1120 $this->count--;
1121 return true;
1123 return false;
1127 * Gets the number of nodes in this collection
1129 * This option uses an internal count rather than counting the actual options to avoid
1130 * a performance hit through the count function.
1132 * @return int
1134 public function count() {
1135 return $this->count;
1138 * Gets an array iterator for the collection.
1140 * This is required by the IteratorAggregator interface and is used by routines
1141 * such as the foreach loop.
1143 * @return ArrayIterator
1145 public function getIterator() {
1146 return new ArrayIterator($this->collection);
1151 * The global navigation class used for... the global navigation
1153 * This class is used by PAGE to store the global navigation for the site
1154 * and is then used by the settings nav and navbar to save on processing and DB calls
1156 * See
1157 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1158 * {@link lib/ajax/getnavbranch.php} Called by ajax
1160 * @package core
1161 * @category navigation
1162 * @copyright 2009 Sam Hemelryk
1163 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1165 class global_navigation extends navigation_node {
1166 /** @var moodle_page The Moodle page this navigation object belongs to. */
1167 protected $page;
1168 /** @var bool switch to let us know if the navigation object is initialised*/
1169 protected $initialised = false;
1170 /** @var array An array of course information */
1171 protected $mycourses = array();
1172 /** @var navigation_node[] An array for containing root navigation nodes */
1173 protected $rootnodes = array();
1174 /** @var bool A switch for whether to show empty sections in the navigation */
1175 protected $showemptysections = true;
1176 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1177 protected $showcategories = null;
1178 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1179 protected $showmycategories = null;
1180 /** @var array An array of stdClasses for users that the navigation is extended for */
1181 protected $extendforuser = array();
1182 /** @var navigation_cache */
1183 protected $cache;
1184 /** @var array An array of course ids that are present in the navigation */
1185 protected $addedcourses = array();
1186 /** @var bool */
1187 protected $allcategoriesloaded = false;
1188 /** @var array An array of category ids that are included in the navigation */
1189 protected $addedcategories = array();
1190 /** @var int expansion limit */
1191 protected $expansionlimit = 0;
1192 /** @var int userid to allow parent to see child's profile page navigation */
1193 protected $useridtouseforparentchecks = 0;
1194 /** @var cache_session A cache that stores information on expanded courses */
1195 protected $cacheexpandcourse = null;
1197 /** Used when loading categories to load all top level categories [parent = 0] **/
1198 const LOAD_ROOT_CATEGORIES = 0;
1199 /** Used when loading categories to load all categories **/
1200 const LOAD_ALL_CATEGORIES = -1;
1203 * Constructs a new global navigation
1205 * @param moodle_page $page The page this navigation object belongs to
1207 public function __construct(moodle_page $page) {
1208 global $CFG, $SITE, $USER;
1210 if (during_initial_install()) {
1211 return;
1214 if (get_home_page() == HOMEPAGE_SITE) {
1215 // We are using the site home for the root element
1216 $properties = array(
1217 'key' => 'home',
1218 'type' => navigation_node::TYPE_SYSTEM,
1219 'text' => get_string('home'),
1220 'action' => new moodle_url('/'),
1221 'icon' => new pix_icon('i/home', '')
1223 } else {
1224 // We are using the users my moodle for the root element
1225 $properties = array(
1226 'key' => 'myhome',
1227 'type' => navigation_node::TYPE_SYSTEM,
1228 'text' => get_string('myhome'),
1229 'action' => new moodle_url('/my/'),
1230 'icon' => new pix_icon('i/dashboard', '')
1234 // Use the parents constructor.... good good reuse
1235 parent::__construct($properties);
1236 $this->showinflatnavigation = true;
1238 // Initalise and set defaults
1239 $this->page = $page;
1240 $this->forceopen = true;
1241 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1245 * Mutator to set userid to allow parent to see child's profile
1246 * page navigation. See MDL-25805 for initial issue. Linked to it
1247 * is an issue explaining why this is a REALLY UGLY HACK thats not
1248 * for you to use!
1250 * @param int $userid userid of profile page that parent wants to navigate around.
1252 public function set_userid_for_parent_checks($userid) {
1253 $this->useridtouseforparentchecks = $userid;
1258 * Initialises the navigation object.
1260 * This causes the navigation object to look at the current state of the page
1261 * that it is associated with and then load the appropriate content.
1263 * This should only occur the first time that the navigation structure is utilised
1264 * which will normally be either when the navbar is called to be displayed or
1265 * when a block makes use of it.
1267 * @return bool
1269 public function initialise() {
1270 global $CFG, $SITE, $USER;
1271 // Check if it has already been initialised
1272 if ($this->initialised || during_initial_install()) {
1273 return true;
1275 $this->initialised = true;
1277 // Set up the five base root nodes. These are nodes where we will put our
1278 // content and are as follows:
1279 // site: Navigation for the front page.
1280 // myprofile: User profile information goes here.
1281 // currentcourse: The course being currently viewed.
1282 // mycourses: The users courses get added here.
1283 // courses: Additional courses are added here.
1284 // users: Other users information loaded here.
1285 $this->rootnodes = array();
1286 if (get_home_page() == HOMEPAGE_SITE) {
1287 // The home element should be my moodle because the root element is the site
1288 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1289 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1290 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
1291 $this->rootnodes['home']->showinflatnavigation = true;
1293 } else {
1294 // The home element should be the site because the root node is my moodle
1295 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1296 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1297 $this->rootnodes['home']->showinflatnavigation = true;
1298 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1299 // We need to stop automatic redirection
1300 $this->rootnodes['home']->action->param('redirect', '0');
1303 $this->rootnodes['site'] = $this->add_course($SITE);
1304 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1305 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1306 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
1307 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1308 if (!core_course_category::user_top()) {
1309 $this->rootnodes['courses']->hide();
1311 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1313 // We always load the frontpage course to ensure it is available without
1314 // JavaScript enabled.
1315 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1316 $this->load_course_sections($SITE, $this->rootnodes['site']);
1318 $course = $this->page->course;
1319 $this->load_courses_enrolled();
1321 // $issite gets set to true if the current pages course is the sites frontpage course
1322 $issite = ($this->page->course->id == $SITE->id);
1324 // Determine if the user is enrolled in any course.
1325 $enrolledinanycourse = enrol_user_sees_own_courses();
1327 $this->rootnodes['currentcourse']->mainnavonly = true;
1328 if ($enrolledinanycourse) {
1329 $this->rootnodes['mycourses']->isexpandable = true;
1330 $this->rootnodes['mycourses']->showinflatnavigation = true;
1331 if ($CFG->navshowallcourses) {
1332 // When we show all courses we need to show both the my courses and the regular courses branch.
1333 $this->rootnodes['courses']->isexpandable = true;
1335 } else {
1336 $this->rootnodes['courses']->isexpandable = true;
1338 $this->rootnodes['mycourses']->forceopen = true;
1340 $canviewcourseprofile = true;
1342 // Next load context specific content into the navigation
1343 switch ($this->page->context->contextlevel) {
1344 case CONTEXT_SYSTEM :
1345 // Nothing left to do here I feel.
1346 break;
1347 case CONTEXT_COURSECAT :
1348 // This is essential, we must load categories.
1349 $this->load_all_categories($this->page->context->instanceid, true);
1350 break;
1351 case CONTEXT_BLOCK :
1352 case CONTEXT_COURSE :
1353 if ($issite) {
1354 // Nothing left to do here.
1355 break;
1358 // Load the course associated with the current page into the navigation.
1359 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1360 // If the course wasn't added then don't try going any further.
1361 if (!$coursenode) {
1362 $canviewcourseprofile = false;
1363 break;
1366 // If the user is not enrolled then we only want to show the
1367 // course node and not populate it.
1369 // Not enrolled, can't view, and hasn't switched roles
1370 if (!can_access_course($course, null, '', true)) {
1371 if ($coursenode->isexpandable === true) {
1372 // Obviously the situation has changed, update the cache and adjust the node.
1373 // This occurs if the user access to a course has been revoked (one way or another) after
1374 // initially logging in for this session.
1375 $this->get_expand_course_cache()->set($course->id, 1);
1376 $coursenode->isexpandable = true;
1377 $coursenode->nodetype = self::NODETYPE_BRANCH;
1379 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1380 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1381 if (!$this->current_user_is_parent_role()) {
1382 $coursenode->make_active();
1383 $canviewcourseprofile = false;
1384 break;
1386 } else if ($coursenode->isexpandable === false) {
1387 // Obviously the situation has changed, update the cache and adjust the node.
1388 // This occurs if the user has been granted access to a course (one way or another) after initially
1389 // logging in for this session.
1390 $this->get_expand_course_cache()->set($course->id, 1);
1391 $coursenode->isexpandable = true;
1392 $coursenode->nodetype = self::NODETYPE_BRANCH;
1395 // Add the essentials such as reports etc...
1396 $this->add_course_essentials($coursenode, $course);
1397 // Extend course navigation with it's sections/activities
1398 $this->load_course_sections($course, $coursenode);
1399 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1400 $coursenode->make_active();
1403 break;
1404 case CONTEXT_MODULE :
1405 if ($issite) {
1406 // If this is the site course then most information will have
1407 // already been loaded.
1408 // However we need to check if there is more content that can
1409 // yet be loaded for the specific module instance.
1410 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1411 if ($activitynode) {
1412 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1414 break;
1417 $course = $this->page->course;
1418 $cm = $this->page->cm;
1420 // Load the course associated with the page into the navigation
1421 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1423 // If the course wasn't added then don't try going any further.
1424 if (!$coursenode) {
1425 $canviewcourseprofile = false;
1426 break;
1429 // If the user is not enrolled then we only want to show the
1430 // course node and not populate it.
1431 if (!can_access_course($course, null, '', true)) {
1432 $coursenode->make_active();
1433 $canviewcourseprofile = false;
1434 break;
1437 $this->add_course_essentials($coursenode, $course);
1439 // Load the course sections into the page
1440 $this->load_course_sections($course, $coursenode, null, $cm);
1441 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1442 if (!empty($activity)) {
1443 // Finally load the cm specific navigaton information
1444 $this->load_activity($cm, $course, $activity);
1445 // Check if we have an active ndoe
1446 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1447 // And make the activity node active.
1448 $activity->make_active();
1451 break;
1452 case CONTEXT_USER :
1453 if ($issite) {
1454 // The users profile information etc is already loaded
1455 // for the front page.
1456 break;
1458 $course = $this->page->course;
1459 // Load the course associated with the user into the navigation
1460 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1462 // If the course wasn't added then don't try going any further.
1463 if (!$coursenode) {
1464 $canviewcourseprofile = false;
1465 break;
1468 // If the user is not enrolled then we only want to show the
1469 // course node and not populate it.
1470 if (!can_access_course($course, null, '', true)) {
1471 $coursenode->make_active();
1472 $canviewcourseprofile = false;
1473 break;
1475 $this->add_course_essentials($coursenode, $course);
1476 $this->load_course_sections($course, $coursenode);
1477 break;
1480 // Load for the current user
1481 $this->load_for_user();
1482 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1483 $this->load_for_user(null, true);
1485 // Load each extending user into the navigation.
1486 foreach ($this->extendforuser as $user) {
1487 if ($user->id != $USER->id) {
1488 $this->load_for_user($user);
1492 // Give the local plugins a chance to include some navigation if they want.
1493 $this->load_local_plugin_navigation();
1495 // Remove any empty root nodes
1496 foreach ($this->rootnodes as $node) {
1497 // Dont remove the home node
1498 /** @var navigation_node $node */
1499 if (!in_array($node->key, ['home', 'myhome']) && !$node->has_children() && !$node->isactive) {
1500 $node->remove();
1504 if (!$this->contains_active_node()) {
1505 $this->search_for_active_node();
1508 // If the user is not logged in modify the navigation structure as detailed
1509 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1510 if (!isloggedin()) {
1511 $activities = clone($this->rootnodes['site']->children);
1512 $this->rootnodes['site']->remove();
1513 $children = clone($this->children);
1514 $this->children = new navigation_node_collection();
1515 foreach ($activities as $child) {
1516 $this->children->add($child);
1518 foreach ($children as $child) {
1519 $this->children->add($child);
1522 return true;
1526 * This function gives local plugins an opportunity to modify navigation.
1528 protected function load_local_plugin_navigation() {
1529 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1530 $function($this);
1535 * Returns true if the current user is a parent of the user being currently viewed.
1537 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1538 * other user being viewed this function returns false.
1539 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1541 * @since Moodle 2.4
1542 * @return bool
1544 protected function current_user_is_parent_role() {
1545 global $USER, $DB;
1546 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1547 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1548 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1549 return false;
1551 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1552 return true;
1555 return false;
1559 * Returns true if courses should be shown within categories on the navigation.
1561 * @param bool $ismycourse Set to true if you are calculating this for a course.
1562 * @return bool
1564 protected function show_categories($ismycourse = false) {
1565 global $CFG, $DB;
1566 if ($ismycourse) {
1567 return $this->show_my_categories();
1569 if ($this->showcategories === null) {
1570 $show = false;
1571 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1572 $show = true;
1573 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1574 $show = true;
1576 $this->showcategories = $show;
1578 return $this->showcategories;
1582 * Returns true if we should show categories in the My Courses branch.
1583 * @return bool
1585 protected function show_my_categories() {
1586 global $CFG;
1587 if ($this->showmycategories === null) {
1588 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
1590 return $this->showmycategories;
1594 * Loads the courses in Moodle into the navigation.
1596 * @global moodle_database $DB
1597 * @param string|array $categoryids An array containing categories to load courses
1598 * for, OR null to load courses for all categories.
1599 * @return array An array of navigation_nodes one for each course
1601 protected function load_all_courses($categoryids = null) {
1602 global $CFG, $DB, $SITE;
1604 // Work out the limit of courses.
1605 $limit = 20;
1606 if (!empty($CFG->navcourselimit)) {
1607 $limit = $CFG->navcourselimit;
1610 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1612 // If we are going to show all courses AND we are showing categories then
1613 // to save us repeated DB calls load all of the categories now
1614 if ($this->show_categories()) {
1615 $this->load_all_categories($toload);
1618 // Will be the return of our efforts
1619 $coursenodes = array();
1621 // Check if we need to show categories.
1622 if ($this->show_categories()) {
1623 // Hmmm we need to show categories... this is going to be painful.
1624 // We now need to fetch up to $limit courses for each category to
1625 // be displayed.
1626 if ($categoryids !== null) {
1627 if (!is_array($categoryids)) {
1628 $categoryids = array($categoryids);
1630 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1631 $categorywhere = 'WHERE cc.id '.$categorywhere;
1632 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1633 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1634 $categoryparams = array();
1635 } else {
1636 $categorywhere = '';
1637 $categoryparams = array();
1640 // First up we are going to get the categories that we are going to
1641 // need so that we can determine how best to load the courses from them.
1642 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1643 FROM {course_categories} cc
1644 LEFT JOIN {course} c ON c.category = cc.id
1645 {$categorywhere}
1646 GROUP BY cc.id";
1647 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1648 $fullfetch = array();
1649 $partfetch = array();
1650 foreach ($categories as $category) {
1651 if (!$this->can_add_more_courses_to_category($category->id)) {
1652 continue;
1654 if ($category->coursecount > $limit * 5) {
1655 $partfetch[] = $category->id;
1656 } else if ($category->coursecount > 0) {
1657 $fullfetch[] = $category->id;
1660 $categories->close();
1662 if (count($fullfetch)) {
1663 // First up fetch all of the courses in categories where we know that we are going to
1664 // need the majority of courses.
1665 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1666 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1667 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1668 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1669 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1670 FROM {course} c
1671 $ccjoin
1672 WHERE c.category {$categoryids}
1673 ORDER BY c.sortorder ASC";
1674 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1675 foreach ($coursesrs as $course) {
1676 if ($course->id == $SITE->id) {
1677 // This should not be necessary, frontpage is not in any category.
1678 continue;
1680 if (array_key_exists($course->id, $this->addedcourses)) {
1681 // It is probably better to not include the already loaded courses
1682 // directly in SQL because inequalities may confuse query optimisers
1683 // and may interfere with query caching.
1684 continue;
1686 if (!$this->can_add_more_courses_to_category($course->category)) {
1687 continue;
1689 context_helper::preload_from_record($course);
1690 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1691 continue;
1693 $coursenodes[$course->id] = $this->add_course($course);
1695 $coursesrs->close();
1698 if (count($partfetch)) {
1699 // Next we will work our way through the categories where we will likely only need a small
1700 // proportion of the courses.
1701 foreach ($partfetch as $categoryid) {
1702 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1703 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1704 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1705 FROM {course} c
1706 $ccjoin
1707 WHERE c.category = :categoryid
1708 ORDER BY c.sortorder ASC";
1709 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1710 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1711 foreach ($coursesrs as $course) {
1712 if ($course->id == $SITE->id) {
1713 // This should not be necessary, frontpage is not in any category.
1714 continue;
1716 if (array_key_exists($course->id, $this->addedcourses)) {
1717 // It is probably better to not include the already loaded courses
1718 // directly in SQL because inequalities may confuse query optimisers
1719 // and may interfere with query caching.
1720 // This also helps to respect expected $limit on repeated executions.
1721 continue;
1723 if (!$this->can_add_more_courses_to_category($course->category)) {
1724 break;
1726 context_helper::preload_from_record($course);
1727 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1728 continue;
1730 $coursenodes[$course->id] = $this->add_course($course);
1732 $coursesrs->close();
1735 } else {
1736 // Prepare the SQL to load the courses and their contexts
1737 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1738 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1739 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1740 $courseparams['contextlevel'] = CONTEXT_COURSE;
1741 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1742 FROM {course} c
1743 $ccjoin
1744 WHERE c.id {$courseids}
1745 ORDER BY c.sortorder ASC";
1746 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1747 foreach ($coursesrs as $course) {
1748 if ($course->id == $SITE->id) {
1749 // frotpage is not wanted here
1750 continue;
1752 if ($this->page->course && ($this->page->course->id == $course->id)) {
1753 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1754 continue;
1756 context_helper::preload_from_record($course);
1757 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1758 continue;
1760 $coursenodes[$course->id] = $this->add_course($course);
1761 if (count($coursenodes) >= $limit) {
1762 break;
1765 $coursesrs->close();
1768 return $coursenodes;
1772 * Returns true if more courses can be added to the provided category.
1774 * @param int|navigation_node|stdClass $category
1775 * @return bool
1777 protected function can_add_more_courses_to_category($category) {
1778 global $CFG;
1779 $limit = 20;
1780 if (!empty($CFG->navcourselimit)) {
1781 $limit = (int)$CFG->navcourselimit;
1783 if (is_numeric($category)) {
1784 if (!array_key_exists($category, $this->addedcategories)) {
1785 return true;
1787 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1788 } else if ($category instanceof navigation_node) {
1789 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1790 return false;
1792 $coursecount = count($category->children->type(self::TYPE_COURSE));
1793 } else if (is_object($category) && property_exists($category,'id')) {
1794 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1796 return ($coursecount <= $limit);
1800 * Loads all categories (top level or if an id is specified for that category)
1802 * @param int $categoryid The category id to load or null/0 to load all base level categories
1803 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1804 * as the requested category and any parent categories.
1805 * @return navigation_node|void returns a navigation node if a category has been loaded.
1807 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1808 global $CFG, $DB;
1810 // Check if this category has already been loaded
1811 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1812 return true;
1815 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1816 $sqlselect = "SELECT cc.*, $catcontextsql
1817 FROM {course_categories} cc
1818 JOIN {context} ctx ON cc.id = ctx.instanceid";
1819 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1820 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1821 $params = array();
1823 $categoriestoload = array();
1824 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1825 // We are going to load all categories regardless... prepare to fire
1826 // on the database server!
1827 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1828 // We are going to load all of the first level categories (categories without parents)
1829 $sqlwhere .= " AND cc.parent = 0";
1830 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1831 // The category itself has been loaded already so we just need to ensure its subcategories
1832 // have been loaded
1833 $addedcategories = $this->addedcategories;
1834 unset($addedcategories[$categoryid]);
1835 if (count($addedcategories) > 0) {
1836 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1837 if ($showbasecategories) {
1838 // We need to include categories with parent = 0 as well
1839 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1840 } else {
1841 // All we need is categories that match the parent
1842 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1845 $params['categoryid'] = $categoryid;
1846 } else {
1847 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1848 // and load this category plus all its parents and subcategories
1849 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1850 $categoriestoload = explode('/', trim($category->path, '/'));
1851 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1852 // We are going to use select twice so double the params
1853 $params = array_merge($params, $params);
1854 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1855 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1858 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1859 $categories = array();
1860 foreach ($categoriesrs as $category) {
1861 // Preload the context.. we'll need it when adding the category in order
1862 // to format the category name.
1863 context_helper::preload_from_record($category);
1864 if (array_key_exists($category->id, $this->addedcategories)) {
1865 // Do nothing, its already been added.
1866 } else if ($category->parent == '0') {
1867 // This is a root category lets add it immediately
1868 $this->add_category($category, $this->rootnodes['courses']);
1869 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1870 // This categories parent has already been added we can add this immediately
1871 $this->add_category($category, $this->addedcategories[$category->parent]);
1872 } else {
1873 $categories[] = $category;
1876 $categoriesrs->close();
1878 // Now we have an array of categories we need to add them to the navigation.
1879 while (!empty($categories)) {
1880 $category = reset($categories);
1881 if (array_key_exists($category->id, $this->addedcategories)) {
1882 // Do nothing
1883 } else if ($category->parent == '0') {
1884 $this->add_category($category, $this->rootnodes['courses']);
1885 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1886 $this->add_category($category, $this->addedcategories[$category->parent]);
1887 } else {
1888 // This category isn't in the navigation and niether is it's parent (yet).
1889 // We need to go through the category path and add all of its components in order.
1890 $path = explode('/', trim($category->path, '/'));
1891 foreach ($path as $catid) {
1892 if (!array_key_exists($catid, $this->addedcategories)) {
1893 // This category isn't in the navigation yet so add it.
1894 $subcategory = $categories[$catid];
1895 if ($subcategory->parent == '0') {
1896 // Yay we have a root category - this likely means we will now be able
1897 // to add categories without problems.
1898 $this->add_category($subcategory, $this->rootnodes['courses']);
1899 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1900 // The parent is in the category (as we'd expect) so add it now.
1901 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1902 // Remove the category from the categories array.
1903 unset($categories[$catid]);
1904 } else {
1905 // We should never ever arrive here - if we have then there is a bigger
1906 // problem at hand.
1907 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1912 // Remove the category from the categories array now that we know it has been added.
1913 unset($categories[$category->id]);
1915 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1916 $this->allcategoriesloaded = true;
1918 // Check if there are any categories to load.
1919 if (count($categoriestoload) > 0) {
1920 $readytoloadcourses = array();
1921 foreach ($categoriestoload as $category) {
1922 if ($this->can_add_more_courses_to_category($category)) {
1923 $readytoloadcourses[] = $category;
1926 if (count($readytoloadcourses)) {
1927 $this->load_all_courses($readytoloadcourses);
1931 // Look for all categories which have been loaded
1932 if (!empty($this->addedcategories)) {
1933 $categoryids = array();
1934 foreach ($this->addedcategories as $category) {
1935 if ($this->can_add_more_courses_to_category($category)) {
1936 $categoryids[] = $category->key;
1939 if ($categoryids) {
1940 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1941 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1942 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1943 FROM {course_categories} cc
1944 JOIN {course} c ON c.category = cc.id
1945 WHERE cc.id {$categoriessql}
1946 GROUP BY cc.id
1947 HAVING COUNT(c.id) > :limit";
1948 $excessivecategories = $DB->get_records_sql($sql, $params);
1949 foreach ($categories as &$category) {
1950 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1951 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1952 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1960 * Adds a structured category to the navigation in the correct order/place
1962 * @param stdClass $category category to be added in navigation.
1963 * @param navigation_node $parent parent navigation node
1964 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1965 * @return void.
1967 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1968 global $CFG;
1969 if (array_key_exists($category->id, $this->addedcategories)) {
1970 return;
1972 $canview = core_course_category::can_view_category($category);
1973 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
1974 $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id));
1975 $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) :
1976 get_string('categoryhidden');
1977 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1978 if (!$canview) {
1979 // User does not have required capabilities to view category.
1980 $categorynode->display = false;
1981 } else if (!$category->visible) {
1982 // Category is hidden but user has capability to view hidden categories.
1983 $categorynode->hidden = true;
1985 $this->addedcategories[$category->id] = $categorynode;
1989 * Loads the given course into the navigation
1991 * @param stdClass $course
1992 * @return navigation_node
1994 protected function load_course(stdClass $course) {
1995 global $SITE;
1996 if ($course->id == $SITE->id) {
1997 // This is always loaded during initialisation
1998 return $this->rootnodes['site'];
1999 } else if (array_key_exists($course->id, $this->addedcourses)) {
2000 // The course has already been loaded so return a reference
2001 return $this->addedcourses[$course->id];
2002 } else {
2003 // Add the course
2004 return $this->add_course($course);
2009 * Loads all of the courses section into the navigation.
2011 * This function calls method from current course format, see
2012 * {@link format_base::extend_course_navigation()}
2013 * If course module ($cm) is specified but course format failed to create the node,
2014 * the activity node is created anyway.
2016 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
2018 * @param stdClass $course Database record for the course
2019 * @param navigation_node $coursenode The course node within the navigation
2020 * @param null|int $sectionnum If specified load the contents of section with this relative number
2021 * @param null|cm_info $cm If specified make sure that activity node is created (either
2022 * in containg section or by calling load_stealth_activity() )
2024 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2025 global $CFG, $SITE;
2026 require_once($CFG->dirroot.'/course/lib.php');
2027 if (isset($cm->sectionnum)) {
2028 $sectionnum = $cm->sectionnum;
2030 if ($sectionnum !== null) {
2031 $this->includesectionnum = $sectionnum;
2033 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2034 if (isset($cm->id)) {
2035 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2036 if (empty($activity)) {
2037 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2043 * Generates an array of sections and an array of activities for the given course.
2045 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2047 * @param stdClass $course
2048 * @return array Array($sections, $activities)
2050 protected function generate_sections_and_activities(stdClass $course) {
2051 global $CFG;
2052 require_once($CFG->dirroot.'/course/lib.php');
2054 $modinfo = get_fast_modinfo($course);
2055 $sections = $modinfo->get_section_info_all();
2057 // For course formats using 'numsections' trim the sections list
2058 $courseformatoptions = course_get_format($course)->get_format_options();
2059 if (isset($courseformatoptions['numsections'])) {
2060 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2063 $activities = array();
2065 foreach ($sections as $key => $section) {
2066 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2067 $sections[$key] = clone($section);
2068 unset($sections[$key]->summary);
2069 $sections[$key]->hasactivites = false;
2070 if (!array_key_exists($section->section, $modinfo->sections)) {
2071 continue;
2073 foreach ($modinfo->sections[$section->section] as $cmid) {
2074 $cm = $modinfo->cms[$cmid];
2075 $activity = new stdClass;
2076 $activity->id = $cm->id;
2077 $activity->course = $course->id;
2078 $activity->section = $section->section;
2079 $activity->name = $cm->name;
2080 $activity->icon = $cm->icon;
2081 $activity->iconcomponent = $cm->iconcomponent;
2082 $activity->hidden = (!$cm->visible);
2083 $activity->modname = $cm->modname;
2084 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2085 $activity->onclick = $cm->onclick;
2086 $url = $cm->url;
2087 if (!$url) {
2088 $activity->url = null;
2089 $activity->display = false;
2090 } else {
2091 $activity->url = $url->out();
2092 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2093 if (self::module_extends_navigation($cm->modname)) {
2094 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2097 $activities[$cmid] = $activity;
2098 if ($activity->display) {
2099 $sections[$key]->hasactivites = true;
2104 return array($sections, $activities);
2108 * Generically loads the course sections into the course's navigation.
2110 * @param stdClass $course
2111 * @param navigation_node $coursenode
2112 * @return array An array of course section nodes
2114 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2115 global $CFG, $DB, $USER, $SITE;
2116 require_once($CFG->dirroot.'/course/lib.php');
2118 list($sections, $activities) = $this->generate_sections_and_activities($course);
2120 $navigationsections = array();
2121 foreach ($sections as $sectionid => $section) {
2122 $section = clone($section);
2123 if ($course->id == $SITE->id) {
2124 $this->load_section_activities($coursenode, $section->section, $activities);
2125 } else {
2126 if (!$section->uservisible || (!$this->showemptysections &&
2127 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2128 continue;
2131 $sectionname = get_section_name($course, $section);
2132 $url = course_get_url($course, $section->section, array('navigation' => true));
2134 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2135 null, $section->id, new pix_icon('i/section', ''));
2136 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2137 $sectionnode->hidden = (!$section->visible || !$section->available);
2138 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2139 $this->load_section_activities($sectionnode, $section->section, $activities);
2141 $section->sectionnode = $sectionnode;
2142 $navigationsections[$sectionid] = $section;
2145 return $navigationsections;
2149 * Loads all of the activities for a section into the navigation structure.
2151 * @param navigation_node $sectionnode
2152 * @param int $sectionnumber
2153 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2154 * @param stdClass $course The course object the section and activities relate to.
2155 * @return array Array of activity nodes
2157 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2158 global $CFG, $SITE;
2159 // A static counter for JS function naming
2160 static $legacyonclickcounter = 0;
2162 $activitynodes = array();
2163 if (empty($activities)) {
2164 return $activitynodes;
2167 if (!is_object($course)) {
2168 $activity = reset($activities);
2169 $courseid = $activity->course;
2170 } else {
2171 $courseid = $course->id;
2173 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2175 foreach ($activities as $activity) {
2176 if ($activity->section != $sectionnumber) {
2177 continue;
2179 if ($activity->icon) {
2180 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2181 } else {
2182 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2185 // Prepare the default name and url for the node
2186 $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activity->id));
2187 $activityname = format_string($activity->name, true, ['context' => $displaycontext]);
2188 $action = new moodle_url($activity->url);
2190 // Check if the onclick property is set (puke!)
2191 if (!empty($activity->onclick)) {
2192 // Increment the counter so that we have a unique number.
2193 $legacyonclickcounter++;
2194 // Generate the function name we will use
2195 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2196 $propogrationhandler = '';
2197 // Check if we need to cancel propogation. Remember inline onclick
2198 // events would return false if they wanted to prevent propogation and the
2199 // default action.
2200 if (strpos($activity->onclick, 'return false')) {
2201 $propogrationhandler = 'e.halt();';
2203 // Decode the onclick - it has already been encoded for display (puke)
2204 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2205 // Build the JS function the click event will call
2206 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2207 $this->page->requires->js_amd_inline($jscode);
2208 // Override the default url with the new action link
2209 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2212 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2213 $activitynode->title(get_string('modulename', $activity->modname));
2214 $activitynode->hidden = $activity->hidden;
2215 $activitynode->display = $showactivities && $activity->display;
2216 $activitynode->nodetype = $activity->nodetype;
2217 $activitynodes[$activity->id] = $activitynode;
2220 return $activitynodes;
2223 * Loads a stealth module from unavailable section
2224 * @param navigation_node $coursenode
2225 * @param stdClass $modinfo
2226 * @return navigation_node or null if not accessible
2228 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2229 if (empty($modinfo->cms[$this->page->cm->id])) {
2230 return null;
2232 $cm = $modinfo->cms[$this->page->cm->id];
2233 if ($cm->icon) {
2234 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2235 } else {
2236 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2238 $url = $cm->url;
2239 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2240 $activitynode->title(get_string('modulename', $cm->modname));
2241 $activitynode->hidden = (!$cm->visible);
2242 if (!$cm->is_visible_on_course_page()) {
2243 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2244 // Also there may be no exception at all in case when teacher is logged in as student.
2245 $activitynode->display = false;
2246 } else if (!$url) {
2247 // Don't show activities that don't have links!
2248 $activitynode->display = false;
2249 } else if (self::module_extends_navigation($cm->modname)) {
2250 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2252 return $activitynode;
2255 * Loads the navigation structure for the given activity into the activities node.
2257 * This method utilises a callback within the modules lib.php file to load the
2258 * content specific to activity given.
2260 * The callback is a method: {modulename}_extend_navigation()
2261 * Examples:
2262 * * {@link forum_extend_navigation()}
2263 * * {@link workshop_extend_navigation()}
2265 * @param cm_info|stdClass $cm
2266 * @param stdClass $course
2267 * @param navigation_node $activity
2268 * @return bool
2270 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2271 global $CFG, $DB;
2273 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2274 if (!($cm instanceof cm_info)) {
2275 $modinfo = get_fast_modinfo($course);
2276 $cm = $modinfo->get_cm($cm->id);
2278 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2279 $activity->make_active();
2280 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2281 $function = $cm->modname.'_extend_navigation';
2283 if (file_exists($file)) {
2284 require_once($file);
2285 if (function_exists($function)) {
2286 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2287 $function($activity, $course, $activtyrecord, $cm);
2291 // Allow the active advanced grading method plugin to append module navigation
2292 $featuresfunc = $cm->modname.'_supports';
2293 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2294 require_once($CFG->dirroot.'/grade/grading/lib.php');
2295 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2296 $gradingman->extend_navigation($this, $activity);
2299 return $activity->has_children();
2302 * Loads user specific information into the navigation in the appropriate place.
2304 * If no user is provided the current user is assumed.
2306 * @param stdClass $user
2307 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2308 * @return bool
2310 protected function load_for_user($user=null, $forceforcontext=false) {
2311 global $DB, $CFG, $USER, $SITE;
2313 require_once($CFG->dirroot . '/course/lib.php');
2315 if ($user === null) {
2316 // We can't require login here but if the user isn't logged in we don't
2317 // want to show anything
2318 if (!isloggedin() || isguestuser()) {
2319 return false;
2321 $user = $USER;
2322 } else if (!is_object($user)) {
2323 // If the user is not an object then get them from the database
2324 $select = context_helper::get_preload_record_columns_sql('ctx');
2325 $sql = "SELECT u.*, $select
2326 FROM {user} u
2327 JOIN {context} ctx ON u.id = ctx.instanceid
2328 WHERE u.id = :userid AND
2329 ctx.contextlevel = :contextlevel";
2330 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2331 context_helper::preload_from_record($user);
2334 $iscurrentuser = ($user->id == $USER->id);
2336 $usercontext = context_user::instance($user->id);
2338 // Get the course set against the page, by default this will be the site
2339 $course = $this->page->course;
2340 $baseargs = array('id'=>$user->id);
2341 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2342 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2343 $baseargs['course'] = $course->id;
2344 $coursecontext = context_course::instance($course->id);
2345 $issitecourse = false;
2346 } else {
2347 // Load all categories and get the context for the system
2348 $coursecontext = context_system::instance();
2349 $issitecourse = true;
2352 // Create a node to add user information under.
2353 $usersnode = null;
2354 if (!$issitecourse) {
2355 // Not the current user so add it to the participants node for the current course.
2356 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2357 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2358 } else if ($USER->id != $user->id) {
2359 // This is the site so add a users node to the root branch.
2360 $usersnode = $this->rootnodes['users'];
2361 if (course_can_view_participants($coursecontext)) {
2362 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2364 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2366 if (!$usersnode) {
2367 // We should NEVER get here, if the course hasn't been populated
2368 // with a participants node then the navigaiton either wasn't generated
2369 // for it (you are missing a require_login or set_context call) or
2370 // you don't have access.... in the interests of no leaking informatin
2371 // we simply quit...
2372 return false;
2374 // Add a branch for the current user.
2375 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2376 $viewprofile = true;
2377 if (!$iscurrentuser) {
2378 require_once($CFG->dirroot . '/user/lib.php');
2379 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2380 $viewprofile = false;
2381 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2382 $viewprofile = false;
2384 if (!$viewprofile) {
2385 $viewprofile = user_can_view_profile($user, null, $usercontext);
2389 // Now, conditionally add the user node.
2390 if ($viewprofile) {
2391 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2392 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2393 } else {
2394 $usernode = $usersnode->add(get_string('user'));
2397 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2398 $usernode->make_active();
2401 // Add user information to the participants or user node.
2402 if ($issitecourse) {
2404 // If the user is the current user or has permission to view the details of the requested
2405 // user than add a view profile link.
2406 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2407 has_capability('moodle/user:viewdetails', $usercontext)) {
2408 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2409 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2410 } else {
2411 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2415 if (!empty($CFG->navadduserpostslinks)) {
2416 // Add nodes for forum posts and discussions if the user can view either or both
2417 // There are no capability checks here as the content of the page is based
2418 // purely on the forums the current user has access too.
2419 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2420 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2421 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2422 array_merge($baseargs, array('mode' => 'discussions'))));
2425 // Add blog nodes.
2426 if (!empty($CFG->enableblogs)) {
2427 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2428 require_once($CFG->dirroot.'/blog/lib.php');
2429 // Get all options for the user.
2430 $options = blog_get_options_for_user($user);
2431 $this->cache->set('userblogoptions'.$user->id, $options);
2432 } else {
2433 $options = $this->cache->{'userblogoptions'.$user->id};
2436 if (count($options) > 0) {
2437 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2438 foreach ($options as $type => $option) {
2439 if ($type == "rss") {
2440 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2441 new pix_icon('i/rss', ''));
2442 } else {
2443 $blogs->add($option['string'], $option['link']);
2449 // Add the messages link.
2450 // It is context based so can appear in the user's profile and in course participants information.
2451 if (!empty($CFG->messaging)) {
2452 $messageargs = array('user1' => $USER->id);
2453 if ($USER->id != $user->id) {
2454 $messageargs['user2'] = $user->id;
2456 $url = new moodle_url('/message/index.php', $messageargs);
2457 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2460 // Add the "My private files" link.
2461 // This link doesn't have a unique display for course context so only display it under the user's profile.
2462 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2463 $url = new moodle_url('/user/files.php');
2464 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2467 // Add a node to view the users notes if permitted.
2468 if (!empty($CFG->enablenotes) &&
2469 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2470 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2471 if ($coursecontext->instanceid != SITEID) {
2472 $url->param('course', $coursecontext->instanceid);
2474 $usernode->add(get_string('notes', 'notes'), $url);
2477 // Show the grades node.
2478 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2479 require_once($CFG->dirroot . '/user/lib.php');
2480 // Set the grades node to link to the "Grades" page.
2481 if ($course->id == SITEID) {
2482 $url = user_mygrades_url($user->id, $course->id);
2483 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2484 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2486 if ($USER->id != $user->id) {
2487 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2488 } else {
2489 $usernode->add(get_string('grades', 'grades'), $url);
2493 // If the user is the current user add the repositories for the current user.
2494 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2495 if (!$iscurrentuser &&
2496 $course->id == $SITE->id &&
2497 has_capability('moodle/user:viewdetails', $usercontext) &&
2498 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2500 // Add view grade report is permitted.
2501 $reports = core_component::get_plugin_list('gradereport');
2502 arsort($reports); // User is last, we want to test it first.
2504 $userscourses = enrol_get_users_courses($user->id, false, '*');
2505 $userscoursesnode = $usernode->add(get_string('courses'));
2507 $count = 0;
2508 foreach ($userscourses as $usercourse) {
2509 if ($count === (int)$CFG->navcourselimit) {
2510 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2511 $userscoursesnode->add(get_string('showallcourses'), $url);
2512 break;
2514 $count++;
2515 $usercoursecontext = context_course::instance($usercourse->id);
2516 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2517 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2518 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2520 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2521 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2522 foreach ($reports as $plugin => $plugindir) {
2523 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2524 // Stop when the first visible plugin is found.
2525 $gradeavailable = true;
2526 break;
2531 if ($gradeavailable) {
2532 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2533 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2534 new pix_icon('i/grades', ''));
2537 // Add a node to view the users notes if permitted.
2538 if (!empty($CFG->enablenotes) &&
2539 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2540 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2541 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2544 if (can_access_course($usercourse, $user->id, '', true)) {
2545 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2546 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2549 $reporttab = $usercoursenode->add(get_string('activityreports'));
2551 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2552 foreach ($reportfunctions as $reportfunction) {
2553 $reportfunction($reporttab, $user, $usercourse);
2556 $reporttab->trim_if_empty();
2560 // Let plugins hook into user navigation.
2561 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2562 foreach ($pluginsfunction as $plugintype => $plugins) {
2563 if ($plugintype != 'report') {
2564 foreach ($plugins as $pluginfunction) {
2565 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2570 return true;
2574 * This method simply checks to see if a given module can extend the navigation.
2576 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2578 * @param string $modname
2579 * @return bool
2581 public static function module_extends_navigation($modname) {
2582 global $CFG;
2583 static $extendingmodules = array();
2584 if (!array_key_exists($modname, $extendingmodules)) {
2585 $extendingmodules[$modname] = false;
2586 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2587 if (file_exists($file)) {
2588 $function = $modname.'_extend_navigation';
2589 require_once($file);
2590 $extendingmodules[$modname] = (function_exists($function));
2593 return $extendingmodules[$modname];
2596 * Extends the navigation for the given user.
2598 * @param stdClass $user A user from the database
2600 public function extend_for_user($user) {
2601 $this->extendforuser[] = $user;
2605 * Returns all of the users the navigation is being extended for
2607 * @return array An array of extending users.
2609 public function get_extending_users() {
2610 return $this->extendforuser;
2613 * Adds the given course to the navigation structure.
2615 * @param stdClass $course
2616 * @param bool $forcegeneric
2617 * @param bool $ismycourse
2618 * @return navigation_node
2620 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2621 global $CFG, $SITE;
2623 // We found the course... we can return it now :)
2624 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2625 return $this->addedcourses[$course->id];
2628 $coursecontext = context_course::instance($course->id);
2630 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
2631 if (is_role_switched($course->id)) {
2632 // user has to be able to access course in order to switch, let's skip the visibility test here
2633 } else if (!core_course_category::can_view_course_info($course)) {
2634 return false;
2638 $issite = ($course->id == $SITE->id);
2639 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
2640 $shortname = format_string($course->shortname, true, ['context' => $displaycontext]);
2641 $fullname = format_string($course->fullname, true, ['context' => $displaycontext]);
2642 // This is the name that will be shown for the course.
2643 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2645 if ($coursetype == self::COURSE_CURRENT) {
2646 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2647 return $coursenode;
2648 } else {
2649 $coursetype = self::COURSE_OTHER;
2653 // Can the user expand the course to see its content.
2654 $canexpandcourse = true;
2655 if ($issite) {
2656 $parent = $this;
2657 $url = null;
2658 if (empty($CFG->usesitenameforsitepages)) {
2659 $coursename = get_string('sitepages');
2661 } else if ($coursetype == self::COURSE_CURRENT) {
2662 $parent = $this->rootnodes['currentcourse'];
2663 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2664 $canexpandcourse = $this->can_expand_course($course);
2665 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2666 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2667 // Nothing to do here the above statement set $parent to the category within mycourses.
2668 } else {
2669 $parent = $this->rootnodes['mycourses'];
2671 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2672 } else {
2673 $parent = $this->rootnodes['courses'];
2674 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2675 // They can only expand the course if they can access it.
2676 $canexpandcourse = $this->can_expand_course($course);
2677 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2678 if (!$this->is_category_fully_loaded($course->category)) {
2679 // We need to load the category structure for this course
2680 $this->load_all_categories($course->category, false);
2682 if (array_key_exists($course->category, $this->addedcategories)) {
2683 $parent = $this->addedcategories[$course->category];
2684 // This could lead to the course being created so we should check whether it is the case again
2685 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2686 return $this->addedcourses[$course->id];
2692 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2693 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2695 $coursenode->hidden = (!$course->visible);
2696 $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false]));
2697 if ($canexpandcourse) {
2698 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2699 $coursenode->nodetype = self::NODETYPE_BRANCH;
2700 $coursenode->isexpandable = true;
2701 } else {
2702 $coursenode->nodetype = self::NODETYPE_LEAF;
2703 $coursenode->isexpandable = false;
2705 if (!$forcegeneric) {
2706 $this->addedcourses[$course->id] = $coursenode;
2709 return $coursenode;
2713 * Returns a cache instance to use for the expand course cache.
2714 * @return cache_session
2716 protected function get_expand_course_cache() {
2717 if ($this->cacheexpandcourse === null) {
2718 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2720 return $this->cacheexpandcourse;
2724 * Checks if a user can expand a course in the navigation.
2726 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2727 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2728 * permits stale data.
2729 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2730 * will be stale.
2731 * It is brought up to date in only one of two ways.
2732 * 1. The user logs out and in again.
2733 * 2. The user browses to the course they've just being given access to.
2735 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2737 * @param stdClass $course
2738 * @return bool
2740 protected function can_expand_course($course) {
2741 $cache = $this->get_expand_course_cache();
2742 $canexpand = $cache->get($course->id);
2743 if ($canexpand === false) {
2744 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2745 $canexpand = (int)$canexpand;
2746 $cache->set($course->id, $canexpand);
2748 return ($canexpand === 1);
2752 * Returns true if the category has already been loaded as have any child categories
2754 * @param int $categoryid
2755 * @return bool
2757 protected function is_category_fully_loaded($categoryid) {
2758 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2762 * Adds essential course nodes to the navigation for the given course.
2764 * This method adds nodes such as reports, blogs and participants
2766 * @param navigation_node $coursenode
2767 * @param stdClass $course
2768 * @return bool returns true on successful addition of a node.
2770 public function add_course_essentials($coursenode, stdClass $course) {
2771 global $CFG, $SITE;
2772 require_once($CFG->dirroot . '/course/lib.php');
2774 if ($course->id == $SITE->id) {
2775 return $this->add_front_page_course_essentials($coursenode, $course);
2778 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2779 return true;
2782 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2784 //Participants
2785 if ($navoptions->participants) {
2786 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2787 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2789 if ($navoptions->blogs) {
2790 $blogsurls = new moodle_url('/blog/index.php');
2791 if ($currentgroup = groups_get_course_group($course, true)) {
2792 $blogsurls->param('groupid', $currentgroup);
2793 } else {
2794 $blogsurls->param('courseid', $course->id);
2796 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2799 if ($navoptions->notes) {
2800 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2802 } else if (count($this->extendforuser) > 0) {
2803 $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2806 // Badges.
2807 if ($navoptions->badges) {
2808 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2810 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2811 navigation_node::TYPE_SETTING, null, 'badgesview',
2812 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2815 // Check access to the course and competencies page.
2816 if ($navoptions->competencies) {
2817 // Just a link to course competency.
2818 $title = get_string('competencies', 'core_competency');
2819 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2820 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2821 new pix_icon('i/competencies', ''));
2823 if ($navoptions->grades) {
2824 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2825 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2826 'grades', new pix_icon('i/grades', ''));
2827 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2828 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2829 $gradenode->make_active();
2833 return true;
2836 * This generates the structure of the course that won't be generated when
2837 * the modules and sections are added.
2839 * Things such as the reports branch, the participants branch, blogs... get
2840 * added to the course node by this method.
2842 * @param navigation_node $coursenode
2843 * @param stdClass $course
2844 * @return bool True for successfull generation
2846 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2847 global $CFG, $USER, $COURSE, $SITE;
2848 require_once($CFG->dirroot . '/course/lib.php');
2850 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2851 return true;
2854 $systemcontext = context_system::instance();
2855 $navoptions = course_get_user_navigation_options($systemcontext, $course);
2857 // Hidden node that we use to determine if the front page navigation is loaded.
2858 // This required as there are not other guaranteed nodes that may be loaded.
2859 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2861 // Participants.
2862 if ($navoptions->participants) {
2863 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2866 // Blogs.
2867 if ($navoptions->blogs) {
2868 $blogsurls = new moodle_url('/blog/index.php');
2869 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2872 $filterselect = 0;
2874 // Badges.
2875 if ($navoptions->badges) {
2876 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2877 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2880 // Notes.
2881 if ($navoptions->notes) {
2882 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2883 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2886 // Tags
2887 if ($navoptions->tags) {
2888 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2889 self::TYPE_SETTING, null, 'tags');
2892 // Search.
2893 if ($navoptions->search) {
2894 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2895 self::TYPE_SETTING, null, 'search');
2898 if ($navoptions->calendar) {
2899 $courseid = $COURSE->id;
2900 $params = array('view' => 'month');
2901 if ($courseid != $SITE->id) {
2902 $params['course'] = $courseid;
2905 // Calendar
2906 $calendarurl = new moodle_url('/calendar/view.php', $params);
2907 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2908 self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
2909 $node->showinflatnavigation = true;
2912 if (isloggedin()) {
2913 $usercontext = context_user::instance($USER->id);
2914 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2915 $url = new moodle_url('/user/files.php');
2916 $node = $coursenode->add(get_string('privatefiles'), $url,
2917 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2918 $node->display = false;
2919 $node->showinflatnavigation = true;
2920 $node->mainnavonly = true;
2924 if (isloggedin()) {
2925 $context = $this->page->context;
2926 switch ($context->contextlevel) {
2927 case CONTEXT_COURSECAT:
2928 // OK, expected context level.
2929 break;
2930 case CONTEXT_COURSE:
2931 // OK, expected context level if not on frontpage.
2932 if ($COURSE->id != $SITE->id) {
2933 break;
2935 default:
2936 // If this context is part of a course (excluding frontpage), use the course context.
2937 // Otherwise, use the system context.
2938 $coursecontext = $context->get_course_context(false);
2939 if ($coursecontext && $coursecontext->instanceid !== $SITE->id) {
2940 $context = $coursecontext;
2941 } else {
2942 $context = $systemcontext;
2946 $params = ['contextid' => $context->id];
2947 if (has_capability('moodle/contentbank:access', $context)) {
2948 $url = new moodle_url('/contentbank/index.php', $params);
2949 $node = $coursenode->add(get_string('contentbank'), $url,
2950 self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', ''));
2951 $node->showinflatnavigation = true;
2955 return true;
2959 * Clears the navigation cache
2961 public function clear_cache() {
2962 $this->cache->clear();
2966 * Sets an expansion limit for the navigation
2968 * The expansion limit is used to prevent the display of content that has a type
2969 * greater than the provided $type.
2971 * Can be used to ensure things such as activities or activity content don't get
2972 * shown on the navigation.
2973 * They are still generated in order to ensure the navbar still makes sense.
2975 * @param int $type One of navigation_node::TYPE_*
2976 * @return bool true when complete.
2978 public function set_expansion_limit($type) {
2979 global $SITE;
2980 $nodes = $this->find_all_of_type($type);
2982 // We only want to hide specific types of nodes.
2983 // Only nodes that represent "structure" in the navigation tree should be hidden.
2984 // If we hide all nodes then we risk hiding vital information.
2985 $typestohide = array(
2986 self::TYPE_CATEGORY,
2987 self::TYPE_COURSE,
2988 self::TYPE_SECTION,
2989 self::TYPE_ACTIVITY
2992 foreach ($nodes as $node) {
2993 // We need to generate the full site node
2994 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2995 continue;
2997 foreach ($node->children as $child) {
2998 $child->hide($typestohide);
3001 return true;
3004 * Attempts to get the navigation with the given key from this nodes children.
3006 * This function only looks at this nodes children, it does NOT look recursivily.
3007 * If the node can't be found then false is returned.
3009 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3011 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3012 * may be of more use to you.
3014 * @param string|int $key The key of the node you wish to receive.
3015 * @param int $type One of navigation_node::TYPE_*
3016 * @return navigation_node|false
3018 public function get($key, $type = null) {
3019 if (!$this->initialised) {
3020 $this->initialise();
3022 return parent::get($key, $type);
3026 * Searches this nodes children and their children to find a navigation node
3027 * with the matching key and type.
3029 * This method is recursive and searches children so until either a node is
3030 * found or there are no more nodes to search.
3032 * If you know that the node being searched for is a child of this node
3033 * then use the {@link global_navigation::get()} method instead.
3035 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3036 * may be of more use to you.
3038 * @param string|int $key The key of the node you wish to receive.
3039 * @param int $type One of navigation_node::TYPE_*
3040 * @return navigation_node|false
3042 public function find($key, $type) {
3043 if (!$this->initialised) {
3044 $this->initialise();
3046 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
3047 return $this->rootnodes[$key];
3049 return parent::find($key, $type);
3053 * They've expanded the 'my courses' branch.
3055 protected function load_courses_enrolled() {
3056 global $CFG;
3058 $limit = (int) $CFG->navcourselimit;
3060 $courses = enrol_get_my_courses('*');
3061 $flatnavcourses = [];
3063 // Go through the courses and see which ones we want to display in the flatnav.
3064 foreach ($courses as $course) {
3065 $classify = course_classify_for_timeline($course);
3067 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3068 $flatnavcourses[$course->id] = $course;
3072 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3073 $numtotalcourses = count($courses);
3074 $numtotalflatnavcourses = count($flatnavcourses);
3076 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3077 $courses = array_slice($courses, 0, $limit, true);
3078 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3080 // Get the number of courses we are going to show for each.
3081 $numshowncourses = count($courses);
3082 $numshownflatnavcourses = count($flatnavcourses);
3083 if ($numshowncourses && $this->show_my_categories()) {
3084 // Generate an array containing unique values of all the courses' categories.
3085 $categoryids = array();
3086 foreach ($courses as $course) {
3087 if (in_array($course->category, $categoryids)) {
3088 continue;
3090 $categoryids[] = $course->category;
3093 // Array of category IDs that include the categories of the user's courses and the related course categories.
3094 $fullpathcategoryids = [];
3095 // Get the course categories for the enrolled courses' category IDs.
3096 $mycoursecategories = core_course_category::get_many($categoryids);
3097 // Loop over each of these categories and build the category tree using each category's path.
3098 foreach ($mycoursecategories as $mycoursecat) {
3099 $pathcategoryids = explode('/', $mycoursecat->path);
3100 // First element of the exploded path is empty since paths begin with '/'.
3101 array_shift($pathcategoryids);
3102 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3103 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3106 // Fetch all of the categories related to the user's courses.
3107 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3108 // Loop over each of these categories and build the category tree.
3109 foreach ($pathcategories as $coursecat) {
3110 // No need to process categories that have already been added.
3111 if (isset($this->addedcategories[$coursecat->id])) {
3112 continue;
3114 // Skip categories that are not visible.
3115 if (!$coursecat->is_uservisible()) {
3116 continue;
3119 // Get this course category's parent node.
3120 $parent = null;
3121 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3122 $parent = $this->addedcategories[$coursecat->parent];
3124 if (!$parent) {
3125 // If it has no parent, then it should be right under the My courses node.
3126 $parent = $this->rootnodes['mycourses'];
3129 // Build the category object based from the coursecat object.
3130 $mycategory = new stdClass();
3131 $mycategory->id = $coursecat->id;
3132 $mycategory->name = $coursecat->name;
3133 $mycategory->visible = $coursecat->visible;
3135 // Add this category to the nav tree.
3136 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3140 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3141 foreach ($courses as $course) {
3142 $node = $this->add_course($course, false, self::COURSE_MY);
3143 if ($node) {
3144 $node->showinflatnavigation = false;
3145 // Check if we should also add this to the flat nav as well.
3146 if (isset($flatnavcourses[$course->id])) {
3147 $node->showinflatnavigation = true;
3152 // Go through each course in the flatnav now.
3153 foreach ($flatnavcourses as $course) {
3154 // Check if we haven't already added it.
3155 if (!isset($courses[$course->id])) {
3156 // Ok, add it to the flatnav only.
3157 $node = $this->add_course($course, false, self::COURSE_MY);
3158 $node->display = false;
3159 $node->showinflatnavigation = true;
3163 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3164 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3165 // Show a link to the course page if there are more courses the user is enrolled in.
3166 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3167 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3168 $url = new moodle_url('/my/');
3169 $parent = $this->rootnodes['mycourses'];
3170 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3172 if ($showmorelinkinnav) {
3173 $coursenode->display = true;
3176 if ($showmorelinkinflatnav) {
3177 $coursenode->showinflatnavigation = true;
3184 * The global navigation class used especially for AJAX requests.
3186 * The primary methods that are used in the global navigation class have been overriden
3187 * to ensure that only the relevant branch is generated at the root of the tree.
3188 * This can be done because AJAX is only used when the backwards structure for the
3189 * requested branch exists.
3190 * This has been done only because it shortens the amounts of information that is generated
3191 * which of course will speed up the response time.. because no one likes laggy AJAX.
3193 * @package core
3194 * @category navigation
3195 * @copyright 2009 Sam Hemelryk
3196 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3198 class global_navigation_for_ajax extends global_navigation {
3200 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3201 protected $branchtype;
3203 /** @var int the instance id */
3204 protected $instanceid;
3206 /** @var array Holds an array of expandable nodes */
3207 protected $expandable = array();
3210 * Constructs the navigation for use in an AJAX request
3212 * @param moodle_page $page moodle_page object
3213 * @param int $branchtype
3214 * @param int $id
3216 public function __construct($page, $branchtype, $id) {
3217 $this->page = $page;
3218 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3219 $this->children = new navigation_node_collection();
3220 $this->branchtype = $branchtype;
3221 $this->instanceid = $id;
3222 $this->initialise();
3225 * Initialise the navigation given the type and id for the branch to expand.
3227 * @return array An array of the expandable nodes
3229 public function initialise() {
3230 global $DB, $SITE;
3232 if ($this->initialised || during_initial_install()) {
3233 return $this->expandable;
3235 $this->initialised = true;
3237 $this->rootnodes = array();
3238 $this->rootnodes['site'] = $this->add_course($SITE);
3239 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3240 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3241 // The courses branch is always displayed, and is always expandable (although may be empty).
3242 // This mimicks what is done during {@link global_navigation::initialise()}.
3243 $this->rootnodes['courses']->isexpandable = true;
3245 // Branchtype will be one of navigation_node::TYPE_*
3246 switch ($this->branchtype) {
3247 case 0:
3248 if ($this->instanceid === 'mycourses') {
3249 $this->load_courses_enrolled();
3250 } else if ($this->instanceid === 'courses') {
3251 $this->load_courses_other();
3253 break;
3254 case self::TYPE_CATEGORY :
3255 $this->load_category($this->instanceid);
3256 break;
3257 case self::TYPE_MY_CATEGORY :
3258 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3259 break;
3260 case self::TYPE_COURSE :
3261 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3262 if (!can_access_course($course, null, '', true)) {
3263 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3264 // add the course node and break. This leads to an empty node.
3265 $this->add_course($course);
3266 break;
3268 require_course_login($course, true, null, false, true);
3269 $this->page->set_context(context_course::instance($course->id));
3270 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3271 $this->add_course_essentials($coursenode, $course);
3272 $this->load_course_sections($course, $coursenode);
3273 break;
3274 case self::TYPE_SECTION :
3275 $sql = 'SELECT c.*, cs.section AS sectionnumber
3276 FROM {course} c
3277 LEFT JOIN {course_sections} cs ON cs.course = c.id
3278 WHERE cs.id = ?';
3279 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3280 require_course_login($course, true, null, false, true);
3281 $this->page->set_context(context_course::instance($course->id));
3282 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3283 $this->add_course_essentials($coursenode, $course);
3284 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3285 break;
3286 case self::TYPE_ACTIVITY :
3287 $sql = "SELECT c.*
3288 FROM {course} c
3289 JOIN {course_modules} cm ON cm.course = c.id
3290 WHERE cm.id = :cmid";
3291 $params = array('cmid' => $this->instanceid);
3292 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3293 $modinfo = get_fast_modinfo($course);
3294 $cm = $modinfo->get_cm($this->instanceid);
3295 require_course_login($course, true, $cm, false, true);
3296 $this->page->set_context(context_module::instance($cm->id));
3297 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3298 $this->load_course_sections($course, $coursenode, null, $cm);
3299 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3300 if ($activitynode) {
3301 $modulenode = $this->load_activity($cm, $course, $activitynode);
3303 break;
3304 default:
3305 throw new Exception('Unknown type');
3306 return $this->expandable;
3309 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3310 $this->load_for_user(null, true);
3313 // Give the local plugins a chance to include some navigation if they want.
3314 $this->load_local_plugin_navigation();
3316 $this->find_expandable($this->expandable);
3317 return $this->expandable;
3321 * They've expanded the general 'courses' branch.
3323 protected function load_courses_other() {
3324 $this->load_all_courses();
3328 * Loads a single category into the AJAX navigation.
3330 * This function is special in that it doesn't concern itself with the parent of
3331 * the requested category or its siblings.
3332 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3333 * request that.
3335 * @global moodle_database $DB
3336 * @param int $categoryid id of category to load in navigation.
3337 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3338 * @return void.
3340 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3341 global $CFG, $DB;
3343 $limit = 20;
3344 if (!empty($CFG->navcourselimit)) {
3345 $limit = (int)$CFG->navcourselimit;
3348 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3349 $sql = "SELECT cc.*, $catcontextsql
3350 FROM {course_categories} cc
3351 JOIN {context} ctx ON cc.id = ctx.instanceid
3352 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3353 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3354 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3355 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3356 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3357 $categorylist = array();
3358 $subcategories = array();
3359 $basecategory = null;
3360 foreach ($categories as $category) {
3361 $categorylist[] = $category->id;
3362 context_helper::preload_from_record($category);
3363 if ($category->id == $categoryid) {
3364 $this->add_category($category, $this, $nodetype);
3365 $basecategory = $this->addedcategories[$category->id];
3366 } else {
3367 $subcategories[$category->id] = $category;
3370 $categories->close();
3373 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3374 // else show all courses.
3375 if ($nodetype === self::TYPE_MY_CATEGORY) {
3376 $courses = enrol_get_my_courses('*');
3377 $categoryids = array();
3379 // Only search for categories if basecategory was found.
3380 if (!is_null($basecategory)) {
3381 // Get course parent category ids.
3382 foreach ($courses as $course) {
3383 $categoryids[] = $course->category;
3386 // Get a unique list of category ids which a part of the path
3387 // to user's courses.
3388 $coursesubcategories = array();
3389 $addedsubcategories = array();
3391 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3392 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3394 foreach ($categories as $category){
3395 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3397 $categories->close();
3398 $coursesubcategories = array_unique($coursesubcategories);
3400 // Only add a subcategory if it is part of the path to user's course and
3401 // wasn't already added.
3402 foreach ($subcategories as $subid => $subcategory) {
3403 if (in_array($subid, $coursesubcategories) &&
3404 !in_array($subid, $addedsubcategories)) {
3405 $this->add_category($subcategory, $basecategory, $nodetype);
3406 $addedsubcategories[] = $subid;
3411 foreach ($courses as $course) {
3412 // Add course if it's in category.
3413 if (in_array($course->category, $categorylist)) {
3414 $this->add_course($course, true, self::COURSE_MY);
3417 } else {
3418 if (!is_null($basecategory)) {
3419 foreach ($subcategories as $key=>$category) {
3420 $this->add_category($category, $basecategory, $nodetype);
3423 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3424 foreach ($courses as $course) {
3425 $this->add_course($course);
3427 $courses->close();
3432 * Returns an array of expandable nodes
3433 * @return array
3435 public function get_expandable() {
3436 return $this->expandable;
3441 * Navbar class
3443 * This class is used to manage the navbar, which is initialised from the navigation
3444 * object held by PAGE
3446 * @package core
3447 * @category navigation
3448 * @copyright 2009 Sam Hemelryk
3449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3451 class navbar extends navigation_node {
3452 /** @var bool A switch for whether the navbar is initialised or not */
3453 protected $initialised = false;
3454 /** @var mixed keys used to reference the nodes on the navbar */
3455 protected $keys = array();
3456 /** @var null|string content of the navbar */
3457 protected $content = null;
3458 /** @var moodle_page object the moodle page that this navbar belongs to */
3459 protected $page;
3460 /** @var bool A switch for whether to ignore the active navigation information */
3461 protected $ignoreactive = false;
3462 /** @var bool A switch to let us know if we are in the middle of an install */
3463 protected $duringinstall = false;
3464 /** @var bool A switch for whether the navbar has items */
3465 protected $hasitems = false;
3466 /** @var array An array of navigation nodes for the navbar */
3467 protected $items;
3468 /** @var array An array of child node objects */
3469 public $children = array();
3470 /** @var bool A switch for whether we want to include the root node in the navbar */
3471 public $includesettingsbase = false;
3472 /** @var breadcrumb_navigation_node[] $prependchildren */
3473 protected $prependchildren = array();
3476 * The almighty constructor
3478 * @param moodle_page $page
3480 public function __construct(moodle_page $page) {
3481 global $CFG;
3482 if (during_initial_install()) {
3483 $this->duringinstall = true;
3484 return false;
3486 $this->page = $page;
3487 $this->text = get_string('home');
3488 $this->shorttext = get_string('home');
3489 $this->action = new moodle_url($CFG->wwwroot);
3490 $this->nodetype = self::NODETYPE_BRANCH;
3491 $this->type = self::TYPE_SYSTEM;
3495 * Quick check to see if the navbar will have items in.
3497 * @return bool Returns true if the navbar will have items, false otherwise
3499 public function has_items() {
3500 if ($this->duringinstall) {
3501 return false;
3502 } else if ($this->hasitems !== false) {
3503 return true;
3505 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3506 // There have been manually added items - there are definitely items.
3507 $outcome = true;
3508 } else if (!$this->ignoreactive) {
3509 // We will need to initialise the navigation structure to check if there are active items.
3510 $this->page->navigation->initialise($this->page);
3511 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3513 $this->hasitems = $outcome;
3514 return $outcome;
3518 * Turn on/off ignore active
3520 * @param bool $setting
3522 public function ignore_active($setting=true) {
3523 $this->ignoreactive = ($setting);
3527 * Gets a navigation node
3529 * @param string|int $key for referencing the navbar nodes
3530 * @param int $type breadcrumb_navigation_node::TYPE_*
3531 * @return breadcrumb_navigation_node|bool
3533 public function get($key, $type = null) {
3534 foreach ($this->children as &$child) {
3535 if ($child->key === $key && ($type == null || $type == $child->type)) {
3536 return $child;
3539 foreach ($this->prependchildren as &$child) {
3540 if ($child->key === $key && ($type == null || $type == $child->type)) {
3541 return $child;
3544 return false;
3547 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3549 * @return array
3551 public function get_items() {
3552 global $CFG;
3553 $items = array();
3554 // Make sure that navigation is initialised
3555 if (!$this->has_items()) {
3556 return $items;
3558 if ($this->items !== null) {
3559 return $this->items;
3562 if (count($this->children) > 0) {
3563 // Add the custom children.
3564 $items = array_reverse($this->children);
3567 // Check if navigation contains the active node
3568 if (!$this->ignoreactive) {
3569 // We will need to ensure the navigation has been initialised.
3570 $this->page->navigation->initialise($this->page);
3571 // Now find the active nodes on both the navigation and settings.
3572 $navigationactivenode = $this->page->navigation->find_active_node();
3573 $settingsactivenode = $this->page->settingsnav->find_active_node();
3575 if ($navigationactivenode && $settingsactivenode) {
3576 // Parse a combined navigation tree
3577 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3578 if (!$settingsactivenode->mainnavonly) {
3579 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3581 $settingsactivenode = $settingsactivenode->parent;
3583 if (!$this->includesettingsbase) {
3584 // Removes the first node from the settings (root node) from the list
3585 array_pop($items);
3587 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3588 if (!$navigationactivenode->mainnavonly) {
3589 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3591 if (!empty($CFG->navshowcategories) &&
3592 $navigationactivenode->type === self::TYPE_COURSE &&
3593 $navigationactivenode->parent->key === 'currentcourse') {
3594 foreach ($this->get_course_categories() as $item) {
3595 $items[] = new breadcrumb_navigation_node($item);
3598 $navigationactivenode = $navigationactivenode->parent;
3600 } else if ($navigationactivenode) {
3601 // Parse the navigation tree to get the active node
3602 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3603 if (!$navigationactivenode->mainnavonly) {
3604 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3606 if (!empty($CFG->navshowcategories) &&
3607 $navigationactivenode->type === self::TYPE_COURSE &&
3608 $navigationactivenode->parent->key === 'currentcourse') {
3609 foreach ($this->get_course_categories() as $item) {
3610 $items[] = new breadcrumb_navigation_node($item);
3613 $navigationactivenode = $navigationactivenode->parent;
3615 } else if ($settingsactivenode) {
3616 // Parse the settings navigation to get the active node
3617 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3618 if (!$settingsactivenode->mainnavonly) {
3619 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3621 $settingsactivenode = $settingsactivenode->parent;
3626 $items[] = new breadcrumb_navigation_node(array(
3627 'text' => $this->page->navigation->text,
3628 'shorttext' => $this->page->navigation->shorttext,
3629 'key' => $this->page->navigation->key,
3630 'action' => $this->page->navigation->action
3633 if (count($this->prependchildren) > 0) {
3634 // Add the custom children
3635 $items = array_merge($items, array_reverse($this->prependchildren));
3638 $last = reset($items);
3639 if ($last) {
3640 $last->set_last(true);
3642 $this->items = array_reverse($items);
3643 return $this->items;
3647 * Get the list of categories leading to this course.
3649 * This function is used by {@link navbar::get_items()} to add back the "courses"
3650 * node and category chain leading to the current course. Note that this is only ever
3651 * called for the current course, so we don't need to bother taking in any parameters.
3653 * @return array
3655 private function get_course_categories() {
3656 global $CFG;
3657 require_once($CFG->dirroot.'/course/lib.php');
3659 $categories = array();
3660 $cap = 'moodle/category:viewhiddencategories';
3661 $showcategories = !core_course_category::is_simple_site();
3663 if ($showcategories) {
3664 foreach ($this->page->categories as $category) {
3665 $context = context_coursecat::instance($category->id);
3666 if (!core_course_category::can_view_category($category)) {
3667 continue;
3670 $displaycontext = \context_helper::get_navigation_filter_context($context);
3671 $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]);
3672 $name = format_string($category->name, true, ['context' => $displaycontext]);
3673 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3674 if (!$category->visible) {
3675 $categorynode->hidden = true;
3677 $categories[] = $categorynode;
3681 // Don't show the 'course' node if enrolled in this course.
3682 $coursecontext = context_course::instance($this->page->course->id);
3683 if (!is_enrolled($coursecontext, null, '', true)) {
3684 $courses = $this->page->navigation->get('courses');
3685 if (!$courses) {
3686 // Courses node may not be present.
3687 $courses = breadcrumb_navigation_node::create(
3688 get_string('courses'),
3689 new moodle_url('/course/index.php'),
3690 self::TYPE_CONTAINER
3693 $categories[] = $courses;
3696 return $categories;
3700 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3702 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3703 * the way nodes get added to allow us to simply call add and have the node added to the
3704 * end of the navbar
3706 * @param string $text
3707 * @param string|moodle_url|action_link $action An action to associate with this node.
3708 * @param int $type One of navigation_node::TYPE_*
3709 * @param string $shorttext
3710 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3711 * @param pix_icon $icon An optional icon to use for this node.
3712 * @return navigation_node
3714 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3715 if ($this->content !== null) {
3716 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3719 // Properties array used when creating the new navigation node
3720 $itemarray = array(
3721 'text' => $text,
3722 'type' => $type
3724 // Set the action if one was provided
3725 if ($action!==null) {
3726 $itemarray['action'] = $action;
3728 // Set the shorttext if one was provided
3729 if ($shorttext!==null) {
3730 $itemarray['shorttext'] = $shorttext;
3732 // Set the icon if one was provided
3733 if ($icon!==null) {
3734 $itemarray['icon'] = $icon;
3736 // Default the key to the number of children if not provided
3737 if ($key === null) {
3738 $key = count($this->children);
3740 // Set the key
3741 $itemarray['key'] = $key;
3742 // Set the parent to this node
3743 $itemarray['parent'] = $this;
3744 // Add the child using the navigation_node_collections add method
3745 $this->children[] = new breadcrumb_navigation_node($itemarray);
3746 return $this;
3750 * Prepends a new navigation_node to the start of the navbar
3752 * @param string $text
3753 * @param string|moodle_url|action_link $action An action to associate with this node.
3754 * @param int $type One of navigation_node::TYPE_*
3755 * @param string $shorttext
3756 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3757 * @param pix_icon $icon An optional icon to use for this node.
3758 * @return navigation_node
3760 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3761 if ($this->content !== null) {
3762 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3764 // Properties array used when creating the new navigation node.
3765 $itemarray = array(
3766 'text' => $text,
3767 'type' => $type
3769 // Set the action if one was provided.
3770 if ($action!==null) {
3771 $itemarray['action'] = $action;
3773 // Set the shorttext if one was provided.
3774 if ($shorttext!==null) {
3775 $itemarray['shorttext'] = $shorttext;
3777 // Set the icon if one was provided.
3778 if ($icon!==null) {
3779 $itemarray['icon'] = $icon;
3781 // Default the key to the number of children if not provided.
3782 if ($key === null) {
3783 $key = count($this->children);
3785 // Set the key.
3786 $itemarray['key'] = $key;
3787 // Set the parent to this node.
3788 $itemarray['parent'] = $this;
3789 // Add the child node to the prepend list.
3790 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3791 return $this;
3796 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3797 * in particular adding extra metadata for search engine robots to leverage.
3799 * @package core
3800 * @category navigation
3801 * @copyright 2015 Brendan Heywood
3802 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3804 class breadcrumb_navigation_node extends navigation_node {
3806 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3807 private $last = false;
3810 * A proxy constructor
3812 * @param mixed $navnode A navigation_node or an array
3814 public function __construct($navnode) {
3815 if (is_array($navnode)) {
3816 parent::__construct($navnode);
3817 } else if ($navnode instanceof navigation_node) {
3819 // Just clone everything.
3820 $objvalues = get_object_vars($navnode);
3821 foreach ($objvalues as $key => $value) {
3822 $this->$key = $value;
3824 } else {
3825 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3830 * Getter for "last"
3831 * @return boolean
3833 public function is_last() {
3834 return $this->last;
3838 * Setter for "last"
3839 * @param $val boolean
3841 public function set_last($val) {
3842 $this->last = $val;
3847 * Subclass of navigation_node allowing different rendering for the flat navigation
3848 * in particular allowing dividers and indents.
3850 * @package core
3851 * @category navigation
3852 * @copyright 2016 Damyon Wiese
3853 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3855 class flat_navigation_node extends navigation_node {
3857 /** @var $indent integer The indent level */
3858 private $indent = 0;
3860 /** @var $showdivider bool Show a divider before this element */
3861 private $showdivider = false;
3863 /** @var $collectionlabel string Label for a group of nodes */
3864 private $collectionlabel = '';
3867 * A proxy constructor
3869 * @param mixed $navnode A navigation_node or an array
3871 public function __construct($navnode, $indent) {
3872 if (is_array($navnode)) {
3873 parent::__construct($navnode);
3874 } else if ($navnode instanceof navigation_node) {
3876 // Just clone everything.
3877 $objvalues = get_object_vars($navnode);
3878 foreach ($objvalues as $key => $value) {
3879 $this->$key = $value;
3881 } else {
3882 throw new coding_exception('Not a valid flat_navigation_node');
3884 $this->indent = $indent;
3888 * Setter, a label is required for a flat navigation node that shows a divider.
3890 * @param string $label
3892 public function set_collectionlabel($label) {
3893 $this->collectionlabel = $label;
3897 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
3899 * @return string
3901 public function get_collectionlabel() {
3902 if (!empty($this->collectionlabel)) {
3903 return $this->collectionlabel;
3905 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) {
3906 return $this->parent->get_collectionlabel();
3908 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3909 return '';
3913 * Does this node represent a course section link.
3914 * @return boolean
3916 public function is_section() {
3917 return $this->type == navigation_node::TYPE_SECTION;
3921 * In flat navigation - sections are active if we are looking at activities in the section.
3922 * @return boolean
3924 public function isactive() {
3925 global $PAGE;
3927 if ($this->is_section()) {
3928 $active = $PAGE->navigation->find_active_node();
3929 while ($active = $active->parent) {
3930 if ($active->key == $this->key && $active->type == $this->type) {
3931 return true;
3935 return $this->isactive;
3939 * Getter for "showdivider"
3940 * @return boolean
3942 public function showdivider() {
3943 return $this->showdivider;
3947 * Setter for "showdivider"
3948 * @param $val boolean
3949 * @param $label string Label for the group of nodes
3951 public function set_showdivider($val, $label = '') {
3952 $this->showdivider = $val;
3953 if ($this->showdivider && empty($label)) {
3954 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3955 } else {
3956 $this->set_collectionlabel($label);
3961 * Getter for "indent"
3962 * @return boolean
3964 public function get_indent() {
3965 return $this->indent;
3969 * Setter for "indent"
3970 * @param $val boolean
3972 public function set_indent($val) {
3973 $this->indent = $val;
3978 * Class used to generate a collection of navigation nodes most closely related
3979 * to the current page.
3981 * @package core
3982 * @copyright 2016 Damyon Wiese
3983 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3985 class flat_navigation extends navigation_node_collection {
3986 /** @var moodle_page the moodle page that the navigation belongs to */
3987 protected $page;
3990 * Constructor.
3992 * @param moodle_page $page
3994 public function __construct(moodle_page &$page) {
3995 if (during_initial_install()) {
3996 return false;
3998 $this->page = $page;
4002 * Build the list of navigation nodes based on the current navigation and settings trees.
4005 public function initialise() {
4006 global $PAGE, $USER, $OUTPUT, $CFG;
4007 if (during_initial_install()) {
4008 return;
4011 $current = false;
4013 $course = $PAGE->course;
4015 $this->page->navigation->initialise();
4017 // First walk the nav tree looking for "flat_navigation" nodes.
4018 if ($course->id > 1) {
4019 // It's a real course.
4020 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4022 $coursecontext = context_course::instance($course->id, MUST_EXIST);
4023 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
4024 // This is the name that will be shown for the course.
4025 $coursename = empty($CFG->navshowfullcoursenames) ?
4026 format_string($course->shortname, true, ['context' => $displaycontext]) :
4027 format_string($course->fullname, true, ['context' => $displaycontext]);
4029 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
4030 $flat->set_collectionlabel($coursename);
4031 $flat->key = 'coursehome';
4032 $flat->icon = new pix_icon('i/course', '');
4034 $courseformat = course_get_format($course);
4035 $coursenode = $PAGE->navigation->find_active_node();
4036 $targettype = navigation_node::TYPE_COURSE;
4038 // Single activity format has no course node - the course node is swapped for the activity node.
4039 if (!$courseformat->has_view_page()) {
4040 $targettype = navigation_node::TYPE_ACTIVITY;
4043 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
4044 $coursenode = $coursenode->parent;
4046 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4047 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4048 if ($coursenode && $coursenode->key != SITEID) {
4049 $this->add($flat);
4050 foreach ($coursenode->children as $child) {
4051 if ($child->action) {
4052 $flat = new flat_navigation_node($child, 0);
4053 $this->add($flat);
4058 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
4059 } else {
4060 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
4063 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
4064 if (!$admin) {
4065 // Try again - crazy nav tree!
4066 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
4068 if ($admin) {
4069 $flat = new flat_navigation_node($admin, 0);
4070 $flat->set_showdivider(true, get_string('sitesettings'));
4071 $flat->key = 'sitesettings';
4072 $flat->icon = new pix_icon('t/preferences', '');
4073 $this->add($flat);
4076 // Add-a-block in editing mode.
4077 if (isset($this->page->theme->addblockposition) &&
4078 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
4079 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) {
4080 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
4081 $addablock = navigation_node::create(get_string('addblock'), $url);
4082 $flat = new flat_navigation_node($addablock, 0);
4083 $flat->set_showdivider(true, get_string('blocksaddedit'));
4084 $flat->key = 'addblock';
4085 $flat->icon = new pix_icon('i/addblock', '');
4086 $this->add($flat);
4088 $addblockurl = "?{$url->get_query_string(false)}";
4090 $PAGE->requires->js_call_amd('core/addblockmodal', 'init',
4091 [$PAGE->pagetype, $PAGE->pagelayout, $addblockurl, $PAGE->subpage]);
4097 * Override the parent so we can set a label for this collection if it has not been set yet.
4099 * @param navigation_node $node Node to add
4100 * @param string $beforekey If specified, adds before a node with this key,
4101 * otherwise adds at end
4102 * @return navigation_node Added node
4104 public function add(navigation_node $node, $beforekey=null) {
4105 $result = parent::add($node, $beforekey);
4106 // Extend the parent to get a name for the collection of nodes if required.
4107 if (empty($this->collectionlabel)) {
4108 if ($node instanceof flat_navigation_node) {
4109 $this->set_collectionlabel($node->get_collectionlabel());
4113 return $result;
4118 * Class used to manage the settings option for the current page
4120 * This class is used to manage the settings options in a tree format (recursively)
4121 * and was created initially for use with the settings blocks.
4123 * @package core
4124 * @category navigation
4125 * @copyright 2009 Sam Hemelryk
4126 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4128 class settings_navigation extends navigation_node {
4129 /** @var stdClass the current context */
4130 protected $context;
4131 /** @var moodle_page the moodle page that the navigation belongs to */
4132 protected $page;
4133 /** @var string contains administration section navigation_nodes */
4134 protected $adminsection;
4135 /** @var bool A switch to see if the navigation node is initialised */
4136 protected $initialised = false;
4137 /** @var array An array of users that the nodes can extend for. */
4138 protected $userstoextendfor = array();
4139 /** @var navigation_cache **/
4140 protected $cache;
4143 * Sets up the object with basic settings and preparse it for use
4145 * @param moodle_page $page
4147 public function __construct(moodle_page &$page) {
4148 if (during_initial_install()) {
4149 return false;
4151 $this->page = $page;
4152 // Initialise the main navigation. It is most important that this is done
4153 // before we try anything
4154 $this->page->navigation->initialise();
4155 // Initialise the navigation cache
4156 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4157 $this->children = new navigation_node_collection();
4161 * Initialise the settings navigation based on the current context
4163 * This function initialises the settings navigation tree for a given context
4164 * by calling supporting functions to generate major parts of the tree.
4167 public function initialise() {
4168 global $DB, $SESSION, $SITE;
4170 if (during_initial_install()) {
4171 return false;
4172 } else if ($this->initialised) {
4173 return true;
4175 $this->id = 'settingsnav';
4176 $this->context = $this->page->context;
4178 $context = $this->context;
4179 if ($context->contextlevel == CONTEXT_BLOCK) {
4180 $this->load_block_settings();
4181 $context = $context->get_parent_context();
4182 $this->context = $context;
4184 switch ($context->contextlevel) {
4185 case CONTEXT_SYSTEM:
4186 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4187 $this->load_front_page_settings(($context->id == $this->context->id));
4189 break;
4190 case CONTEXT_COURSECAT:
4191 $this->load_category_settings();
4192 break;
4193 case CONTEXT_COURSE:
4194 if ($this->page->course->id != $SITE->id) {
4195 $this->load_course_settings(($context->id == $this->context->id));
4196 } else {
4197 $this->load_front_page_settings(($context->id == $this->context->id));
4199 break;
4200 case CONTEXT_MODULE:
4201 $this->load_module_settings();
4202 $this->load_course_settings();
4203 break;
4204 case CONTEXT_USER:
4205 if ($this->page->course->id != $SITE->id) {
4206 $this->load_course_settings();
4208 break;
4211 $usersettings = $this->load_user_settings($this->page->course->id);
4213 $adminsettings = false;
4214 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4215 $isadminpage = $this->is_admin_tree_needed();
4217 if (has_capability('moodle/site:configview', context_system::instance())) {
4218 if (has_capability('moodle/site:config', context_system::instance())) {
4219 // Make sure this works even if config capability changes on the fly
4220 // and also make it fast for admin right after login.
4221 $SESSION->load_navigation_admin = 1;
4222 if ($isadminpage) {
4223 $adminsettings = $this->load_administration_settings();
4226 } else if (!isset($SESSION->load_navigation_admin)) {
4227 $adminsettings = $this->load_administration_settings();
4228 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4230 } else if ($SESSION->load_navigation_admin) {
4231 if ($isadminpage) {
4232 $adminsettings = $this->load_administration_settings();
4236 // Print empty navigation node, if needed.
4237 if ($SESSION->load_navigation_admin && !$isadminpage) {
4238 if ($adminsettings) {
4239 // Do not print settings tree on pages that do not need it, this helps with performance.
4240 $adminsettings->remove();
4241 $adminsettings = false;
4243 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4244 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4245 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4246 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4247 $siteadminnode->requiresajaxloading = 'true';
4252 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4253 $adminsettings->force_open();
4254 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4255 $usersettings->force_open();
4258 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4259 $this->load_local_plugin_settings();
4261 foreach ($this->children as $key=>$node) {
4262 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4263 // Site administration is shown as link.
4264 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4265 continue;
4267 $node->remove();
4270 $this->initialised = true;
4273 * Override the parent function so that we can add preceeding hr's and set a
4274 * root node class against all first level element
4276 * It does this by first calling the parent's add method {@link navigation_node::add()}
4277 * and then proceeds to use the key to set class and hr
4279 * @param string $text text to be used for the link.
4280 * @param string|moodle_url $url url for the new node
4281 * @param int $type the type of node navigation_node::TYPE_*
4282 * @param string $shorttext
4283 * @param string|int $key a key to access the node by.
4284 * @param pix_icon $icon An icon that appears next to the node.
4285 * @return navigation_node with the new node added to it.
4287 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4288 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4289 $node->add_class('root_node');
4290 return $node;
4294 * This function allows the user to add something to the start of the settings
4295 * navigation, which means it will be at the top of the settings navigation block
4297 * @param string $text text to be used for the link.
4298 * @param string|moodle_url $url url for the new node
4299 * @param int $type the type of node navigation_node::TYPE_*
4300 * @param string $shorttext
4301 * @param string|int $key a key to access the node by.
4302 * @param pix_icon $icon An icon that appears next to the node.
4303 * @return navigation_node $node with the new node added to it.
4305 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4306 $children = $this->children;
4307 $childrenclass = get_class($children);
4308 $this->children = new $childrenclass;
4309 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4310 foreach ($children as $child) {
4311 $this->children->add($child);
4313 return $node;
4317 * Does this page require loading of full admin tree or is
4318 * it enough rely on AJAX?
4320 * @return bool
4322 protected function is_admin_tree_needed() {
4323 if (self::$loadadmintree) {
4324 // Usually external admin page or settings page.
4325 return true;
4328 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4329 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4330 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4331 return false;
4333 return true;
4336 return false;
4340 * Load the site administration tree
4342 * This function loads the site administration tree by using the lib/adminlib library functions
4344 * @param navigation_node $referencebranch A reference to a branch in the settings
4345 * navigation tree
4346 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4347 * tree and start at the beginning
4348 * @return mixed A key to access the admin tree by
4350 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4351 global $CFG;
4353 // Check if we are just starting to generate this navigation.
4354 if ($referencebranch === null) {
4356 // Require the admin lib then get an admin structure
4357 if (!function_exists('admin_get_root')) {
4358 require_once($CFG->dirroot.'/lib/adminlib.php');
4360 $adminroot = admin_get_root(false, false);
4361 // This is the active section identifier
4362 $this->adminsection = $this->page->url->param('section');
4364 // Disable the navigation from automatically finding the active node
4365 navigation_node::$autofindactive = false;
4366 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4367 foreach ($adminroot->children as $adminbranch) {
4368 $this->load_administration_settings($referencebranch, $adminbranch);
4370 navigation_node::$autofindactive = true;
4372 // Use the admin structure to locate the active page
4373 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4374 $currentnode = $this;
4375 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4376 $currentnode = $currentnode->get($pathkey);
4378 if ($currentnode) {
4379 $currentnode->make_active();
4381 } else {
4382 $this->scan_for_active_node($referencebranch);
4384 return $referencebranch;
4385 } else if ($adminbranch->check_access()) {
4386 // We have a reference branch that we can access and is not hidden `hurrah`
4387 // Now we need to display it and any children it may have
4388 $url = null;
4389 $icon = null;
4390 if ($adminbranch instanceof admin_settingpage) {
4391 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
4392 } else if ($adminbranch instanceof admin_externalpage) {
4393 $url = $adminbranch->url;
4394 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4395 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
4398 // Add the branch
4399 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4401 if ($adminbranch->is_hidden()) {
4402 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4403 $reference->add_class('hidden');
4404 } else {
4405 $reference->display = false;
4409 // Check if we are generating the admin notifications and whether notificiations exist
4410 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4411 $reference->add_class('criticalnotification');
4413 // Check if this branch has children
4414 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4415 foreach ($adminbranch->children as $branch) {
4416 // Generate the child branches as well now using this branch as the reference
4417 $this->load_administration_settings($reference, $branch);
4419 } else {
4420 $reference->icon = new pix_icon('i/settings', '');
4426 * This function recursivily scans nodes until it finds the active node or there
4427 * are no more nodes.
4428 * @param navigation_node $node
4430 protected function scan_for_active_node(navigation_node $node) {
4431 if (!$node->check_if_active() && $node->children->count()>0) {
4432 foreach ($node->children as &$child) {
4433 $this->scan_for_active_node($child);
4439 * Gets a navigation node given an array of keys that represent the path to
4440 * the desired node.
4442 * @param array $path
4443 * @return navigation_node|false
4445 protected function get_by_path(array $path) {
4446 $node = $this->get(array_shift($path));
4447 foreach ($path as $key) {
4448 $node->get($key);
4450 return $node;
4454 * This function loads the course settings that are available for the user
4456 * @param bool $forceopen If set to true the course node will be forced open
4457 * @return navigation_node|false
4459 protected function load_course_settings($forceopen = false) {
4460 global $CFG, $USER;
4461 require_once($CFG->dirroot . '/course/lib.php');
4463 $course = $this->page->course;
4464 $coursecontext = context_course::instance($course->id);
4465 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4467 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4469 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4470 if ($forceopen) {
4471 $coursenode->force_open();
4475 if ($adminoptions->update) {
4476 // Add the course settings link
4477 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4478 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
4481 if ($adminoptions->editcompletion) {
4482 // Add the course completion settings link
4483 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4484 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null,
4485 new pix_icon('i/settings', ''));
4488 if (!$adminoptions->update && $adminoptions->tags) {
4489 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4490 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4493 // add enrol nodes
4494 enrol_add_course_navigation($coursenode, $course);
4496 // Manage filters
4497 if ($adminoptions->filters) {
4498 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4499 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4502 // View course reports.
4503 if ($adminoptions->reports) {
4504 $reportnav = $coursenode->add(get_string('reports'),
4505 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]),
4506 self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', ''));
4507 $coursereports = core_component::get_plugin_list('coursereport');
4508 foreach ($coursereports as $report => $dir) {
4509 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4510 if (file_exists($libfile)) {
4511 require_once($libfile);
4512 $reportfunction = $report.'_report_extend_navigation';
4513 if (function_exists($report.'_report_extend_navigation')) {
4514 $reportfunction($reportnav, $course, $coursecontext);
4519 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4520 foreach ($reports as $reportfunction) {
4521 $reportfunction($reportnav, $course, $coursecontext);
4525 // Check if we can view the gradebook's setup page.
4526 if ($adminoptions->gradebook) {
4527 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4528 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4529 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4532 // Add the context locking node.
4533 $this->add_context_locking_node($coursenode, $coursecontext);
4535 // Add outcome if permitted
4536 if ($adminoptions->outcomes) {
4537 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4538 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4541 //Add badges navigation
4542 if ($adminoptions->badges) {
4543 require_once($CFG->libdir .'/badgeslib.php');
4544 badges_add_course_navigation($coursenode, $course);
4547 // Backup this course
4548 if ($adminoptions->backup) {
4549 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4550 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4553 // Restore to this course
4554 if ($adminoptions->restore) {
4555 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4556 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4559 // Import data from other courses
4560 if ($adminoptions->import) {
4561 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
4562 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4565 // Copy this course.
4566 if ($adminoptions->copy) {
4567 $url = new moodle_url('/backup/copy.php', array('id' => $course->id));
4568 $coursenode->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', ''));
4571 // Reset this course
4572 if ($adminoptions->reset) {
4573 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4574 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4577 // Questions
4578 require_once($CFG->libdir . '/questionlib.php');
4579 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4581 if ($adminoptions->update) {
4582 // Repository Instances
4583 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4584 require_once($CFG->dirroot . '/repository/lib.php');
4585 $editabletypes = repository::get_editable_types($coursecontext);
4586 $haseditabletypes = !empty($editabletypes);
4587 unset($editabletypes);
4588 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4589 } else {
4590 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4592 if ($haseditabletypes) {
4593 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4594 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4598 // Manage files
4599 if ($adminoptions->files) {
4600 // hidden in new courses and courses where legacy files were turned off
4601 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4602 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4606 // Let plugins hook into course navigation.
4607 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4608 foreach ($pluginsfunction as $plugintype => $plugins) {
4609 // Ignore the report plugin as it was already loaded above.
4610 if ($plugintype == 'report') {
4611 continue;
4613 foreach ($plugins as $pluginfunction) {
4614 $pluginfunction($coursenode, $course, $coursecontext);
4618 // Prepare data for course content download functionality if it is enabled.
4619 // Will only be included here if the action menu is already in use, otherwise a button will be added to the UI elsewhere.
4620 if (\core\content::can_export_context($coursecontext, $USER) && !empty($coursenode->get_children_key_list())) {
4621 $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext);
4622 $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes);
4624 $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download',
4625 new pix_icon('t/download', ''));
4628 // Return we are done
4629 return $coursenode;
4633 * This function calls the module function to inject module settings into the
4634 * settings navigation tree.
4636 * This only gets called if there is a corrosponding function in the modules
4637 * lib file.
4639 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4641 * @return navigation_node|false
4643 protected function load_module_settings() {
4644 global $CFG;
4646 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4647 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4648 $this->page->set_cm($cm, $this->page->course);
4651 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4652 if (file_exists($file)) {
4653 require_once($file);
4656 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4657 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4658 $modulenode->force_open();
4660 // Settings for the module
4661 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4662 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4663 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit',
4664 new pix_icon('i/settings', ''));
4666 // Assign local roles
4667 if (count(get_assignable_roles($this->page->cm->context))>0) {
4668 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4669 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign',
4670 new pix_icon('i/role', ''));
4672 // Override roles
4673 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4674 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4675 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride',
4676 new pix_icon('i/permissions', ''));
4678 // Check role permissions
4679 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4680 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4681 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck',
4682 new pix_icon('i/checkpermissions', ''));
4685 // Add the context locking node.
4686 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4688 // Manage filters
4689 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4690 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4691 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage',
4692 new pix_icon('i/filter', ''));
4694 // Add reports
4695 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4696 foreach ($reports as $reportfunction) {
4697 $reportfunction($modulenode, $this->page->cm);
4699 // Add a backup link
4700 $featuresfunc = $this->page->activityname.'_supports';
4701 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4702 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4703 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4706 // Restore this activity
4707 $featuresfunc = $this->page->activityname.'_supports';
4708 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4709 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4710 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4713 // Allow the active advanced grading method plugin to append its settings
4714 $featuresfunc = $this->page->activityname.'_supports';
4715 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4716 require_once($CFG->dirroot.'/grade/grading/lib.php');
4717 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4718 $gradingman->extend_settings_navigation($this, $modulenode);
4721 $function = $this->page->activityname.'_extend_settings_navigation';
4722 if (function_exists($function)) {
4723 $function($this, $modulenode);
4726 // Remove the module node if there are no children.
4727 if ($modulenode->children->count() <= 0) {
4728 $modulenode->remove();
4731 return $modulenode;
4735 * Loads the user settings block of the settings nav
4737 * This function is simply works out the userid and whether we need to load
4738 * just the current users profile settings, or the current user and the user the
4739 * current user is viewing.
4741 * This function has some very ugly code to work out the user, if anyone has
4742 * any bright ideas please feel free to intervene.
4744 * @param int $courseid The course id of the current course
4745 * @return navigation_node|false
4747 protected function load_user_settings($courseid = SITEID) {
4748 global $USER, $CFG;
4750 if (isguestuser() || !isloggedin()) {
4751 return false;
4754 $navusers = $this->page->navigation->get_extending_users();
4756 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4757 $usernode = null;
4758 foreach ($this->userstoextendfor as $userid) {
4759 if ($userid == $USER->id) {
4760 continue;
4762 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4763 if (is_null($usernode)) {
4764 $usernode = $node;
4767 foreach ($navusers as $user) {
4768 if ($user->id == $USER->id) {
4769 continue;
4771 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4772 if (is_null($usernode)) {
4773 $usernode = $node;
4776 $this->generate_user_settings($courseid, $USER->id);
4777 } else {
4778 $usernode = $this->generate_user_settings($courseid, $USER->id);
4780 return $usernode;
4784 * Extends the settings navigation for the given user.
4786 * Note: This method gets called automatically if you call
4787 * $PAGE->navigation->extend_for_user($userid)
4789 * @param int $userid
4791 public function extend_for_user($userid) {
4792 global $CFG;
4794 if (!in_array($userid, $this->userstoextendfor)) {
4795 $this->userstoextendfor[] = $userid;
4796 if ($this->initialised) {
4797 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4798 $children = array();
4799 foreach ($this->children as $child) {
4800 $children[] = $child;
4802 array_unshift($children, array_pop($children));
4803 $this->children = new navigation_node_collection();
4804 foreach ($children as $child) {
4805 $this->children->add($child);
4812 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4813 * what can be shown/done
4815 * @param int $courseid The current course' id
4816 * @param int $userid The user id to load for
4817 * @param string $gstitle The string to pass to get_string for the branch title
4818 * @return navigation_node|false
4820 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4821 global $DB, $CFG, $USER, $SITE;
4823 if ($courseid != $SITE->id) {
4824 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4825 $course = $this->page->course;
4826 } else {
4827 $select = context_helper::get_preload_record_columns_sql('ctx');
4828 $sql = "SELECT c.*, $select
4829 FROM {course} c
4830 JOIN {context} ctx ON c.id = ctx.instanceid
4831 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4832 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4833 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4834 context_helper::preload_from_record($course);
4836 } else {
4837 $course = $SITE;
4840 $coursecontext = context_course::instance($course->id); // Course context
4841 $systemcontext = context_system::instance();
4842 $currentuser = ($USER->id == $userid);
4844 if ($currentuser) {
4845 $user = $USER;
4846 $usercontext = context_user::instance($user->id); // User context
4847 } else {
4848 $select = context_helper::get_preload_record_columns_sql('ctx');
4849 $sql = "SELECT u.*, $select
4850 FROM {user} u
4851 JOIN {context} ctx ON u.id = ctx.instanceid
4852 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4853 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4854 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4855 if (!$user) {
4856 return false;
4858 context_helper::preload_from_record($user);
4860 // Check that the user can view the profile
4861 $usercontext = context_user::instance($user->id); // User context
4862 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4864 if ($course->id == $SITE->id) {
4865 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4866 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4867 return false;
4869 } else {
4870 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4871 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4872 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4873 return false;
4875 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4876 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4877 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4878 if ($courseid == $this->page->course->id) {
4879 $mygroups = get_fast_modinfo($this->page->course)->groups;
4880 } else {
4881 $mygroups = groups_get_user_groups($courseid);
4883 $usergroups = groups_get_user_groups($courseid, $userid);
4884 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4885 return false;
4891 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4893 $key = $gstitle;
4894 $prefurl = new moodle_url('/user/preferences.php');
4895 if ($gstitle != 'usercurrentsettings') {
4896 $key .= $userid;
4897 $prefurl->param('userid', $userid);
4900 // Add a user setting branch.
4901 if ($gstitle == 'usercurrentsettings') {
4902 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4903 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4904 // breadcrumb.
4905 $dashboard->display = false;
4906 if (get_home_page() == HOMEPAGE_MY) {
4907 $dashboard->mainnavonly = true;
4910 $iscurrentuser = ($user->id == $USER->id);
4912 $baseargs = array('id' => $user->id);
4913 if ($course->id != $SITE->id && !$iscurrentuser) {
4914 $baseargs['course'] = $course->id;
4915 $issitecourse = false;
4916 } else {
4917 // Load all categories and get the context for the system.
4918 $issitecourse = true;
4921 // Add the user profile to the dashboard.
4922 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4923 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4925 if (!empty($CFG->navadduserpostslinks)) {
4926 // Add nodes for forum posts and discussions if the user can view either or both
4927 // There are no capability checks here as the content of the page is based
4928 // purely on the forums the current user has access too.
4929 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4930 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4931 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4932 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4935 // Add blog nodes.
4936 if (!empty($CFG->enableblogs)) {
4937 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4938 require_once($CFG->dirroot.'/blog/lib.php');
4939 // Get all options for the user.
4940 $options = blog_get_options_for_user($user);
4941 $this->cache->set('userblogoptions'.$user->id, $options);
4942 } else {
4943 $options = $this->cache->{'userblogoptions'.$user->id};
4946 if (count($options) > 0) {
4947 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4948 foreach ($options as $type => $option) {
4949 if ($type == "rss") {
4950 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4951 new pix_icon('i/rss', ''));
4952 } else {
4953 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4959 // Add the messages link.
4960 // It is context based so can appear in the user's profile and in course participants information.
4961 if (!empty($CFG->messaging)) {
4962 $messageargs = array('user1' => $USER->id);
4963 if ($USER->id != $user->id) {
4964 $messageargs['user2'] = $user->id;
4966 $url = new moodle_url('/message/index.php', $messageargs);
4967 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4970 // Add the "My private files" link.
4971 // This link doesn't have a unique display for course context so only display it under the user's profile.
4972 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4973 $url = new moodle_url('/user/files.php');
4974 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
4977 // Add a node to view the users notes if permitted.
4978 if (!empty($CFG->enablenotes) &&
4979 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4980 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4981 if ($coursecontext->instanceid != SITEID) {
4982 $url->param('course', $coursecontext->instanceid);
4984 $profilenode->add(get_string('notes', 'notes'), $url);
4987 // Show the grades node.
4988 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
4989 require_once($CFG->dirroot . '/user/lib.php');
4990 // Set the grades node to link to the "Grades" page.
4991 if ($course->id == SITEID) {
4992 $url = user_mygrades_url($user->id, $course->id);
4993 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4994 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
4996 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
4999 // Let plugins hook into user navigation.
5000 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5001 foreach ($pluginsfunction as $plugintype => $plugins) {
5002 if ($plugintype != 'report') {
5003 foreach ($plugins as $pluginfunction) {
5004 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5009 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5010 $dashboard->add_node($usersetting);
5011 } else {
5012 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5013 $usersetting->display = false;
5015 $usersetting->id = 'usersettings';
5017 // Check if the user has been deleted.
5018 if ($user->deleted) {
5019 if (!has_capability('moodle/user:update', $coursecontext)) {
5020 // We can't edit the user so just show the user deleted message.
5021 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
5022 } else {
5023 // We can edit the user so show the user deleted message and link it to the profile.
5024 if ($course->id == $SITE->id) {
5025 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
5026 } else {
5027 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
5029 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
5031 return true;
5034 $userauthplugin = false;
5035 if (!empty($user->auth)) {
5036 $userauthplugin = get_auth_plugin($user->auth);
5039 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
5041 // Add the profile edit link.
5042 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5043 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
5044 has_capability('moodle/user:update', $systemcontext)) {
5045 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
5046 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5047 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5048 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5049 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5050 $url = $userauthplugin->edit_profile_url();
5051 if (empty($url)) {
5052 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
5054 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5059 // Change password link.
5060 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
5061 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5062 $passwordchangeurl = $userauthplugin->change_password_url();
5063 if (empty($passwordchangeurl)) {
5064 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
5066 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
5069 // Default homepage.
5070 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER));
5071 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5072 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5073 has_capability('moodle/user:editprofile', $usercontext)) {
5074 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]);
5075 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser');
5079 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5080 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5081 has_capability('moodle/user:editprofile', $usercontext)) {
5082 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
5083 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
5086 $pluginmanager = core_plugin_manager::instance();
5087 $enabled = $pluginmanager->get_enabled_plugins('mod');
5088 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5089 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5090 has_capability('moodle/user:editprofile', $usercontext)) {
5091 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
5092 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
5095 $editors = editors_get_enabled();
5096 if (count($editors) > 1) {
5097 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5098 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5099 has_capability('moodle/user:editprofile', $usercontext)) {
5100 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
5101 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
5106 // Add "Calendar preferences" link.
5107 if (isloggedin() && !isguestuser($user)) {
5108 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5109 has_capability('moodle/user:editprofile', $usercontext)) {
5110 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
5111 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
5115 // Add "Content bank preferences" link.
5116 if (isloggedin() && !isguestuser($user)) {
5117 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5118 has_capability('moodle/user:editprofile', $usercontext)) {
5119 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]);
5120 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING,
5121 null, 'contentbankpreferences');
5125 // View the roles settings.
5126 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5127 'moodle/role:manage'], $usercontext)) {
5128 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
5130 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]);
5131 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
5133 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
5135 if (!empty($assignableroles)) {
5136 $url = new moodle_url('/admin/roles/assign.php',
5137 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5138 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
5141 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
5142 $url = new moodle_url('/admin/roles/permissions.php',
5143 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5144 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5147 $url = new moodle_url('/admin/roles/check.php',
5148 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5149 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5152 // Repositories.
5153 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5154 require_once($CFG->dirroot . '/repository/lib.php');
5155 $editabletypes = repository::get_editable_types($usercontext);
5156 $haseditabletypes = !empty($editabletypes);
5157 unset($editabletypes);
5158 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5159 } else {
5160 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5162 if ($haseditabletypes) {
5163 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5164 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5165 array('contextid' => $usercontext->id)));
5168 // Portfolio.
5169 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5170 require_once($CFG->libdir . '/portfoliolib.php');
5171 if (portfolio_has_visible_instances()) {
5172 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5174 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5175 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5177 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5178 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5182 $enablemanagetokens = false;
5183 if (!empty($CFG->enablerssfeeds)) {
5184 $enablemanagetokens = true;
5185 } else if (!is_siteadmin($USER->id)
5186 && !empty($CFG->enablewebservices)
5187 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5188 $enablemanagetokens = true;
5190 // Security keys.
5191 if ($currentuser && $enablemanagetokens) {
5192 $url = new moodle_url('/user/managetoken.php');
5193 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5196 // Messaging.
5197 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5198 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5199 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5200 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5201 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5202 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5205 // Blogs.
5206 if ($currentuser && !empty($CFG->enableblogs)) {
5207 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5208 if (has_capability('moodle/blog:view', $systemcontext)) {
5209 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5210 navigation_node::TYPE_SETTING);
5212 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5213 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5214 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5215 navigation_node::TYPE_SETTING);
5216 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5217 navigation_node::TYPE_SETTING);
5219 // Remove the blog node if empty.
5220 $blog->trim_if_empty();
5223 // Badges.
5224 if ($currentuser && !empty($CFG->enablebadges)) {
5225 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5226 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5227 $url = new moodle_url('/badges/mybadges.php');
5228 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5230 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5231 navigation_node::TYPE_SETTING);
5232 if (!empty($CFG->badges_allowexternalbackpack)) {
5233 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5234 navigation_node::TYPE_SETTING);
5238 // Let plugins hook into user settings navigation.
5239 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5240 foreach ($pluginsfunction as $plugintype => $plugins) {
5241 foreach ($plugins as $pluginfunction) {
5242 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5246 return $usersetting;
5250 * Loads block specific settings in the navigation
5252 * @return navigation_node
5254 protected function load_block_settings() {
5255 global $CFG;
5257 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5258 $blocknode->force_open();
5260 // Assign local roles
5261 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5262 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5263 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5264 'roles', new pix_icon('i/assignroles', ''));
5267 // Override roles
5268 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5269 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5270 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5271 'permissions', new pix_icon('i/permissions', ''));
5273 // Check role permissions
5274 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5275 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5276 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5277 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5280 // Add the context locking node.
5281 $this->add_context_locking_node($blocknode, $this->context);
5283 return $blocknode;
5287 * Loads category specific settings in the navigation
5289 * @return navigation_node
5291 protected function load_category_settings() {
5292 global $CFG;
5294 // We can land here while being in the context of a block, in which case we
5295 // should get the parent context which should be the category one. See self::initialise().
5296 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5297 $catcontext = $this->context->get_parent_context();
5298 } else {
5299 $catcontext = $this->context;
5302 // Let's make sure that we always have the right context when getting here.
5303 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5304 throw new coding_exception('Unexpected context while loading category settings.');
5307 $categorynodetype = navigation_node::TYPE_CONTAINER;
5308 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5309 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5310 $categorynode->force_open();
5312 if (can_edit_in_category($catcontext->instanceid)) {
5313 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5314 $editstring = get_string('managecategorythis');
5315 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5318 if (has_capability('moodle/category:manage', $catcontext)) {
5319 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5320 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5322 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5323 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5326 // Assign local roles
5327 $assignableroles = get_assignable_roles($catcontext);
5328 if (!empty($assignableroles)) {
5329 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5330 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5333 // Override roles
5334 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5335 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5336 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5338 // Check role permissions
5339 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5340 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5341 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5342 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5345 // Add the context locking node.
5346 $this->add_context_locking_node($categorynode, $catcontext);
5348 // Cohorts
5349 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5350 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5351 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5354 // Manage filters
5355 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5356 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5357 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5360 // Restore.
5361 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5362 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5363 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5366 // Let plugins hook into category settings navigation.
5367 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5368 foreach ($pluginsfunction as $plugintype => $plugins) {
5369 foreach ($plugins as $pluginfunction) {
5370 $pluginfunction($categorynode, $catcontext);
5374 return $categorynode;
5378 * Determine whether the user is assuming another role
5380 * This function checks to see if the user is assuming another role by means of
5381 * role switching. In doing this we compare each RSW key (context path) against
5382 * the current context path. This ensures that we can provide the switching
5383 * options against both the course and any page shown under the course.
5385 * @return bool|int The role(int) if the user is in another role, false otherwise
5387 protected function in_alternative_role() {
5388 global $USER;
5389 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5390 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5391 return $USER->access['rsw'][$this->page->context->path];
5393 foreach ($USER->access['rsw'] as $key=>$role) {
5394 if (strpos($this->context->path,$key)===0) {
5395 return $role;
5399 return false;
5403 * This function loads all of the front page settings into the settings navigation.
5404 * This function is called when the user is on the front page, or $COURSE==$SITE
5405 * @param bool $forceopen (optional)
5406 * @return navigation_node
5408 protected function load_front_page_settings($forceopen = false) {
5409 global $SITE, $CFG;
5410 require_once($CFG->dirroot . '/course/lib.php');
5412 $course = clone($SITE);
5413 $coursecontext = context_course::instance($course->id); // Course context
5414 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5416 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5417 if ($forceopen) {
5418 $frontpage->force_open();
5420 $frontpage->id = 'frontpagesettings';
5422 if ($this->page->user_allowed_editing()) {
5424 // Add the turn on/off settings
5425 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5426 if ($this->page->user_is_editing()) {
5427 $url->param('edit', 'off');
5428 $editstring = get_string('turneditingoff');
5429 } else {
5430 $url->param('edit', 'on');
5431 $editstring = get_string('turneditingon');
5433 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5436 if ($adminoptions->update) {
5437 // Add the course settings link
5438 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5439 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5442 // add enrol nodes
5443 enrol_add_course_navigation($frontpage, $course);
5445 // Manage filters
5446 if ($adminoptions->filters) {
5447 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5448 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5451 // View course reports.
5452 if ($adminoptions->reports) {
5453 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5454 new pix_icon('i/stats', ''));
5455 $coursereports = core_component::get_plugin_list('coursereport');
5456 foreach ($coursereports as $report=>$dir) {
5457 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5458 if (file_exists($libfile)) {
5459 require_once($libfile);
5460 $reportfunction = $report.'_report_extend_navigation';
5461 if (function_exists($report.'_report_extend_navigation')) {
5462 $reportfunction($frontpagenav, $course, $coursecontext);
5467 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5468 foreach ($reports as $reportfunction) {
5469 $reportfunction($frontpagenav, $course, $coursecontext);
5473 // Backup this course
5474 if ($adminoptions->backup) {
5475 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5476 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5479 // Restore to this course
5480 if ($adminoptions->restore) {
5481 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5482 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5485 // Questions
5486 require_once($CFG->libdir . '/questionlib.php');
5487 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5489 // Manage files
5490 if ($adminoptions->files) {
5491 //hiden in new installs
5492 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5493 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5496 // Let plugins hook into frontpage navigation.
5497 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5498 foreach ($pluginsfunction as $plugintype => $plugins) {
5499 foreach ($plugins as $pluginfunction) {
5500 $pluginfunction($frontpage, $course, $coursecontext);
5504 return $frontpage;
5508 * This function gives local plugins an opportunity to modify the settings navigation.
5510 protected function load_local_plugin_settings() {
5512 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5513 $function($this, $this->context);
5518 * This function marks the cache as volatile so it is cleared during shutdown
5520 public function clear_cache() {
5521 $this->cache->volatile();
5525 * Checks to see if there are child nodes available in the specific user's preference node.
5526 * If so, then they have the appropriate permissions view this user's preferences.
5528 * @since Moodle 2.9.3
5529 * @param int $userid The user's ID.
5530 * @return bool True if child nodes exist to view, otherwise false.
5532 public function can_view_user_preferences($userid) {
5533 if (is_siteadmin()) {
5534 return true;
5536 // See if any nodes are present in the preferences section for this user.
5537 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5538 if ($preferencenode && $preferencenode->has_children()) {
5539 // Run through each child node.
5540 foreach ($preferencenode->children as $childnode) {
5541 // If the child node has children then this user has access to a link in the preferences page.
5542 if ($childnode->has_children()) {
5543 return true;
5547 // No links found for the user to access on the preferences page.
5548 return false;
5553 * Class used to populate site admin navigation for ajax.
5555 * @package core
5556 * @category navigation
5557 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5560 class settings_navigation_ajax extends settings_navigation {
5562 * Constructs the navigation for use in an AJAX request
5564 * @param moodle_page $page
5566 public function __construct(moodle_page &$page) {
5567 $this->page = $page;
5568 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5569 $this->children = new navigation_node_collection();
5570 $this->initialise();
5574 * Initialise the site admin navigation.
5576 * @return array An array of the expandable nodes
5578 public function initialise() {
5579 if ($this->initialised || during_initial_install()) {
5580 return false;
5582 $this->context = $this->page->context;
5583 $this->load_administration_settings();
5585 // Check if local plugins is adding node to site admin.
5586 $this->load_local_plugin_settings();
5588 $this->initialised = true;
5593 * Simple class used to output a navigation branch in XML
5595 * @package core
5596 * @category navigation
5597 * @copyright 2009 Sam Hemelryk
5598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5600 class navigation_json {
5601 /** @var array An array of different node types */
5602 protected $nodetype = array('node','branch');
5603 /** @var array An array of node keys and types */
5604 protected $expandable = array();
5606 * Turns a branch and all of its children into XML
5608 * @param navigation_node $branch
5609 * @return string XML string
5611 public function convert($branch) {
5612 $xml = $this->convert_child($branch);
5613 return $xml;
5616 * Set the expandable items in the array so that we have enough information
5617 * to attach AJAX events
5618 * @param array $expandable
5620 public function set_expandable($expandable) {
5621 foreach ($expandable as $node) {
5622 $this->expandable[$node['key'].':'.$node['type']] = $node;
5626 * Recusively converts a child node and its children to XML for output
5628 * @param navigation_node $child The child to convert
5629 * @param int $depth Pointlessly used to track the depth of the XML structure
5630 * @return string JSON
5632 protected function convert_child($child, $depth=1) {
5633 if (!$child->display) {
5634 return '';
5636 $attributes = array();
5637 $attributes['id'] = $child->id;
5638 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5639 $attributes['type'] = $child->type;
5640 $attributes['key'] = $child->key;
5641 $attributes['class'] = $child->get_css_type();
5642 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5644 if ($child->icon instanceof pix_icon) {
5645 $attributes['icon'] = array(
5646 'component' => $child->icon->component,
5647 'pix' => $child->icon->pix,
5649 foreach ($child->icon->attributes as $key=>$value) {
5650 if ($key == 'class') {
5651 $attributes['icon']['classes'] = explode(' ', $value);
5652 } else if (!array_key_exists($key, $attributes['icon'])) {
5653 $attributes['icon'][$key] = $value;
5657 } else if (!empty($child->icon)) {
5658 $attributes['icon'] = (string)$child->icon;
5661 if ($child->forcetitle || $child->title !== $child->text) {
5662 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5664 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5665 $attributes['expandable'] = $child->key;
5666 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5669 if (count($child->classes)>0) {
5670 $attributes['class'] .= ' '.join(' ',$child->classes);
5672 if (is_string($child->action)) {
5673 $attributes['link'] = $child->action;
5674 } else if ($child->action instanceof moodle_url) {
5675 $attributes['link'] = $child->action->out();
5676 } else if ($child->action instanceof action_link) {
5677 $attributes['link'] = $child->action->url->out();
5679 $attributes['hidden'] = ($child->hidden);
5680 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5681 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5683 if ($child->children->count() > 0) {
5684 $attributes['children'] = array();
5685 foreach ($child->children as $subchild) {
5686 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5690 if ($depth > 1) {
5691 return $attributes;
5692 } else {
5693 return json_encode($attributes);
5699 * The cache class used by global navigation and settings navigation.
5701 * It is basically an easy access point to session with a bit of smarts to make
5702 * sure that the information that is cached is valid still.
5704 * Example use:
5705 * <code php>
5706 * if (!$cache->viewdiscussion()) {
5707 * // Code to do stuff and produce cachable content
5708 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5710 * $content = $cache->viewdiscussion;
5711 * </code>
5713 * @package core
5714 * @category navigation
5715 * @copyright 2009 Sam Hemelryk
5716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5718 class navigation_cache {
5719 /** @var int represents the time created */
5720 protected $creation;
5721 /** @var array An array of session keys */
5722 protected $session;
5724 * The string to use to segregate this particular cache. It can either be
5725 * unique to start a fresh cache or if you want to share a cache then make
5726 * it the string used in the original cache.
5727 * @var string
5729 protected $area;
5730 /** @var int a time that the information will time out */
5731 protected $timeout;
5732 /** @var stdClass The current context */
5733 protected $currentcontext;
5734 /** @var int cache time information */
5735 const CACHETIME = 0;
5736 /** @var int cache user id */
5737 const CACHEUSERID = 1;
5738 /** @var int cache value */
5739 const CACHEVALUE = 2;
5740 /** @var null|array An array of navigation cache areas to expire on shutdown */
5741 public static $volatilecaches;
5744 * Contructor for the cache. Requires two arguments
5746 * @param string $area The string to use to segregate this particular cache
5747 * it can either be unique to start a fresh cache or if you want
5748 * to share a cache then make it the string used in the original
5749 * cache
5750 * @param int $timeout The number of seconds to time the information out after
5752 public function __construct($area, $timeout=1800) {
5753 $this->creation = time();
5754 $this->area = $area;
5755 $this->timeout = time() - $timeout;
5756 if (rand(0,100) === 0) {
5757 $this->garbage_collection();
5762 * Used to set up the cache within the SESSION.
5764 * This is called for each access and ensure that we don't put anything into the session before
5765 * it is required.
5767 protected function ensure_session_cache_initialised() {
5768 global $SESSION;
5769 if (empty($this->session)) {
5770 if (!isset($SESSION->navcache)) {
5771 $SESSION->navcache = new stdClass;
5773 if (!isset($SESSION->navcache->{$this->area})) {
5774 $SESSION->navcache->{$this->area} = array();
5776 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5781 * Magic Method to retrieve something by simply calling using = cache->key
5783 * @param mixed $key The identifier for the information you want out again
5784 * @return void|mixed Either void or what ever was put in
5786 public function __get($key) {
5787 if (!$this->cached($key)) {
5788 return;
5790 $information = $this->session[$key][self::CACHEVALUE];
5791 return unserialize($information);
5795 * Magic method that simply uses {@link set();} to store something in the cache
5797 * @param string|int $key
5798 * @param mixed $information
5800 public function __set($key, $information) {
5801 $this->set($key, $information);
5805 * Sets some information against the cache (session) for later retrieval
5807 * @param string|int $key
5808 * @param mixed $information
5810 public function set($key, $information) {
5811 global $USER;
5812 $this->ensure_session_cache_initialised();
5813 $information = serialize($information);
5814 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5817 * Check the existence of the identifier in the cache
5819 * @param string|int $key
5820 * @return bool
5822 public function cached($key) {
5823 global $USER;
5824 $this->ensure_session_cache_initialised();
5825 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) {
5826 return false;
5828 return true;
5831 * Compare something to it's equivilant in the cache
5833 * @param string $key
5834 * @param mixed $value
5835 * @param bool $serialise Whether to serialise the value before comparison
5836 * this should only be set to false if the value is already
5837 * serialised
5838 * @return bool If the value is the same false if it is not set or doesn't match
5840 public function compare($key, $value, $serialise = true) {
5841 if ($this->cached($key)) {
5842 if ($serialise) {
5843 $value = serialize($value);
5845 if ($this->session[$key][self::CACHEVALUE] === $value) {
5846 return true;
5849 return false;
5852 * Wipes the entire cache, good to force regeneration
5854 public function clear() {
5855 global $SESSION;
5856 unset($SESSION->navcache);
5857 $this->session = null;
5860 * Checks all cache entries and removes any that have expired, good ole cleanup
5862 protected function garbage_collection() {
5863 if (empty($this->session)) {
5864 return true;
5866 foreach ($this->session as $key=>$cachedinfo) {
5867 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5868 unset($this->session[$key]);
5874 * Marks the cache as being volatile (likely to change)
5876 * Any caches marked as volatile will be destroyed at the on shutdown by
5877 * {@link navigation_node::destroy_volatile_caches()} which is registered
5878 * as a shutdown function if any caches are marked as volatile.
5880 * @param bool $setting True to destroy the cache false not too
5882 public function volatile($setting = true) {
5883 if (self::$volatilecaches===null) {
5884 self::$volatilecaches = array();
5885 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5888 if ($setting) {
5889 self::$volatilecaches[$this->area] = $this->area;
5890 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5891 unset(self::$volatilecaches[$this->area]);
5896 * Destroys all caches marked as volatile
5898 * This function is static and works in conjunction with the static volatilecaches
5899 * property of navigation cache.
5900 * Because this function is static it manually resets the cached areas back to an
5901 * empty array.
5903 public static function destroy_volatile_caches() {
5904 global $SESSION;
5905 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5906 foreach (self::$volatilecaches as $area) {
5907 $SESSION->navcache->{$area} = array();
5909 } else {
5910 $SESSION->navcache = new stdClass;