Merge branch 'master_check_cached_empty_modnames' of https://github.com/opitz/moodle
[moodle.git] / lib / navigationlib.php
blobf56a6ef65c73e025d84fac6c664d50ab51f234d7
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since Moodle 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 use core\moodlenet\utilities;
27 use core_contentbank\contentbank;
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * The name that will be used to separate the navigation cache within SESSION
34 define('NAVIGATION_CACHE_NAME', 'navigation');
35 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
37 /**
38 * This class is used to represent a node in a navigation tree
40 * This class is used to represent a node in a navigation tree within Moodle,
41 * the tree could be one of global navigation, settings navigation, or the navbar.
42 * Each node can be one of two types either a Leaf (default) or a branch.
43 * When a node is first created it is created as a leaf, when/if children are added
44 * the node then becomes a branch.
46 * @package core
47 * @category navigation
48 * @copyright 2009 Sam Hemelryk
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 class navigation_node implements renderable {
52 /** @var int Used to identify this node a leaf (default) 0 */
53 const NODETYPE_LEAF = 0;
54 /** @var int Used to identify this node a branch, happens with children 1 */
55 const NODETYPE_BRANCH = 1;
56 /** @var null Unknown node type null */
57 const TYPE_UNKNOWN = null;
58 /** @var int System node type 0 */
59 const TYPE_ROOTNODE = 0;
60 /** @var int System node type 1 */
61 const TYPE_SYSTEM = 1;
62 /** @var int Category node type 10 */
63 const TYPE_CATEGORY = 10;
64 /** var int Category displayed in MyHome navigation node */
65 const TYPE_MY_CATEGORY = 11;
66 /** @var int Course node type 20 */
67 const TYPE_COURSE = 20;
68 /** @var int Course Structure node type 30 */
69 const TYPE_SECTION = 30;
70 /** @var int Activity node type, e.g. Forum, Quiz 40 */
71 const TYPE_ACTIVITY = 40;
72 /** @var int Resource node type, e.g. Link to a file, or label 50 */
73 const TYPE_RESOURCE = 50;
74 /** @var int A custom node type, default when adding without specifing type 60 */
75 const TYPE_CUSTOM = 60;
76 /** @var int Setting node type, used only within settings nav 70 */
77 const TYPE_SETTING = 70;
78 /** @var int site admin branch node type, used only within settings nav 71 */
79 const TYPE_SITE_ADMIN = 71;
80 /** @var int Setting node type, used only within settings nav 80 */
81 const TYPE_USER = 80;
82 /** @var int Setting node type, used for containers of no importance 90 */
83 const TYPE_CONTAINER = 90;
84 /** var int Course the current user is not enrolled in */
85 const COURSE_OTHER = 0;
86 /** var int Course the current user is enrolled in but not viewing */
87 const COURSE_MY = 1;
88 /** var int Course the current user is currently viewing */
89 const COURSE_CURRENT = 2;
90 /** var string The course index page navigation node */
91 const COURSE_INDEX_PAGE = 'courseindexpage';
93 /** @var int Parameter to aid the coder in tracking [optional] */
94 public $id = null;
95 /** @var string|int The identifier for the node, used to retrieve the node */
96 public $key = null;
97 /** @var string|lang_string The text to use for the node */
98 public $text = null;
99 /** @var string Short text to use if requested [optional] */
100 public $shorttext = null;
101 /** @var string The title attribute for an action if one is defined */
102 public $title = null;
103 /** @var string A string that can be used to build a help button */
104 public $helpbutton = null;
105 /** @var moodle_url|action_link|null An action for the node (link) */
106 public $action = null;
107 /** @var pix_icon The path to an icon to use for this node */
108 public $icon = null;
109 /** @var int See TYPE_* constants defined for this class */
110 public $type = self::TYPE_UNKNOWN;
111 /** @var int See NODETYPE_* constants defined for this class */
112 public $nodetype = self::NODETYPE_LEAF;
113 /** @var bool If set to true the node will be collapsed by default */
114 public $collapse = false;
115 /** @var bool If set to true the node will be expanded by default */
116 public $forceopen = false;
117 /** @var array An array of CSS classes for the node */
118 public $classes = array();
119 /** @var navigation_node_collection An array of child nodes */
120 public $children = array();
121 /** @var bool If set to true the node will be recognised as active */
122 public $isactive = false;
123 /** @var bool If set to true the node will be dimmed */
124 public $hidden = false;
125 /** @var bool If set to false the node will not be displayed */
126 public $display = true;
127 /** @var bool If set to true then an HR will be printed before the node */
128 public $preceedwithhr = false;
129 /** @var bool If set to true the the navigation bar should ignore this node */
130 public $mainnavonly = false;
131 /** @var bool If set to true a title will be added to the action no matter what */
132 public $forcetitle = false;
133 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
134 public $parent = null;
135 /** @var bool Override to not display the icon even if one is provided **/
136 public $hideicon = false;
137 /** @var bool Set to true if we KNOW that this node can be expanded. */
138 public $isexpandable = false;
139 /** @var array */
140 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
141 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
142 90 => 'container');
143 /** @var moodle_url */
144 protected static $fullmeurl = null;
145 /** @var bool toogles auto matching of active node */
146 public static $autofindactive = true;
147 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
148 protected static $loadadmintree = false;
149 /** @var mixed If set to an int, that section will be included even if it has no activities */
150 public $includesectionnum = false;
151 /** @var bool does the node need to be loaded via ajax */
152 public $requiresajaxloading = false;
153 /** @var bool If set to true this node will be added to the "flat" navigation */
154 public $showinflatnavigation = false;
155 /** @var bool If set to true this node will be forced into a "more" menu whenever possible */
156 public $forceintomoremenu = false;
157 /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */
158 public $showinsecondarynavigation = true;
159 /** @var bool If set to true the children of this node will be displayed within a submenu when applicable */
160 public $showchildreninsubmenu = false;
161 /** @var string tab element ID. */
162 public $tab;
163 /** @var string unique identifier. */
164 public $moremenuid;
165 /** @var bool node that have children. */
166 public $haschildren;
169 * Constructs a new navigation_node
171 * @param array|string $properties Either an array of properties or a string to use
172 * as the text for the node
174 public function __construct($properties) {
175 if (is_array($properties)) {
176 // Check the array for each property that we allow to set at construction.
177 // text - The main content for the node
178 // shorttext - A short text if required for the node
179 // icon - The icon to display for the node
180 // type - The type of the node
181 // key - The key to use to identify the node
182 // parent - A reference to the nodes parent
183 // action - The action to attribute to this node, usually a URL to link to
184 if (array_key_exists('text', $properties)) {
185 $this->text = $properties['text'];
187 if (array_key_exists('shorttext', $properties)) {
188 $this->shorttext = $properties['shorttext'];
190 if (!array_key_exists('icon', $properties)) {
191 $properties['icon'] = new pix_icon('i/navigationitem', '');
193 $this->icon = $properties['icon'];
194 if ($this->icon instanceof pix_icon) {
195 if (empty($this->icon->attributes['class'])) {
196 $this->icon->attributes['class'] = 'navicon';
197 } else {
198 $this->icon->attributes['class'] .= ' navicon';
201 if (array_key_exists('type', $properties)) {
202 $this->type = $properties['type'];
203 } else {
204 $this->type = self::TYPE_CUSTOM;
206 if (array_key_exists('key', $properties)) {
207 $this->key = $properties['key'];
209 // This needs to happen last because of the check_if_active call that occurs
210 if (array_key_exists('action', $properties)) {
211 $this->action = $properties['action'];
212 if (is_string($this->action)) {
213 $this->action = new moodle_url($this->action);
215 if (self::$autofindactive) {
216 $this->check_if_active();
219 if (array_key_exists('parent', $properties)) {
220 $this->set_parent($properties['parent']);
222 } else if (is_string($properties)) {
223 $this->text = $properties;
225 if ($this->text === null) {
226 throw new coding_exception('You must set the text for the node when you create it.');
228 // Instantiate a new navigation node collection for this nodes children
229 $this->children = new navigation_node_collection();
233 * Checks if this node is the active node.
235 * This is determined by comparing the action for the node against the
236 * defined URL for the page. A match will see this node marked as active.
238 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
239 * @return bool
241 public function check_if_active($strength=URL_MATCH_EXACT) {
242 global $FULLME, $PAGE;
243 // Set fullmeurl if it hasn't already been set
244 if (self::$fullmeurl == null) {
245 if ($PAGE->has_set_url()) {
246 self::override_active_url(new moodle_url($PAGE->url));
247 } else {
248 self::override_active_url(new moodle_url($FULLME));
252 // Compare the action of this node against the fullmeurl
253 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
254 $this->make_active();
255 return true;
257 return false;
261 * True if this nav node has siblings in the tree.
263 * @return bool
265 public function has_siblings() {
266 if (empty($this->parent) || empty($this->parent->children)) {
267 return false;
269 if ($this->parent->children instanceof navigation_node_collection) {
270 $count = $this->parent->children->count();
271 } else {
272 $count = count($this->parent->children);
274 return ($count > 1);
278 * Get a list of sibling navigation nodes at the same level as this one.
280 * @return bool|array of navigation_node
282 public function get_siblings() {
283 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
284 // the in-page links or the breadcrumb links.
285 $siblings = false;
287 if ($this->has_siblings()) {
288 $siblings = [];
289 foreach ($this->parent->children as $child) {
290 if ($child->display) {
291 $siblings[] = $child;
295 return $siblings;
299 * This sets the URL that the URL of new nodes get compared to when locating
300 * the active node.
302 * The active node is the node that matches the URL set here. By default this
303 * is either $PAGE->url or if that hasn't been set $FULLME.
305 * @param moodle_url $url The url to use for the fullmeurl.
306 * @param bool $loadadmintree use true if the URL point to administration tree
308 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
309 // Clone the URL, in case the calling script changes their URL later.
310 self::$fullmeurl = new moodle_url($url);
311 // True means we do not want AJAX loaded admin tree, required for all admin pages.
312 if ($loadadmintree) {
313 // Do not change back to false if already set.
314 self::$loadadmintree = true;
319 * Use when page is linked from the admin tree,
320 * if not used navigation could not find the page using current URL
321 * because the tree is not fully loaded.
323 public static function require_admin_tree() {
324 self::$loadadmintree = true;
328 * Creates a navigation node, ready to add it as a child using add_node
329 * function. (The created node needs to be added before you can use it.)
330 * @param string $text
331 * @param moodle_url|action_link $action
332 * @param int $type
333 * @param string $shorttext
334 * @param string|int $key
335 * @param pix_icon $icon
336 * @return navigation_node
338 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
339 $shorttext=null, $key=null, pix_icon $icon=null) {
340 if ($action && !($action instanceof moodle_url || $action instanceof action_link)) {
341 debugging(
342 "It is required that the action provided be either an action_url|moodle_url." .
343 " Please update your definition.", E_NOTICE);
345 // Properties array used when creating the new navigation node
346 $itemarray = array(
347 'text' => $text,
348 'type' => $type
350 // Set the action if one was provided
351 if ($action!==null) {
352 $itemarray['action'] = $action;
354 // Set the shorttext if one was provided
355 if ($shorttext!==null) {
356 $itemarray['shorttext'] = $shorttext;
358 // Set the icon if one was provided
359 if ($icon!==null) {
360 $itemarray['icon'] = $icon;
362 // Set the key
363 $itemarray['key'] = $key;
364 // Construct and return
365 return new navigation_node($itemarray);
369 * Adds a navigation node as a child of this node.
371 * @param string $text
372 * @param moodle_url|action_link|string $action
373 * @param int $type
374 * @param string $shorttext
375 * @param string|int $key
376 * @param pix_icon $icon
377 * @return navigation_node
379 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
380 if ($action && is_string($action)) {
381 $action = new moodle_url($action);
383 // Create child node
384 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
386 // Add the child to end and return
387 return $this->add_node($childnode);
391 * Adds a navigation node as a child of this one, given a $node object
392 * created using the create function.
393 * @param navigation_node $childnode Node to add
394 * @param string $beforekey
395 * @return navigation_node The added node
397 public function add_node(navigation_node $childnode, $beforekey=null) {
398 // First convert the nodetype for this node to a branch as it will now have children
399 if ($this->nodetype !== self::NODETYPE_BRANCH) {
400 $this->nodetype = self::NODETYPE_BRANCH;
402 // Set the parent to this node
403 $childnode->set_parent($this);
405 // Default the key to the number of children if not provided
406 if ($childnode->key === null) {
407 $childnode->key = $this->children->count();
410 // Add the child using the navigation_node_collections add method
411 $node = $this->children->add($childnode, $beforekey);
413 // If added node is a category node or the user is logged in and it's a course
414 // then mark added node as a branch (makes it expandable by AJAX)
415 $type = $childnode->type;
416 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
417 ($type === self::TYPE_SITE_ADMIN)) {
418 $node->nodetype = self::NODETYPE_BRANCH;
420 // If this node is hidden mark it's children as hidden also
421 if ($this->hidden) {
422 $node->hidden = true;
424 // Return added node (reference returned by $this->children->add()
425 return $node;
429 * Return a list of all the keys of all the child nodes.
430 * @return array the keys.
432 public function get_children_key_list() {
433 return $this->children->get_key_list();
437 * Searches for a node of the given type with the given key.
439 * This searches this node plus all of its children, and their children....
440 * If you know the node you are looking for is a child of this node then please
441 * use the get method instead.
443 * @param int|string $key The key of the node we are looking for
444 * @param int $type One of navigation_node::TYPE_*
445 * @return navigation_node|false
447 public function find($key, $type) {
448 return $this->children->find($key, $type);
452 * Walk the tree building up a list of all the flat navigation nodes.
454 * @deprecated since Moodle 4.0
455 * @param flat_navigation $nodes List of the found flat navigation nodes.
456 * @param boolean $showdivider Show a divider before the first node.
457 * @param string $label A label for the collection of navigation links.
459 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
460 debugging("Function has been deprecated with the deprecation of the flat_navigation class.");
461 if ($this->showinflatnavigation) {
462 $indent = 0;
463 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
464 $indent = 1;
466 $flat = new flat_navigation_node($this, $indent);
467 $flat->set_showdivider($showdivider, $label);
468 $nodes->add($flat);
470 foreach ($this->children as $child) {
471 $child->build_flat_navigation_list($nodes, false);
476 * Get the child of this node that has the given key + (optional) type.
478 * If you are looking for a node and want to search all children + their children
479 * then please use the find method instead.
481 * @param int|string $key The key of the node we are looking for
482 * @param int $type One of navigation_node::TYPE_*
483 * @return navigation_node|false
485 public function get($key, $type=null) {
486 return $this->children->get($key, $type);
490 * Removes this node.
492 * @return bool
494 public function remove() {
495 return $this->parent->children->remove($this->key, $this->type);
499 * Checks if this node has or could have any children
501 * @return bool Returns true if it has children or could have (by AJAX expansion)
503 public function has_children() {
504 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
508 * Marks this node as active and forces it open.
510 * Important: If you are here because you need to mark a node active to get
511 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
512 * You can use it to specify a different URL to match the active navigation node on
513 * rather than having to locate and manually mark a node active.
515 public function make_active() {
516 $this->isactive = true;
517 $this->add_class('active_tree_node');
518 $this->force_open();
519 if ($this->parent !== null) {
520 $this->parent->make_inactive();
525 * Marks a node as inactive and recusised back to the base of the tree
526 * doing the same to all parents.
528 public function make_inactive() {
529 $this->isactive = false;
530 $this->remove_class('active_tree_node');
531 if ($this->parent !== null) {
532 $this->parent->make_inactive();
537 * Forces this node to be open and at the same time forces open all
538 * parents until the root node.
540 * Recursive.
542 public function force_open() {
543 $this->forceopen = true;
544 if ($this->parent !== null) {
545 $this->parent->force_open();
550 * Adds a CSS class to this node.
552 * @param string $class
553 * @return bool
555 public function add_class($class) {
556 if (!in_array($class, $this->classes)) {
557 $this->classes[] = $class;
559 return true;
563 * Removes a CSS class from this node.
565 * @param string $class
566 * @return bool True if the class was successfully removed.
568 public function remove_class($class) {
569 if (in_array($class, $this->classes)) {
570 $key = array_search($class,$this->classes);
571 if ($key!==false) {
572 // Remove the class' array element.
573 unset($this->classes[$key]);
574 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
575 $this->classes = array_values($this->classes);
577 return true;
580 return false;
584 * Sets the title for this node and forces Moodle to utilise it.
586 * Note that this method is named identically to the public "title" property of the class, which unfortunately confuses
587 * our Mustache renderer, because it will see the method and try and call it without any arguments (hence must be nullable)
588 * before trying to access the public property
590 * @param string|null $title
591 * @return string
593 public function title(?string $title = null): string {
594 if ($title !== null) {
595 $this->title = $title;
596 $this->forcetitle = true;
598 return (string) $this->title;
602 * Resets the page specific information on this node if it is being unserialised.
604 public function __wakeup(){
605 $this->forceopen = false;
606 $this->isactive = false;
607 $this->remove_class('active_tree_node');
611 * Checks if this node or any of its children contain the active node.
613 * Recursive.
615 * @return bool
617 public function contains_active_node() {
618 if ($this->isactive) {
619 return true;
620 } else {
621 foreach ($this->children as $child) {
622 if ($child->isactive || $child->contains_active_node()) {
623 return true;
627 return false;
631 * To better balance the admin tree, we want to group all the short top branches together.
633 * This means < 8 nodes and no subtrees.
635 * @return bool
637 public function is_short_branch() {
638 $limit = 8;
639 if ($this->children->count() >= $limit) {
640 return false;
642 foreach ($this->children as $child) {
643 if ($child->has_children()) {
644 return false;
647 return true;
651 * Finds the active node.
653 * Searches this nodes children plus all of the children for the active node
654 * and returns it if found.
656 * Recursive.
658 * @return navigation_node|false
660 public function find_active_node() {
661 if ($this->isactive) {
662 return $this;
663 } else {
664 foreach ($this->children as &$child) {
665 $outcome = $child->find_active_node();
666 if ($outcome !== false) {
667 return $outcome;
671 return false;
675 * Searches all children for the best matching active node
676 * @param int $strength The url match to be made.
677 * @return navigation_node|false
679 public function search_for_active_node($strength = URL_MATCH_BASE) {
680 if ($this->check_if_active($strength)) {
681 return $this;
682 } else {
683 foreach ($this->children as &$child) {
684 $outcome = $child->search_for_active_node($strength);
685 if ($outcome !== false) {
686 return $outcome;
690 return false;
694 * Gets the content for this node.
696 * @param bool $shorttext If true shorttext is used rather than the normal text
697 * @return string
699 public function get_content($shorttext=false) {
700 $navcontext = \context_helper::get_navigation_filter_context(null);
701 $options = !empty($navcontext) ? ['context' => $navcontext] : null;
703 if ($shorttext && $this->shorttext!==null) {
704 return format_string($this->shorttext, null, $options);
705 } else {
706 return format_string($this->text, null, $options);
711 * Gets the title to use for this node.
713 * @return string
715 public function get_title() {
716 if ($this->forcetitle || $this->action != null){
717 return $this->title;
718 } else {
719 return '';
724 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
726 * @return boolean
728 public function has_action() {
729 return !empty($this->action);
733 * Used to easily determine if the action is an internal link.
735 * @return bool
737 public function has_internal_action(): bool {
738 global $CFG;
739 if ($this->has_action()) {
740 $url = $this->action();
741 if ($this->action() instanceof \action_link) {
742 $url = $this->action()->url;
745 if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) {
746 return true;
749 return false;
753 * Used to easily determine if this link in the breadcrumbs is hidden.
755 * @return boolean
757 public function is_hidden() {
758 return $this->hidden;
762 * Gets the CSS class to add to this node to describe its type
764 * @return string
766 public function get_css_type() {
767 if (array_key_exists($this->type, $this->namedtypes)) {
768 return 'type_'.$this->namedtypes[$this->type];
770 return 'type_unknown';
774 * Finds all nodes that are expandable by AJAX
776 * @param array $expandable An array by reference to populate with expandable nodes.
778 public function find_expandable(array &$expandable) {
779 foreach ($this->children as &$child) {
780 if ($child->display && $child->has_children() && $child->children->count() == 0) {
781 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
782 $this->add_class('canexpand');
783 $child->requiresajaxloading = true;
784 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
786 $child->find_expandable($expandable);
791 * Finds all nodes of a given type (recursive)
793 * @param int $type One of navigation_node::TYPE_*
794 * @return array
796 public function find_all_of_type($type) {
797 $nodes = $this->children->type($type);
798 foreach ($this->children as &$node) {
799 $childnodes = $node->find_all_of_type($type);
800 $nodes = array_merge($nodes, $childnodes);
802 return $nodes;
806 * Removes this node if it is empty
808 public function trim_if_empty() {
809 if ($this->children->count() == 0) {
810 $this->remove();
815 * Creates a tab representation of this nodes children that can be used
816 * with print_tabs to produce the tabs on a page.
818 * call_user_func_array('print_tabs', $node->get_tabs_array());
820 * @param array $inactive
821 * @param bool $return
822 * @return array Array (tabs, selected, inactive, activated, return)
824 public function get_tabs_array(array $inactive=array(), $return=false) {
825 $tabs = array();
826 $rows = array();
827 $selected = null;
828 $activated = array();
829 foreach ($this->children as $node) {
830 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
831 if ($node->contains_active_node()) {
832 if ($node->children->count() > 0) {
833 $activated[] = $node->key;
834 foreach ($node->children as $child) {
835 if ($child->contains_active_node()) {
836 $selected = $child->key;
838 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
840 } else {
841 $selected = $node->key;
845 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
849 * Sets the parent for this node and if this node is active ensures that the tree is properly
850 * adjusted as well.
852 * @param navigation_node $parent
854 public function set_parent(navigation_node $parent) {
855 // Set the parent (thats the easy part)
856 $this->parent = $parent;
857 // Check if this node is active (this is checked during construction)
858 if ($this->isactive) {
859 // Force all of the parent nodes open so you can see this node
860 $this->parent->force_open();
861 // Make all parents inactive so that its clear where we are.
862 $this->parent->make_inactive();
867 * Hides the node and any children it has.
869 * @since Moodle 2.5
870 * @param array $typestohide Optional. An array of node types that should be hidden.
871 * If null all nodes will be hidden.
872 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
873 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
875 public function hide(array $typestohide = null) {
876 if ($typestohide === null || in_array($this->type, $typestohide)) {
877 $this->display = false;
878 if ($this->has_children()) {
879 foreach ($this->children as $child) {
880 $child->hide($typestohide);
887 * Get the action url for this navigation node.
888 * Called from templates.
890 * @since Moodle 3.2
892 public function action() {
893 if ($this->action instanceof moodle_url) {
894 return $this->action;
895 } else if ($this->action instanceof action_link) {
896 return $this->action->url;
898 return $this->action;
902 * Return an array consisting of the additional attributes for the action url.
904 * @return array Formatted array to parse in a template
906 public function actionattributes() {
907 if ($this->action instanceof action_link) {
908 return array_map(function($key, $value) {
909 return [
910 'name' => $key,
911 'value' => $value
913 }, array_keys($this->action->attributes), $this->action->attributes);
916 return [];
920 * Check whether the node's action is of type action_link.
922 * @return bool
924 public function is_action_link() {
925 return $this->action instanceof action_link;
929 * Return an array consisting of the actions for the action link.
931 * @return array Formatted array to parse in a template
933 public function action_link_actions() {
934 global $PAGE;
936 if (!$this->is_action_link()) {
937 return [];
940 $actionid = $this->action->attributes['id'];
941 $actionsdata = array_map(function($action) use ($PAGE, $actionid) {
942 $data = $action->export_for_template($PAGE->get_renderer('core'));
943 $data->id = $actionid;
944 return $data;
945 }, !empty($this->action->actions) ? $this->action->actions : []);
947 return ['actions' => $actionsdata];
951 * Sets whether the node and its children should be added into a "more" menu whenever possible.
953 * @param bool $forceintomoremenu
955 public function set_force_into_more_menu(bool $forceintomoremenu = false) {
956 $this->forceintomoremenu = $forceintomoremenu;
957 foreach ($this->children as $child) {
958 $child->set_force_into_more_menu($forceintomoremenu);
963 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable.
965 * @param bool $show
967 public function set_show_in_secondary_navigation(bool $show = true) {
968 $this->showinsecondarynavigation = $show;
969 foreach ($this->children as $child) {
970 $child->set_show_in_secondary_navigation($show);
975 * Add the menu item to handle locking and unlocking of a conext.
977 * @param \navigation_node $node Node to add
978 * @param \context $context The context to be locked
980 protected function add_context_locking_node(\navigation_node $node, \context $context) {
981 global $CFG;
982 // Manage context locking.
983 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
984 $parentcontext = $context->get_parent_context();
985 if (empty($parentcontext) || !$parentcontext->locked) {
986 if ($context->locked) {
987 $lockicon = 'i/unlock';
988 $lockstring = get_string('managecontextunlock', 'admin');
989 } else {
990 $lockicon = 'i/lock';
991 $lockstring = get_string('managecontextlock', 'admin');
993 $node->add(
994 $lockstring,
995 new moodle_url(
996 '/admin/lock.php',
998 'id' => $context->id,
1001 self::TYPE_SETTING,
1002 null,
1003 'contextlocking',
1004 new pix_icon($lockicon, '')
1013 * Navigation node collection
1015 * This class is responsible for managing a collection of navigation nodes.
1016 * It is required because a node's unique identifier is a combination of both its
1017 * key and its type.
1019 * Originally an array was used with a string key that was a combination of the two
1020 * however it was decided that a better solution would be to use a class that
1021 * implements the standard IteratorAggregate interface.
1023 * @package core
1024 * @category navigation
1025 * @copyright 2010 Sam Hemelryk
1026 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1028 class navigation_node_collection implements IteratorAggregate, Countable {
1030 * A multidimensional array to where the first key is the type and the second
1031 * key is the nodes key.
1032 * @var array
1034 protected $collection = array();
1036 * An array that contains references to nodes in the same order they were added.
1037 * This is maintained as a progressive array.
1038 * @var array
1040 protected $orderedcollection = array();
1042 * A reference to the last node that was added to the collection
1043 * @var navigation_node
1045 protected $last = null;
1047 * The total number of items added to this array.
1048 * @var int
1050 protected $count = 0;
1053 * Label for collection of nodes.
1054 * @var string
1056 protected $collectionlabel = '';
1059 * Adds a navigation node to the collection
1061 * @param navigation_node $node Node to add
1062 * @param string $beforekey If specified, adds before a node with this key,
1063 * otherwise adds at end
1064 * @return navigation_node Added node
1066 public function add(navigation_node $node, $beforekey=null) {
1067 global $CFG;
1068 $key = $node->key;
1069 $type = $node->type;
1071 // First check we have a 2nd dimension for this type
1072 if (!array_key_exists($type, $this->orderedcollection)) {
1073 $this->orderedcollection[$type] = array();
1075 // Check for a collision and report if debugging is turned on
1076 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
1077 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
1080 // Find the key to add before
1081 $newindex = $this->count;
1082 $last = true;
1083 if ($beforekey !== null) {
1084 foreach ($this->collection as $index => $othernode) {
1085 if ($othernode->key === $beforekey) {
1086 $newindex = $index;
1087 $last = false;
1088 break;
1091 if ($newindex === $this->count) {
1092 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
1093 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
1097 // Add the node to the appropriate place in the by-type structure (which
1098 // is not ordered, despite the variable name)
1099 $this->orderedcollection[$type][$key] = $node;
1100 if (!$last) {
1101 // Update existing references in the ordered collection (which is the
1102 // one that isn't called 'ordered') to shuffle them along if required
1103 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
1104 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
1107 // Add a reference to the node to the progressive collection.
1108 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
1109 // Update the last property to a reference to this new node.
1110 $this->last = $this->orderedcollection[$type][$key];
1112 // Reorder the array by index if needed
1113 if (!$last) {
1114 ksort($this->collection);
1116 $this->count++;
1117 // Return the reference to the now added node
1118 return $node;
1122 * Return a list of all the keys of all the nodes.
1123 * @return array the keys.
1125 public function get_key_list() {
1126 $keys = array();
1127 foreach ($this->collection as $node) {
1128 $keys[] = $node->key;
1130 return $keys;
1134 * Set a label for this collection.
1136 * @param string $label
1138 public function set_collectionlabel($label) {
1139 $this->collectionlabel = $label;
1143 * Return a label for this collection.
1145 * @return string
1147 public function get_collectionlabel() {
1148 return $this->collectionlabel;
1152 * Fetches a node from this collection.
1154 * @param string|int $key The key of the node we want to find.
1155 * @param int $type One of navigation_node::TYPE_*.
1156 * @return navigation_node|null
1158 public function get($key, $type=null) {
1159 if ($type !== null) {
1160 // If the type is known then we can simply check and fetch
1161 if (!empty($this->orderedcollection[$type][$key])) {
1162 return $this->orderedcollection[$type][$key];
1164 } else {
1165 // Because we don't know the type we look in the progressive array
1166 foreach ($this->collection as $node) {
1167 if ($node->key === $key) {
1168 return $node;
1172 return false;
1176 * Searches for a node with matching key and type.
1178 * This function searches both the nodes in this collection and all of
1179 * the nodes in each collection belonging to the nodes in this collection.
1181 * Recursive.
1183 * @param string|int $key The key of the node we want to find.
1184 * @param int $type One of navigation_node::TYPE_*.
1185 * @return navigation_node|false
1187 public function find($key, $type=null) {
1188 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1189 return $this->orderedcollection[$type][$key];
1190 } else {
1191 $nodes = $this->getIterator();
1192 // Search immediate children first
1193 foreach ($nodes as &$node) {
1194 if ($node->key === $key && ($type === null || $type === $node->type)) {
1195 return $node;
1198 // Now search each childs children
1199 foreach ($nodes as &$node) {
1200 $result = $node->children->find($key, $type);
1201 if ($result !== false) {
1202 return $result;
1206 return false;
1210 * Fetches the last node that was added to this collection
1212 * @return navigation_node
1214 public function last() {
1215 return $this->last;
1219 * Fetches all nodes of a given type from this collection
1221 * @param string|int $type node type being searched for.
1222 * @return array ordered collection
1224 public function type($type) {
1225 if (!array_key_exists($type, $this->orderedcollection)) {
1226 $this->orderedcollection[$type] = array();
1228 return $this->orderedcollection[$type];
1231 * Removes the node with the given key and type from the collection
1233 * @param string|int $key The key of the node we want to find.
1234 * @param int $type
1235 * @return bool
1237 public function remove($key, $type=null) {
1238 $child = $this->get($key, $type);
1239 if ($child !== false) {
1240 foreach ($this->collection as $colkey => $node) {
1241 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1242 unset($this->collection[$colkey]);
1243 $this->collection = array_values($this->collection);
1244 break;
1247 unset($this->orderedcollection[$child->type][$child->key]);
1248 $this->count--;
1249 return true;
1251 return false;
1255 * Gets the number of nodes in this collection
1257 * This option uses an internal count rather than counting the actual options to avoid
1258 * a performance hit through the count function.
1260 * @return int
1262 public function count(): int {
1263 return $this->count;
1266 * Gets an array iterator for the collection.
1268 * This is required by the IteratorAggregator interface and is used by routines
1269 * such as the foreach loop.
1271 * @return ArrayIterator
1273 public function getIterator(): Traversable {
1274 return new ArrayIterator($this->collection);
1279 * The global navigation class used for... the global navigation
1281 * This class is used by PAGE to store the global navigation for the site
1282 * and is then used by the settings nav and navbar to save on processing and DB calls
1284 * See
1285 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1286 * {@link lib/ajax/getnavbranch.php} Called by ajax
1288 * @package core
1289 * @category navigation
1290 * @copyright 2009 Sam Hemelryk
1291 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1293 class global_navigation extends navigation_node {
1294 /** @var moodle_page The Moodle page this navigation object belongs to. */
1295 protected $page;
1296 /** @var bool switch to let us know if the navigation object is initialised*/
1297 protected $initialised = false;
1298 /** @var array An array of course information */
1299 protected $mycourses = array();
1300 /** @var navigation_node[] An array for containing root navigation nodes */
1301 protected $rootnodes = array();
1302 /** @var bool A switch for whether to show empty sections in the navigation */
1303 protected $showemptysections = true;
1304 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1305 protected $showcategories = null;
1306 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1307 protected $showmycategories = null;
1308 /** @var array An array of stdClasses for users that the navigation is extended for */
1309 protected $extendforuser = array();
1310 /** @var navigation_cache */
1311 protected $cache;
1312 /** @var array An array of course ids that are present in the navigation */
1313 protected $addedcourses = array();
1314 /** @var bool */
1315 protected $allcategoriesloaded = false;
1316 /** @var array An array of category ids that are included in the navigation */
1317 protected $addedcategories = array();
1318 /** @var int expansion limit */
1319 protected $expansionlimit = 0;
1320 /** @var int userid to allow parent to see child's profile page navigation */
1321 protected $useridtouseforparentchecks = 0;
1322 /** @var cache_session A cache that stores information on expanded courses */
1323 protected $cacheexpandcourse = null;
1325 /** Used when loading categories to load all top level categories [parent = 0] **/
1326 const LOAD_ROOT_CATEGORIES = 0;
1327 /** Used when loading categories to load all categories **/
1328 const LOAD_ALL_CATEGORIES = -1;
1331 * Constructs a new global navigation
1333 * @param moodle_page $page The page this navigation object belongs to
1335 public function __construct(moodle_page $page) {
1336 global $CFG, $SITE, $USER;
1338 if (during_initial_install()) {
1339 return;
1342 $homepage = get_home_page();
1343 if ($homepage == HOMEPAGE_SITE) {
1344 // We are using the site home for the root element.
1345 $properties = array(
1346 'key' => 'home',
1347 'type' => navigation_node::TYPE_SYSTEM,
1348 'text' => get_string('home'),
1349 'action' => new moodle_url('/'),
1350 'icon' => new pix_icon('i/home', '')
1352 } else if ($homepage == HOMEPAGE_MYCOURSES) {
1353 // We are using the user's course summary page for the root element.
1354 $properties = array(
1355 'key' => 'mycourses',
1356 'type' => navigation_node::TYPE_SYSTEM,
1357 'text' => get_string('mycourses'),
1358 'action' => new moodle_url('/my/courses.php'),
1359 'icon' => new pix_icon('i/course', '')
1361 } else {
1362 // We are using the users my moodle for the root element.
1363 $properties = array(
1364 'key' => 'myhome',
1365 'type' => navigation_node::TYPE_SYSTEM,
1366 'text' => get_string('myhome'),
1367 'action' => new moodle_url('/my/'),
1368 'icon' => new pix_icon('i/dashboard', '')
1372 // Use the parents constructor.... good good reuse
1373 parent::__construct($properties);
1374 $this->showinflatnavigation = true;
1376 // Initalise and set defaults
1377 $this->page = $page;
1378 $this->forceopen = true;
1379 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1383 * Mutator to set userid to allow parent to see child's profile
1384 * page navigation. See MDL-25805 for initial issue. Linked to it
1385 * is an issue explaining why this is a REALLY UGLY HACK thats not
1386 * for you to use!
1388 * @param int $userid userid of profile page that parent wants to navigate around.
1390 public function set_userid_for_parent_checks($userid) {
1391 $this->useridtouseforparentchecks = $userid;
1396 * Initialises the navigation object.
1398 * This causes the navigation object to look at the current state of the page
1399 * that it is associated with and then load the appropriate content.
1401 * This should only occur the first time that the navigation structure is utilised
1402 * which will normally be either when the navbar is called to be displayed or
1403 * when a block makes use of it.
1405 * @return bool
1407 public function initialise() {
1408 global $CFG, $SITE, $USER;
1409 // Check if it has already been initialised
1410 if ($this->initialised || during_initial_install()) {
1411 return true;
1413 $this->initialised = true;
1415 // Set up the five base root nodes. These are nodes where we will put our
1416 // content and are as follows:
1417 // site: Navigation for the front page.
1418 // myprofile: User profile information goes here.
1419 // currentcourse: The course being currently viewed.
1420 // mycourses: The users courses get added here.
1421 // courses: Additional courses are added here.
1422 // users: Other users information loaded here.
1423 $this->rootnodes = array();
1424 $defaulthomepage = get_home_page();
1425 if ($defaulthomepage == HOMEPAGE_SITE) {
1426 // The home element should be my moodle because the root element is the site
1427 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1428 if (!empty($CFG->enabledashboard)) {
1429 // Only add dashboard to home if it's enabled.
1430 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1431 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
1432 $this->rootnodes['home']->showinflatnavigation = true;
1435 } else {
1436 // The home element should be the site because the root node is my moodle
1437 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1438 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1439 $this->rootnodes['home']->showinflatnavigation = true;
1440 if (!empty($CFG->defaulthomepage) &&
1441 ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) {
1442 // We need to stop automatic redirection
1443 $this->rootnodes['home']->action->param('redirect', '0');
1446 $this->rootnodes['site'] = $this->add_course($SITE);
1447 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1448 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1449 $this->rootnodes['mycourses'] = $this->add(
1450 get_string('mycourses'),
1451 new moodle_url('/my/courses.php'),
1452 self::TYPE_ROOTNODE,
1453 null,
1454 'mycourses',
1455 new pix_icon('i/course', '')
1457 // We do not need to show this node in the breadcrumbs if the default homepage is mycourses.
1458 // It will be automatically handled by the breadcrumb generator.
1459 if ($defaulthomepage == HOMEPAGE_MYCOURSES) {
1460 $this->rootnodes['mycourses']->mainnavonly = true;
1463 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1464 if (!core_course_category::user_top()) {
1465 $this->rootnodes['courses']->hide();
1467 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1469 // We always load the frontpage course to ensure it is available without
1470 // JavaScript enabled.
1471 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1472 $this->load_course_sections($SITE, $this->rootnodes['site']);
1474 $course = $this->page->course;
1475 $this->load_courses_enrolled();
1477 // $issite gets set to true if the current pages course is the sites frontpage course
1478 $issite = ($this->page->course->id == $SITE->id);
1480 // Determine if the user is enrolled in any course.
1481 $enrolledinanycourse = enrol_user_sees_own_courses();
1483 $this->rootnodes['currentcourse']->mainnavonly = true;
1484 if ($enrolledinanycourse) {
1485 $this->rootnodes['mycourses']->isexpandable = true;
1486 $this->rootnodes['mycourses']->showinflatnavigation = true;
1487 if ($CFG->navshowallcourses) {
1488 // When we show all courses we need to show both the my courses and the regular courses branch.
1489 $this->rootnodes['courses']->isexpandable = true;
1491 } else {
1492 $this->rootnodes['courses']->isexpandable = true;
1494 $this->rootnodes['mycourses']->forceopen = true;
1496 $canviewcourseprofile = true;
1498 // Next load context specific content into the navigation
1499 switch ($this->page->context->contextlevel) {
1500 case CONTEXT_SYSTEM :
1501 // Nothing left to do here I feel.
1502 break;
1503 case CONTEXT_COURSECAT :
1504 // This is essential, we must load categories.
1505 $this->load_all_categories($this->page->context->instanceid, true);
1506 break;
1507 case CONTEXT_BLOCK :
1508 case CONTEXT_COURSE :
1509 if ($issite) {
1510 // Nothing left to do here.
1511 break;
1514 // Load the course associated with the current page into the navigation.
1515 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1516 // If the course wasn't added then don't try going any further.
1517 if (!$coursenode) {
1518 $canviewcourseprofile = false;
1519 break;
1522 // If the user is not enrolled then we only want to show the
1523 // course node and not populate it.
1525 // Not enrolled, can't view, and hasn't switched roles
1526 if (!can_access_course($course, null, '', true)) {
1527 if ($coursenode->isexpandable === true) {
1528 // Obviously the situation has changed, update the cache and adjust the node.
1529 // This occurs if the user access to a course has been revoked (one way or another) after
1530 // initially logging in for this session.
1531 $this->get_expand_course_cache()->set($course->id, 1);
1532 $coursenode->isexpandable = true;
1533 $coursenode->nodetype = self::NODETYPE_BRANCH;
1535 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1536 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1537 if (!$this->current_user_is_parent_role()) {
1538 $coursenode->make_active();
1539 $canviewcourseprofile = false;
1540 break;
1542 } else if ($coursenode->isexpandable === false) {
1543 // Obviously the situation has changed, update the cache and adjust the node.
1544 // This occurs if the user has been granted access to a course (one way or another) after initially
1545 // logging in for this session.
1546 $this->get_expand_course_cache()->set($course->id, 1);
1547 $coursenode->isexpandable = true;
1548 $coursenode->nodetype = self::NODETYPE_BRANCH;
1551 // Add the essentials such as reports etc...
1552 $this->add_course_essentials($coursenode, $course);
1553 // Extend course navigation with it's sections/activities
1554 $this->load_course_sections($course, $coursenode);
1555 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1556 $coursenode->make_active();
1559 break;
1560 case CONTEXT_MODULE :
1561 if ($issite) {
1562 // If this is the site course then most information will have
1563 // already been loaded.
1564 // However we need to check if there is more content that can
1565 // yet be loaded for the specific module instance.
1566 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1567 if ($activitynode) {
1568 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1570 break;
1573 $course = $this->page->course;
1574 $cm = $this->page->cm;
1576 // Load the course associated with the page into the navigation
1577 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1579 // If the course wasn't added then don't try going any further.
1580 if (!$coursenode) {
1581 $canviewcourseprofile = false;
1582 break;
1585 // If the user is not enrolled then we only want to show the
1586 // course node and not populate it.
1587 if (!can_access_course($course, null, '', true)) {
1588 $coursenode->make_active();
1589 $canviewcourseprofile = false;
1590 break;
1593 $this->add_course_essentials($coursenode, $course);
1595 // Load the course sections into the page
1596 $this->load_course_sections($course, $coursenode, null, $cm);
1597 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1598 if (!empty($activity)) {
1599 // Finally load the cm specific navigaton information
1600 $this->load_activity($cm, $course, $activity);
1601 // Check if we have an active ndoe
1602 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1603 // And make the activity node active.
1604 $activity->make_active();
1607 break;
1608 case CONTEXT_USER :
1609 if ($issite) {
1610 // The users profile information etc is already loaded
1611 // for the front page.
1612 break;
1614 $course = $this->page->course;
1615 // Load the course associated with the user into the navigation
1616 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1618 // If the course wasn't added then don't try going any further.
1619 if (!$coursenode) {
1620 $canviewcourseprofile = false;
1621 break;
1624 // If the user is not enrolled then we only want to show the
1625 // course node and not populate it.
1626 if (!can_access_course($course, null, '', true)) {
1627 $coursenode->make_active();
1628 $canviewcourseprofile = false;
1629 break;
1631 $this->add_course_essentials($coursenode, $course);
1632 $this->load_course_sections($course, $coursenode);
1633 break;
1636 // Load for the current user
1637 $this->load_for_user();
1638 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1639 $this->load_for_user(null, true);
1641 // Load each extending user into the navigation.
1642 foreach ($this->extendforuser as $user) {
1643 if ($user->id != $USER->id) {
1644 $this->load_for_user($user);
1648 // Give the local plugins a chance to include some navigation if they want.
1649 $this->load_local_plugin_navigation();
1651 // Remove any empty root nodes
1652 foreach ($this->rootnodes as $node) {
1653 // Dont remove the home node
1654 /** @var navigation_node $node */
1655 if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) {
1656 $node->remove();
1660 if (!$this->contains_active_node()) {
1661 $this->search_for_active_node();
1664 // If the user is not logged in modify the navigation structure.
1665 if (!isloggedin()) {
1666 $activities = clone($this->rootnodes['site']->children);
1667 $this->rootnodes['site']->remove();
1668 $children = clone($this->children);
1669 $this->children = new navigation_node_collection();
1670 foreach ($activities as $child) {
1671 $this->children->add($child);
1673 foreach ($children as $child) {
1674 $this->children->add($child);
1677 return true;
1681 * This function gives local plugins an opportunity to modify navigation.
1683 protected function load_local_plugin_navigation() {
1684 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1685 $function($this);
1690 * Returns true if the current user is a parent of the user being currently viewed.
1692 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1693 * other user being viewed this function returns false.
1694 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1696 * @since Moodle 2.4
1697 * @return bool
1699 protected function current_user_is_parent_role() {
1700 global $USER, $DB;
1701 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1702 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1703 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1704 return false;
1706 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1707 return true;
1710 return false;
1714 * Returns true if courses should be shown within categories on the navigation.
1716 * @param bool $ismycourse Set to true if you are calculating this for a course.
1717 * @return bool
1719 protected function show_categories($ismycourse = false) {
1720 global $CFG, $DB;
1721 if ($ismycourse) {
1722 return $this->show_my_categories();
1724 if ($this->showcategories === null) {
1725 $show = false;
1726 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1727 $show = true;
1728 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1729 $show = true;
1731 $this->showcategories = $show;
1733 return $this->showcategories;
1737 * Returns true if we should show categories in the My Courses branch.
1738 * @return bool
1740 protected function show_my_categories() {
1741 global $CFG;
1742 if ($this->showmycategories === null) {
1743 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
1745 return $this->showmycategories;
1749 * Loads the courses in Moodle into the navigation.
1751 * @global moodle_database $DB
1752 * @param string|array $categoryids An array containing categories to load courses
1753 * for, OR null to load courses for all categories.
1754 * @return array An array of navigation_nodes one for each course
1756 protected function load_all_courses($categoryids = null) {
1757 global $CFG, $DB, $SITE;
1759 // Work out the limit of courses.
1760 $limit = 20;
1761 if (!empty($CFG->navcourselimit)) {
1762 $limit = $CFG->navcourselimit;
1765 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1767 // If we are going to show all courses AND we are showing categories then
1768 // to save us repeated DB calls load all of the categories now
1769 if ($this->show_categories()) {
1770 $this->load_all_categories($toload);
1773 // Will be the return of our efforts
1774 $coursenodes = array();
1776 // Check if we need to show categories.
1777 if ($this->show_categories()) {
1778 // Hmmm we need to show categories... this is going to be painful.
1779 // We now need to fetch up to $limit courses for each category to
1780 // be displayed.
1781 if ($categoryids !== null) {
1782 if (!is_array($categoryids)) {
1783 $categoryids = array($categoryids);
1785 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1786 $categorywhere = 'WHERE cc.id '.$categorywhere;
1787 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1788 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1789 $categoryparams = array();
1790 } else {
1791 $categorywhere = '';
1792 $categoryparams = array();
1795 // First up we are going to get the categories that we are going to
1796 // need so that we can determine how best to load the courses from them.
1797 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1798 FROM {course_categories} cc
1799 LEFT JOIN {course} c ON c.category = cc.id
1800 {$categorywhere}
1801 GROUP BY cc.id";
1802 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1803 $fullfetch = array();
1804 $partfetch = array();
1805 foreach ($categories as $category) {
1806 if (!$this->can_add_more_courses_to_category($category->id)) {
1807 continue;
1809 if ($category->coursecount > $limit * 5) {
1810 $partfetch[] = $category->id;
1811 } else if ($category->coursecount > 0) {
1812 $fullfetch[] = $category->id;
1815 $categories->close();
1817 if (count($fullfetch)) {
1818 // First up fetch all of the courses in categories where we know that we are going to
1819 // need the majority of courses.
1820 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1821 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1822 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1823 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1824 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1825 FROM {course} c
1826 $ccjoin
1827 WHERE c.category {$categoryids}
1828 ORDER BY c.sortorder ASC";
1829 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1830 foreach ($coursesrs as $course) {
1831 if ($course->id == $SITE->id) {
1832 // This should not be necessary, frontpage is not in any category.
1833 continue;
1835 if (array_key_exists($course->id, $this->addedcourses)) {
1836 // It is probably better to not include the already loaded courses
1837 // directly in SQL because inequalities may confuse query optimisers
1838 // and may interfere with query caching.
1839 continue;
1841 if (!$this->can_add_more_courses_to_category($course->category)) {
1842 continue;
1844 context_helper::preload_from_record($course);
1845 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1846 continue;
1848 $coursenodes[$course->id] = $this->add_course($course);
1850 $coursesrs->close();
1853 if (count($partfetch)) {
1854 // Next we will work our way through the categories where we will likely only need a small
1855 // proportion of the courses.
1856 foreach ($partfetch as $categoryid) {
1857 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1858 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1859 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1860 FROM {course} c
1861 $ccjoin
1862 WHERE c.category = :categoryid
1863 ORDER BY c.sortorder ASC";
1864 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1865 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1866 foreach ($coursesrs as $course) {
1867 if ($course->id == $SITE->id) {
1868 // This should not be necessary, frontpage is not in any category.
1869 continue;
1871 if (array_key_exists($course->id, $this->addedcourses)) {
1872 // It is probably better to not include the already loaded courses
1873 // directly in SQL because inequalities may confuse query optimisers
1874 // and may interfere with query caching.
1875 // This also helps to respect expected $limit on repeated executions.
1876 continue;
1878 if (!$this->can_add_more_courses_to_category($course->category)) {
1879 break;
1881 context_helper::preload_from_record($course);
1882 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1883 continue;
1885 $coursenodes[$course->id] = $this->add_course($course);
1887 $coursesrs->close();
1890 } else {
1891 // Prepare the SQL to load the courses and their contexts
1892 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1893 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1894 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1895 $courseparams['contextlevel'] = CONTEXT_COURSE;
1896 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1897 FROM {course} c
1898 $ccjoin
1899 WHERE c.id {$courseids}
1900 ORDER BY c.sortorder ASC";
1901 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1902 foreach ($coursesrs as $course) {
1903 if ($course->id == $SITE->id) {
1904 // frotpage is not wanted here
1905 continue;
1907 if ($this->page->course && ($this->page->course->id == $course->id)) {
1908 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1909 continue;
1911 context_helper::preload_from_record($course);
1912 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1913 continue;
1915 $coursenodes[$course->id] = $this->add_course($course);
1916 if (count($coursenodes) >= $limit) {
1917 break;
1920 $coursesrs->close();
1923 return $coursenodes;
1927 * Returns true if more courses can be added to the provided category.
1929 * @param int|navigation_node|stdClass $category
1930 * @return bool
1932 protected function can_add_more_courses_to_category($category) {
1933 global $CFG;
1934 $limit = 20;
1935 if (!empty($CFG->navcourselimit)) {
1936 $limit = (int)$CFG->navcourselimit;
1938 if (is_numeric($category)) {
1939 if (!array_key_exists($category, $this->addedcategories)) {
1940 return true;
1942 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1943 } else if ($category instanceof navigation_node) {
1944 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1945 return false;
1947 $coursecount = count($category->children->type(self::TYPE_COURSE));
1948 } else if (is_object($category) && property_exists($category,'id')) {
1949 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1951 return ($coursecount <= $limit);
1955 * Loads all categories (top level or if an id is specified for that category)
1957 * @param int $categoryid The category id to load or null/0 to load all base level categories
1958 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1959 * as the requested category and any parent categories.
1960 * @return navigation_node|void returns a navigation node if a category has been loaded.
1962 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1963 global $CFG, $DB;
1965 // Check if this category has already been loaded
1966 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1967 return true;
1970 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1971 $sqlselect = "SELECT cc.*, $catcontextsql
1972 FROM {course_categories} cc
1973 JOIN {context} ctx ON cc.id = ctx.instanceid";
1974 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1975 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1976 $params = array();
1978 $categoriestoload = array();
1979 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1980 // We are going to load all categories regardless... prepare to fire
1981 // on the database server!
1982 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1983 // We are going to load all of the first level categories (categories without parents)
1984 $sqlwhere .= " AND cc.parent = 0";
1985 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1986 // The category itself has been loaded already so we just need to ensure its subcategories
1987 // have been loaded
1988 $addedcategories = $this->addedcategories;
1989 unset($addedcategories[$categoryid]);
1990 if (count($addedcategories) > 0) {
1991 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1992 if ($showbasecategories) {
1993 // We need to include categories with parent = 0 as well
1994 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1995 } else {
1996 // All we need is categories that match the parent
1997 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
2000 $params['categoryid'] = $categoryid;
2001 } else {
2002 // This category hasn't been loaded yet so we need to fetch it, work out its category path
2003 // and load this category plus all its parents and subcategories
2004 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
2005 $categoriestoload = explode('/', trim($category->path, '/'));
2006 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
2007 // We are going to use select twice so double the params
2008 $params = array_merge($params, $params);
2009 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
2010 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
2013 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
2014 $categories = array();
2015 foreach ($categoriesrs as $category) {
2016 // Preload the context.. we'll need it when adding the category in order
2017 // to format the category name.
2018 context_helper::preload_from_record($category);
2019 if (array_key_exists($category->id, $this->addedcategories)) {
2020 // Do nothing, its already been added.
2021 } else if ($category->parent == '0') {
2022 // This is a root category lets add it immediately
2023 $this->add_category($category, $this->rootnodes['courses']);
2024 } else if (array_key_exists($category->parent, $this->addedcategories)) {
2025 // This categories parent has already been added we can add this immediately
2026 $this->add_category($category, $this->addedcategories[$category->parent]);
2027 } else {
2028 $categories[] = $category;
2031 $categoriesrs->close();
2033 // Now we have an array of categories we need to add them to the navigation.
2034 while (!empty($categories)) {
2035 $category = reset($categories);
2036 if (array_key_exists($category->id, $this->addedcategories)) {
2037 // Do nothing
2038 } else if ($category->parent == '0') {
2039 $this->add_category($category, $this->rootnodes['courses']);
2040 } else if (array_key_exists($category->parent, $this->addedcategories)) {
2041 $this->add_category($category, $this->addedcategories[$category->parent]);
2042 } else {
2043 // This category isn't in the navigation and niether is it's parent (yet).
2044 // We need to go through the category path and add all of its components in order.
2045 $path = explode('/', trim($category->path, '/'));
2046 foreach ($path as $catid) {
2047 if (!array_key_exists($catid, $this->addedcategories)) {
2048 // This category isn't in the navigation yet so add it.
2049 $subcategory = $categories[$catid];
2050 if ($subcategory->parent == '0') {
2051 // Yay we have a root category - this likely means we will now be able
2052 // to add categories without problems.
2053 $this->add_category($subcategory, $this->rootnodes['courses']);
2054 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
2055 // The parent is in the category (as we'd expect) so add it now.
2056 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
2057 // Remove the category from the categories array.
2058 unset($categories[$catid]);
2059 } else {
2060 // We should never ever arrive here - if we have then there is a bigger
2061 // problem at hand.
2062 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
2067 // Remove the category from the categories array now that we know it has been added.
2068 unset($categories[$category->id]);
2070 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
2071 $this->allcategoriesloaded = true;
2073 // Check if there are any categories to load.
2074 if (count($categoriestoload) > 0) {
2075 $readytoloadcourses = array();
2076 foreach ($categoriestoload as $category) {
2077 if ($this->can_add_more_courses_to_category($category)) {
2078 $readytoloadcourses[] = $category;
2081 if (count($readytoloadcourses)) {
2082 $this->load_all_courses($readytoloadcourses);
2086 // Look for all categories which have been loaded
2087 if (!empty($this->addedcategories)) {
2088 $categoryids = array();
2089 foreach ($this->addedcategories as $category) {
2090 if ($this->can_add_more_courses_to_category($category)) {
2091 $categoryids[] = $category->key;
2094 if ($categoryids) {
2095 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
2096 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
2097 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
2098 FROM {course_categories} cc
2099 JOIN {course} c ON c.category = cc.id
2100 WHERE cc.id {$categoriessql}
2101 GROUP BY cc.id
2102 HAVING COUNT(c.id) > :limit";
2103 $excessivecategories = $DB->get_records_sql($sql, $params);
2104 foreach ($categories as &$category) {
2105 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
2106 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
2107 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
2115 * Adds a structured category to the navigation in the correct order/place
2117 * @param stdClass $category category to be added in navigation.
2118 * @param navigation_node $parent parent navigation node
2119 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2120 * @return void.
2122 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
2123 global $CFG;
2124 if (array_key_exists($category->id, $this->addedcategories)) {
2125 return;
2127 $canview = core_course_category::can_view_category($category);
2128 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
2129 $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id));
2130 $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) :
2131 get_string('categoryhidden');
2132 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
2133 if (!$canview) {
2134 // User does not have required capabilities to view category.
2135 $categorynode->display = false;
2136 } else if (!$category->visible) {
2137 // Category is hidden but user has capability to view hidden categories.
2138 $categorynode->hidden = true;
2140 $this->addedcategories[$category->id] = $categorynode;
2144 * Loads the given course into the navigation
2146 * @param stdClass $course
2147 * @return navigation_node
2149 protected function load_course(stdClass $course) {
2150 global $SITE;
2151 if ($course->id == $SITE->id) {
2152 // This is always loaded during initialisation
2153 return $this->rootnodes['site'];
2154 } else if (array_key_exists($course->id, $this->addedcourses)) {
2155 // The course has already been loaded so return a reference
2156 return $this->addedcourses[$course->id];
2157 } else {
2158 // Add the course
2159 return $this->add_course($course);
2164 * Loads all of the courses section into the navigation.
2166 * This function calls method from current course format, see
2167 * core_courseformat\base::extend_course_navigation()
2168 * If course module ($cm) is specified but course format failed to create the node,
2169 * the activity node is created anyway.
2171 * By default course formats call the method global_navigation::load_generic_course_sections()
2173 * @param stdClass $course Database record for the course
2174 * @param navigation_node $coursenode The course node within the navigation
2175 * @param null|int $sectionnum If specified load the contents of section with this relative number
2176 * @param null|cm_info $cm If specified make sure that activity node is created (either
2177 * in containg section or by calling load_stealth_activity() )
2179 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2180 global $CFG, $SITE;
2181 require_once($CFG->dirroot.'/course/lib.php');
2182 if (isset($cm->sectionnum)) {
2183 $sectionnum = $cm->sectionnum;
2185 if ($sectionnum !== null) {
2186 $this->includesectionnum = $sectionnum;
2188 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2189 if (isset($cm->id)) {
2190 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2191 if (empty($activity)) {
2192 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2198 * Generates an array of sections and an array of activities for the given course.
2200 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2202 * @param stdClass $course
2203 * @return array Array($sections, $activities)
2205 protected function generate_sections_and_activities(stdClass $course) {
2206 global $CFG;
2207 require_once($CFG->dirroot.'/course/lib.php');
2209 $modinfo = get_fast_modinfo($course);
2210 $sections = $modinfo->get_section_info_all();
2212 // For course formats using 'numsections' trim the sections list
2213 $courseformatoptions = course_get_format($course)->get_format_options();
2214 if (isset($courseformatoptions['numsections'])) {
2215 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2218 $activities = array();
2220 foreach ($sections as $key => $section) {
2221 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2222 $sections[$key] = clone($section);
2223 unset($sections[$key]->summary);
2224 $sections[$key]->hasactivites = false;
2225 if (!array_key_exists($section->section, $modinfo->sections)) {
2226 continue;
2228 foreach ($modinfo->sections[$section->section] as $cmid) {
2229 $cm = $modinfo->cms[$cmid];
2230 $activity = new stdClass;
2231 $activity->id = $cm->id;
2232 $activity->course = $course->id;
2233 $activity->section = $section->section;
2234 $activity->name = $cm->name;
2235 $activity->icon = $cm->icon;
2236 $activity->iconcomponent = $cm->iconcomponent;
2237 $activity->hidden = (!$cm->visible);
2238 $activity->modname = $cm->modname;
2239 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2240 $activity->onclick = $cm->onclick;
2241 $url = $cm->url;
2242 if (!$url) {
2243 $activity->url = null;
2244 $activity->display = false;
2245 } else {
2246 $activity->url = $url->out();
2247 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2248 if (self::module_extends_navigation($cm->modname)) {
2249 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2252 $activities[$cmid] = $activity;
2253 if ($activity->display) {
2254 $sections[$key]->hasactivites = true;
2259 return array($sections, $activities);
2263 * Generically loads the course sections into the course's navigation.
2265 * @param stdClass $course
2266 * @param navigation_node $coursenode
2267 * @return array An array of course section nodes
2269 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2270 global $CFG, $DB, $USER, $SITE;
2271 require_once($CFG->dirroot.'/course/lib.php');
2273 list($sections, $activities) = $this->generate_sections_and_activities($course);
2275 $navigationsections = array();
2276 foreach ($sections as $sectionid => $section) {
2277 $section = clone($section);
2278 if ($course->id == $SITE->id) {
2279 $this->load_section_activities($coursenode, $section->section, $activities);
2280 } else {
2281 if (!$section->uservisible || (!$this->showemptysections &&
2282 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2283 continue;
2286 $sectionname = get_section_name($course, $section);
2287 $url = course_get_url($course, $section->section, array('navigation' => true));
2289 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2290 null, $section->id, new pix_icon('i/section', ''));
2291 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2292 $sectionnode->hidden = (!$section->visible || !$section->available);
2293 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2294 $this->load_section_activities($sectionnode, $section->section, $activities);
2296 $navigationsections[$sectionid] = $section;
2299 return $navigationsections;
2303 * Loads all of the activities for a section into the navigation structure.
2305 * @param navigation_node $sectionnode
2306 * @param int $sectionnumber
2307 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2308 * @param stdClass $course The course object the section and activities relate to.
2309 * @return array Array of activity nodes
2311 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2312 global $CFG, $SITE;
2313 // A static counter for JS function naming
2314 static $legacyonclickcounter = 0;
2316 $activitynodes = array();
2317 if (empty($activities)) {
2318 return $activitynodes;
2321 if (!is_object($course)) {
2322 $activity = reset($activities);
2323 $courseid = $activity->course;
2324 } else {
2325 $courseid = $course->id;
2327 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2329 foreach ($activities as $activity) {
2330 if ($activity->section != $sectionnumber) {
2331 continue;
2333 if ($activity->icon) {
2334 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2335 } else {
2336 $icon = new pix_icon('monologo', get_string('modulename', $activity->modname), $activity->modname);
2339 // Prepare the default name and url for the node
2340 $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activity->id));
2341 $activityname = format_string($activity->name, true, ['context' => $displaycontext]);
2342 $action = new moodle_url($activity->url);
2344 // Check if the onclick property is set (puke!)
2345 if (!empty($activity->onclick)) {
2346 // Increment the counter so that we have a unique number.
2347 $legacyonclickcounter++;
2348 // Generate the function name we will use
2349 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2350 $propogrationhandler = '';
2351 // Check if we need to cancel propogation. Remember inline onclick
2352 // events would return false if they wanted to prevent propogation and the
2353 // default action.
2354 if (strpos($activity->onclick, 'return false')) {
2355 $propogrationhandler = 'e.halt();';
2357 // Decode the onclick - it has already been encoded for display (puke)
2358 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2359 // Build the JS function the click event will call
2360 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2361 $this->page->requires->js_amd_inline($jscode);
2362 // Override the default url with the new action link
2363 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2366 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2367 $activitynode->title(get_string('modulename', $activity->modname));
2368 $activitynode->hidden = $activity->hidden;
2369 $activitynode->display = $showactivities && $activity->display;
2370 $activitynode->nodetype = $activity->nodetype;
2371 $activitynodes[$activity->id] = $activitynode;
2374 return $activitynodes;
2377 * Loads a stealth module from unavailable section
2378 * @param navigation_node $coursenode
2379 * @param stdClass|course_modinfo $modinfo
2380 * @return navigation_node or null if not accessible
2382 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2383 if (empty($modinfo->cms[$this->page->cm->id])) {
2384 return null;
2386 $cm = $modinfo->cms[$this->page->cm->id];
2387 if ($cm->icon) {
2388 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2389 } else {
2390 $icon = new pix_icon('monologo', get_string('modulename', $cm->modname), $cm->modname);
2392 $url = $cm->url;
2393 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2394 $activitynode->title(get_string('modulename', $cm->modname));
2395 $activitynode->hidden = (!$cm->visible);
2396 if (!$cm->is_visible_on_course_page()) {
2397 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2398 // Also there may be no exception at all in case when teacher is logged in as student.
2399 $activitynode->display = false;
2400 } else if (!$url) {
2401 // Don't show activities that don't have links!
2402 $activitynode->display = false;
2403 } else if (self::module_extends_navigation($cm->modname)) {
2404 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2406 return $activitynode;
2409 * Loads the navigation structure for the given activity into the activities node.
2411 * This method utilises a callback within the modules lib.php file to load the
2412 * content specific to activity given.
2414 * The callback is a method: {modulename}_extend_navigation()
2415 * Examples:
2416 * * {@link forum_extend_navigation()}
2417 * * {@link workshop_extend_navigation()}
2419 * @param cm_info|stdClass $cm
2420 * @param stdClass $course
2421 * @param navigation_node $activity
2422 * @return bool
2424 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2425 global $CFG, $DB;
2427 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2428 if (!($cm instanceof cm_info)) {
2429 $modinfo = get_fast_modinfo($course);
2430 $cm = $modinfo->get_cm($cm->id);
2432 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2433 $activity->make_active();
2434 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2435 $function = $cm->modname.'_extend_navigation';
2437 if (file_exists($file)) {
2438 require_once($file);
2439 if (function_exists($function)) {
2440 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2441 $function($activity, $course, $activtyrecord, $cm);
2445 // Allow the active advanced grading method plugin to append module navigation
2446 $featuresfunc = $cm->modname.'_supports';
2447 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2448 require_once($CFG->dirroot.'/grade/grading/lib.php');
2449 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2450 $gradingman->extend_navigation($this, $activity);
2453 return $activity->has_children();
2456 * Loads user specific information into the navigation in the appropriate place.
2458 * If no user is provided the current user is assumed.
2460 * @param stdClass $user
2461 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2462 * @return bool
2464 protected function load_for_user($user=null, $forceforcontext=false) {
2465 global $DB, $CFG, $USER, $SITE;
2467 require_once($CFG->dirroot . '/course/lib.php');
2469 if ($user === null) {
2470 // We can't require login here but if the user isn't logged in we don't
2471 // want to show anything
2472 if (!isloggedin() || isguestuser()) {
2473 return false;
2475 $user = $USER;
2476 } else if (!is_object($user)) {
2477 // If the user is not an object then get them from the database
2478 $select = context_helper::get_preload_record_columns_sql('ctx');
2479 $sql = "SELECT u.*, $select
2480 FROM {user} u
2481 JOIN {context} ctx ON u.id = ctx.instanceid
2482 WHERE u.id = :userid AND
2483 ctx.contextlevel = :contextlevel";
2484 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2485 context_helper::preload_from_record($user);
2488 $iscurrentuser = ($user->id == $USER->id);
2490 $usercontext = context_user::instance($user->id);
2492 // Get the course set against the page, by default this will be the site
2493 $course = $this->page->course;
2494 $baseargs = array('id'=>$user->id);
2495 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2496 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2497 $baseargs['course'] = $course->id;
2498 $coursecontext = context_course::instance($course->id);
2499 $issitecourse = false;
2500 } else {
2501 // Load all categories and get the context for the system
2502 $coursecontext = context_system::instance();
2503 $issitecourse = true;
2506 // Create a node to add user information under.
2507 $usersnode = null;
2508 if (!$issitecourse) {
2509 // Not the current user so add it to the participants node for the current course.
2510 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2511 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2512 } else if ($USER->id != $user->id) {
2513 // This is the site so add a users node to the root branch.
2514 $usersnode = $this->rootnodes['users'];
2515 if (course_can_view_participants($coursecontext)) {
2516 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2518 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2520 if (!$usersnode) {
2521 // We should NEVER get here, if the course hasn't been populated
2522 // with a participants node then the navigaiton either wasn't generated
2523 // for it (you are missing a require_login or set_context call) or
2524 // you don't have access.... in the interests of no leaking informatin
2525 // we simply quit...
2526 return false;
2528 // Add a branch for the current user.
2529 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2530 $viewprofile = true;
2531 if (!$iscurrentuser) {
2532 require_once($CFG->dirroot . '/user/lib.php');
2533 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2534 $viewprofile = false;
2535 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2536 $viewprofile = false;
2538 if (!$viewprofile) {
2539 $viewprofile = user_can_view_profile($user, null, $usercontext);
2543 // Now, conditionally add the user node.
2544 if ($viewprofile) {
2545 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2546 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2547 } else {
2548 $usernode = $usersnode->add(get_string('user'));
2551 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2552 $usernode->make_active();
2555 // Add user information to the participants or user node.
2556 if ($issitecourse) {
2558 // If the user is the current user or has permission to view the details of the requested
2559 // user than add a view profile link.
2560 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2561 has_capability('moodle/user:viewdetails', $usercontext)) {
2562 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2563 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2564 } else {
2565 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2569 if (!empty($CFG->navadduserpostslinks)) {
2570 // Add nodes for forum posts and discussions if the user can view either or both
2571 // There are no capability checks here as the content of the page is based
2572 // purely on the forums the current user has access too.
2573 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2574 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2575 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2576 array_merge($baseargs, array('mode' => 'discussions'))));
2579 // Add blog nodes.
2580 if (!empty($CFG->enableblogs)) {
2581 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2582 require_once($CFG->dirroot.'/blog/lib.php');
2583 // Get all options for the user.
2584 $options = blog_get_options_for_user($user);
2585 $this->cache->set('userblogoptions'.$user->id, $options);
2586 } else {
2587 $options = $this->cache->{'userblogoptions'.$user->id};
2590 if (count($options) > 0) {
2591 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2592 foreach ($options as $type => $option) {
2593 if ($type == "rss") {
2594 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2595 new pix_icon('i/rss', ''));
2596 } else {
2597 $blogs->add($option['string'], $option['link']);
2603 // Add the messages link.
2604 // It is context based so can appear in the user's profile and in course participants information.
2605 if (!empty($CFG->messaging)) {
2606 $messageargs = array('user1' => $USER->id);
2607 if ($USER->id != $user->id) {
2608 $messageargs['user2'] = $user->id;
2610 $url = new moodle_url('/message/index.php', $messageargs);
2611 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2614 // Add the "My private files" link.
2615 // This link doesn't have a unique display for course context so only display it under the user's profile.
2616 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2617 $url = new moodle_url('/user/files.php');
2618 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2621 // Add a node to view the users notes if permitted.
2622 if (!empty($CFG->enablenotes) &&
2623 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2624 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2625 if ($coursecontext->instanceid != SITEID) {
2626 $url->param('course', $coursecontext->instanceid);
2628 $usernode->add(get_string('notes', 'notes'), $url);
2631 // Show the grades node.
2632 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2633 require_once($CFG->dirroot . '/user/lib.php');
2634 // Set the grades node to link to the "Grades" page.
2635 if ($course->id == SITEID) {
2636 $url = user_mygrades_url($user->id, $course->id);
2637 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2638 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2640 if ($USER->id != $user->id) {
2641 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2642 } else {
2643 $usernode->add(get_string('grades', 'grades'), $url);
2647 // If the user is the current user add the repositories for the current user.
2648 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2649 if (!$iscurrentuser &&
2650 $course->id == $SITE->id &&
2651 has_capability('moodle/user:viewdetails', $usercontext) &&
2652 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2654 // Add view grade report is permitted.
2655 $reports = core_component::get_plugin_list('gradereport');
2656 arsort($reports); // User is last, we want to test it first.
2658 $userscourses = enrol_get_users_courses($user->id, false, '*');
2659 $userscoursesnode = $usernode->add(get_string('courses'));
2661 $count = 0;
2662 foreach ($userscourses as $usercourse) {
2663 if ($count === (int)$CFG->navcourselimit) {
2664 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2665 $userscoursesnode->add(get_string('showallcourses'), $url);
2666 break;
2668 $count++;
2669 $usercoursecontext = context_course::instance($usercourse->id);
2670 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2671 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2672 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2674 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2675 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2676 foreach ($reports as $plugin => $plugindir) {
2677 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2678 // Stop when the first visible plugin is found.
2679 $gradeavailable = true;
2680 break;
2685 if ($gradeavailable) {
2686 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2687 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2688 new pix_icon('i/grades', ''));
2691 // Add a node to view the users notes if permitted.
2692 if (!empty($CFG->enablenotes) &&
2693 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2694 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2695 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2698 if (can_access_course($usercourse, $user->id, '', true)) {
2699 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2700 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2703 $reporttab = $usercoursenode->add(get_string('activityreports'));
2705 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2706 foreach ($reportfunctions as $reportfunction) {
2707 $reportfunction($reporttab, $user, $usercourse);
2710 $reporttab->trim_if_empty();
2714 // Let plugins hook into user navigation.
2715 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2716 foreach ($pluginsfunction as $plugintype => $plugins) {
2717 if ($plugintype != 'report') {
2718 foreach ($plugins as $pluginfunction) {
2719 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2724 return true;
2728 * This method simply checks to see if a given module can extend the navigation.
2730 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2732 * @param string $modname
2733 * @return bool
2735 public static function module_extends_navigation($modname) {
2736 global $CFG;
2737 static $extendingmodules = array();
2738 if (!array_key_exists($modname, $extendingmodules)) {
2739 $extendingmodules[$modname] = false;
2740 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2741 if (file_exists($file)) {
2742 $function = $modname.'_extend_navigation';
2743 require_once($file);
2744 $extendingmodules[$modname] = (function_exists($function));
2747 return $extendingmodules[$modname];
2750 * Extends the navigation for the given user.
2752 * @param stdClass $user A user from the database
2754 public function extend_for_user($user) {
2755 $this->extendforuser[] = $user;
2759 * Returns all of the users the navigation is being extended for
2761 * @return array An array of extending users.
2763 public function get_extending_users() {
2764 return $this->extendforuser;
2767 * Adds the given course to the navigation structure.
2769 * @param stdClass $course
2770 * @param bool $forcegeneric
2771 * @param bool $ismycourse
2772 * @return navigation_node
2774 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2775 global $CFG, $SITE;
2777 // We found the course... we can return it now :)
2778 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2779 return $this->addedcourses[$course->id];
2782 $coursecontext = context_course::instance($course->id);
2784 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
2785 if (is_role_switched($course->id)) {
2786 // user has to be able to access course in order to switch, let's skip the visibility test here
2787 } else if (!core_course_category::can_view_course_info($course)) {
2788 return false;
2792 $issite = ($course->id == $SITE->id);
2793 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
2794 $shortname = format_string($course->shortname, true, ['context' => $displaycontext]);
2795 $fullname = format_string($course->fullname, true, ['context' => $displaycontext]);
2796 // This is the name that will be shown for the course.
2797 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2799 if ($coursetype == self::COURSE_CURRENT) {
2800 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2801 return $coursenode;
2802 } else {
2803 $coursetype = self::COURSE_OTHER;
2807 // Can the user expand the course to see its content.
2808 $canexpandcourse = true;
2809 if ($issite) {
2810 $parent = $this;
2811 $url = null;
2812 if (empty($CFG->usesitenameforsitepages)) {
2813 $coursename = get_string('sitepages');
2815 } else if ($coursetype == self::COURSE_CURRENT) {
2816 $parent = $this->rootnodes['currentcourse'];
2817 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2818 $canexpandcourse = $this->can_expand_course($course);
2819 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2820 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2821 // Nothing to do here the above statement set $parent to the category within mycourses.
2822 } else {
2823 $parent = $this->rootnodes['mycourses'];
2825 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2826 } else {
2827 $parent = $this->rootnodes['courses'];
2828 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2829 // They can only expand the course if they can access it.
2830 $canexpandcourse = $this->can_expand_course($course);
2831 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2832 if (!$this->is_category_fully_loaded($course->category)) {
2833 // We need to load the category structure for this course
2834 $this->load_all_categories($course->category, false);
2836 if (array_key_exists($course->category, $this->addedcategories)) {
2837 $parent = $this->addedcategories[$course->category];
2838 // This could lead to the course being created so we should check whether it is the case again
2839 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2840 return $this->addedcourses[$course->id];
2846 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2847 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2849 $coursenode->hidden = (!$course->visible);
2850 $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false]));
2851 if ($canexpandcourse) {
2852 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2853 $coursenode->nodetype = self::NODETYPE_BRANCH;
2854 $coursenode->isexpandable = true;
2855 } else {
2856 $coursenode->nodetype = self::NODETYPE_LEAF;
2857 $coursenode->isexpandable = false;
2859 if (!$forcegeneric) {
2860 $this->addedcourses[$course->id] = $coursenode;
2863 return $coursenode;
2867 * Returns a cache instance to use for the expand course cache.
2868 * @return cache_session
2870 protected function get_expand_course_cache() {
2871 if ($this->cacheexpandcourse === null) {
2872 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2874 return $this->cacheexpandcourse;
2878 * Checks if a user can expand a course in the navigation.
2880 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2881 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2882 * permits stale data.
2883 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2884 * will be stale.
2885 * It is brought up to date in only one of two ways.
2886 * 1. The user logs out and in again.
2887 * 2. The user browses to the course they've just being given access to.
2889 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2891 * @param stdClass $course
2892 * @return bool
2894 protected function can_expand_course($course) {
2895 $cache = $this->get_expand_course_cache();
2896 $canexpand = $cache->get($course->id);
2897 if ($canexpand === false) {
2898 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2899 $canexpand = (int)$canexpand;
2900 $cache->set($course->id, $canexpand);
2902 return ($canexpand === 1);
2906 * Returns true if the category has already been loaded as have any child categories
2908 * @param int $categoryid
2909 * @return bool
2911 protected function is_category_fully_loaded($categoryid) {
2912 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2916 * Adds essential course nodes to the navigation for the given course.
2918 * This method adds nodes such as reports, blogs and participants
2920 * @param navigation_node $coursenode
2921 * @param stdClass $course
2922 * @return bool returns true on successful addition of a node.
2924 public function add_course_essentials($coursenode, stdClass $course) {
2925 global $CFG, $SITE;
2926 require_once($CFG->dirroot . '/course/lib.php');
2928 if ($course->id == $SITE->id) {
2929 return $this->add_front_page_course_essentials($coursenode, $course);
2932 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2933 return true;
2936 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2938 //Participants
2939 if ($navoptions->participants) {
2940 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2941 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2943 if ($navoptions->blogs) {
2944 $blogsurls = new moodle_url('/blog/index.php');
2945 if ($currentgroup = groups_get_course_group($course, true)) {
2946 $blogsurls->param('groupid', $currentgroup);
2947 } else {
2948 $blogsurls->param('courseid', $course->id);
2950 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2953 if ($navoptions->notes) {
2954 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2956 } else if (count($this->extendforuser) > 0) {
2957 $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2960 // Badges.
2961 if ($navoptions->badges) {
2962 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2964 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2965 navigation_node::TYPE_SETTING, null, 'badgesview',
2966 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2969 // Check access to the course and competencies page.
2970 if ($navoptions->competencies) {
2971 // Just a link to course competency.
2972 $title = get_string('competencies', 'core_competency');
2973 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2974 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2975 new pix_icon('i/competencies', ''));
2977 if ($navoptions->grades) {
2978 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2979 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2980 'grades', new pix_icon('i/grades', ''));
2981 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2982 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2983 $gradenode->make_active();
2987 // Add link for configuring communication.
2988 if ($navoptions->communication) {
2989 $url = new moodle_url('/communication/configure.php', [
2990 'contextid' => \core\context\course::instance($course->id)->id,
2991 'instanceid' => $course->id,
2992 'instancetype' => 'coursecommunication',
2993 'component' => 'core_course',
2995 $coursenode->add(get_string('communication', 'communication'), $url,
2996 navigation_node::TYPE_SETTING, null, 'communication');
2999 return true;
3002 * This generates the structure of the course that won't be generated when
3003 * the modules and sections are added.
3005 * Things such as the reports branch, the participants branch, blogs... get
3006 * added to the course node by this method.
3008 * @param navigation_node $coursenode
3009 * @param stdClass $course
3010 * @return bool True for successfull generation
3012 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
3013 global $CFG, $USER, $COURSE, $SITE;
3014 require_once($CFG->dirroot . '/course/lib.php');
3016 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
3017 return true;
3020 $systemcontext = context_system::instance();
3021 $navoptions = course_get_user_navigation_options($systemcontext, $course);
3023 // Hidden node that we use to determine if the front page navigation is loaded.
3024 // This required as there are not other guaranteed nodes that may be loaded.
3025 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
3027 // Add My courses to the site pages within the navigation structure so the block can read it.
3028 $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses');
3030 // Participants.
3031 if ($navoptions->participants) {
3032 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
3033 self::TYPE_CUSTOM, get_string('participants'), 'participants');
3036 // Blogs.
3037 if ($navoptions->blogs) {
3038 $blogsurls = new moodle_url('/blog/index.php');
3039 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
3042 $filterselect = 0;
3044 // Badges.
3045 if ($navoptions->badges) {
3046 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
3047 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
3050 // Notes.
3051 if ($navoptions->notes) {
3052 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
3053 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
3056 // Tags
3057 if ($navoptions->tags) {
3058 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
3059 self::TYPE_SETTING, null, 'tags');
3062 // Search.
3063 if ($navoptions->search) {
3064 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
3065 self::TYPE_SETTING, null, 'search');
3068 if (isloggedin()) {
3069 $usercontext = context_user::instance($USER->id);
3070 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
3071 $url = new moodle_url('/user/files.php');
3072 $node = $coursenode->add(get_string('privatefiles'), $url,
3073 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
3074 $node->display = false;
3075 $node->showinflatnavigation = true;
3076 $node->mainnavonly = true;
3080 if (isloggedin()) {
3081 $context = $this->page->context;
3082 switch ($context->contextlevel) {
3083 case CONTEXT_COURSECAT:
3084 // OK, expected context level.
3085 break;
3086 case CONTEXT_COURSE:
3087 // OK, expected context level if not on frontpage.
3088 if ($COURSE->id != $SITE->id) {
3089 break;
3091 default:
3092 // If this context is part of a course (excluding frontpage), use the course context.
3093 // Otherwise, use the system context.
3094 $coursecontext = $context->get_course_context(false);
3095 if ($coursecontext && $coursecontext->instanceid !== $SITE->id) {
3096 $context = $coursecontext;
3097 } else {
3098 $context = $systemcontext;
3102 $params = ['contextid' => $context->id];
3103 if (has_capability('moodle/contentbank:access', $context)) {
3104 $url = new moodle_url('/contentbank/index.php', $params);
3105 $node = $coursenode->add(get_string('contentbank'), $url,
3106 self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', ''));
3107 $node->showinflatnavigation = true;
3111 return true;
3115 * Clears the navigation cache
3117 public function clear_cache() {
3118 $this->cache->clear();
3122 * Sets an expansion limit for the navigation
3124 * The expansion limit is used to prevent the display of content that has a type
3125 * greater than the provided $type.
3127 * Can be used to ensure things such as activities or activity content don't get
3128 * shown on the navigation.
3129 * They are still generated in order to ensure the navbar still makes sense.
3131 * @param int $type One of navigation_node::TYPE_*
3132 * @return bool true when complete.
3134 public function set_expansion_limit($type) {
3135 global $SITE;
3136 $nodes = $this->find_all_of_type($type);
3138 // We only want to hide specific types of nodes.
3139 // Only nodes that represent "structure" in the navigation tree should be hidden.
3140 // If we hide all nodes then we risk hiding vital information.
3141 $typestohide = array(
3142 self::TYPE_CATEGORY,
3143 self::TYPE_COURSE,
3144 self::TYPE_SECTION,
3145 self::TYPE_ACTIVITY
3148 foreach ($nodes as $node) {
3149 // We need to generate the full site node
3150 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
3151 continue;
3153 foreach ($node->children as $child) {
3154 $child->hide($typestohide);
3157 return true;
3160 * Attempts to get the navigation with the given key from this nodes children.
3162 * This function only looks at this nodes children, it does NOT look recursivily.
3163 * If the node can't be found then false is returned.
3165 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3167 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3168 * may be of more use to you.
3170 * @param string|int $key The key of the node you wish to receive.
3171 * @param int $type One of navigation_node::TYPE_*
3172 * @return navigation_node|false
3174 public function get($key, $type = null) {
3175 if (!$this->initialised) {
3176 $this->initialise();
3178 return parent::get($key, $type);
3182 * Searches this nodes children and their children to find a navigation node
3183 * with the matching key and type.
3185 * This method is recursive and searches children so until either a node is
3186 * found or there are no more nodes to search.
3188 * If you know that the node being searched for is a child of this node
3189 * then use the {@link global_navigation::get()} method instead.
3191 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3192 * may be of more use to you.
3194 * @param string|int $key The key of the node you wish to receive.
3195 * @param int $type One of navigation_node::TYPE_*
3196 * @return navigation_node|false
3198 public function find($key, $type) {
3199 if (!$this->initialised) {
3200 $this->initialise();
3202 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
3203 return $this->rootnodes[$key];
3205 return parent::find($key, $type);
3209 * They've expanded the 'my courses' branch.
3211 protected function load_courses_enrolled() {
3212 global $CFG;
3214 $limit = (int) $CFG->navcourselimit;
3216 $courses = enrol_get_my_courses('*');
3217 $flatnavcourses = [];
3219 // Go through the courses and see which ones we want to display in the flatnav.
3220 foreach ($courses as $course) {
3221 $classify = course_classify_for_timeline($course);
3223 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3224 $flatnavcourses[$course->id] = $course;
3228 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3229 $numtotalcourses = count($courses);
3230 $numtotalflatnavcourses = count($flatnavcourses);
3232 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3233 $courses = array_slice($courses, 0, $limit, true);
3234 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3236 // Get the number of courses we are going to show for each.
3237 $numshowncourses = count($courses);
3238 $numshownflatnavcourses = count($flatnavcourses);
3239 if ($numshowncourses && $this->show_my_categories()) {
3240 // Generate an array containing unique values of all the courses' categories.
3241 $categoryids = array();
3242 foreach ($courses as $course) {
3243 if (in_array($course->category, $categoryids)) {
3244 continue;
3246 $categoryids[] = $course->category;
3249 // Array of category IDs that include the categories of the user's courses and the related course categories.
3250 $fullpathcategoryids = [];
3251 // Get the course categories for the enrolled courses' category IDs.
3252 $mycoursecategories = core_course_category::get_many($categoryids);
3253 // Loop over each of these categories and build the category tree using each category's path.
3254 foreach ($mycoursecategories as $mycoursecat) {
3255 $pathcategoryids = explode('/', $mycoursecat->path);
3256 // First element of the exploded path is empty since paths begin with '/'.
3257 array_shift($pathcategoryids);
3258 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3259 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3262 // Fetch all of the categories related to the user's courses.
3263 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3264 // Loop over each of these categories and build the category tree.
3265 foreach ($pathcategories as $coursecat) {
3266 // No need to process categories that have already been added.
3267 if (isset($this->addedcategories[$coursecat->id])) {
3268 continue;
3270 // Skip categories that are not visible.
3271 if (!$coursecat->is_uservisible()) {
3272 continue;
3275 // Get this course category's parent node.
3276 $parent = null;
3277 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3278 $parent = $this->addedcategories[$coursecat->parent];
3280 if (!$parent) {
3281 // If it has no parent, then it should be right under the My courses node.
3282 $parent = $this->rootnodes['mycourses'];
3285 // Build the category object based from the coursecat object.
3286 $mycategory = new stdClass();
3287 $mycategory->id = $coursecat->id;
3288 $mycategory->name = $coursecat->name;
3289 $mycategory->visible = $coursecat->visible;
3291 // Add this category to the nav tree.
3292 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3296 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3297 foreach ($courses as $course) {
3298 $node = $this->add_course($course, false, self::COURSE_MY);
3299 if ($node) {
3300 $node->showinflatnavigation = false;
3301 // Check if we should also add this to the flat nav as well.
3302 if (isset($flatnavcourses[$course->id])) {
3303 $node->showinflatnavigation = true;
3308 // Go through each course in the flatnav now.
3309 foreach ($flatnavcourses as $course) {
3310 // Check if we haven't already added it.
3311 if (!isset($courses[$course->id])) {
3312 // Ok, add it to the flatnav only.
3313 $node = $this->add_course($course, false, self::COURSE_MY);
3314 $node->display = false;
3315 $node->showinflatnavigation = true;
3319 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3320 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3321 // Show a link to the course page if there are more courses the user is enrolled in.
3322 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3323 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3324 $url = new moodle_url('/my/courses.php');
3325 $parent = $this->rootnodes['mycourses'];
3326 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3328 if ($showmorelinkinnav) {
3329 $coursenode->display = true;
3332 if ($showmorelinkinflatnav) {
3333 $coursenode->showinflatnavigation = true;
3340 * The global navigation class used especially for AJAX requests.
3342 * The primary methods that are used in the global navigation class have been overriden
3343 * to ensure that only the relevant branch is generated at the root of the tree.
3344 * This can be done because AJAX is only used when the backwards structure for the
3345 * requested branch exists.
3346 * This has been done only because it shortens the amounts of information that is generated
3347 * which of course will speed up the response time.. because no one likes laggy AJAX.
3349 * @package core
3350 * @category navigation
3351 * @copyright 2009 Sam Hemelryk
3352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3354 class global_navigation_for_ajax extends global_navigation {
3356 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3357 protected $branchtype;
3359 /** @var int the instance id */
3360 protected $instanceid;
3362 /** @var array Holds an array of expandable nodes */
3363 protected $expandable = array();
3366 * Constructs the navigation for use in an AJAX request
3368 * @param moodle_page $page moodle_page object
3369 * @param int $branchtype
3370 * @param int $id
3372 public function __construct($page, $branchtype, $id) {
3373 $this->page = $page;
3374 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3375 $this->children = new navigation_node_collection();
3376 $this->branchtype = $branchtype;
3377 $this->instanceid = $id;
3378 $this->initialise();
3381 * Initialise the navigation given the type and id for the branch to expand.
3383 * @return array An array of the expandable nodes
3385 public function initialise() {
3386 global $DB, $SITE;
3388 if ($this->initialised || during_initial_install()) {
3389 return $this->expandable;
3391 $this->initialised = true;
3393 $this->rootnodes = array();
3394 $this->rootnodes['site'] = $this->add_course($SITE);
3395 $this->rootnodes['mycourses'] = $this->add(
3396 get_string('mycourses'),
3397 new moodle_url('/my/courses.php'),
3398 self::TYPE_ROOTNODE,
3399 null,
3400 'mycourses'
3402 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3403 // The courses branch is always displayed, and is always expandable (although may be empty).
3404 // This mimicks what is done during {@link global_navigation::initialise()}.
3405 $this->rootnodes['courses']->isexpandable = true;
3407 // Branchtype will be one of navigation_node::TYPE_*
3408 switch ($this->branchtype) {
3409 case 0:
3410 if ($this->instanceid === 'mycourses') {
3411 $this->load_courses_enrolled();
3412 } else if ($this->instanceid === 'courses') {
3413 $this->load_courses_other();
3415 break;
3416 case self::TYPE_CATEGORY :
3417 $this->load_category($this->instanceid);
3418 break;
3419 case self::TYPE_MY_CATEGORY :
3420 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3421 break;
3422 case self::TYPE_COURSE :
3423 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3424 if (!can_access_course($course, null, '', true)) {
3425 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3426 // add the course node and break. This leads to an empty node.
3427 $this->add_course($course);
3428 break;
3430 require_course_login($course, true, null, false, true);
3431 $this->page->set_context(context_course::instance($course->id));
3432 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3433 $this->add_course_essentials($coursenode, $course);
3434 $this->load_course_sections($course, $coursenode);
3435 break;
3436 case self::TYPE_SECTION :
3437 $sql = 'SELECT c.*, cs.section AS sectionnumber
3438 FROM {course} c
3439 LEFT JOIN {course_sections} cs ON cs.course = c.id
3440 WHERE cs.id = ?';
3441 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3442 require_course_login($course, true, null, false, true);
3443 $this->page->set_context(context_course::instance($course->id));
3444 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3445 $this->add_course_essentials($coursenode, $course);
3446 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3447 break;
3448 case self::TYPE_ACTIVITY :
3449 $sql = "SELECT c.*
3450 FROM {course} c
3451 JOIN {course_modules} cm ON cm.course = c.id
3452 WHERE cm.id = :cmid";
3453 $params = array('cmid' => $this->instanceid);
3454 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3455 $modinfo = get_fast_modinfo($course);
3456 $cm = $modinfo->get_cm($this->instanceid);
3457 require_course_login($course, true, $cm, false, true);
3458 $this->page->set_context(context_module::instance($cm->id));
3459 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3460 $this->load_course_sections($course, $coursenode, null, $cm);
3461 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3462 if ($activitynode) {
3463 $modulenode = $this->load_activity($cm, $course, $activitynode);
3465 break;
3466 default:
3467 throw new Exception('Unknown type');
3468 return $this->expandable;
3471 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3472 $this->load_for_user(null, true);
3475 // Give the local plugins a chance to include some navigation if they want.
3476 $this->load_local_plugin_navigation();
3478 $this->find_expandable($this->expandable);
3479 return $this->expandable;
3483 * They've expanded the general 'courses' branch.
3485 protected function load_courses_other() {
3486 $this->load_all_courses();
3490 * Loads a single category into the AJAX navigation.
3492 * This function is special in that it doesn't concern itself with the parent of
3493 * the requested category or its siblings.
3494 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3495 * request that.
3497 * @global moodle_database $DB
3498 * @param int $categoryid id of category to load in navigation.
3499 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3500 * @return void.
3502 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3503 global $CFG, $DB;
3505 $limit = 20;
3506 if (!empty($CFG->navcourselimit)) {
3507 $limit = (int)$CFG->navcourselimit;
3510 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3511 $sql = "SELECT cc.*, $catcontextsql
3512 FROM {course_categories} cc
3513 JOIN {context} ctx ON cc.id = ctx.instanceid
3514 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3515 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3516 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3517 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3518 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3519 $categorylist = array();
3520 $subcategories = array();
3521 $basecategory = null;
3522 foreach ($categories as $category) {
3523 $categorylist[] = $category->id;
3524 context_helper::preload_from_record($category);
3525 if ($category->id == $categoryid) {
3526 $this->add_category($category, $this, $nodetype);
3527 $basecategory = $this->addedcategories[$category->id];
3528 } else {
3529 $subcategories[$category->id] = $category;
3532 $categories->close();
3535 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3536 // else show all courses.
3537 if ($nodetype === self::TYPE_MY_CATEGORY) {
3538 $courses = enrol_get_my_courses('*');
3539 $categoryids = array();
3541 // Only search for categories if basecategory was found.
3542 if (!is_null($basecategory)) {
3543 // Get course parent category ids.
3544 foreach ($courses as $course) {
3545 $categoryids[] = $course->category;
3548 // Get a unique list of category ids which a part of the path
3549 // to user's courses.
3550 $coursesubcategories = array();
3551 $addedsubcategories = array();
3553 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3554 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3556 foreach ($categories as $category){
3557 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3559 $categories->close();
3560 $coursesubcategories = array_unique($coursesubcategories);
3562 // Only add a subcategory if it is part of the path to user's course and
3563 // wasn't already added.
3564 foreach ($subcategories as $subid => $subcategory) {
3565 if (in_array($subid, $coursesubcategories) &&
3566 !in_array($subid, $addedsubcategories)) {
3567 $this->add_category($subcategory, $basecategory, $nodetype);
3568 $addedsubcategories[] = $subid;
3573 foreach ($courses as $course) {
3574 // Add course if it's in category.
3575 if (in_array($course->category, $categorylist)) {
3576 $this->add_course($course, true, self::COURSE_MY);
3579 } else {
3580 if (!is_null($basecategory)) {
3581 foreach ($subcategories as $key=>$category) {
3582 $this->add_category($category, $basecategory, $nodetype);
3585 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3586 foreach ($courses as $course) {
3587 $this->add_course($course);
3589 $courses->close();
3594 * Returns an array of expandable nodes
3595 * @return array
3597 public function get_expandable() {
3598 return $this->expandable;
3603 * Navbar class
3605 * This class is used to manage the navbar, which is initialised from the navigation
3606 * object held by PAGE
3608 * @package core
3609 * @category navigation
3610 * @copyright 2009 Sam Hemelryk
3611 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3613 class navbar extends navigation_node {
3614 /** @var bool A switch for whether the navbar is initialised or not */
3615 protected $initialised = false;
3616 /** @var mixed keys used to reference the nodes on the navbar */
3617 protected $keys = array();
3618 /** @var null|string content of the navbar */
3619 protected $content = null;
3620 /** @var moodle_page object the moodle page that this navbar belongs to */
3621 protected $page;
3622 /** @var bool A switch for whether to ignore the active navigation information */
3623 protected $ignoreactive = false;
3624 /** @var bool A switch to let us know if we are in the middle of an install */
3625 protected $duringinstall = false;
3626 /** @var bool A switch for whether the navbar has items */
3627 protected $hasitems = false;
3628 /** @var array An array of navigation nodes for the navbar */
3629 protected $items;
3630 /** @var array An array of child node objects */
3631 public $children = array();
3632 /** @var bool A switch for whether we want to include the root node in the navbar */
3633 public $includesettingsbase = false;
3634 /** @var breadcrumb_navigation_node[] $prependchildren */
3635 protected $prependchildren = array();
3638 * The almighty constructor
3640 * @param moodle_page $page
3642 public function __construct(moodle_page $page) {
3643 global $CFG;
3644 if (during_initial_install()) {
3645 $this->duringinstall = true;
3646 return false;
3648 $this->page = $page;
3649 $this->text = get_string('home');
3650 $this->shorttext = get_string('home');
3651 $this->action = new moodle_url($CFG->wwwroot);
3652 $this->nodetype = self::NODETYPE_BRANCH;
3653 $this->type = self::TYPE_SYSTEM;
3657 * Quick check to see if the navbar will have items in.
3659 * @return bool Returns true if the navbar will have items, false otherwise
3661 public function has_items() {
3662 if ($this->duringinstall) {
3663 return false;
3664 } else if ($this->hasitems !== false) {
3665 return true;
3667 $outcome = false;
3668 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3669 // There have been manually added items - there are definitely items.
3670 $outcome = true;
3671 } else if (!$this->ignoreactive) {
3672 // We will need to initialise the navigation structure to check if there are active items.
3673 $this->page->navigation->initialise($this->page);
3674 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3676 $this->hasitems = $outcome;
3677 return $outcome;
3681 * Turn on/off ignore active
3683 * @param bool $setting
3685 public function ignore_active($setting=true) {
3686 $this->ignoreactive = ($setting);
3690 * Gets a navigation node
3692 * @param string|int $key for referencing the navbar nodes
3693 * @param int $type breadcrumb_navigation_node::TYPE_*
3694 * @return breadcrumb_navigation_node|bool
3696 public function get($key, $type = null) {
3697 foreach ($this->children as &$child) {
3698 if ($child->key === $key && ($type == null || $type == $child->type)) {
3699 return $child;
3702 foreach ($this->prependchildren as &$child) {
3703 if ($child->key === $key && ($type == null || $type == $child->type)) {
3704 return $child;
3707 return false;
3710 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3712 * @return array
3714 public function get_items() {
3715 global $CFG;
3716 $items = array();
3717 // Make sure that navigation is initialised
3718 if (!$this->has_items()) {
3719 return $items;
3721 if ($this->items !== null) {
3722 return $this->items;
3725 if (count($this->children) > 0) {
3726 // Add the custom children.
3727 $items = array_reverse($this->children);
3730 // Check if navigation contains the active node
3731 if (!$this->ignoreactive) {
3732 // We will need to ensure the navigation has been initialised.
3733 $this->page->navigation->initialise($this->page);
3734 // Now find the active nodes on both the navigation and settings.
3735 $navigationactivenode = $this->page->navigation->find_active_node();
3736 $settingsactivenode = $this->page->settingsnav->find_active_node();
3738 if ($navigationactivenode && $settingsactivenode) {
3739 // Parse a combined navigation tree
3740 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3741 if (!$settingsactivenode->mainnavonly) {
3742 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3744 $settingsactivenode = $settingsactivenode->parent;
3746 if (!$this->includesettingsbase) {
3747 // Removes the first node from the settings (root node) from the list
3748 array_pop($items);
3750 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3751 if (!$navigationactivenode->mainnavonly) {
3752 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3754 if (!empty($CFG->navshowcategories) &&
3755 $navigationactivenode->type === self::TYPE_COURSE &&
3756 $navigationactivenode->parent->key === 'currentcourse') {
3757 foreach ($this->get_course_categories() as $item) {
3758 $items[] = new breadcrumb_navigation_node($item);
3761 $navigationactivenode = $navigationactivenode->parent;
3763 } else if ($navigationactivenode) {
3764 // Parse the navigation tree to get the active node
3765 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3766 if (!$navigationactivenode->mainnavonly) {
3767 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3769 if (!empty($CFG->navshowcategories) &&
3770 $navigationactivenode->type === self::TYPE_COURSE &&
3771 $navigationactivenode->parent->key === 'currentcourse') {
3772 foreach ($this->get_course_categories() as $item) {
3773 $items[] = new breadcrumb_navigation_node($item);
3776 $navigationactivenode = $navigationactivenode->parent;
3778 } else if ($settingsactivenode) {
3779 // Parse the settings navigation to get the active node
3780 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3781 if (!$settingsactivenode->mainnavonly) {
3782 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3784 $settingsactivenode = $settingsactivenode->parent;
3789 $items[] = new breadcrumb_navigation_node(array(
3790 'text' => $this->page->navigation->text,
3791 'shorttext' => $this->page->navigation->shorttext,
3792 'key' => $this->page->navigation->key,
3793 'action' => $this->page->navigation->action
3796 if (count($this->prependchildren) > 0) {
3797 // Add the custom children
3798 $items = array_merge($items, array_reverse($this->prependchildren));
3801 $last = reset($items);
3802 if ($last) {
3803 $last->set_last(true);
3805 $this->items = array_reverse($items);
3806 return $this->items;
3810 * Get the list of categories leading to this course.
3812 * This function is used by {@link navbar::get_items()} to add back the "courses"
3813 * node and category chain leading to the current course. Note that this is only ever
3814 * called for the current course, so we don't need to bother taking in any parameters.
3816 * @return array
3818 private function get_course_categories() {
3819 global $CFG;
3820 require_once($CFG->dirroot.'/course/lib.php');
3822 $categories = array();
3823 $cap = 'moodle/category:viewhiddencategories';
3824 $showcategories = !core_course_category::is_simple_site();
3826 if ($showcategories) {
3827 foreach ($this->page->categories as $category) {
3828 $context = context_coursecat::instance($category->id);
3829 if (!core_course_category::can_view_category($category)) {
3830 continue;
3833 $displaycontext = \context_helper::get_navigation_filter_context($context);
3834 $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]);
3835 $name = format_string($category->name, true, ['context' => $displaycontext]);
3836 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3837 if (!$category->visible) {
3838 $categorynode->hidden = true;
3840 $categories[] = $categorynode;
3844 // Don't show the 'course' node if enrolled in this course.
3845 $coursecontext = context_course::instance($this->page->course->id);
3846 if (!is_enrolled($coursecontext, null, '', true)) {
3847 $courses = $this->page->navigation->get('courses');
3848 if (!$courses) {
3849 // Courses node may not be present.
3850 $courses = breadcrumb_navigation_node::create(
3851 get_string('courses'),
3852 new moodle_url('/course/index.php'),
3853 self::TYPE_CONTAINER
3856 $categories[] = $courses;
3859 return $categories;
3863 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3865 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3866 * the way nodes get added to allow us to simply call add and have the node added to the
3867 * end of the navbar
3869 * @param string $text
3870 * @param string|moodle_url|action_link $action An action to associate with this node.
3871 * @param int $type One of navigation_node::TYPE_*
3872 * @param string $shorttext
3873 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3874 * @param pix_icon $icon An optional icon to use for this node.
3875 * @return navigation_node
3877 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3878 if ($this->content !== null) {
3879 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3882 // Properties array used when creating the new navigation node
3883 $itemarray = array(
3884 'text' => $text,
3885 'type' => $type
3887 // Set the action if one was provided
3888 if ($action!==null) {
3889 $itemarray['action'] = $action;
3891 // Set the shorttext if one was provided
3892 if ($shorttext!==null) {
3893 $itemarray['shorttext'] = $shorttext;
3895 // Set the icon if one was provided
3896 if ($icon!==null) {
3897 $itemarray['icon'] = $icon;
3899 // Default the key to the number of children if not provided
3900 if ($key === null) {
3901 $key = count($this->children);
3903 // Set the key
3904 $itemarray['key'] = $key;
3905 // Set the parent to this node
3906 $itemarray['parent'] = $this;
3907 // Add the child using the navigation_node_collections add method
3908 $this->children[] = new breadcrumb_navigation_node($itemarray);
3909 return $this;
3913 * Prepends a new navigation_node to the start of the navbar
3915 * @param string $text
3916 * @param string|moodle_url|action_link $action An action to associate with this node.
3917 * @param int $type One of navigation_node::TYPE_*
3918 * @param string $shorttext
3919 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3920 * @param pix_icon $icon An optional icon to use for this node.
3921 * @return navigation_node
3923 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3924 if ($this->content !== null) {
3925 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3927 // Properties array used when creating the new navigation node.
3928 $itemarray = array(
3929 'text' => $text,
3930 'type' => $type
3932 // Set the action if one was provided.
3933 if ($action!==null) {
3934 $itemarray['action'] = $action;
3936 // Set the shorttext if one was provided.
3937 if ($shorttext!==null) {
3938 $itemarray['shorttext'] = $shorttext;
3940 // Set the icon if one was provided.
3941 if ($icon!==null) {
3942 $itemarray['icon'] = $icon;
3944 // Default the key to the number of children if not provided.
3945 if ($key === null) {
3946 $key = count($this->children);
3948 // Set the key.
3949 $itemarray['key'] = $key;
3950 // Set the parent to this node.
3951 $itemarray['parent'] = $this;
3952 // Add the child node to the prepend list.
3953 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3954 return $this;
3959 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3960 * in particular adding extra metadata for search engine robots to leverage.
3962 * @package core
3963 * @category navigation
3964 * @copyright 2015 Brendan Heywood
3965 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3967 class breadcrumb_navigation_node extends navigation_node {
3969 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3970 private $last = false;
3973 * A proxy constructor
3975 * @param mixed $navnode A navigation_node or an array
3977 public function __construct($navnode) {
3978 if (is_array($navnode)) {
3979 parent::__construct($navnode);
3980 } else if ($navnode instanceof navigation_node) {
3982 // Just clone everything.
3983 $objvalues = get_object_vars($navnode);
3984 foreach ($objvalues as $key => $value) {
3985 $this->$key = $value;
3987 } else {
3988 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3993 * Getter for "last"
3994 * @return boolean
3996 public function is_last() {
3997 return $this->last;
4001 * Setter for "last"
4002 * @param $val boolean
4004 public function set_last($val) {
4005 $this->last = $val;
4010 * Subclass of navigation_node allowing different rendering for the flat navigation
4011 * in particular allowing dividers and indents.
4013 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts
4014 * @package core
4015 * @category navigation
4016 * @copyright 2016 Damyon Wiese
4017 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4019 class flat_navigation_node extends navigation_node {
4021 /** @var $indent integer The indent level */
4022 private $indent = 0;
4024 /** @var $showdivider bool Show a divider before this element */
4025 private $showdivider = false;
4027 /** @var $collectionlabel string Label for a group of nodes */
4028 private $collectionlabel = '';
4031 * A proxy constructor
4033 * @param mixed $navnode A navigation_node or an array
4035 public function __construct($navnode, $indent) {
4036 debugging("Flat nav has been deprecated in favour of primary/secondary navigation concepts");
4037 if (is_array($navnode)) {
4038 parent::__construct($navnode);
4039 } else if ($navnode instanceof navigation_node) {
4041 // Just clone everything.
4042 $objvalues = get_object_vars($navnode);
4043 foreach ($objvalues as $key => $value) {
4044 $this->$key = $value;
4046 } else {
4047 throw new coding_exception('Not a valid flat_navigation_node');
4049 $this->indent = $indent;
4053 * Setter, a label is required for a flat navigation node that shows a divider.
4055 * @param string $label
4057 public function set_collectionlabel($label) {
4058 $this->collectionlabel = $label;
4062 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
4064 * @return string
4066 public function get_collectionlabel() {
4067 if (!empty($this->collectionlabel)) {
4068 return $this->collectionlabel;
4070 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) {
4071 return $this->parent->get_collectionlabel();
4073 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
4074 return '';
4078 * Does this node represent a course section link.
4079 * @return boolean
4081 public function is_section() {
4082 return $this->type == navigation_node::TYPE_SECTION;
4086 * In flat navigation - sections are active if we are looking at activities in the section.
4087 * @return boolean
4089 public function isactive() {
4090 global $PAGE;
4092 if ($this->is_section()) {
4093 $active = $PAGE->navigation->find_active_node();
4094 if ($active) {
4095 while ($active = $active->parent) {
4096 if ($active->key == $this->key && $active->type == $this->type) {
4097 return true;
4102 return $this->isactive;
4106 * Getter for "showdivider"
4107 * @return boolean
4109 public function showdivider() {
4110 return $this->showdivider;
4114 * Setter for "showdivider"
4115 * @param $val boolean
4116 * @param $label string Label for the group of nodes
4118 public function set_showdivider($val, $label = '') {
4119 $this->showdivider = $val;
4120 if ($this->showdivider && empty($label)) {
4121 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
4122 } else {
4123 $this->set_collectionlabel($label);
4128 * Getter for "indent"
4129 * @return boolean
4131 public function get_indent() {
4132 return $this->indent;
4136 * Setter for "indent"
4137 * @param $val boolean
4139 public function set_indent($val) {
4140 $this->indent = $val;
4145 * Class used to generate a collection of navigation nodes most closely related
4146 * to the current page.
4148 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts
4149 * @package core
4150 * @copyright 2016 Damyon Wiese
4151 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4153 class flat_navigation extends navigation_node_collection {
4154 /** @var moodle_page the moodle page that the navigation belongs to */
4155 protected $page;
4158 * Constructor.
4160 * @param moodle_page $page
4162 public function __construct(moodle_page &$page) {
4163 if (during_initial_install()) {
4164 return false;
4166 debugging("Flat navigation has been deprecated in favour of primary/secondary navigation concepts");
4167 $this->page = $page;
4171 * Build the list of navigation nodes based on the current navigation and settings trees.
4174 public function initialise() {
4175 global $PAGE, $USER, $OUTPUT, $CFG;
4176 if (during_initial_install()) {
4177 return;
4180 $current = false;
4182 $course = $PAGE->course;
4184 $this->page->navigation->initialise();
4186 // First walk the nav tree looking for "flat_navigation" nodes.
4187 if ($course->id > 1) {
4188 // It's a real course.
4189 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4191 $coursecontext = context_course::instance($course->id, MUST_EXIST);
4192 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
4193 // This is the name that will be shown for the course.
4194 $coursename = empty($CFG->navshowfullcoursenames) ?
4195 format_string($course->shortname, true, ['context' => $displaycontext]) :
4196 format_string($course->fullname, true, ['context' => $displaycontext]);
4198 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
4199 $flat->set_collectionlabel($coursename);
4200 $flat->key = 'coursehome';
4201 $flat->icon = new pix_icon('i/course', '');
4203 $courseformat = course_get_format($course);
4204 $coursenode = $PAGE->navigation->find_active_node();
4205 $targettype = navigation_node::TYPE_COURSE;
4207 // Single activity format has no course node - the course node is swapped for the activity node.
4208 if (!$courseformat->has_view_page()) {
4209 $targettype = navigation_node::TYPE_ACTIVITY;
4212 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
4213 $coursenode = $coursenode->parent;
4215 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4216 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4217 if ($coursenode && $coursenode->key != SITEID) {
4218 $this->add($flat);
4219 foreach ($coursenode->children as $child) {
4220 if ($child->action) {
4221 $flat = new flat_navigation_node($child, 0);
4222 $this->add($flat);
4227 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
4228 } else {
4229 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
4232 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
4233 if (!$admin) {
4234 // Try again - crazy nav tree!
4235 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
4237 if ($admin) {
4238 $flat = new flat_navigation_node($admin, 0);
4239 $flat->set_showdivider(true, get_string('sitesettings'));
4240 $flat->key = 'sitesettings';
4241 $flat->icon = new pix_icon('t/preferences', '');
4242 $this->add($flat);
4245 // Add-a-block in editing mode.
4246 if (isset($this->page->theme->addblockposition) &&
4247 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
4248 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) {
4249 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
4250 $addablock = navigation_node::create(get_string('addblock'), $url);
4251 $flat = new flat_navigation_node($addablock, 0);
4252 $flat->set_showdivider(true, get_string('blocksaddedit'));
4253 $flat->key = 'addblock';
4254 $flat->icon = new pix_icon('i/addblock', '');
4255 $this->add($flat);
4257 $addblockurl = "?{$url->get_query_string(false)}";
4259 $PAGE->requires->js_call_amd('core_block/add_modal', 'init',
4260 [$addblockurl, $this->page->get_edited_page_hash()]);
4265 * Override the parent so we can set a label for this collection if it has not been set yet.
4267 * @param navigation_node $node Node to add
4268 * @param string $beforekey If specified, adds before a node with this key,
4269 * otherwise adds at end
4270 * @return navigation_node Added node
4272 public function add(navigation_node $node, $beforekey=null) {
4273 $result = parent::add($node, $beforekey);
4274 // Extend the parent to get a name for the collection of nodes if required.
4275 if (empty($this->collectionlabel)) {
4276 if ($node instanceof flat_navigation_node) {
4277 $this->set_collectionlabel($node->get_collectionlabel());
4281 return $result;
4286 * Class used to manage the settings option for the current page
4288 * This class is used to manage the settings options in a tree format (recursively)
4289 * and was created initially for use with the settings blocks.
4291 * @package core
4292 * @category navigation
4293 * @copyright 2009 Sam Hemelryk
4294 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4296 class settings_navigation extends navigation_node {
4297 /** @var context the current context */
4298 protected $context;
4299 /** @var moodle_page the moodle page that the navigation belongs to */
4300 protected $page;
4301 /** @var string contains administration section navigation_nodes */
4302 protected $adminsection;
4303 /** @var bool A switch to see if the navigation node is initialised */
4304 protected $initialised = false;
4305 /** @var array An array of users that the nodes can extend for. */
4306 protected $userstoextendfor = array();
4307 /** @var navigation_cache **/
4308 protected $cache;
4311 * Sets up the object with basic settings and preparse it for use
4313 * @param moodle_page $page
4315 public function __construct(moodle_page &$page) {
4316 if (during_initial_install()) {
4317 return false;
4319 $this->page = $page;
4320 // Initialise the main navigation. It is most important that this is done
4321 // before we try anything
4322 $this->page->navigation->initialise();
4323 // Initialise the navigation cache
4324 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4325 $this->children = new navigation_node_collection();
4329 * Initialise the settings navigation based on the current context
4331 * This function initialises the settings navigation tree for a given context
4332 * by calling supporting functions to generate major parts of the tree.
4335 public function initialise() {
4336 global $DB, $SESSION, $SITE;
4338 if (during_initial_install()) {
4339 return false;
4340 } else if ($this->initialised) {
4341 return true;
4343 $this->id = 'settingsnav';
4344 $this->context = $this->page->context;
4346 $context = $this->context;
4347 if ($context->contextlevel == CONTEXT_BLOCK) {
4348 $this->load_block_settings();
4349 $context = $context->get_parent_context();
4350 $this->context = $context;
4352 switch ($context->contextlevel) {
4353 case CONTEXT_SYSTEM:
4354 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4355 $this->load_front_page_settings(($context->id == $this->context->id));
4357 break;
4358 case CONTEXT_COURSECAT:
4359 $this->load_category_settings();
4360 break;
4361 case CONTEXT_COURSE:
4362 if ($this->page->course->id != $SITE->id) {
4363 $this->load_course_settings(($context->id == $this->context->id));
4364 } else {
4365 $this->load_front_page_settings(($context->id == $this->context->id));
4367 break;
4368 case CONTEXT_MODULE:
4369 $this->load_module_settings();
4370 $this->load_course_settings();
4371 break;
4372 case CONTEXT_USER:
4373 if ($this->page->course->id != $SITE->id) {
4374 $this->load_course_settings();
4376 break;
4379 $usersettings = $this->load_user_settings($this->page->course->id);
4381 $adminsettings = false;
4382 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4383 $isadminpage = $this->is_admin_tree_needed();
4385 if (has_capability('moodle/site:configview', context_system::instance())) {
4386 if (has_capability('moodle/site:config', context_system::instance())) {
4387 // Make sure this works even if config capability changes on the fly
4388 // and also make it fast for admin right after login.
4389 $SESSION->load_navigation_admin = 1;
4390 if ($isadminpage) {
4391 $adminsettings = $this->load_administration_settings();
4394 } else if (!isset($SESSION->load_navigation_admin)) {
4395 $adminsettings = $this->load_administration_settings();
4396 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4398 } else if ($SESSION->load_navigation_admin) {
4399 if ($isadminpage) {
4400 $adminsettings = $this->load_administration_settings();
4404 // Print empty navigation node, if needed.
4405 if ($SESSION->load_navigation_admin && !$isadminpage) {
4406 if ($adminsettings) {
4407 // Do not print settings tree on pages that do not need it, this helps with performance.
4408 $adminsettings->remove();
4409 $adminsettings = false;
4411 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4412 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4413 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4414 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4415 $siteadminnode->requiresajaxloading = 'true';
4420 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4421 $adminsettings->force_open();
4422 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4423 $usersettings->force_open();
4426 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4427 $this->load_local_plugin_settings();
4429 foreach ($this->children as $key=>$node) {
4430 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4431 // Site administration is shown as link.
4432 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4433 continue;
4435 $node->remove();
4438 $this->initialised = true;
4441 * Override the parent function so that we can add preceeding hr's and set a
4442 * root node class against all first level element
4444 * It does this by first calling the parent's add method {@link navigation_node::add()}
4445 * and then proceeds to use the key to set class and hr
4447 * @param string $text text to be used for the link.
4448 * @param string|moodle_url $url url for the new node
4449 * @param int $type the type of node navigation_node::TYPE_*
4450 * @param string $shorttext
4451 * @param string|int $key a key to access the node by.
4452 * @param pix_icon $icon An icon that appears next to the node.
4453 * @return navigation_node with the new node added to it.
4455 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4456 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4457 $node->add_class('root_node');
4458 return $node;
4462 * This function allows the user to add something to the start of the settings
4463 * navigation, which means it will be at the top of the settings navigation block
4465 * @param string $text text to be used for the link.
4466 * @param string|moodle_url $url url for the new node
4467 * @param int $type the type of node navigation_node::TYPE_*
4468 * @param string $shorttext
4469 * @param string|int $key a key to access the node by.
4470 * @param pix_icon $icon An icon that appears next to the node.
4471 * @return navigation_node $node with the new node added to it.
4473 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4474 $children = $this->children;
4475 $childrenclass = get_class($children);
4476 $this->children = new $childrenclass;
4477 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4478 foreach ($children as $child) {
4479 $this->children->add($child);
4481 return $node;
4485 * Does this page require loading of full admin tree or is
4486 * it enough rely on AJAX?
4488 * @return bool
4490 protected function is_admin_tree_needed() {
4491 if (self::$loadadmintree) {
4492 // Usually external admin page or settings page.
4493 return true;
4496 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4497 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4498 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4499 return false;
4501 return true;
4504 return false;
4508 * Load the site administration tree
4510 * This function loads the site administration tree by using the lib/adminlib library functions
4512 * @param navigation_node $referencebranch A reference to a branch in the settings
4513 * navigation tree
4514 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4515 * tree and start at the beginning
4516 * @return mixed A key to access the admin tree by
4518 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4519 global $CFG;
4521 // Check if we are just starting to generate this navigation.
4522 if ($referencebranch === null) {
4524 // Require the admin lib then get an admin structure
4525 if (!function_exists('admin_get_root')) {
4526 require_once($CFG->dirroot.'/lib/adminlib.php');
4528 $adminroot = admin_get_root(false, false);
4529 // This is the active section identifier
4530 $this->adminsection = $this->page->url->param('section');
4532 // Disable the navigation from automatically finding the active node
4533 navigation_node::$autofindactive = false;
4534 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4535 foreach ($adminroot->children as $adminbranch) {
4536 $this->load_administration_settings($referencebranch, $adminbranch);
4538 navigation_node::$autofindactive = true;
4540 // Use the admin structure to locate the active page
4541 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4542 $currentnode = $this;
4543 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4544 $currentnode = $currentnode->get($pathkey);
4546 if ($currentnode) {
4547 $currentnode->make_active();
4549 } else {
4550 $this->scan_for_active_node($referencebranch);
4552 return $referencebranch;
4553 } else if ($adminbranch->check_access()) {
4554 // We have a reference branch that we can access and is not hidden `hurrah`
4555 // Now we need to display it and any children it may have
4556 $url = null;
4557 $icon = null;
4559 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) {
4560 if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4561 $url = null;
4562 } else {
4563 $url = $adminbranch->get_settings_page_url();
4567 // Add the branch
4568 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4570 if ($adminbranch->is_hidden()) {
4571 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4572 $reference->add_class('hidden');
4573 } else {
4574 $reference->display = false;
4578 // Check if we are generating the admin notifications and whether notificiations exist
4579 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4580 $reference->add_class('criticalnotification');
4582 // Check if this branch has children
4583 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4584 foreach ($adminbranch->children as $branch) {
4585 // Generate the child branches as well now using this branch as the reference
4586 $this->load_administration_settings($reference, $branch);
4588 } else {
4589 $reference->icon = new pix_icon('i/settings', '');
4595 * This function recursivily scans nodes until it finds the active node or there
4596 * are no more nodes.
4597 * @param navigation_node $node
4599 protected function scan_for_active_node(navigation_node $node) {
4600 if (!$node->check_if_active() && $node->children->count()>0) {
4601 foreach ($node->children as &$child) {
4602 $this->scan_for_active_node($child);
4608 * Gets a navigation node given an array of keys that represent the path to
4609 * the desired node.
4611 * @param array $path
4612 * @return navigation_node|false
4614 protected function get_by_path(array $path) {
4615 $node = $this->get(array_shift($path));
4616 foreach ($path as $key) {
4617 $node->get($key);
4619 return $node;
4623 * This function loads the course settings that are available for the user
4625 * @param bool $forceopen If set to true the course node will be forced open
4626 * @return navigation_node|false
4628 protected function load_course_settings($forceopen = false) {
4629 global $CFG, $USER;
4630 require_once($CFG->dirroot . '/course/lib.php');
4632 $course = $this->page->course;
4633 $coursecontext = context_course::instance($course->id);
4634 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4636 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4638 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4639 if ($forceopen) {
4640 $coursenode->force_open();
4643 // MoodleNet links.
4644 if ($this->page->user_is_editing()) {
4645 $this->page->requires->js_call_amd('core/moodlenet/mutations', 'init');
4647 $usercanshare = utilities::can_user_share($coursecontext, $USER->id, 'course');
4648 $issuerid = get_config('moodlenet', 'oauthservice');
4649 try {
4650 $issuer = \core\oauth2\api::get_issuer($issuerid);
4651 $isvalidinstance = utilities::is_valid_instance($issuer);
4652 if ($usercanshare && $isvalidinstance) {
4653 $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init');
4654 $action = new action_link(new moodle_url(''), '', null, [
4655 'data-action' => 'sendtomoodlenet',
4656 'data-type' => 'course',
4658 // Share course to MoodleNet link.
4659 $coursenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'),
4660 $action, self::TYPE_SETTING, null, 'exportcoursetomoodlenet')->set_force_into_more_menu(true);
4661 // MoodleNet share progress link.
4662 $url = new moodle_url('/moodlenet/shareprogress.php');
4663 $coursenode->add(get_string('moodlenet:shareprogress'),
4664 $url, self::TYPE_SETTING, null, 'moodlenetshareprogress')->set_force_into_more_menu(true);
4666 } catch (dml_missing_record_exception $e) {
4667 debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " .
4668 "This must be a valid issuer.");
4671 if ($adminoptions->update) {
4672 // Add the course settings link
4673 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4674 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null,
4675 'editsettings', new pix_icon('i/settings', ''));
4678 if ($adminoptions->editcompletion) {
4679 // Add the course completion settings link
4680 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4681 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion',
4682 new pix_icon('i/settings', ''));
4685 if (!$adminoptions->update && $adminoptions->tags) {
4686 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4687 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4688 $coursenode->get('coursetags')->set_force_into_more_menu();
4691 // add enrol nodes
4692 enrol_add_course_navigation($coursenode, $course);
4694 // Manage filters
4695 if ($adminoptions->filters) {
4696 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4697 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
4698 null, 'filtermanagement', new pix_icon('i/filter', ''));
4701 // View course reports.
4702 if ($adminoptions->reports) {
4703 $reportnav = $coursenode->add(get_string('reports'),
4704 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]),
4705 self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', ''));
4706 $coursereports = core_component::get_plugin_list('coursereport');
4707 foreach ($coursereports as $report => $dir) {
4708 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4709 if (file_exists($libfile)) {
4710 require_once($libfile);
4711 $reportfunction = $report.'_report_extend_navigation';
4712 if (function_exists($report.'_report_extend_navigation')) {
4713 $reportfunction($reportnav, $course, $coursecontext);
4718 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4719 foreach ($reports as $reportfunction) {
4720 $reportfunction($reportnav, $course, $coursecontext);
4723 if (!$reportnav->has_children()) {
4724 $reportnav->remove();
4728 // Check if we can view the gradebook's setup page.
4729 if ($adminoptions->gradebook) {
4730 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4731 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4732 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4735 // Add the context locking node.
4736 $this->add_context_locking_node($coursenode, $coursecontext);
4738 // Add outcome if permitted
4739 if ($adminoptions->outcomes) {
4740 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4741 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4744 //Add badges navigation
4745 if ($adminoptions->badges) {
4746 require_once($CFG->libdir .'/badgeslib.php');
4747 badges_add_course_navigation($coursenode, $course);
4750 // Questions
4751 require_once($CFG->libdir . '/questionlib.php');
4752 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4754 if ($adminoptions->update) {
4755 // Repository Instances
4756 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4757 require_once($CFG->dirroot . '/repository/lib.php');
4758 $editabletypes = repository::get_editable_types($coursecontext);
4759 $haseditabletypes = !empty($editabletypes);
4760 unset($editabletypes);
4761 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4762 } else {
4763 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4765 if ($haseditabletypes) {
4766 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4767 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4771 // Manage files
4772 if ($adminoptions->files) {
4773 // hidden in new courses and courses where legacy files were turned off
4774 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4775 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4779 // Let plugins hook into course navigation.
4780 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4781 foreach ($pluginsfunction as $plugintype => $plugins) {
4782 // Ignore the report plugin as it was already loaded above.
4783 if ($plugintype == 'report') {
4784 continue;
4786 foreach ($plugins as $pluginfunction) {
4787 $pluginfunction($coursenode, $course, $coursecontext);
4791 // Prepare data for course content download functionality if it is enabled.
4792 if (\core\content::can_export_context($coursecontext, $USER)) {
4793 $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext);
4794 $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes);
4796 $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download',
4797 new pix_icon('t/download', ''));
4798 $coursenode->get('download')->set_force_into_more_menu(true);
4801 // Course reuse options.
4802 if ($adminoptions->import
4803 || $adminoptions->backup
4804 || $adminoptions->restore
4805 || $adminoptions->copy
4806 || $adminoptions->reset) {
4807 $coursereusenav = $coursenode->add(
4808 get_string('coursereuse'),
4809 new moodle_url('/backup/view.php', ['id' => $course->id]),
4810 self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''),
4813 // Import data from other courses.
4814 if ($adminoptions->import) {
4815 $url = new moodle_url('/backup/import.php', ['id' => $course->id]);
4816 $coursereusenav->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4819 // Backup this course.
4820 if ($adminoptions->backup) {
4821 $url = new moodle_url('/backup/backup.php', ['id' => $course->id]);
4822 $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4825 // Restore to this course.
4826 if ($adminoptions->restore) {
4827 $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]);
4828 $coursereusenav->add(
4829 get_string('restore'),
4830 $url,
4831 self::TYPE_SETTING,
4832 null,
4833 'restore',
4834 new pix_icon('i/restore', ''),
4838 // Copy this course.
4839 if ($adminoptions->copy) {
4840 $url = new moodle_url('/backup/copy.php', ['id' => $course->id]);
4841 $coursereusenav->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', ''));
4844 // Reset this course.
4845 if ($adminoptions->reset) {
4846 $url = new moodle_url('/course/reset.php', ['id' => $course->id]);
4847 $coursereusenav->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4851 // Return we are done
4852 return $coursenode;
4856 * Get the moodle_page object associated to the current settings navigation.
4858 * @return moodle_page
4860 public function get_page(): moodle_page {
4861 return $this->page;
4865 * This function calls the module function to inject module settings into the
4866 * settings navigation tree.
4868 * This only gets called if there is a corrosponding function in the modules
4869 * lib file.
4871 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4873 * @return navigation_node|false
4875 protected function load_module_settings() {
4876 global $CFG, $USER;
4878 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4879 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4880 $this->page->set_cm($cm, $this->page->course);
4883 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4884 if (file_exists($file)) {
4885 require_once($file);
4888 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4889 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4890 $modulenode->force_open();
4892 // Settings for the module
4893 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4894 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4895 $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', ''));
4897 // Assign local roles
4898 if (count(get_assignable_roles($this->page->cm->context))>0) {
4899 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4900 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign',
4901 new pix_icon('i/role', ''));
4903 // Override roles
4904 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4905 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4906 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride',
4907 new pix_icon('i/permissions', ''));
4909 // Check role permissions
4910 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4911 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4912 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck',
4913 new pix_icon('i/checkpermissions', ''));
4916 // Add the context locking node.
4917 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4919 // Manage filters
4920 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4921 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4922 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage',
4923 new pix_icon('i/filter', ''));
4925 // Add reports
4926 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4927 foreach ($reports as $reportfunction) {
4928 $reportfunction($modulenode, $this->page->cm);
4930 // Add a backup link
4931 $featuresfunc = $this->page->activityname.'_supports';
4932 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4933 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4934 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4937 // Restore this activity
4938 $featuresfunc = $this->page->activityname.'_supports';
4939 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4940 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4941 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4944 // Allow the active advanced grading method plugin to append its settings
4945 $featuresfunc = $this->page->activityname.'_supports';
4946 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4947 require_once($CFG->dirroot.'/grade/grading/lib.php');
4948 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4949 $gradingman->extend_settings_navigation($this, $modulenode);
4952 $function = $this->page->activityname.'_extend_settings_navigation';
4953 if (function_exists($function)) {
4954 $function($this, $modulenode);
4957 // Send activity to MoodleNet.
4958 $usercanshare = utilities::can_user_share($this->context->get_course_context(), $USER->id);
4959 $issuerid = get_config('moodlenet', 'oauthservice');
4960 try {
4961 $issuer = \core\oauth2\api::get_issuer($issuerid);
4962 $isvalidinstance = utilities::is_valid_instance($issuer);
4963 if ($usercanshare && $isvalidinstance) {
4964 $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init');
4965 $action = new action_link(new moodle_url(''), '', null, [
4966 'data-action' => 'sendtomoodlenet',
4967 'data-type' => 'activity',
4969 $modulenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'),
4970 $action, self::TYPE_SETTING, null, 'exportmoodlenet')->set_force_into_more_menu(true);
4972 } catch (dml_missing_record_exception $e) {
4973 debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " .
4974 "This must be a valid issuer.");
4977 // Remove the module node if there are no children.
4978 if ($modulenode->children->count() <= 0) {
4979 $modulenode->remove();
4982 return $modulenode;
4986 * Loads the user settings block of the settings nav
4988 * This function is simply works out the userid and whether we need to load
4989 * just the current users profile settings, or the current user and the user the
4990 * current user is viewing.
4992 * This function has some very ugly code to work out the user, if anyone has
4993 * any bright ideas please feel free to intervene.
4995 * @param int $courseid The course id of the current course
4996 * @return navigation_node|false
4998 protected function load_user_settings($courseid = SITEID) {
4999 global $USER, $CFG;
5001 if (isguestuser() || !isloggedin()) {
5002 return false;
5005 $navusers = $this->page->navigation->get_extending_users();
5007 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
5008 $usernode = null;
5009 foreach ($this->userstoextendfor as $userid) {
5010 if ($userid == $USER->id) {
5011 continue;
5013 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
5014 if (is_null($usernode)) {
5015 $usernode = $node;
5018 foreach ($navusers as $user) {
5019 if ($user->id == $USER->id) {
5020 continue;
5022 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
5023 if (is_null($usernode)) {
5024 $usernode = $node;
5027 $this->generate_user_settings($courseid, $USER->id);
5028 } else {
5029 $usernode = $this->generate_user_settings($courseid, $USER->id);
5031 return $usernode;
5035 * Extends the settings navigation for the given user.
5037 * Note: This method gets called automatically if you call
5038 * $PAGE->navigation->extend_for_user($userid)
5040 * @param int $userid
5042 public function extend_for_user($userid) {
5043 global $CFG;
5045 if (!in_array($userid, $this->userstoextendfor)) {
5046 $this->userstoextendfor[] = $userid;
5047 if ($this->initialised) {
5048 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
5049 $children = array();
5050 foreach ($this->children as $child) {
5051 $children[] = $child;
5053 array_unshift($children, array_pop($children));
5054 $this->children = new navigation_node_collection();
5055 foreach ($children as $child) {
5056 $this->children->add($child);
5063 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
5064 * what can be shown/done
5066 * @param int $courseid The current course' id
5067 * @param int $userid The user id to load for
5068 * @param string $gstitle The string to pass to get_string for the branch title
5069 * @return navigation_node|false
5071 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
5072 global $DB, $CFG, $USER, $SITE;
5074 if ($courseid != $SITE->id) {
5075 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
5076 $course = $this->page->course;
5077 } else {
5078 $select = context_helper::get_preload_record_columns_sql('ctx');
5079 $sql = "SELECT c.*, $select
5080 FROM {course} c
5081 JOIN {context} ctx ON c.id = ctx.instanceid
5082 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
5083 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
5084 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
5085 context_helper::preload_from_record($course);
5087 } else {
5088 $course = $SITE;
5091 $coursecontext = context_course::instance($course->id); // Course context
5092 $systemcontext = context_system::instance();
5093 $currentuser = ($USER->id == $userid);
5095 if ($currentuser) {
5096 $user = $USER;
5097 $usercontext = context_user::instance($user->id); // User context
5098 } else {
5099 $select = context_helper::get_preload_record_columns_sql('ctx');
5100 $sql = "SELECT u.*, $select
5101 FROM {user} u
5102 JOIN {context} ctx ON u.id = ctx.instanceid
5103 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
5104 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
5105 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
5106 if (!$user) {
5107 return false;
5109 context_helper::preload_from_record($user);
5111 // Check that the user can view the profile
5112 $usercontext = context_user::instance($user->id); // User context
5113 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
5115 if ($course->id == $SITE->id) {
5116 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
5117 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
5118 return false;
5120 } else {
5121 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
5122 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
5123 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
5124 return false;
5126 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
5127 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
5128 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
5129 if ($courseid == $this->page->course->id) {
5130 $mygroups = get_fast_modinfo($this->page->course)->groups;
5131 } else {
5132 $mygroups = groups_get_user_groups($courseid);
5134 $usergroups = groups_get_user_groups($courseid, $userid);
5135 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
5136 return false;
5142 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
5144 $key = $gstitle;
5145 $prefurl = new moodle_url('/user/preferences.php');
5146 if ($gstitle != 'usercurrentsettings') {
5147 $key .= $userid;
5148 $prefurl->param('userid', $userid);
5151 // Add a user setting branch.
5152 if ($gstitle == 'usercurrentsettings') {
5153 $mainpage = $this->add(get_string('home'), new moodle_url('/'), self::TYPE_CONTAINER, null, 'site');
5155 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
5156 // breadcrumb.
5157 $mainpage->display = false;
5158 $homepage = get_home_page();
5159 if (($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES)) {
5160 $mainpage->mainnavonly = true;
5163 $iscurrentuser = ($user->id == $USER->id);
5165 $baseargs = array('id' => $user->id);
5166 if ($course->id != $SITE->id && !$iscurrentuser) {
5167 $baseargs['course'] = $course->id;
5168 $issitecourse = false;
5169 } else {
5170 // Load all categories and get the context for the system.
5171 $issitecourse = true;
5174 // Add the user profile to the dashboard.
5175 $profilenode = $mainpage->add(get_string('profile'), new moodle_url('/user/profile.php',
5176 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
5178 if (!empty($CFG->navadduserpostslinks)) {
5179 // Add nodes for forum posts and discussions if the user can view either or both
5180 // There are no capability checks here as the content of the page is based
5181 // purely on the forums the current user has access too.
5182 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
5183 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
5184 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
5185 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
5188 // Add blog nodes.
5189 if (!empty($CFG->enableblogs)) {
5190 if (!$this->cache->cached('userblogoptions'.$user->id)) {
5191 require_once($CFG->dirroot.'/blog/lib.php');
5192 // Get all options for the user.
5193 $options = blog_get_options_for_user($user);
5194 $this->cache->set('userblogoptions'.$user->id, $options);
5195 } else {
5196 $options = $this->cache->{'userblogoptions'.$user->id};
5199 if (count($options) > 0) {
5200 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
5201 foreach ($options as $type => $option) {
5202 if ($type == "rss") {
5203 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
5204 new pix_icon('i/rss', ''));
5205 } else {
5206 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
5212 // Add the messages link.
5213 // It is context based so can appear in the user's profile and in course participants information.
5214 if (!empty($CFG->messaging)) {
5215 $messageargs = array('user1' => $USER->id);
5216 if ($USER->id != $user->id) {
5217 $messageargs['user2'] = $user->id;
5219 $url = new moodle_url('/message/index.php', $messageargs);
5220 $mainpage->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
5223 // Add the "My private files" link.
5224 // This link doesn't have a unique display for course context so only display it under the user's profile.
5225 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
5226 $url = new moodle_url('/user/files.php');
5227 $mainpage->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
5230 // Add a node to view the users notes if permitted.
5231 if (!empty($CFG->enablenotes) &&
5232 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
5233 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
5234 if ($coursecontext->instanceid != SITEID) {
5235 $url->param('course', $coursecontext->instanceid);
5237 $profilenode->add(get_string('notes', 'notes'), $url);
5240 // Show the grades node.
5241 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
5242 require_once($CFG->dirroot . '/user/lib.php');
5243 // Set the grades node to link to the "Grades" page.
5244 if ($course->id == SITEID) {
5245 $url = user_mygrades_url($user->id, $course->id);
5246 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
5247 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
5249 $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
5252 // Let plugins hook into user navigation.
5253 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5254 foreach ($pluginsfunction as $plugintype => $plugins) {
5255 if ($plugintype != 'report') {
5256 foreach ($plugins as $pluginfunction) {
5257 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5262 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5263 $mainpage->add_node($usersetting);
5264 } else {
5265 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5266 $usersetting->display = false;
5268 $usersetting->id = 'usersettings';
5270 // Check if the user has been deleted.
5271 if ($user->deleted) {
5272 if (!has_capability('moodle/user:update', $coursecontext)) {
5273 // We can't edit the user so just show the user deleted message.
5274 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
5275 } else {
5276 // We can edit the user so show the user deleted message and link it to the profile.
5277 if ($course->id == $SITE->id) {
5278 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
5279 } else {
5280 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
5282 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
5284 return true;
5287 $userauthplugin = false;
5288 if (!empty($user->auth)) {
5289 $userauthplugin = get_auth_plugin($user->auth);
5292 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
5294 // Add the profile edit link.
5295 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5296 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
5297 has_capability('moodle/user:update', $systemcontext)) {
5298 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
5299 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5300 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5301 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5302 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5303 $url = $userauthplugin->edit_profile_url();
5304 if (empty($url)) {
5305 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
5307 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5312 // Change password link.
5313 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
5314 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5315 $passwordchangeurl = $userauthplugin->change_password_url();
5316 if (empty($passwordchangeurl)) {
5317 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
5319 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
5322 // Default homepage.
5323 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER));
5324 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5325 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5326 has_capability('moodle/user:editprofile', $usercontext)) {
5327 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]);
5328 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser');
5332 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5333 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5334 has_capability('moodle/user:editprofile', $usercontext)) {
5335 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
5336 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
5339 $pluginmanager = core_plugin_manager::instance();
5340 $enabled = $pluginmanager->get_enabled_plugins('mod');
5341 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5342 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5343 has_capability('moodle/user:editprofile', $usercontext)) {
5344 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
5345 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
5348 $editors = editors_get_enabled();
5349 if (count($editors) > 1) {
5350 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5351 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5352 has_capability('moodle/user:editprofile', $usercontext)) {
5353 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
5354 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
5359 // Add "Calendar preferences" link.
5360 if (isloggedin() && !isguestuser($user)) {
5361 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5362 has_capability('moodle/user:editprofile', $usercontext)) {
5363 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
5364 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
5368 // Add "Content bank preferences" link.
5369 if (isloggedin() && !isguestuser($user)) {
5370 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5371 has_capability('moodle/user:editprofile', $usercontext)) {
5372 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]);
5373 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING,
5374 null, 'contentbankpreferences');
5378 // View the roles settings.
5379 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5380 'moodle/role:manage'], $usercontext)) {
5381 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
5383 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]);
5384 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
5386 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
5388 if (!empty($assignableroles)) {
5389 $url = new moodle_url('/admin/roles/assign.php',
5390 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5391 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
5394 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
5395 $url = new moodle_url('/admin/roles/permissions.php',
5396 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5397 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5400 $url = new moodle_url('/admin/roles/check.php',
5401 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5402 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5405 // Repositories.
5406 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5407 require_once($CFG->dirroot . '/repository/lib.php');
5408 $editabletypes = repository::get_editable_types($usercontext);
5409 $haseditabletypes = !empty($editabletypes);
5410 unset($editabletypes);
5411 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5412 } else {
5413 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5415 if ($haseditabletypes) {
5416 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5417 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5418 array('contextid' => $usercontext->id)));
5421 // Portfolio.
5422 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5423 require_once($CFG->libdir . '/portfoliolib.php');
5424 if (portfolio_has_visible_instances()) {
5425 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5427 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5428 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5430 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5431 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5435 $enablemanagetokens = false;
5436 if (!empty($CFG->enablerssfeeds)) {
5437 $enablemanagetokens = true;
5438 } else if (!is_siteadmin($USER->id)
5439 && !empty($CFG->enablewebservices)
5440 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5441 $enablemanagetokens = true;
5443 // Security keys.
5444 if ($currentuser && $enablemanagetokens) {
5445 $url = new moodle_url('/user/managetoken.php');
5446 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5449 // Messaging.
5450 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5451 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5452 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5453 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5454 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5455 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5458 // Blogs.
5459 if ($currentuser && !empty($CFG->enableblogs)) {
5460 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5461 if (has_capability('moodle/blog:view', $systemcontext)) {
5462 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5463 navigation_node::TYPE_SETTING);
5465 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5466 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5467 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5468 navigation_node::TYPE_SETTING);
5469 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5470 navigation_node::TYPE_SETTING);
5472 // Remove the blog node if empty.
5473 $blog->trim_if_empty();
5476 // Badges.
5477 if ($currentuser && !empty($CFG->enablebadges)) {
5478 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5479 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5480 $url = new moodle_url('/badges/mybadges.php');
5481 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5483 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5484 navigation_node::TYPE_SETTING);
5485 if (!empty($CFG->badges_allowexternalbackpack)) {
5486 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5487 navigation_node::TYPE_SETTING);
5491 // Let plugins hook into user settings navigation.
5492 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5493 foreach ($pluginsfunction as $plugintype => $plugins) {
5494 foreach ($plugins as $pluginfunction) {
5495 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5499 return $usersetting;
5503 * Loads block specific settings in the navigation
5505 * @return navigation_node
5507 protected function load_block_settings() {
5508 global $CFG;
5510 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5511 $blocknode->force_open();
5513 // Assign local roles
5514 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5515 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5516 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5517 'roles', new pix_icon('i/assignroles', ''));
5520 // Override roles
5521 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5522 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5523 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5524 'permissions', new pix_icon('i/permissions', ''));
5526 // Check role permissions
5527 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5528 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5529 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5530 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5533 // Add the context locking node.
5534 $this->add_context_locking_node($blocknode, $this->context);
5536 return $blocknode;
5540 * Loads category specific settings in the navigation
5542 * @return navigation_node
5544 protected function load_category_settings() {
5545 global $CFG;
5547 // We can land here while being in the context of a block, in which case we
5548 // should get the parent context which should be the category one. See self::initialise().
5549 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5550 $catcontext = $this->context->get_parent_context();
5551 } else {
5552 $catcontext = $this->context;
5555 // Let's make sure that we always have the right context when getting here.
5556 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5557 throw new coding_exception('Unexpected context while loading category settings.');
5560 $categorynodetype = navigation_node::TYPE_CONTAINER;
5561 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5562 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5563 $categorynode->force_open();
5565 if (can_edit_in_category($catcontext->instanceid)) {
5566 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5567 $editstring = get_string('managecategorythis');
5568 $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', ''));
5569 $node->set_show_in_secondary_navigation(false);
5572 if (has_capability('moodle/category:manage', $catcontext)) {
5573 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5574 $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5576 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5577 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null,
5578 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false);
5581 // Assign local roles
5582 $assignableroles = get_assignable_roles($catcontext);
5583 if (!empty($assignableroles)) {
5584 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5585 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5588 // Override roles
5589 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5590 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5591 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5593 // Check role permissions
5594 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5595 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5596 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5597 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', ''));
5600 // Add the context locking node.
5601 $this->add_context_locking_node($categorynode, $catcontext);
5603 // Cohorts
5604 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5605 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5606 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5609 // Manage filters
5610 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5611 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5612 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5615 // Restore.
5616 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5617 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5618 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5621 // Let plugins hook into category settings navigation.
5622 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5623 foreach ($pluginsfunction as $plugintype => $plugins) {
5624 foreach ($plugins as $pluginfunction) {
5625 $pluginfunction($categorynode, $catcontext);
5629 $cb = new contentbank();
5630 if ($cb->is_context_allowed($catcontext)
5631 && has_capability('moodle/contentbank:access', $catcontext)) {
5632 $url = new \moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id]);
5633 $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null,
5634 'contentbank', new \pix_icon('i/contentbank', ''));
5637 return $categorynode;
5641 * Determine whether the user is assuming another role
5643 * This function checks to see if the user is assuming another role by means of
5644 * role switching. In doing this we compare each RSW key (context path) against
5645 * the current context path. This ensures that we can provide the switching
5646 * options against both the course and any page shown under the course.
5648 * @return bool|int The role(int) if the user is in another role, false otherwise
5650 protected function in_alternative_role() {
5651 global $USER;
5652 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5653 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5654 return $USER->access['rsw'][$this->page->context->path];
5656 foreach ($USER->access['rsw'] as $key=>$role) {
5657 if (strpos($this->context->path,$key)===0) {
5658 return $role;
5662 return false;
5666 * This function loads all of the front page settings into the settings navigation.
5667 * This function is called when the user is on the front page, or $COURSE==$SITE
5668 * @param bool $forceopen (optional)
5669 * @return navigation_node
5671 protected function load_front_page_settings($forceopen = false) {
5672 global $SITE, $CFG;
5673 require_once($CFG->dirroot . '/course/lib.php');
5675 $course = clone($SITE);
5676 $coursecontext = context_course::instance($course->id); // Course context
5677 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5679 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5680 if ($forceopen) {
5681 $frontpage->force_open();
5683 $frontpage->id = 'frontpagesettings';
5685 if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) {
5687 // Add the turn on/off settings
5688 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5689 if ($this->page->user_is_editing()) {
5690 $url->param('edit', 'off');
5691 $editstring = get_string('turneditingoff');
5692 } else {
5693 $url->param('edit', 'on');
5694 $editstring = get_string('turneditingon');
5696 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5699 if ($adminoptions->update) {
5700 // Add the course settings link
5701 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5702 $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null,
5703 'editsettings', new pix_icon('i/settings', ''));
5706 // add enrol nodes
5707 enrol_add_course_navigation($frontpage, $course);
5709 // Manage filters
5710 if ($adminoptions->filters) {
5711 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5712 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
5713 null, 'filtermanagement', new pix_icon('i/filter', ''));
5716 // View course reports.
5717 if ($adminoptions->reports) {
5718 $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php',
5719 ['courseid' => $coursecontext->instanceid]),
5720 self::TYPE_CONTAINER, null, 'coursereports',
5721 new pix_icon('i/stats', ''));
5722 $coursereports = core_component::get_plugin_list('coursereport');
5723 foreach ($coursereports as $report=>$dir) {
5724 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5725 if (file_exists($libfile)) {
5726 require_once($libfile);
5727 $reportfunction = $report.'_report_extend_navigation';
5728 if (function_exists($report.'_report_extend_navigation')) {
5729 $reportfunction($frontpagenav, $course, $coursecontext);
5734 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5735 foreach ($reports as $reportfunction) {
5736 $reportfunction($frontpagenav, $course, $coursecontext);
5739 if (!$frontpagenav->has_children()) {
5740 $frontpagenav->remove();
5744 // Questions
5745 require_once($CFG->libdir . '/questionlib.php');
5746 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5748 // Manage files
5749 if ($adminoptions->files) {
5750 //hiden in new installs
5751 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5752 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5755 // Let plugins hook into frontpage navigation.
5756 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5757 foreach ($pluginsfunction as $plugintype => $plugins) {
5758 foreach ($plugins as $pluginfunction) {
5759 $pluginfunction($frontpage, $course, $coursecontext);
5763 // Course reuse options.
5764 if ($adminoptions->backup || $adminoptions->restore) {
5765 $coursereusenav = $frontpage->add(
5766 get_string('coursereuse'),
5767 new moodle_url('/backup/view.php', ['id' => $course->id]),
5768 self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''),
5771 // Backup this course.
5772 if ($adminoptions->backup) {
5773 $url = new moodle_url('/backup/backup.php', ['id' => $course->id]);
5774 $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
5777 // Restore to this course.
5778 if ($adminoptions->restore) {
5779 $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]);
5780 $coursereusenav->add(
5781 get_string('restore'),
5782 $url,
5783 self::TYPE_SETTING,
5784 null,
5785 'restore',
5786 new pix_icon('i/restore', ''),
5791 return $frontpage;
5795 * This function gives local plugins an opportunity to modify the settings navigation.
5797 protected function load_local_plugin_settings() {
5799 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5800 $function($this, $this->context);
5805 * This function marks the cache as volatile so it is cleared during shutdown
5807 public function clear_cache() {
5808 $this->cache->volatile();
5812 * Checks to see if there are child nodes available in the specific user's preference node.
5813 * If so, then they have the appropriate permissions view this user's preferences.
5815 * @since Moodle 2.9.3
5816 * @param int $userid The user's ID.
5817 * @return bool True if child nodes exist to view, otherwise false.
5819 public function can_view_user_preferences($userid) {
5820 if (is_siteadmin()) {
5821 return true;
5823 // See if any nodes are present in the preferences section for this user.
5824 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5825 if ($preferencenode && $preferencenode->has_children()) {
5826 // Run through each child node.
5827 foreach ($preferencenode->children as $childnode) {
5828 // If the child node has children then this user has access to a link in the preferences page.
5829 if ($childnode->has_children()) {
5830 return true;
5834 // No links found for the user to access on the preferences page.
5835 return false;
5840 * Class used to populate site admin navigation for ajax.
5842 * @package core
5843 * @category navigation
5844 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5845 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5847 class settings_navigation_ajax extends settings_navigation {
5849 * Constructs the navigation for use in an AJAX request
5851 * @param moodle_page $page
5853 public function __construct(moodle_page &$page) {
5854 $this->page = $page;
5855 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5856 $this->children = new navigation_node_collection();
5857 $this->initialise();
5861 * Initialise the site admin navigation.
5863 public function initialise() {
5864 if ($this->initialised || during_initial_install()) {
5865 return false;
5867 $this->context = $this->page->context;
5868 $this->load_administration_settings();
5870 // Check if local plugins is adding node to site admin.
5871 $this->load_local_plugin_settings();
5873 $this->initialised = true;
5878 * Simple class used to output a navigation branch in XML
5880 * @package core
5881 * @category navigation
5882 * @copyright 2009 Sam Hemelryk
5883 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5885 class navigation_json {
5886 /** @var array An array of different node types */
5887 protected $nodetype = array('node','branch');
5888 /** @var array An array of node keys and types */
5889 protected $expandable = array();
5891 * Turns a branch and all of its children into XML
5893 * @param navigation_node $branch
5894 * @return string XML string
5896 public function convert($branch) {
5897 $xml = $this->convert_child($branch);
5898 return $xml;
5901 * Set the expandable items in the array so that we have enough information
5902 * to attach AJAX events
5903 * @param array $expandable
5905 public function set_expandable($expandable) {
5906 foreach ($expandable as $node) {
5907 $this->expandable[$node['key'].':'.$node['type']] = $node;
5911 * Recusively converts a child node and its children to XML for output
5913 * @param navigation_node $child The child to convert
5914 * @param int $depth Pointlessly used to track the depth of the XML structure
5915 * @return string JSON
5917 protected function convert_child($child, $depth=1) {
5918 if (!$child->display) {
5919 return '';
5921 $attributes = array();
5922 $attributes['id'] = $child->id;
5923 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5924 $attributes['type'] = $child->type;
5925 $attributes['key'] = $child->key;
5926 $attributes['class'] = $child->get_css_type();
5927 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5929 if ($child->icon instanceof pix_icon) {
5930 $attributes['icon'] = array(
5931 'component' => $child->icon->component,
5932 'pix' => $child->icon->pix,
5934 foreach ($child->icon->attributes as $key=>$value) {
5935 if ($key == 'class') {
5936 $attributes['icon']['classes'] = explode(' ', $value);
5937 } else if (!array_key_exists($key, $attributes['icon'])) {
5938 $attributes['icon'][$key] = $value;
5942 } else if (!empty($child->icon)) {
5943 $attributes['icon'] = (string)$child->icon;
5946 if ($child->forcetitle || $child->title !== $child->text) {
5947 $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8');
5949 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5950 $attributes['expandable'] = $child->key;
5951 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5954 if (count($child->classes)>0) {
5955 $attributes['class'] .= ' '.join(' ',$child->classes);
5957 if (is_string($child->action)) {
5958 $attributes['link'] = $child->action;
5959 } else if ($child->action instanceof moodle_url) {
5960 $attributes['link'] = $child->action->out();
5961 } else if ($child->action instanceof action_link) {
5962 $attributes['link'] = $child->action->url->out();
5964 $attributes['hidden'] = ($child->hidden);
5965 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5966 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5968 if ($child->children->count() > 0) {
5969 $attributes['children'] = array();
5970 foreach ($child->children as $subchild) {
5971 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5975 if ($depth > 1) {
5976 return $attributes;
5977 } else {
5978 return json_encode($attributes);
5984 * The cache class used by global navigation and settings navigation.
5986 * It is basically an easy access point to session with a bit of smarts to make
5987 * sure that the information that is cached is valid still.
5989 * Example use:
5990 * <code php>
5991 * if (!$cache->viewdiscussion()) {
5992 * // Code to do stuff and produce cachable content
5993 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5995 * $content = $cache->viewdiscussion;
5996 * </code>
5998 * @package core
5999 * @category navigation
6000 * @copyright 2009 Sam Hemelryk
6001 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6003 class navigation_cache {
6004 /** @var int represents the time created */
6005 protected $creation;
6006 /** @var array An array of session keys */
6007 protected $session;
6009 * The string to use to segregate this particular cache. It can either be
6010 * unique to start a fresh cache or if you want to share a cache then make
6011 * it the string used in the original cache.
6012 * @var string
6014 protected $area;
6015 /** @var int a time that the information will time out */
6016 protected $timeout;
6017 /** @var stdClass The current context */
6018 protected $currentcontext;
6019 /** @var int cache time information */
6020 const CACHETIME = 0;
6021 /** @var int cache user id */
6022 const CACHEUSERID = 1;
6023 /** @var int cache value */
6024 const CACHEVALUE = 2;
6025 /** @var null|array An array of navigation cache areas to expire on shutdown */
6026 public static $volatilecaches;
6029 * Contructor for the cache. Requires two arguments
6031 * @param string $area The string to use to segregate this particular cache
6032 * it can either be unique to start a fresh cache or if you want
6033 * to share a cache then make it the string used in the original
6034 * cache
6035 * @param int $timeout The number of seconds to time the information out after
6037 public function __construct($area, $timeout=1800) {
6038 $this->creation = time();
6039 $this->area = $area;
6040 $this->timeout = time() - $timeout;
6041 if (rand(0,100) === 0) {
6042 $this->garbage_collection();
6047 * Used to set up the cache within the SESSION.
6049 * This is called for each access and ensure that we don't put anything into the session before
6050 * it is required.
6052 protected function ensure_session_cache_initialised() {
6053 global $SESSION;
6054 if (empty($this->session)) {
6055 if (!isset($SESSION->navcache)) {
6056 $SESSION->navcache = new stdClass;
6058 if (!isset($SESSION->navcache->{$this->area})) {
6059 $SESSION->navcache->{$this->area} = array();
6061 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
6066 * Magic Method to retrieve something by simply calling using = cache->key
6068 * @param mixed $key The identifier for the information you want out again
6069 * @return void|mixed Either void or what ever was put in
6071 public function __get($key) {
6072 if (!$this->cached($key)) {
6073 return;
6075 $information = $this->session[$key][self::CACHEVALUE];
6076 return unserialize($information);
6080 * Magic method that simply uses {@link set();} to store something in the cache
6082 * @param string|int $key
6083 * @param mixed $information
6085 public function __set($key, $information) {
6086 $this->set($key, $information);
6090 * Sets some information against the cache (session) for later retrieval
6092 * @param string|int $key
6093 * @param mixed $information
6095 public function set($key, $information) {
6096 global $USER;
6097 $this->ensure_session_cache_initialised();
6098 $information = serialize($information);
6099 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
6102 * Check the existence of the identifier in the cache
6104 * @param string|int $key
6105 * @return bool
6107 public function cached($key) {
6108 global $USER;
6109 $this->ensure_session_cache_initialised();
6110 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) {
6111 return false;
6113 return true;
6116 * Compare something to it's equivilant in the cache
6118 * @param string $key
6119 * @param mixed $value
6120 * @param bool $serialise Whether to serialise the value before comparison
6121 * this should only be set to false if the value is already
6122 * serialised
6123 * @return bool If the value is the same false if it is not set or doesn't match
6125 public function compare($key, $value, $serialise = true) {
6126 if ($this->cached($key)) {
6127 if ($serialise) {
6128 $value = serialize($value);
6130 if ($this->session[$key][self::CACHEVALUE] === $value) {
6131 return true;
6134 return false;
6137 * Wipes the entire cache, good to force regeneration
6139 public function clear() {
6140 global $SESSION;
6141 unset($SESSION->navcache);
6142 $this->session = null;
6145 * Checks all cache entries and removes any that have expired, good ole cleanup
6147 protected function garbage_collection() {
6148 if (empty($this->session)) {
6149 return true;
6151 foreach ($this->session as $key=>$cachedinfo) {
6152 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
6153 unset($this->session[$key]);
6159 * Marks the cache as being volatile (likely to change)
6161 * Any caches marked as volatile will be destroyed at the on shutdown by
6162 * {@link navigation_node::destroy_volatile_caches()} which is registered
6163 * as a shutdown function if any caches are marked as volatile.
6165 * @param bool $setting True to destroy the cache false not too
6167 public function volatile($setting = true) {
6168 if (self::$volatilecaches===null) {
6169 self::$volatilecaches = array();
6170 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
6173 if ($setting) {
6174 self::$volatilecaches[$this->area] = $this->area;
6175 } else if (array_key_exists($this->area, self::$volatilecaches)) {
6176 unset(self::$volatilecaches[$this->area]);
6181 * Destroys all caches marked as volatile
6183 * This function is static and works in conjunction with the static volatilecaches
6184 * property of navigation cache.
6185 * Because this function is static it manually resets the cached areas back to an
6186 * empty array.
6188 public static function destroy_volatile_caches() {
6189 global $SESSION;
6190 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
6191 foreach (self::$volatilecaches as $area) {
6192 $SESSION->navcache->{$area} = array();
6194 } else {
6195 $SESSION->navcache = new stdClass;