Merge branch 'MDL-80715-main' of https://github.com/ferranrecio/moodle
[moodle.git] / lib / navigationlib.php
blob09cfc188f1e0c230c15a3a68dbb04ea306bbe4e6
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 array An array of HTML attributes for the node */
120 public $attributes = [];
121 /** @var navigation_node_collection An array of child nodes */
122 public $children = array();
123 /** @var bool If set to true the node will be recognised as active */
124 public $isactive = false;
125 /** @var bool If set to true the node will be dimmed */
126 public $hidden = false;
127 /** @var bool If set to false the node will not be displayed */
128 public $display = true;
129 /** @var bool If set to true then an HR will be printed before the node */
130 public $preceedwithhr = false;
131 /** @var bool If set to true the the navigation bar should ignore this node */
132 public $mainnavonly = false;
133 /** @var bool If set to true a title will be added to the action no matter what */
134 public $forcetitle = false;
135 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
136 public $parent = null;
137 /** @var bool Override to not display the icon even if one is provided **/
138 public $hideicon = false;
139 /** @var bool Set to true if we KNOW that this node can be expanded. */
140 public $isexpandable = false;
141 /** @var array */
142 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
143 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
144 90 => 'container');
145 /** @var moodle_url */
146 protected static $fullmeurl = null;
147 /** @var bool toogles auto matching of active node */
148 public static $autofindactive = true;
149 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
150 protected static $loadadmintree = false;
151 /** @var mixed If set to an int, that section will be included even if it has no activities */
152 public $includesectionnum = false;
153 /** @var bool does the node need to be loaded via ajax */
154 public $requiresajaxloading = false;
155 /** @var bool If set to true this node will be added to the "flat" navigation */
156 public $showinflatnavigation = false;
157 /** @var bool If set to true this node will be forced into a "more" menu whenever possible */
158 public $forceintomoremenu = false;
159 /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */
160 public $showinsecondarynavigation = true;
161 /** @var bool If set to true the children of this node will be displayed within a submenu when applicable */
162 public $showchildreninsubmenu = false;
163 /** @var string tab element ID. */
164 public $tab;
165 /** @var string unique identifier. */
166 public $moremenuid;
167 /** @var bool node that have children. */
168 public $haschildren;
171 * Constructs a new navigation_node
173 * @param array|string $properties Either an array of properties or a string to use
174 * as the text for the node
176 public function __construct($properties) {
177 if (is_array($properties)) {
178 // Check the array for each property that we allow to set at construction.
179 // text - The main content for the node
180 // shorttext - A short text if required for the node
181 // icon - The icon to display for the node
182 // type - The type of the node
183 // key - The key to use to identify the node
184 // parent - A reference to the nodes parent
185 // action - The action to attribute to this node, usually a URL to link to
186 if (array_key_exists('text', $properties)) {
187 $this->text = $properties['text'];
189 if (array_key_exists('shorttext', $properties)) {
190 $this->shorttext = $properties['shorttext'];
192 if (!array_key_exists('icon', $properties)) {
193 $properties['icon'] = new pix_icon('i/navigationitem', '');
195 $this->icon = $properties['icon'];
196 if ($this->icon instanceof pix_icon) {
197 if (empty($this->icon->attributes['class'])) {
198 $this->icon->attributes['class'] = 'navicon';
199 } else {
200 $this->icon->attributes['class'] .= ' navicon';
203 if (array_key_exists('type', $properties)) {
204 $this->type = $properties['type'];
205 } else {
206 $this->type = self::TYPE_CUSTOM;
208 if (array_key_exists('key', $properties)) {
209 $this->key = $properties['key'];
211 // This needs to happen last because of the check_if_active call that occurs
212 if (array_key_exists('action', $properties)) {
213 $this->action = $properties['action'];
214 if (is_string($this->action)) {
215 $this->action = new moodle_url($this->action);
217 if (self::$autofindactive) {
218 $this->check_if_active();
221 if (array_key_exists('parent', $properties)) {
222 $this->set_parent($properties['parent']);
224 } else if (is_string($properties)) {
225 $this->text = $properties;
227 if ($this->text === null) {
228 throw new coding_exception('You must set the text for the node when you create it.');
230 // Instantiate a new navigation node collection for this nodes children
231 $this->children = new navigation_node_collection();
235 * Checks if this node is the active node.
237 * This is determined by comparing the action for the node against the
238 * defined URL for the page. A match will see this node marked as active.
240 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
241 * @return bool
243 public function check_if_active($strength=URL_MATCH_EXACT) {
244 global $FULLME, $PAGE;
245 // Set fullmeurl if it hasn't already been set
246 if (self::$fullmeurl == null) {
247 if ($PAGE->has_set_url()) {
248 self::override_active_url(new moodle_url($PAGE->url));
249 } else {
250 self::override_active_url(new moodle_url($FULLME));
254 // Compare the action of this node against the fullmeurl
255 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
256 $this->make_active();
257 return true;
259 return false;
263 * True if this nav node has siblings in the tree.
265 * @return bool
267 public function has_siblings() {
268 if (empty($this->parent) || empty($this->parent->children)) {
269 return false;
271 if ($this->parent->children instanceof navigation_node_collection) {
272 $count = $this->parent->children->count();
273 } else {
274 $count = count($this->parent->children);
276 return ($count > 1);
280 * Get a list of sibling navigation nodes at the same level as this one.
282 * @return bool|array of navigation_node
284 public function get_siblings() {
285 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
286 // the in-page links or the breadcrumb links.
287 $siblings = false;
289 if ($this->has_siblings()) {
290 $siblings = [];
291 foreach ($this->parent->children as $child) {
292 if ($child->display) {
293 $siblings[] = $child;
297 return $siblings;
301 * This sets the URL that the URL of new nodes get compared to when locating
302 * the active node.
304 * The active node is the node that matches the URL set here. By default this
305 * is either $PAGE->url or if that hasn't been set $FULLME.
307 * @param moodle_url $url The url to use for the fullmeurl.
308 * @param bool $loadadmintree use true if the URL point to administration tree
310 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
311 // Clone the URL, in case the calling script changes their URL later.
312 self::$fullmeurl = new moodle_url($url);
313 // True means we do not want AJAX loaded admin tree, required for all admin pages.
314 if ($loadadmintree) {
315 // Do not change back to false if already set.
316 self::$loadadmintree = true;
321 * Use when page is linked from the admin tree,
322 * if not used navigation could not find the page using current URL
323 * because the tree is not fully loaded.
325 public static function require_admin_tree() {
326 self::$loadadmintree = true;
330 * Creates a navigation node, ready to add it as a child using add_node
331 * function. (The created node needs to be added before you can use it.)
332 * @param string $text
333 * @param moodle_url|action_link $action
334 * @param int $type
335 * @param string $shorttext
336 * @param string|int $key
337 * @param pix_icon $icon
338 * @return navigation_node
340 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
341 $shorttext=null, $key=null, pix_icon $icon=null) {
342 if ($action && !($action instanceof moodle_url || $action instanceof action_link)) {
343 debugging(
344 "It is required that the action provided be either an action_url|moodle_url." .
345 " Please update your definition.", E_NOTICE);
347 // Properties array used when creating the new navigation node
348 $itemarray = array(
349 'text' => $text,
350 'type' => $type
352 // Set the action if one was provided
353 if ($action!==null) {
354 $itemarray['action'] = $action;
356 // Set the shorttext if one was provided
357 if ($shorttext!==null) {
358 $itemarray['shorttext'] = $shorttext;
360 // Set the icon if one was provided
361 if ($icon!==null) {
362 $itemarray['icon'] = $icon;
364 // Set the key
365 $itemarray['key'] = $key;
366 // Construct and return
367 return new navigation_node($itemarray);
371 * Adds a navigation node as a child of this node.
373 * @param string $text
374 * @param moodle_url|action_link|string $action
375 * @param int $type
376 * @param string $shorttext
377 * @param string|int $key
378 * @param pix_icon $icon
379 * @return navigation_node
381 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
382 if ($action && is_string($action)) {
383 $action = new moodle_url($action);
385 // Create child node
386 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
388 // Add the child to end and return
389 return $this->add_node($childnode);
393 * Adds a navigation node as a child of this one, given a $node object
394 * created using the create function.
395 * @param navigation_node $childnode Node to add
396 * @param string $beforekey
397 * @return navigation_node The added node
399 public function add_node(navigation_node $childnode, $beforekey=null) {
400 // First convert the nodetype for this node to a branch as it will now have children
401 if ($this->nodetype !== self::NODETYPE_BRANCH) {
402 $this->nodetype = self::NODETYPE_BRANCH;
404 // Set the parent to this node
405 $childnode->set_parent($this);
407 // Default the key to the number of children if not provided
408 if ($childnode->key === null) {
409 $childnode->key = $this->children->count();
412 // Add the child using the navigation_node_collections add method
413 $node = $this->children->add($childnode, $beforekey);
415 // If added node is a category node or the user is logged in and it's a course
416 // then mark added node as a branch (makes it expandable by AJAX)
417 $type = $childnode->type;
418 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
419 ($type === self::TYPE_SITE_ADMIN)) {
420 $node->nodetype = self::NODETYPE_BRANCH;
422 // If this node is hidden mark it's children as hidden also
423 if ($this->hidden) {
424 $node->hidden = true;
426 // Return added node (reference returned by $this->children->add()
427 return $node;
431 * Return a list of all the keys of all the child nodes.
432 * @return array the keys.
434 public function get_children_key_list() {
435 return $this->children->get_key_list();
439 * Searches for a node of the given type with the given key.
441 * This searches this node plus all of its children, and their children....
442 * If you know the node you are looking for is a child of this node then please
443 * use the get method instead.
445 * @param int|string $key The key of the node we are looking for
446 * @param int $type One of navigation_node::TYPE_*
447 * @return navigation_node|false
449 public function find($key, $type) {
450 return $this->children->find($key, $type);
454 * Walk the tree building up a list of all the flat navigation nodes.
456 * @deprecated since Moodle 4.0
457 * @param flat_navigation $nodes List of the found flat navigation nodes.
458 * @param boolean $showdivider Show a divider before the first node.
459 * @param string $label A label for the collection of navigation links.
461 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
462 debugging("Function has been deprecated with the deprecation of the flat_navigation class.");
463 if ($this->showinflatnavigation) {
464 $indent = 0;
465 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
466 $indent = 1;
468 $flat = new flat_navigation_node($this, $indent);
469 $flat->set_showdivider($showdivider, $label);
470 $nodes->add($flat);
472 foreach ($this->children as $child) {
473 $child->build_flat_navigation_list($nodes, false);
478 * Get the child of this node that has the given key + (optional) type.
480 * If you are looking for a node and want to search all children + their children
481 * then please use the find method instead.
483 * @param int|string $key The key of the node we are looking for
484 * @param int $type One of navigation_node::TYPE_*
485 * @return navigation_node|false
487 public function get($key, $type=null) {
488 return $this->children->get($key, $type);
492 * Removes this node.
494 * @return bool
496 public function remove() {
497 return $this->parent->children->remove($this->key, $this->type);
501 * Checks if this node has or could have any children
503 * @return bool Returns true if it has children or could have (by AJAX expansion)
505 public function has_children() {
506 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
510 * Marks this node as active and forces it open.
512 * Important: If you are here because you need to mark a node active to get
513 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
514 * You can use it to specify a different URL to match the active navigation node on
515 * rather than having to locate and manually mark a node active.
517 public function make_active() {
518 $this->isactive = true;
519 $this->add_class('active_tree_node');
520 $this->force_open();
521 if ($this->parent !== null) {
522 $this->parent->make_inactive();
527 * Marks a node as inactive and recusised back to the base of the tree
528 * doing the same to all parents.
530 public function make_inactive() {
531 $this->isactive = false;
532 $this->remove_class('active_tree_node');
533 if ($this->parent !== null) {
534 $this->parent->make_inactive();
539 * Forces this node to be open and at the same time forces open all
540 * parents until the root node.
542 * Recursive.
544 public function force_open() {
545 $this->forceopen = true;
546 if ($this->parent !== null) {
547 $this->parent->force_open();
552 * Adds a CSS class to this node.
554 * @param string $class
555 * @return bool
557 public function add_class($class) {
558 if (!in_array($class, $this->classes)) {
559 $this->classes[] = $class;
561 return true;
565 * Adds an HTML attribute to this node.
567 * @param string $name
568 * @param string $value
570 public function add_attribute(string $name, string $value): void {
571 $this->attributes[] = ['name' => $name, 'value' => $value];
575 * Removes a CSS class from this node.
577 * @param string $class
578 * @return bool True if the class was successfully removed.
580 public function remove_class($class) {
581 if (in_array($class, $this->classes)) {
582 $key = array_search($class,$this->classes);
583 if ($key!==false) {
584 // Remove the class' array element.
585 unset($this->classes[$key]);
586 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
587 $this->classes = array_values($this->classes);
589 return true;
592 return false;
596 * Sets the title for this node and forces Moodle to utilise it.
598 * Note that this method is named identically to the public "title" property of the class, which unfortunately confuses
599 * our Mustache renderer, because it will see the method and try and call it without any arguments (hence must be nullable)
600 * before trying to access the public property
602 * @param string|null $title
603 * @return string
605 public function title(?string $title = null): string {
606 if ($title !== null) {
607 $this->title = $title;
608 $this->forcetitle = true;
610 return (string) $this->title;
614 * Resets the page specific information on this node if it is being unserialised.
616 public function __wakeup(){
617 $this->forceopen = false;
618 $this->isactive = false;
619 $this->remove_class('active_tree_node');
623 * Checks if this node or any of its children contain the active node.
625 * Recursive.
627 * @return bool
629 public function contains_active_node() {
630 if ($this->isactive) {
631 return true;
632 } else {
633 foreach ($this->children as $child) {
634 if ($child->isactive || $child->contains_active_node()) {
635 return true;
639 return false;
643 * To better balance the admin tree, we want to group all the short top branches together.
645 * This means < 8 nodes and no subtrees.
647 * @return bool
649 public function is_short_branch() {
650 $limit = 8;
651 if ($this->children->count() >= $limit) {
652 return false;
654 foreach ($this->children as $child) {
655 if ($child->has_children()) {
656 return false;
659 return true;
663 * Finds the active node.
665 * Searches this nodes children plus all of the children for the active node
666 * and returns it if found.
668 * Recursive.
670 * @return navigation_node|false
672 public function find_active_node() {
673 if ($this->isactive) {
674 return $this;
675 } else {
676 foreach ($this->children as &$child) {
677 $outcome = $child->find_active_node();
678 if ($outcome !== false) {
679 return $outcome;
683 return false;
687 * Searches all children for the best matching active node
688 * @param int $strength The url match to be made.
689 * @return navigation_node|false
691 public function search_for_active_node($strength = URL_MATCH_BASE) {
692 if ($this->check_if_active($strength)) {
693 return $this;
694 } else {
695 foreach ($this->children as &$child) {
696 $outcome = $child->search_for_active_node($strength);
697 if ($outcome !== false) {
698 return $outcome;
702 return false;
706 * Gets the content for this node.
708 * @param bool $shorttext If true shorttext is used rather than the normal text
709 * @return string
711 public function get_content($shorttext=false) {
712 $navcontext = \context_helper::get_navigation_filter_context(null);
713 $options = !empty($navcontext) ? ['context' => $navcontext] : null;
715 if ($shorttext && $this->shorttext!==null) {
716 return format_string($this->shorttext, null, $options);
717 } else {
718 return format_string($this->text, null, $options);
723 * Gets the title to use for this node.
725 * @return string
727 public function get_title() {
728 if ($this->forcetitle || $this->action != null){
729 return $this->title;
730 } else {
731 return '';
736 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
738 * @return boolean
740 public function has_action() {
741 return !empty($this->action);
745 * Used to easily determine if the action is an internal link.
747 * @return bool
749 public function has_internal_action(): bool {
750 global $CFG;
751 if ($this->has_action()) {
752 $url = $this->action();
753 if ($this->action() instanceof \action_link) {
754 $url = $this->action()->url;
757 if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) {
758 return true;
761 return false;
765 * Used to easily determine if this link in the breadcrumbs is hidden.
767 * @return boolean
769 public function is_hidden() {
770 return $this->hidden;
774 * Gets the CSS class to add to this node to describe its type
776 * @return string
778 public function get_css_type() {
779 if (array_key_exists($this->type, $this->namedtypes)) {
780 return 'type_'.$this->namedtypes[$this->type];
782 return 'type_unknown';
786 * Finds all nodes that are expandable by AJAX
788 * @param array $expandable An array by reference to populate with expandable nodes.
790 public function find_expandable(array &$expandable) {
791 foreach ($this->children as &$child) {
792 if ($child->display && $child->has_children() && $child->children->count() == 0) {
793 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
794 $this->add_class('canexpand');
795 $child->requiresajaxloading = true;
796 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
798 $child->find_expandable($expandable);
803 * Finds all nodes of a given type (recursive)
805 * @param int $type One of navigation_node::TYPE_*
806 * @return array
808 public function find_all_of_type($type) {
809 $nodes = $this->children->type($type);
810 foreach ($this->children as &$node) {
811 $childnodes = $node->find_all_of_type($type);
812 $nodes = array_merge($nodes, $childnodes);
814 return $nodes;
818 * Removes this node if it is empty
820 public function trim_if_empty() {
821 if ($this->children->count() == 0) {
822 $this->remove();
827 * Creates a tab representation of this nodes children that can be used
828 * with print_tabs to produce the tabs on a page.
830 * call_user_func_array('print_tabs', $node->get_tabs_array());
832 * @param array $inactive
833 * @param bool $return
834 * @return array Array (tabs, selected, inactive, activated, return)
836 public function get_tabs_array(array $inactive=array(), $return=false) {
837 $tabs = array();
838 $rows = array();
839 $selected = null;
840 $activated = array();
841 foreach ($this->children as $node) {
842 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
843 if ($node->contains_active_node()) {
844 if ($node->children->count() > 0) {
845 $activated[] = $node->key;
846 foreach ($node->children as $child) {
847 if ($child->contains_active_node()) {
848 $selected = $child->key;
850 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
852 } else {
853 $selected = $node->key;
857 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
861 * Sets the parent for this node and if this node is active ensures that the tree is properly
862 * adjusted as well.
864 * @param navigation_node $parent
866 public function set_parent(navigation_node $parent) {
867 // Set the parent (thats the easy part)
868 $this->parent = $parent;
869 // Check if this node is active (this is checked during construction)
870 if ($this->isactive) {
871 // Force all of the parent nodes open so you can see this node
872 $this->parent->force_open();
873 // Make all parents inactive so that its clear where we are.
874 $this->parent->make_inactive();
879 * Hides the node and any children it has.
881 * @since Moodle 2.5
882 * @param array $typestohide Optional. An array of node types that should be hidden.
883 * If null all nodes will be hidden.
884 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
885 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
887 public function hide(array $typestohide = null) {
888 if ($typestohide === null || in_array($this->type, $typestohide)) {
889 $this->display = false;
890 if ($this->has_children()) {
891 foreach ($this->children as $child) {
892 $child->hide($typestohide);
899 * Get the action url for this navigation node.
900 * Called from templates.
902 * @since Moodle 3.2
904 public function action() {
905 if ($this->action instanceof moodle_url) {
906 return $this->action;
907 } else if ($this->action instanceof action_link) {
908 return $this->action->url;
910 return $this->action;
914 * Return an array consisting of the additional attributes for the action url.
916 * @return array Formatted array to parse in a template
918 public function actionattributes() {
919 if ($this->action instanceof action_link) {
920 return array_map(function($key, $value) {
921 return [
922 'name' => $key,
923 'value' => $value
925 }, array_keys($this->action->attributes), $this->action->attributes);
928 return [];
932 * Check whether the node's action is of type action_link.
934 * @return bool
936 public function is_action_link() {
937 return $this->action instanceof action_link;
941 * Return an array consisting of the actions for the action link.
943 * @return array Formatted array to parse in a template
945 public function action_link_actions() {
946 global $PAGE;
948 if (!$this->is_action_link()) {
949 return [];
952 $actionid = $this->action->attributes['id'];
953 $actionsdata = array_map(function($action) use ($PAGE, $actionid) {
954 $data = $action->export_for_template($PAGE->get_renderer('core'));
955 $data->id = $actionid;
956 return $data;
957 }, !empty($this->action->actions) ? $this->action->actions : []);
959 return ['actions' => $actionsdata];
963 * Sets whether the node and its children should be added into a "more" menu whenever possible.
965 * @param bool $forceintomoremenu
967 public function set_force_into_more_menu(bool $forceintomoremenu = false) {
968 $this->forceintomoremenu = $forceintomoremenu;
969 foreach ($this->children as $child) {
970 $child->set_force_into_more_menu($forceintomoremenu);
975 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable.
977 * @param bool $show
979 public function set_show_in_secondary_navigation(bool $show = true) {
980 $this->showinsecondarynavigation = $show;
981 foreach ($this->children as $child) {
982 $child->set_show_in_secondary_navigation($show);
987 * Add the menu item to handle locking and unlocking of a conext.
989 * @param \navigation_node $node Node to add
990 * @param \context $context The context to be locked
992 protected function add_context_locking_node(\navigation_node $node, \context $context) {
993 global $CFG;
994 // Manage context locking.
995 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
996 $parentcontext = $context->get_parent_context();
997 if (empty($parentcontext) || !$parentcontext->locked) {
998 if ($context->locked) {
999 $lockicon = 'i/unlock';
1000 $lockstring = get_string('managecontextunlock', 'admin');
1001 } else {
1002 $lockicon = 'i/lock';
1003 $lockstring = get_string('managecontextlock', 'admin');
1005 $node->add(
1006 $lockstring,
1007 new moodle_url(
1008 '/admin/lock.php',
1010 'id' => $context->id,
1013 self::TYPE_SETTING,
1014 null,
1015 'contextlocking',
1016 new pix_icon($lockicon, '')
1025 * Navigation node collection
1027 * This class is responsible for managing a collection of navigation nodes.
1028 * It is required because a node's unique identifier is a combination of both its
1029 * key and its type.
1031 * Originally an array was used with a string key that was a combination of the two
1032 * however it was decided that a better solution would be to use a class that
1033 * implements the standard IteratorAggregate interface.
1035 * @package core
1036 * @category navigation
1037 * @copyright 2010 Sam Hemelryk
1038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1040 class navigation_node_collection implements IteratorAggregate, Countable {
1042 * A multidimensional array to where the first key is the type and the second
1043 * key is the nodes key.
1044 * @var array
1046 protected $collection = array();
1048 * An array that contains references to nodes in the same order they were added.
1049 * This is maintained as a progressive array.
1050 * @var array
1052 protected $orderedcollection = array();
1054 * A reference to the last node that was added to the collection
1055 * @var navigation_node
1057 protected $last = null;
1059 * The total number of items added to this array.
1060 * @var int
1062 protected $count = 0;
1065 * Label for collection of nodes.
1066 * @var string
1068 protected $collectionlabel = '';
1071 * Adds a navigation node to the collection
1073 * @param navigation_node $node Node to add
1074 * @param string $beforekey If specified, adds before a node with this key,
1075 * otherwise adds at end
1076 * @return navigation_node Added node
1078 public function add(navigation_node $node, $beforekey=null) {
1079 global $CFG;
1080 $key = $node->key;
1081 $type = $node->type;
1083 // First check we have a 2nd dimension for this type
1084 if (!array_key_exists($type, $this->orderedcollection)) {
1085 $this->orderedcollection[$type] = array();
1087 // Check for a collision and report if debugging is turned on
1088 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
1089 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
1092 // Find the key to add before
1093 $newindex = $this->count;
1094 $last = true;
1095 if ($beforekey !== null) {
1096 foreach ($this->collection as $index => $othernode) {
1097 if ($othernode->key === $beforekey) {
1098 $newindex = $index;
1099 $last = false;
1100 break;
1103 if ($newindex === $this->count) {
1104 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
1105 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
1109 // Add the node to the appropriate place in the by-type structure (which
1110 // is not ordered, despite the variable name)
1111 $this->orderedcollection[$type][$key] = $node;
1112 if (!$last) {
1113 // Update existing references in the ordered collection (which is the
1114 // one that isn't called 'ordered') to shuffle them along if required
1115 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
1116 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
1119 // Add a reference to the node to the progressive collection.
1120 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
1121 // Update the last property to a reference to this new node.
1122 $this->last = $this->orderedcollection[$type][$key];
1124 // Reorder the array by index if needed
1125 if (!$last) {
1126 ksort($this->collection);
1128 $this->count++;
1129 // Return the reference to the now added node
1130 return $node;
1134 * Return a list of all the keys of all the nodes.
1135 * @return array the keys.
1137 public function get_key_list() {
1138 $keys = array();
1139 foreach ($this->collection as $node) {
1140 $keys[] = $node->key;
1142 return $keys;
1146 * Set a label for this collection.
1148 * @param string $label
1150 public function set_collectionlabel($label) {
1151 $this->collectionlabel = $label;
1155 * Return a label for this collection.
1157 * @return string
1159 public function get_collectionlabel() {
1160 return $this->collectionlabel;
1164 * Fetches a node from this collection.
1166 * @param string|int $key The key of the node we want to find.
1167 * @param int $type One of navigation_node::TYPE_*.
1168 * @return navigation_node|null
1170 public function get($key, $type=null) {
1171 if ($type !== null) {
1172 // If the type is known then we can simply check and fetch
1173 if (!empty($this->orderedcollection[$type][$key])) {
1174 return $this->orderedcollection[$type][$key];
1176 } else {
1177 // Because we don't know the type we look in the progressive array
1178 foreach ($this->collection as $node) {
1179 if ($node->key === $key) {
1180 return $node;
1184 return false;
1188 * Searches for a node with matching key and type.
1190 * This function searches both the nodes in this collection and all of
1191 * the nodes in each collection belonging to the nodes in this collection.
1193 * Recursive.
1195 * @param string|int $key The key of the node we want to find.
1196 * @param int $type One of navigation_node::TYPE_*.
1197 * @return navigation_node|false
1199 public function find($key, $type=null) {
1200 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1201 return $this->orderedcollection[$type][$key];
1202 } else {
1203 $nodes = $this->getIterator();
1204 // Search immediate children first
1205 foreach ($nodes as &$node) {
1206 if ($node->key === $key && ($type === null || $type === $node->type)) {
1207 return $node;
1210 // Now search each childs children
1211 foreach ($nodes as &$node) {
1212 $result = $node->children->find($key, $type);
1213 if ($result !== false) {
1214 return $result;
1218 return false;
1222 * Fetches the last node that was added to this collection
1224 * @return navigation_node
1226 public function last() {
1227 return $this->last;
1231 * Fetches all nodes of a given type from this collection
1233 * @param string|int $type node type being searched for.
1234 * @return array ordered collection
1236 public function type($type) {
1237 if (!array_key_exists($type, $this->orderedcollection)) {
1238 $this->orderedcollection[$type] = array();
1240 return $this->orderedcollection[$type];
1243 * Removes the node with the given key and type from the collection
1245 * @param string|int $key The key of the node we want to find.
1246 * @param int $type
1247 * @return bool
1249 public function remove($key, $type=null) {
1250 $child = $this->get($key, $type);
1251 if ($child !== false) {
1252 foreach ($this->collection as $colkey => $node) {
1253 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1254 unset($this->collection[$colkey]);
1255 $this->collection = array_values($this->collection);
1256 break;
1259 unset($this->orderedcollection[$child->type][$child->key]);
1260 $this->count--;
1261 return true;
1263 return false;
1267 * Gets the number of nodes in this collection
1269 * This option uses an internal count rather than counting the actual options to avoid
1270 * a performance hit through the count function.
1272 * @return int
1274 public function count(): int {
1275 return $this->count;
1278 * Gets an array iterator for the collection.
1280 * This is required by the IteratorAggregator interface and is used by routines
1281 * such as the foreach loop.
1283 * @return ArrayIterator
1285 public function getIterator(): Traversable {
1286 return new ArrayIterator($this->collection);
1291 * The global navigation class used for... the global navigation
1293 * This class is used by PAGE to store the global navigation for the site
1294 * and is then used by the settings nav and navbar to save on processing and DB calls
1296 * See
1297 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1298 * {@link lib/ajax/getnavbranch.php} Called by ajax
1300 * @package core
1301 * @category navigation
1302 * @copyright 2009 Sam Hemelryk
1303 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1305 class global_navigation extends navigation_node {
1306 /** @var moodle_page The Moodle page this navigation object belongs to. */
1307 protected $page;
1308 /** @var bool switch to let us know if the navigation object is initialised*/
1309 protected $initialised = false;
1310 /** @var array An array of course information */
1311 protected $mycourses = array();
1312 /** @var navigation_node[] An array for containing root navigation nodes */
1313 protected $rootnodes = array();
1314 /** @var bool A switch for whether to show empty sections in the navigation */
1315 protected $showemptysections = true;
1316 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1317 protected $showcategories = null;
1318 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1319 protected $showmycategories = null;
1320 /** @var array An array of stdClasses for users that the navigation is extended for */
1321 protected $extendforuser = array();
1322 /** @var navigation_cache */
1323 protected $cache;
1324 /** @var array An array of course ids that are present in the navigation */
1325 protected $addedcourses = array();
1326 /** @var bool */
1327 protected $allcategoriesloaded = false;
1328 /** @var array An array of category ids that are included in the navigation */
1329 protected $addedcategories = array();
1330 /** @var int expansion limit */
1331 protected $expansionlimit = 0;
1332 /** @var int userid to allow parent to see child's profile page navigation */
1333 protected $useridtouseforparentchecks = 0;
1334 /** @var cache_session A cache that stores information on expanded courses */
1335 protected $cacheexpandcourse = null;
1337 /** Used when loading categories to load all top level categories [parent = 0] **/
1338 const LOAD_ROOT_CATEGORIES = 0;
1339 /** Used when loading categories to load all categories **/
1340 const LOAD_ALL_CATEGORIES = -1;
1343 * Constructs a new global navigation
1345 * @param moodle_page $page The page this navigation object belongs to
1347 public function __construct(moodle_page $page) {
1348 global $CFG, $SITE, $USER;
1350 if (during_initial_install()) {
1351 return;
1354 $homepage = get_home_page();
1355 if ($homepage == HOMEPAGE_SITE) {
1356 // We are using the site home for the root element.
1357 $properties = array(
1358 'key' => 'home',
1359 'type' => navigation_node::TYPE_SYSTEM,
1360 'text' => get_string('home'),
1361 'action' => new moodle_url('/'),
1362 'icon' => new pix_icon('i/home', '')
1364 } else if ($homepage == HOMEPAGE_MYCOURSES) {
1365 // We are using the user's course summary page for the root element.
1366 $properties = array(
1367 'key' => 'mycourses',
1368 'type' => navigation_node::TYPE_SYSTEM,
1369 'text' => get_string('mycourses'),
1370 'action' => new moodle_url('/my/courses.php'),
1371 'icon' => new pix_icon('i/course', '')
1373 } else {
1374 // We are using the users my moodle for the root element.
1375 $properties = array(
1376 'key' => 'myhome',
1377 'type' => navigation_node::TYPE_SYSTEM,
1378 'text' => get_string('myhome'),
1379 'action' => new moodle_url('/my/'),
1380 'icon' => new pix_icon('i/dashboard', '')
1384 // Use the parents constructor.... good good reuse
1385 parent::__construct($properties);
1386 $this->showinflatnavigation = true;
1388 // Initalise and set defaults
1389 $this->page = $page;
1390 $this->forceopen = true;
1391 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1395 * Mutator to set userid to allow parent to see child's profile
1396 * page navigation. See MDL-25805 for initial issue. Linked to it
1397 * is an issue explaining why this is a REALLY UGLY HACK thats not
1398 * for you to use!
1400 * @param int $userid userid of profile page that parent wants to navigate around.
1402 public function set_userid_for_parent_checks($userid) {
1403 $this->useridtouseforparentchecks = $userid;
1408 * Initialises the navigation object.
1410 * This causes the navigation object to look at the current state of the page
1411 * that it is associated with and then load the appropriate content.
1413 * This should only occur the first time that the navigation structure is utilised
1414 * which will normally be either when the navbar is called to be displayed or
1415 * when a block makes use of it.
1417 * @return bool
1419 public function initialise() {
1420 global $CFG, $SITE, $USER;
1421 // Check if it has already been initialised
1422 if ($this->initialised || during_initial_install()) {
1423 return true;
1425 $this->initialised = true;
1427 // Set up the five base root nodes. These are nodes where we will put our
1428 // content and are as follows:
1429 // site: Navigation for the front page.
1430 // myprofile: User profile information goes here.
1431 // currentcourse: The course being currently viewed.
1432 // mycourses: The users courses get added here.
1433 // courses: Additional courses are added here.
1434 // users: Other users information loaded here.
1435 $this->rootnodes = array();
1436 $defaulthomepage = get_home_page();
1437 if ($defaulthomepage == HOMEPAGE_SITE) {
1438 // The home element should be my moodle because the root element is the site
1439 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1440 if (!empty($CFG->enabledashboard)) {
1441 // Only add dashboard to home if it's enabled.
1442 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1443 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
1444 $this->rootnodes['home']->showinflatnavigation = true;
1447 } else {
1448 // The home element should be the site because the root node is my moodle
1449 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1450 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1451 $this->rootnodes['home']->showinflatnavigation = true;
1452 if (!empty($CFG->defaulthomepage) &&
1453 ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) {
1454 // We need to stop automatic redirection
1455 $this->rootnodes['home']->action->param('redirect', '0');
1458 $this->rootnodes['site'] = $this->add_course($SITE);
1459 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1460 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1461 $this->rootnodes['mycourses'] = $this->add(
1462 get_string('mycourses'),
1463 new moodle_url('/my/courses.php'),
1464 self::TYPE_ROOTNODE,
1465 null,
1466 'mycourses',
1467 new pix_icon('i/course', '')
1469 // We do not need to show this node in the breadcrumbs if the default homepage is mycourses.
1470 // It will be automatically handled by the breadcrumb generator.
1471 if ($defaulthomepage == HOMEPAGE_MYCOURSES) {
1472 $this->rootnodes['mycourses']->mainnavonly = true;
1475 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1476 if (!core_course_category::user_top()) {
1477 $this->rootnodes['courses']->hide();
1479 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1481 // We always load the frontpage course to ensure it is available without
1482 // JavaScript enabled.
1483 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1484 $this->load_course_sections($SITE, $this->rootnodes['site']);
1486 $course = $this->page->course;
1487 $this->load_courses_enrolled();
1489 // $issite gets set to true if the current pages course is the sites frontpage course
1490 $issite = ($this->page->course->id == $SITE->id);
1492 // Determine if the user is enrolled in any course.
1493 $enrolledinanycourse = enrol_user_sees_own_courses();
1495 $this->rootnodes['currentcourse']->mainnavonly = true;
1496 if ($enrolledinanycourse) {
1497 $this->rootnodes['mycourses']->isexpandable = true;
1498 $this->rootnodes['mycourses']->showinflatnavigation = true;
1499 if ($CFG->navshowallcourses) {
1500 // When we show all courses we need to show both the my courses and the regular courses branch.
1501 $this->rootnodes['courses']->isexpandable = true;
1503 } else {
1504 $this->rootnodes['courses']->isexpandable = true;
1506 $this->rootnodes['mycourses']->forceopen = true;
1508 $canviewcourseprofile = true;
1510 // Next load context specific content into the navigation
1511 switch ($this->page->context->contextlevel) {
1512 case CONTEXT_SYSTEM :
1513 // Nothing left to do here I feel.
1514 break;
1515 case CONTEXT_COURSECAT :
1516 // This is essential, we must load categories.
1517 $this->load_all_categories($this->page->context->instanceid, true);
1518 break;
1519 case CONTEXT_BLOCK :
1520 case CONTEXT_COURSE :
1521 if ($issite) {
1522 // Nothing left to do here.
1523 break;
1526 // Load the course associated with the current page into the navigation.
1527 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1528 // If the course wasn't added then don't try going any further.
1529 if (!$coursenode) {
1530 $canviewcourseprofile = false;
1531 break;
1534 // If the user is not enrolled then we only want to show the
1535 // course node and not populate it.
1537 // Not enrolled, can't view, and hasn't switched roles
1538 if (!can_access_course($course, null, '', true)) {
1539 if ($coursenode->isexpandable === true) {
1540 // Obviously the situation has changed, update the cache and adjust the node.
1541 // This occurs if the user access to a course has been revoked (one way or another) after
1542 // initially logging in for this session.
1543 $this->get_expand_course_cache()->set($course->id, 1);
1544 $coursenode->isexpandable = true;
1545 $coursenode->nodetype = self::NODETYPE_BRANCH;
1547 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1548 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1549 if (!$this->current_user_is_parent_role()) {
1550 $coursenode->make_active();
1551 $canviewcourseprofile = false;
1552 break;
1554 } else if ($coursenode->isexpandable === false) {
1555 // Obviously the situation has changed, update the cache and adjust the node.
1556 // This occurs if the user has been granted access to a course (one way or another) after initially
1557 // logging in for this session.
1558 $this->get_expand_course_cache()->set($course->id, 1);
1559 $coursenode->isexpandable = true;
1560 $coursenode->nodetype = self::NODETYPE_BRANCH;
1563 // Add the essentials such as reports etc...
1564 $this->add_course_essentials($coursenode, $course);
1565 // Extend course navigation with it's sections/activities
1566 $this->load_course_sections($course, $coursenode);
1567 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1568 $coursenode->make_active();
1571 break;
1572 case CONTEXT_MODULE :
1573 if ($issite) {
1574 // If this is the site course then most information will have
1575 // already been loaded.
1576 // However we need to check if there is more content that can
1577 // yet be loaded for the specific module instance.
1578 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1579 if ($activitynode) {
1580 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1582 break;
1585 $course = $this->page->course;
1586 $cm = $this->page->cm;
1588 // Load the course associated with the page into the navigation
1589 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1591 // If the course wasn't added then don't try going any further.
1592 if (!$coursenode) {
1593 $canviewcourseprofile = false;
1594 break;
1597 // If the user is not enrolled then we only want to show the
1598 // course node and not populate it.
1599 if (!can_access_course($course, null, '', true)) {
1600 $coursenode->make_active();
1601 $canviewcourseprofile = false;
1602 break;
1605 $this->add_course_essentials($coursenode, $course);
1607 // Load the course sections into the page
1608 $this->load_course_sections($course, $coursenode, null, $cm);
1609 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1610 if (!empty($activity)) {
1611 // Finally load the cm specific navigaton information
1612 $this->load_activity($cm, $course, $activity);
1613 // Check if we have an active ndoe
1614 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1615 // And make the activity node active.
1616 $activity->make_active();
1619 break;
1620 case CONTEXT_USER :
1621 if ($issite) {
1622 // The users profile information etc is already loaded
1623 // for the front page.
1624 break;
1626 $course = $this->page->course;
1627 // Load the course associated with the user into the navigation
1628 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1630 // If the course wasn't added then don't try going any further.
1631 if (!$coursenode) {
1632 $canviewcourseprofile = false;
1633 break;
1636 // If the user is not enrolled then we only want to show the
1637 // course node and not populate it.
1638 if (!can_access_course($course, null, '', true)) {
1639 $coursenode->make_active();
1640 $canviewcourseprofile = false;
1641 break;
1643 $this->add_course_essentials($coursenode, $course);
1644 $this->load_course_sections($course, $coursenode);
1645 break;
1648 // Load for the current user
1649 $this->load_for_user();
1650 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1651 $this->load_for_user(null, true);
1653 // Load each extending user into the navigation.
1654 foreach ($this->extendforuser as $user) {
1655 if ($user->id != $USER->id) {
1656 $this->load_for_user($user);
1660 // Give the local plugins a chance to include some navigation if they want.
1661 $this->load_local_plugin_navigation();
1663 // Remove any empty root nodes
1664 foreach ($this->rootnodes as $node) {
1665 // Dont remove the home node
1666 /** @var navigation_node $node */
1667 if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) {
1668 $node->remove();
1672 if (!$this->contains_active_node()) {
1673 $this->search_for_active_node();
1676 // If the user is not logged in modify the navigation structure.
1677 if (!isloggedin()) {
1678 $activities = clone($this->rootnodes['site']->children);
1679 $this->rootnodes['site']->remove();
1680 $children = clone($this->children);
1681 $this->children = new navigation_node_collection();
1682 foreach ($activities as $child) {
1683 $this->children->add($child);
1685 foreach ($children as $child) {
1686 $this->children->add($child);
1689 return true;
1693 * This function gives local plugins an opportunity to modify navigation.
1695 protected function load_local_plugin_navigation() {
1696 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1697 $function($this);
1702 * Returns true if the current user is a parent of the user being currently viewed.
1704 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1705 * other user being viewed this function returns false.
1706 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1708 * @since Moodle 2.4
1709 * @return bool
1711 protected function current_user_is_parent_role() {
1712 global $USER, $DB;
1713 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1714 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1715 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1716 return false;
1718 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1719 return true;
1722 return false;
1726 * Returns true if courses should be shown within categories on the navigation.
1728 * @param bool $ismycourse Set to true if you are calculating this for a course.
1729 * @return bool
1731 protected function show_categories($ismycourse = false) {
1732 global $CFG, $DB;
1733 if ($ismycourse) {
1734 return $this->show_my_categories();
1736 if ($this->showcategories === null) {
1737 $show = false;
1738 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1739 $show = true;
1740 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1741 $show = true;
1743 $this->showcategories = $show;
1745 return $this->showcategories;
1749 * Returns true if we should show categories in the My Courses branch.
1750 * @return bool
1752 protected function show_my_categories() {
1753 global $CFG;
1754 if ($this->showmycategories === null) {
1755 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
1757 return $this->showmycategories;
1761 * Loads the courses in Moodle into the navigation.
1763 * @global moodle_database $DB
1764 * @param string|array $categoryids An array containing categories to load courses
1765 * for, OR null to load courses for all categories.
1766 * @return array An array of navigation_nodes one for each course
1768 protected function load_all_courses($categoryids = null) {
1769 global $CFG, $DB, $SITE;
1771 // Work out the limit of courses.
1772 $limit = 20;
1773 if (!empty($CFG->navcourselimit)) {
1774 $limit = $CFG->navcourselimit;
1777 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1779 // If we are going to show all courses AND we are showing categories then
1780 // to save us repeated DB calls load all of the categories now
1781 if ($this->show_categories()) {
1782 $this->load_all_categories($toload);
1785 // Will be the return of our efforts
1786 $coursenodes = array();
1788 // Check if we need to show categories.
1789 if ($this->show_categories()) {
1790 // Hmmm we need to show categories... this is going to be painful.
1791 // We now need to fetch up to $limit courses for each category to
1792 // be displayed.
1793 if ($categoryids !== null) {
1794 if (!is_array($categoryids)) {
1795 $categoryids = array($categoryids);
1797 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1798 $categorywhere = 'WHERE cc.id '.$categorywhere;
1799 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1800 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1801 $categoryparams = array();
1802 } else {
1803 $categorywhere = '';
1804 $categoryparams = array();
1807 // First up we are going to get the categories that we are going to
1808 // need so that we can determine how best to load the courses from them.
1809 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1810 FROM {course_categories} cc
1811 LEFT JOIN {course} c ON c.category = cc.id
1812 {$categorywhere}
1813 GROUP BY cc.id";
1814 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1815 $fullfetch = array();
1816 $partfetch = array();
1817 foreach ($categories as $category) {
1818 if (!$this->can_add_more_courses_to_category($category->id)) {
1819 continue;
1821 if ($category->coursecount > $limit * 5) {
1822 $partfetch[] = $category->id;
1823 } else if ($category->coursecount > 0) {
1824 $fullfetch[] = $category->id;
1827 $categories->close();
1829 if (count($fullfetch)) {
1830 // First up fetch all of the courses in categories where we know that we are going to
1831 // need the majority of courses.
1832 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1833 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1834 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1835 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1836 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1837 FROM {course} c
1838 $ccjoin
1839 WHERE c.category {$categoryids}
1840 ORDER BY c.sortorder ASC";
1841 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1842 foreach ($coursesrs as $course) {
1843 if ($course->id == $SITE->id) {
1844 // This should not be necessary, frontpage is not in any category.
1845 continue;
1847 if (array_key_exists($course->id, $this->addedcourses)) {
1848 // It is probably better to not include the already loaded courses
1849 // directly in SQL because inequalities may confuse query optimisers
1850 // and may interfere with query caching.
1851 continue;
1853 if (!$this->can_add_more_courses_to_category($course->category)) {
1854 continue;
1856 context_helper::preload_from_record($course);
1857 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1858 continue;
1860 $coursenodes[$course->id] = $this->add_course($course);
1862 $coursesrs->close();
1865 if (count($partfetch)) {
1866 // Next we will work our way through the categories where we will likely only need a small
1867 // proportion of the courses.
1868 foreach ($partfetch as $categoryid) {
1869 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1870 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1871 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1872 FROM {course} c
1873 $ccjoin
1874 WHERE c.category = :categoryid
1875 ORDER BY c.sortorder ASC";
1876 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1877 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1878 foreach ($coursesrs as $course) {
1879 if ($course->id == $SITE->id) {
1880 // This should not be necessary, frontpage is not in any category.
1881 continue;
1883 if (array_key_exists($course->id, $this->addedcourses)) {
1884 // It is probably better to not include the already loaded courses
1885 // directly in SQL because inequalities may confuse query optimisers
1886 // and may interfere with query caching.
1887 // This also helps to respect expected $limit on repeated executions.
1888 continue;
1890 if (!$this->can_add_more_courses_to_category($course->category)) {
1891 break;
1893 context_helper::preload_from_record($course);
1894 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1895 continue;
1897 $coursenodes[$course->id] = $this->add_course($course);
1899 $coursesrs->close();
1902 } else {
1903 // Prepare the SQL to load the courses and their contexts
1904 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1905 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1906 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1907 $courseparams['contextlevel'] = CONTEXT_COURSE;
1908 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1909 FROM {course} c
1910 $ccjoin
1911 WHERE c.id {$courseids}
1912 ORDER BY c.sortorder ASC";
1913 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1914 foreach ($coursesrs as $course) {
1915 if ($course->id == $SITE->id) {
1916 // frotpage is not wanted here
1917 continue;
1919 if ($this->page->course && ($this->page->course->id == $course->id)) {
1920 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1921 continue;
1923 context_helper::preload_from_record($course);
1924 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1925 continue;
1927 $coursenodes[$course->id] = $this->add_course($course);
1928 if (count($coursenodes) >= $limit) {
1929 break;
1932 $coursesrs->close();
1935 return $coursenodes;
1939 * Returns true if more courses can be added to the provided category.
1941 * @param int|navigation_node|stdClass $category
1942 * @return bool
1944 protected function can_add_more_courses_to_category($category) {
1945 global $CFG;
1946 $limit = 20;
1947 if (!empty($CFG->navcourselimit)) {
1948 $limit = (int)$CFG->navcourselimit;
1950 if (is_numeric($category)) {
1951 if (!array_key_exists($category, $this->addedcategories)) {
1952 return true;
1954 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1955 } else if ($category instanceof navigation_node) {
1956 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1957 return false;
1959 $coursecount = count($category->children->type(self::TYPE_COURSE));
1960 } else if (is_object($category) && property_exists($category,'id')) {
1961 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1963 return ($coursecount <= $limit);
1967 * Loads all categories (top level or if an id is specified for that category)
1969 * @param int $categoryid The category id to load or null/0 to load all base level categories
1970 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1971 * as the requested category and any parent categories.
1972 * @return navigation_node|void returns a navigation node if a category has been loaded.
1974 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1975 global $CFG, $DB;
1977 // Check if this category has already been loaded
1978 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1979 return true;
1982 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1983 $sqlselect = "SELECT cc.*, $catcontextsql
1984 FROM {course_categories} cc
1985 JOIN {context} ctx ON cc.id = ctx.instanceid";
1986 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1987 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1988 $params = array();
1990 $categoriestoload = array();
1991 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1992 // We are going to load all categories regardless... prepare to fire
1993 // on the database server!
1994 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1995 // We are going to load all of the first level categories (categories without parents)
1996 $sqlwhere .= " AND cc.parent = 0";
1997 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1998 // The category itself has been loaded already so we just need to ensure its subcategories
1999 // have been loaded
2000 $addedcategories = $this->addedcategories;
2001 unset($addedcategories[$categoryid]);
2002 if (count($addedcategories) > 0) {
2003 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
2004 if ($showbasecategories) {
2005 // We need to include categories with parent = 0 as well
2006 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
2007 } else {
2008 // All we need is categories that match the parent
2009 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
2012 $params['categoryid'] = $categoryid;
2013 } else {
2014 // This category hasn't been loaded yet so we need to fetch it, work out its category path
2015 // and load this category plus all its parents and subcategories
2016 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
2017 $categoriestoload = explode('/', trim($category->path, '/'));
2018 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
2019 // We are going to use select twice so double the params
2020 $params = array_merge($params, $params);
2021 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
2022 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
2025 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
2026 $categories = array();
2027 foreach ($categoriesrs as $category) {
2028 // Preload the context.. we'll need it when adding the category in order
2029 // to format the category name.
2030 context_helper::preload_from_record($category);
2031 if (array_key_exists($category->id, $this->addedcategories)) {
2032 // Do nothing, its already been added.
2033 } else if ($category->parent == '0') {
2034 // This is a root category lets add it immediately
2035 $this->add_category($category, $this->rootnodes['courses']);
2036 } else if (array_key_exists($category->parent, $this->addedcategories)) {
2037 // This categories parent has already been added we can add this immediately
2038 $this->add_category($category, $this->addedcategories[$category->parent]);
2039 } else {
2040 $categories[] = $category;
2043 $categoriesrs->close();
2045 // Now we have an array of categories we need to add them to the navigation.
2046 while (!empty($categories)) {
2047 $category = reset($categories);
2048 if (array_key_exists($category->id, $this->addedcategories)) {
2049 // Do nothing
2050 } else if ($category->parent == '0') {
2051 $this->add_category($category, $this->rootnodes['courses']);
2052 } else if (array_key_exists($category->parent, $this->addedcategories)) {
2053 $this->add_category($category, $this->addedcategories[$category->parent]);
2054 } else {
2055 // This category isn't in the navigation and niether is it's parent (yet).
2056 // We need to go through the category path and add all of its components in order.
2057 $path = explode('/', trim($category->path, '/'));
2058 foreach ($path as $catid) {
2059 if (!array_key_exists($catid, $this->addedcategories)) {
2060 // This category isn't in the navigation yet so add it.
2061 $subcategory = $categories[$catid];
2062 if ($subcategory->parent == '0') {
2063 // Yay we have a root category - this likely means we will now be able
2064 // to add categories without problems.
2065 $this->add_category($subcategory, $this->rootnodes['courses']);
2066 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
2067 // The parent is in the category (as we'd expect) so add it now.
2068 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
2069 // Remove the category from the categories array.
2070 unset($categories[$catid]);
2071 } else {
2072 // We should never ever arrive here - if we have then there is a bigger
2073 // problem at hand.
2074 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
2079 // Remove the category from the categories array now that we know it has been added.
2080 unset($categories[$category->id]);
2082 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
2083 $this->allcategoriesloaded = true;
2085 // Check if there are any categories to load.
2086 if (count($categoriestoload) > 0) {
2087 $readytoloadcourses = array();
2088 foreach ($categoriestoload as $category) {
2089 if ($this->can_add_more_courses_to_category($category)) {
2090 $readytoloadcourses[] = $category;
2093 if (count($readytoloadcourses)) {
2094 $this->load_all_courses($readytoloadcourses);
2098 // Look for all categories which have been loaded
2099 if (!empty($this->addedcategories)) {
2100 $categoryids = array();
2101 foreach ($this->addedcategories as $category) {
2102 if ($this->can_add_more_courses_to_category($category)) {
2103 $categoryids[] = $category->key;
2106 if ($categoryids) {
2107 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
2108 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
2109 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
2110 FROM {course_categories} cc
2111 JOIN {course} c ON c.category = cc.id
2112 WHERE cc.id {$categoriessql}
2113 GROUP BY cc.id
2114 HAVING COUNT(c.id) > :limit";
2115 $excessivecategories = $DB->get_records_sql($sql, $params);
2116 foreach ($categories as &$category) {
2117 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
2118 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
2119 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
2127 * Adds a structured category to the navigation in the correct order/place
2129 * @param stdClass $category category to be added in navigation.
2130 * @param navigation_node $parent parent navigation node
2131 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2132 * @return void.
2134 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
2135 global $CFG;
2136 if (array_key_exists($category->id, $this->addedcategories)) {
2137 return;
2139 $canview = core_course_category::can_view_category($category);
2140 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
2141 $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id));
2142 $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) :
2143 get_string('categoryhidden');
2144 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
2145 if (!$canview) {
2146 // User does not have required capabilities to view category.
2147 $categorynode->display = false;
2148 } else if (!$category->visible) {
2149 // Category is hidden but user has capability to view hidden categories.
2150 $categorynode->hidden = true;
2152 $this->addedcategories[$category->id] = $categorynode;
2156 * Loads the given course into the navigation
2158 * @param stdClass $course
2159 * @return navigation_node
2161 protected function load_course(stdClass $course) {
2162 global $SITE;
2163 if ($course->id == $SITE->id) {
2164 // This is always loaded during initialisation
2165 return $this->rootnodes['site'];
2166 } else if (array_key_exists($course->id, $this->addedcourses)) {
2167 // The course has already been loaded so return a reference
2168 return $this->addedcourses[$course->id];
2169 } else {
2170 // Add the course
2171 return $this->add_course($course);
2176 * Loads all of the courses section into the navigation.
2178 * This function calls method from current course format, see
2179 * core_courseformat\base::extend_course_navigation()
2180 * If course module ($cm) is specified but course format failed to create the node,
2181 * the activity node is created anyway.
2183 * By default course formats call the method global_navigation::load_generic_course_sections()
2185 * @param stdClass $course Database record for the course
2186 * @param navigation_node $coursenode The course node within the navigation
2187 * @param null|int $sectionnum If specified load the contents of section with this relative number
2188 * @param null|cm_info $cm If specified make sure that activity node is created (either
2189 * in containg section or by calling load_stealth_activity() )
2191 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2192 global $CFG, $SITE;
2193 require_once($CFG->dirroot.'/course/lib.php');
2194 if (isset($cm->sectionnum)) {
2195 $sectionnum = $cm->sectionnum;
2197 if ($sectionnum !== null) {
2198 $this->includesectionnum = $sectionnum;
2200 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2201 if (isset($cm->id)) {
2202 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2203 if (empty($activity)) {
2204 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2210 * Generates an array of sections and an array of activities for the given course.
2212 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2214 * @param stdClass $course
2215 * @return array Array($sections, $activities)
2217 protected function generate_sections_and_activities(stdClass $course) {
2218 global $CFG;
2219 require_once($CFG->dirroot.'/course/lib.php');
2221 $modinfo = get_fast_modinfo($course);
2222 $sections = $modinfo->get_section_info_all();
2224 // For course formats using 'numsections' trim the sections list
2225 $courseformatoptions = course_get_format($course)->get_format_options();
2226 if (isset($courseformatoptions['numsections'])) {
2227 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2230 $activities = array();
2232 foreach ($sections as $key => $section) {
2233 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2234 $sections[$key] = clone($section);
2235 unset($sections[$key]->summary);
2236 $sections[$key]->hasactivites = false;
2237 if (!array_key_exists($section->section, $modinfo->sections)) {
2238 continue;
2240 foreach ($modinfo->sections[$section->section] as $cmid) {
2241 $cm = $modinfo->cms[$cmid];
2242 $activity = new stdClass;
2243 $activity->id = $cm->id;
2244 $activity->course = $course->id;
2245 $activity->section = $section->section;
2246 $activity->name = $cm->name;
2247 $activity->icon = $cm->icon;
2248 $activity->iconcomponent = $cm->iconcomponent;
2249 $activity->hidden = (!$cm->visible);
2250 $activity->modname = $cm->modname;
2251 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2252 $activity->onclick = $cm->onclick;
2253 $url = $cm->url;
2254 if (!$url) {
2255 $activity->url = null;
2256 $activity->display = false;
2257 } else {
2258 $activity->url = $url->out();
2259 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2260 if (self::module_extends_navigation($cm->modname)) {
2261 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2264 $activities[$cmid] = $activity;
2265 if ($activity->display) {
2266 $sections[$key]->hasactivites = true;
2271 return array($sections, $activities);
2275 * Generically loads the course sections into the course's navigation.
2277 * @param stdClass $course
2278 * @param navigation_node $coursenode
2279 * @return array An array of course section nodes
2281 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2282 global $CFG, $DB, $USER, $SITE;
2283 require_once($CFG->dirroot.'/course/lib.php');
2285 list($sections, $activities) = $this->generate_sections_and_activities($course);
2287 $navigationsections = array();
2288 foreach ($sections as $sectionid => $section) {
2289 $section = clone($section);
2290 if ($course->id == $SITE->id) {
2291 $this->load_section_activities($coursenode, $section->section, $activities);
2292 } else {
2293 if (!$section->uservisible || (!$this->showemptysections &&
2294 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2295 continue;
2298 $sectionname = get_section_name($course, $section);
2299 $url = course_get_url($course, $section->section, array('navigation' => true));
2301 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2302 null, $section->id, new pix_icon('i/section', ''));
2303 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2304 $sectionnode->hidden = (!$section->visible || !$section->available);
2305 $sectionnode->add_attribute('data-section-name-for', $section->id);
2306 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2307 $this->load_section_activities($sectionnode, $section->section, $activities);
2309 $navigationsections[$sectionid] = $section;
2312 return $navigationsections;
2316 * Loads all of the activities for a section into the navigation structure.
2318 * @param navigation_node $sectionnode
2319 * @param int $sectionnumber
2320 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2321 * @param stdClass $course The course object the section and activities relate to.
2322 * @return array Array of activity nodes
2324 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2325 global $CFG, $SITE;
2326 // A static counter for JS function naming
2327 static $legacyonclickcounter = 0;
2329 $activitynodes = array();
2330 if (empty($activities)) {
2331 return $activitynodes;
2334 if (!is_object($course)) {
2335 $activity = reset($activities);
2336 $courseid = $activity->course;
2337 } else {
2338 $courseid = $course->id;
2340 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2342 foreach ($activities as $activity) {
2343 if ($activity->section != $sectionnumber) {
2344 continue;
2346 if ($activity->icon) {
2347 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2348 } else {
2349 $icon = new pix_icon('monologo', get_string('modulename', $activity->modname), $activity->modname);
2352 // Prepare the default name and url for the node
2353 $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activity->id));
2354 $activityname = format_string($activity->name, true, ['context' => $displaycontext]);
2355 $action = new moodle_url($activity->url);
2357 // Check if the onclick property is set (puke!)
2358 if (!empty($activity->onclick)) {
2359 // Increment the counter so that we have a unique number.
2360 $legacyonclickcounter++;
2361 // Generate the function name we will use
2362 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2363 $propogrationhandler = '';
2364 // Check if we need to cancel propogation. Remember inline onclick
2365 // events would return false if they wanted to prevent propogation and the
2366 // default action.
2367 if (strpos($activity->onclick, 'return false')) {
2368 $propogrationhandler = 'e.halt();';
2370 // Decode the onclick - it has already been encoded for display (puke)
2371 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2372 // Build the JS function the click event will call
2373 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2374 $this->page->requires->js_amd_inline($jscode);
2375 // Override the default url with the new action link
2376 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2379 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2380 $activitynode->title(get_string('modulename', $activity->modname));
2381 $activitynode->hidden = $activity->hidden;
2382 $activitynode->display = $showactivities && $activity->display;
2383 $activitynode->nodetype = $activity->nodetype;
2384 $activitynodes[$activity->id] = $activitynode;
2387 return $activitynodes;
2390 * Loads a stealth module from unavailable section
2391 * @param navigation_node $coursenode
2392 * @param stdClass|course_modinfo $modinfo
2393 * @return navigation_node or null if not accessible
2395 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2396 if (empty($modinfo->cms[$this->page->cm->id])) {
2397 return null;
2399 $cm = $modinfo->cms[$this->page->cm->id];
2400 if ($cm->icon) {
2401 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2402 } else {
2403 $icon = new pix_icon('monologo', get_string('modulename', $cm->modname), $cm->modname);
2405 $url = $cm->url;
2406 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2407 $activitynode->title(get_string('modulename', $cm->modname));
2408 $activitynode->hidden = (!$cm->visible);
2409 if (!$cm->is_visible_on_course_page()) {
2410 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2411 // Also there may be no exception at all in case when teacher is logged in as student.
2412 $activitynode->display = false;
2413 } else if (!$url) {
2414 // Don't show activities that don't have links!
2415 $activitynode->display = false;
2416 } else if (self::module_extends_navigation($cm->modname)) {
2417 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2419 return $activitynode;
2422 * Loads the navigation structure for the given activity into the activities node.
2424 * This method utilises a callback within the modules lib.php file to load the
2425 * content specific to activity given.
2427 * The callback is a method: {modulename}_extend_navigation()
2428 * Examples:
2429 * * {@link forum_extend_navigation()}
2430 * * {@link workshop_extend_navigation()}
2432 * @param cm_info|stdClass $cm
2433 * @param stdClass $course
2434 * @param navigation_node $activity
2435 * @return bool
2437 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2438 global $CFG, $DB;
2440 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2441 if (!($cm instanceof cm_info)) {
2442 $modinfo = get_fast_modinfo($course);
2443 $cm = $modinfo->get_cm($cm->id);
2445 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2446 $activity->make_active();
2447 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2448 $function = $cm->modname.'_extend_navigation';
2450 if (file_exists($file)) {
2451 require_once($file);
2452 if (function_exists($function)) {
2453 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2454 $function($activity, $course, $activtyrecord, $cm);
2458 // Allow the active advanced grading method plugin to append module navigation
2459 $featuresfunc = $cm->modname.'_supports';
2460 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2461 require_once($CFG->dirroot.'/grade/grading/lib.php');
2462 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2463 $gradingman->extend_navigation($this, $activity);
2466 return $activity->has_children();
2469 * Loads user specific information into the navigation in the appropriate place.
2471 * If no user is provided the current user is assumed.
2473 * @param stdClass $user
2474 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2475 * @return bool
2477 protected function load_for_user($user=null, $forceforcontext=false) {
2478 global $DB, $CFG, $USER, $SITE;
2480 require_once($CFG->dirroot . '/course/lib.php');
2482 if ($user === null) {
2483 // We can't require login here but if the user isn't logged in we don't
2484 // want to show anything
2485 if (!isloggedin() || isguestuser()) {
2486 return false;
2488 $user = $USER;
2489 } else if (!is_object($user)) {
2490 // If the user is not an object then get them from the database
2491 $select = context_helper::get_preload_record_columns_sql('ctx');
2492 $sql = "SELECT u.*, $select
2493 FROM {user} u
2494 JOIN {context} ctx ON u.id = ctx.instanceid
2495 WHERE u.id = :userid AND
2496 ctx.contextlevel = :contextlevel";
2497 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2498 context_helper::preload_from_record($user);
2501 $iscurrentuser = ($user->id == $USER->id);
2503 $usercontext = context_user::instance($user->id);
2505 // Get the course set against the page, by default this will be the site
2506 $course = $this->page->course;
2507 $baseargs = array('id'=>$user->id);
2508 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2509 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2510 $baseargs['course'] = $course->id;
2511 $coursecontext = context_course::instance($course->id);
2512 $issitecourse = false;
2513 } else {
2514 // Load all categories and get the context for the system
2515 $coursecontext = context_system::instance();
2516 $issitecourse = true;
2519 // Create a node to add user information under.
2520 $usersnode = null;
2521 if (!$issitecourse) {
2522 // Not the current user so add it to the participants node for the current course.
2523 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2524 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2525 } else if ($USER->id != $user->id) {
2526 // This is the site so add a users node to the root branch.
2527 $usersnode = $this->rootnodes['users'];
2528 if (course_can_view_participants($coursecontext)) {
2529 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2531 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2533 if (!$usersnode) {
2534 // We should NEVER get here, if the course hasn't been populated
2535 // with a participants node then the navigaiton either wasn't generated
2536 // for it (you are missing a require_login or set_context call) or
2537 // you don't have access.... in the interests of no leaking informatin
2538 // we simply quit...
2539 return false;
2541 // Add a branch for the current user.
2542 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2543 $viewprofile = true;
2544 if (!$iscurrentuser) {
2545 require_once($CFG->dirroot . '/user/lib.php');
2546 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2547 $viewprofile = false;
2548 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2549 $viewprofile = false;
2551 if (!$viewprofile) {
2552 $viewprofile = user_can_view_profile($user, null, $usercontext);
2556 // Now, conditionally add the user node.
2557 if ($viewprofile) {
2558 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2559 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2560 } else {
2561 $usernode = $usersnode->add(get_string('user'));
2564 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2565 $usernode->make_active();
2568 // Add user information to the participants or user node.
2569 if ($issitecourse) {
2571 // If the user is the current user or has permission to view the details of the requested
2572 // user than add a view profile link.
2573 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2574 has_capability('moodle/user:viewdetails', $usercontext)) {
2575 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2576 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2577 } else {
2578 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2582 if (!empty($CFG->navadduserpostslinks)) {
2583 // Add nodes for forum posts and discussions if the user can view either or both
2584 // There are no capability checks here as the content of the page is based
2585 // purely on the forums the current user has access too.
2586 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2587 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2588 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2589 array_merge($baseargs, array('mode' => 'discussions'))));
2592 // Add blog nodes.
2593 if (!empty($CFG->enableblogs)) {
2594 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2595 require_once($CFG->dirroot.'/blog/lib.php');
2596 // Get all options for the user.
2597 $options = blog_get_options_for_user($user);
2598 $this->cache->set('userblogoptions'.$user->id, $options);
2599 } else {
2600 $options = $this->cache->{'userblogoptions'.$user->id};
2603 if (count($options) > 0) {
2604 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2605 foreach ($options as $type => $option) {
2606 if ($type == "rss") {
2607 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2608 new pix_icon('i/rss', ''));
2609 } else {
2610 $blogs->add($option['string'], $option['link']);
2616 // Add the messages link.
2617 // It is context based so can appear in the user's profile and in course participants information.
2618 if (!empty($CFG->messaging)) {
2619 $messageargs = array('user1' => $USER->id);
2620 if ($USER->id != $user->id) {
2621 $messageargs['user2'] = $user->id;
2623 $url = new moodle_url('/message/index.php', $messageargs);
2624 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2627 // Add the "My private files" link.
2628 // This link doesn't have a unique display for course context so only display it under the user's profile.
2629 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2630 $url = new moodle_url('/user/files.php');
2631 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2634 // Add a node to view the users notes if permitted.
2635 if (!empty($CFG->enablenotes) &&
2636 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2637 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2638 if ($coursecontext->instanceid != SITEID) {
2639 $url->param('course', $coursecontext->instanceid);
2641 $usernode->add(get_string('notes', 'notes'), $url);
2644 // Show the grades node.
2645 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2646 require_once($CFG->dirroot . '/user/lib.php');
2647 // Set the grades node to link to the "Grades" page.
2648 if ($course->id == SITEID) {
2649 $url = user_mygrades_url($user->id, $course->id);
2650 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2651 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2653 if ($USER->id != $user->id) {
2654 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2655 } else {
2656 $usernode->add(get_string('grades', 'grades'), $url);
2660 // If the user is the current user add the repositories for the current user.
2661 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2662 if (!$iscurrentuser &&
2663 $course->id == $SITE->id &&
2664 has_capability('moodle/user:viewdetails', $usercontext) &&
2665 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2667 // Add view grade report is permitted.
2668 $reports = core_component::get_plugin_list('gradereport');
2669 arsort($reports); // User is last, we want to test it first.
2671 $userscourses = enrol_get_users_courses($user->id, false, '*');
2672 $userscoursesnode = $usernode->add(get_string('courses'));
2674 $count = 0;
2675 foreach ($userscourses as $usercourse) {
2676 if ($count === (int)$CFG->navcourselimit) {
2677 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2678 $userscoursesnode->add(get_string('showallcourses'), $url);
2679 break;
2681 $count++;
2682 $usercoursecontext = context_course::instance($usercourse->id);
2683 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2684 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2685 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2687 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2688 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2689 foreach ($reports as $plugin => $plugindir) {
2690 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2691 // Stop when the first visible plugin is found.
2692 $gradeavailable = true;
2693 break;
2698 if ($gradeavailable) {
2699 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2700 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2701 new pix_icon('i/grades', ''));
2704 // Add a node to view the users notes if permitted.
2705 if (!empty($CFG->enablenotes) &&
2706 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2707 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2708 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2711 if (can_access_course($usercourse, $user->id, '', true)) {
2712 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2713 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2716 $reporttab = $usercoursenode->add(get_string('activityreports'));
2718 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2719 foreach ($reportfunctions as $reportfunction) {
2720 $reportfunction($reporttab, $user, $usercourse);
2723 $reporttab->trim_if_empty();
2727 // Let plugins hook into user navigation.
2728 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2729 foreach ($pluginsfunction as $plugintype => $plugins) {
2730 if ($plugintype != 'report') {
2731 foreach ($plugins as $pluginfunction) {
2732 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2737 return true;
2741 * This method simply checks to see if a given module can extend the navigation.
2743 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2745 * @param string $modname
2746 * @return bool
2748 public static function module_extends_navigation($modname) {
2749 global $CFG;
2750 static $extendingmodules = array();
2751 if (!array_key_exists($modname, $extendingmodules)) {
2752 $extendingmodules[$modname] = false;
2753 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2754 if (file_exists($file)) {
2755 $function = $modname.'_extend_navigation';
2756 require_once($file);
2757 $extendingmodules[$modname] = (function_exists($function));
2760 return $extendingmodules[$modname];
2763 * Extends the navigation for the given user.
2765 * @param stdClass $user A user from the database
2767 public function extend_for_user($user) {
2768 $this->extendforuser[] = $user;
2772 * Returns all of the users the navigation is being extended for
2774 * @return array An array of extending users.
2776 public function get_extending_users() {
2777 return $this->extendforuser;
2780 * Adds the given course to the navigation structure.
2782 * @param stdClass $course
2783 * @param bool $forcegeneric
2784 * @param bool $ismycourse
2785 * @return navigation_node
2787 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2788 global $CFG, $SITE;
2790 // We found the course... we can return it now :)
2791 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2792 return $this->addedcourses[$course->id];
2795 $coursecontext = context_course::instance($course->id);
2797 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
2798 if (is_role_switched($course->id)) {
2799 // user has to be able to access course in order to switch, let's skip the visibility test here
2800 } else if (!core_course_category::can_view_course_info($course)) {
2801 return false;
2805 $issite = ($course->id == $SITE->id);
2806 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
2807 $shortname = format_string($course->shortname, true, ['context' => $displaycontext]);
2808 $fullname = format_string($course->fullname, true, ['context' => $displaycontext]);
2809 // This is the name that will be shown for the course.
2810 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2812 if ($coursetype == self::COURSE_CURRENT) {
2813 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2814 return $coursenode;
2815 } else {
2816 $coursetype = self::COURSE_OTHER;
2820 // Can the user expand the course to see its content.
2821 $canexpandcourse = true;
2822 if ($issite) {
2823 $parent = $this;
2824 $url = null;
2825 if (empty($CFG->usesitenameforsitepages)) {
2826 $coursename = get_string('sitepages');
2828 } else if ($coursetype == self::COURSE_CURRENT) {
2829 $parent = $this->rootnodes['currentcourse'];
2830 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2831 $canexpandcourse = $this->can_expand_course($course);
2832 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2833 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2834 // Nothing to do here the above statement set $parent to the category within mycourses.
2835 } else {
2836 $parent = $this->rootnodes['mycourses'];
2838 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2839 } else {
2840 $parent = $this->rootnodes['courses'];
2841 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2842 // They can only expand the course if they can access it.
2843 $canexpandcourse = $this->can_expand_course($course);
2844 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2845 if (!$this->is_category_fully_loaded($course->category)) {
2846 // We need to load the category structure for this course
2847 $this->load_all_categories($course->category, false);
2849 if (array_key_exists($course->category, $this->addedcategories)) {
2850 $parent = $this->addedcategories[$course->category];
2851 // This could lead to the course being created so we should check whether it is the case again
2852 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2853 return $this->addedcourses[$course->id];
2859 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2860 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2862 $coursenode->hidden = (!$course->visible);
2863 $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false]));
2864 if ($canexpandcourse) {
2865 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2866 $coursenode->nodetype = self::NODETYPE_BRANCH;
2867 $coursenode->isexpandable = true;
2868 } else {
2869 $coursenode->nodetype = self::NODETYPE_LEAF;
2870 $coursenode->isexpandable = false;
2872 if (!$forcegeneric) {
2873 $this->addedcourses[$course->id] = $coursenode;
2876 return $coursenode;
2880 * Returns a cache instance to use for the expand course cache.
2881 * @return cache_session
2883 protected function get_expand_course_cache() {
2884 if ($this->cacheexpandcourse === null) {
2885 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2887 return $this->cacheexpandcourse;
2891 * Checks if a user can expand a course in the navigation.
2893 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2894 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2895 * permits stale data.
2896 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2897 * will be stale.
2898 * It is brought up to date in only one of two ways.
2899 * 1. The user logs out and in again.
2900 * 2. The user browses to the course they've just being given access to.
2902 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2904 * @param stdClass $course
2905 * @return bool
2907 protected function can_expand_course($course) {
2908 $cache = $this->get_expand_course_cache();
2909 $canexpand = $cache->get($course->id);
2910 if ($canexpand === false) {
2911 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2912 $canexpand = (int)$canexpand;
2913 $cache->set($course->id, $canexpand);
2915 return ($canexpand === 1);
2919 * Returns true if the category has already been loaded as have any child categories
2921 * @param int $categoryid
2922 * @return bool
2924 protected function is_category_fully_loaded($categoryid) {
2925 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2929 * Adds essential course nodes to the navigation for the given course.
2931 * This method adds nodes such as reports, blogs and participants
2933 * @param navigation_node $coursenode
2934 * @param stdClass $course
2935 * @return bool returns true on successful addition of a node.
2937 public function add_course_essentials($coursenode, stdClass $course) {
2938 global $CFG, $SITE;
2939 require_once($CFG->dirroot . '/course/lib.php');
2941 if ($course->id == $SITE->id) {
2942 return $this->add_front_page_course_essentials($coursenode, $course);
2945 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2946 return true;
2949 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2951 //Participants
2952 if ($navoptions->participants) {
2953 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2954 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2956 if ($navoptions->blogs) {
2957 $blogsurls = new moodle_url('/blog/index.php');
2958 if ($currentgroup = groups_get_course_group($course, true)) {
2959 $blogsurls->param('groupid', $currentgroup);
2960 } else {
2961 $blogsurls->param('courseid', $course->id);
2963 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2966 if ($navoptions->notes) {
2967 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2969 } else if (count($this->extendforuser) > 0) {
2970 $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2973 // Badges.
2974 if ($navoptions->badges) {
2975 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2977 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2978 navigation_node::TYPE_SETTING, null, 'badgesview',
2979 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2982 // Check access to the course and competencies page.
2983 if ($navoptions->competencies) {
2984 // Just a link to course competency.
2985 $title = get_string('competencies', 'core_competency');
2986 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2987 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2988 new pix_icon('i/competencies', ''));
2990 if ($navoptions->grades) {
2991 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2992 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2993 'grades', new pix_icon('i/grades', ''));
2994 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2995 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2996 $gradenode->make_active();
3000 // Add link for configuring communication.
3001 if ($navoptions->communication) {
3002 $url = new moodle_url('/communication/configure.php', [
3003 'contextid' => \core\context\course::instance($course->id)->id,
3004 'instanceid' => $course->id,
3005 'instancetype' => 'coursecommunication',
3006 'component' => 'core_course',
3008 $coursenode->add(get_string('communication', 'communication'), $url,
3009 navigation_node::TYPE_SETTING, null, 'communication');
3012 return true;
3015 * This generates the structure of the course that won't be generated when
3016 * the modules and sections are added.
3018 * Things such as the reports branch, the participants branch, blogs... get
3019 * added to the course node by this method.
3021 * @param navigation_node $coursenode
3022 * @param stdClass $course
3023 * @return bool True for successfull generation
3025 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
3026 global $CFG, $USER, $COURSE, $SITE;
3027 require_once($CFG->dirroot . '/course/lib.php');
3029 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
3030 return true;
3033 $systemcontext = context_system::instance();
3034 $navoptions = course_get_user_navigation_options($systemcontext, $course);
3036 // Hidden node that we use to determine if the front page navigation is loaded.
3037 // This required as there are not other guaranteed nodes that may be loaded.
3038 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
3040 // Add My courses to the site pages within the navigation structure so the block can read it.
3041 $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses');
3043 // Participants.
3044 if ($navoptions->participants) {
3045 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
3046 self::TYPE_CUSTOM, get_string('participants'), 'participants');
3049 // Blogs.
3050 if ($navoptions->blogs) {
3051 $blogsurls = new moodle_url('/blog/index.php');
3052 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
3055 $filterselect = 0;
3057 // Badges.
3058 if ($navoptions->badges) {
3059 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
3060 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
3063 // Notes.
3064 if ($navoptions->notes) {
3065 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
3066 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
3069 // Tags
3070 if ($navoptions->tags) {
3071 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
3072 self::TYPE_SETTING, null, 'tags');
3075 // Search.
3076 if ($navoptions->search) {
3077 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
3078 self::TYPE_SETTING, null, 'search');
3081 if (isloggedin()) {
3082 $usercontext = context_user::instance($USER->id);
3083 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
3084 $url = new moodle_url('/user/files.php');
3085 $node = $coursenode->add(get_string('privatefiles'), $url,
3086 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
3087 $node->display = false;
3088 $node->showinflatnavigation = true;
3089 $node->mainnavonly = true;
3093 if (isloggedin()) {
3094 $context = $this->page->context;
3095 switch ($context->contextlevel) {
3096 case CONTEXT_COURSECAT:
3097 // OK, expected context level.
3098 break;
3099 case CONTEXT_COURSE:
3100 // OK, expected context level if not on frontpage.
3101 if ($COURSE->id != $SITE->id) {
3102 break;
3104 default:
3105 // If this context is part of a course (excluding frontpage), use the course context.
3106 // Otherwise, use the system context.
3107 $coursecontext = $context->get_course_context(false);
3108 if ($coursecontext && $coursecontext->instanceid !== $SITE->id) {
3109 $context = $coursecontext;
3110 } else {
3111 $context = $systemcontext;
3115 $params = ['contextid' => $context->id];
3116 if (has_capability('moodle/contentbank:access', $context)) {
3117 $url = new moodle_url('/contentbank/index.php', $params);
3118 $node = $coursenode->add(get_string('contentbank'), $url,
3119 self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', ''));
3120 $node->showinflatnavigation = true;
3124 return true;
3128 * Clears the navigation cache
3130 public function clear_cache() {
3131 $this->cache->clear();
3135 * Sets an expansion limit for the navigation
3137 * The expansion limit is used to prevent the display of content that has a type
3138 * greater than the provided $type.
3140 * Can be used to ensure things such as activities or activity content don't get
3141 * shown on the navigation.
3142 * They are still generated in order to ensure the navbar still makes sense.
3144 * @param int $type One of navigation_node::TYPE_*
3145 * @return bool true when complete.
3147 public function set_expansion_limit($type) {
3148 global $SITE;
3149 $nodes = $this->find_all_of_type($type);
3151 // We only want to hide specific types of nodes.
3152 // Only nodes that represent "structure" in the navigation tree should be hidden.
3153 // If we hide all nodes then we risk hiding vital information.
3154 $typestohide = array(
3155 self::TYPE_CATEGORY,
3156 self::TYPE_COURSE,
3157 self::TYPE_SECTION,
3158 self::TYPE_ACTIVITY
3161 foreach ($nodes as $node) {
3162 // We need to generate the full site node
3163 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
3164 continue;
3166 foreach ($node->children as $child) {
3167 $child->hide($typestohide);
3170 return true;
3173 * Attempts to get the navigation with the given key from this nodes children.
3175 * This function only looks at this nodes children, it does NOT look recursivily.
3176 * If the node can't be found then false is returned.
3178 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3180 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3181 * may be of more use to you.
3183 * @param string|int $key The key of the node you wish to receive.
3184 * @param int $type One of navigation_node::TYPE_*
3185 * @return navigation_node|false
3187 public function get($key, $type = null) {
3188 if (!$this->initialised) {
3189 $this->initialise();
3191 return parent::get($key, $type);
3195 * Searches this nodes children and their children to find a navigation node
3196 * with the matching key and type.
3198 * This method is recursive and searches children so until either a node is
3199 * found or there are no more nodes to search.
3201 * If you know that the node being searched for is a child of this node
3202 * then use the {@link global_navigation::get()} method instead.
3204 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3205 * may be of more use to you.
3207 * @param string|int $key The key of the node you wish to receive.
3208 * @param int $type One of navigation_node::TYPE_*
3209 * @return navigation_node|false
3211 public function find($key, $type) {
3212 if (!$this->initialised) {
3213 $this->initialise();
3215 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
3216 return $this->rootnodes[$key];
3218 return parent::find($key, $type);
3222 * They've expanded the 'my courses' branch.
3224 protected function load_courses_enrolled() {
3225 global $CFG;
3227 $limit = (int) $CFG->navcourselimit;
3229 $courses = enrol_get_my_courses('*');
3230 $flatnavcourses = [];
3232 // Go through the courses and see which ones we want to display in the flatnav.
3233 foreach ($courses as $course) {
3234 $classify = course_classify_for_timeline($course);
3236 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3237 $flatnavcourses[$course->id] = $course;
3241 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3242 $numtotalcourses = count($courses);
3243 $numtotalflatnavcourses = count($flatnavcourses);
3245 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3246 $courses = array_slice($courses, 0, $limit, true);
3247 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3249 // Get the number of courses we are going to show for each.
3250 $numshowncourses = count($courses);
3251 $numshownflatnavcourses = count($flatnavcourses);
3252 if ($numshowncourses && $this->show_my_categories()) {
3253 // Generate an array containing unique values of all the courses' categories.
3254 $categoryids = array();
3255 foreach ($courses as $course) {
3256 if (in_array($course->category, $categoryids)) {
3257 continue;
3259 $categoryids[] = $course->category;
3262 // Array of category IDs that include the categories of the user's courses and the related course categories.
3263 $fullpathcategoryids = [];
3264 // Get the course categories for the enrolled courses' category IDs.
3265 $mycoursecategories = core_course_category::get_many($categoryids);
3266 // Loop over each of these categories and build the category tree using each category's path.
3267 foreach ($mycoursecategories as $mycoursecat) {
3268 $pathcategoryids = explode('/', $mycoursecat->path);
3269 // First element of the exploded path is empty since paths begin with '/'.
3270 array_shift($pathcategoryids);
3271 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3272 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3275 // Fetch all of the categories related to the user's courses.
3276 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3277 // Loop over each of these categories and build the category tree.
3278 foreach ($pathcategories as $coursecat) {
3279 // No need to process categories that have already been added.
3280 if (isset($this->addedcategories[$coursecat->id])) {
3281 continue;
3283 // Skip categories that are not visible.
3284 if (!$coursecat->is_uservisible()) {
3285 continue;
3288 // Get this course category's parent node.
3289 $parent = null;
3290 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3291 $parent = $this->addedcategories[$coursecat->parent];
3293 if (!$parent) {
3294 // If it has no parent, then it should be right under the My courses node.
3295 $parent = $this->rootnodes['mycourses'];
3298 // Build the category object based from the coursecat object.
3299 $mycategory = new stdClass();
3300 $mycategory->id = $coursecat->id;
3301 $mycategory->name = $coursecat->name;
3302 $mycategory->visible = $coursecat->visible;
3304 // Add this category to the nav tree.
3305 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3309 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3310 foreach ($courses as $course) {
3311 $node = $this->add_course($course, false, self::COURSE_MY);
3312 if ($node) {
3313 $node->showinflatnavigation = false;
3314 // Check if we should also add this to the flat nav as well.
3315 if (isset($flatnavcourses[$course->id])) {
3316 $node->showinflatnavigation = true;
3321 // Go through each course in the flatnav now.
3322 foreach ($flatnavcourses as $course) {
3323 // Check if we haven't already added it.
3324 if (!isset($courses[$course->id])) {
3325 // Ok, add it to the flatnav only.
3326 $node = $this->add_course($course, false, self::COURSE_MY);
3327 $node->display = false;
3328 $node->showinflatnavigation = true;
3332 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3333 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3334 // Show a link to the course page if there are more courses the user is enrolled in.
3335 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3336 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3337 $url = new moodle_url('/my/courses.php');
3338 $parent = $this->rootnodes['mycourses'];
3339 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3341 if ($showmorelinkinnav) {
3342 $coursenode->display = true;
3345 if ($showmorelinkinflatnav) {
3346 $coursenode->showinflatnavigation = true;
3353 * The global navigation class used especially for AJAX requests.
3355 * The primary methods that are used in the global navigation class have been overriden
3356 * to ensure that only the relevant branch is generated at the root of the tree.
3357 * This can be done because AJAX is only used when the backwards structure for the
3358 * requested branch exists.
3359 * This has been done only because it shortens the amounts of information that is generated
3360 * which of course will speed up the response time.. because no one likes laggy AJAX.
3362 * @package core
3363 * @category navigation
3364 * @copyright 2009 Sam Hemelryk
3365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3367 class global_navigation_for_ajax extends global_navigation {
3369 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3370 protected $branchtype;
3372 /** @var int the instance id */
3373 protected $instanceid;
3375 /** @var array Holds an array of expandable nodes */
3376 protected $expandable = array();
3379 * Constructs the navigation for use in an AJAX request
3381 * @param moodle_page $page moodle_page object
3382 * @param int $branchtype
3383 * @param int $id
3385 public function __construct($page, $branchtype, $id) {
3386 $this->page = $page;
3387 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3388 $this->children = new navigation_node_collection();
3389 $this->branchtype = $branchtype;
3390 $this->instanceid = $id;
3391 $this->initialise();
3394 * Initialise the navigation given the type and id for the branch to expand.
3396 * @return array An array of the expandable nodes
3398 public function initialise() {
3399 global $DB, $SITE;
3401 if ($this->initialised || during_initial_install()) {
3402 return $this->expandable;
3404 $this->initialised = true;
3406 $this->rootnodes = array();
3407 $this->rootnodes['site'] = $this->add_course($SITE);
3408 $this->rootnodes['mycourses'] = $this->add(
3409 get_string('mycourses'),
3410 new moodle_url('/my/courses.php'),
3411 self::TYPE_ROOTNODE,
3412 null,
3413 'mycourses'
3415 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3416 // The courses branch is always displayed, and is always expandable (although may be empty).
3417 // This mimicks what is done during {@link global_navigation::initialise()}.
3418 $this->rootnodes['courses']->isexpandable = true;
3420 // Branchtype will be one of navigation_node::TYPE_*
3421 switch ($this->branchtype) {
3422 case 0:
3423 if ($this->instanceid === 'mycourses') {
3424 $this->load_courses_enrolled();
3425 } else if ($this->instanceid === 'courses') {
3426 $this->load_courses_other();
3428 break;
3429 case self::TYPE_CATEGORY :
3430 $this->load_category($this->instanceid);
3431 break;
3432 case self::TYPE_MY_CATEGORY :
3433 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3434 break;
3435 case self::TYPE_COURSE :
3436 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3437 if (!can_access_course($course, null, '', true)) {
3438 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3439 // add the course node and break. This leads to an empty node.
3440 $this->add_course($course);
3441 break;
3443 require_course_login($course, true, null, false, true);
3444 $this->page->set_context(context_course::instance($course->id));
3445 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3446 $this->add_course_essentials($coursenode, $course);
3447 $this->load_course_sections($course, $coursenode);
3448 break;
3449 case self::TYPE_SECTION :
3450 $sql = 'SELECT c.*, cs.section AS sectionnumber
3451 FROM {course} c
3452 LEFT JOIN {course_sections} cs ON cs.course = c.id
3453 WHERE cs.id = ?';
3454 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3455 require_course_login($course, true, null, false, true);
3456 $this->page->set_context(context_course::instance($course->id));
3457 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3458 $this->add_course_essentials($coursenode, $course);
3459 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3460 break;
3461 case self::TYPE_ACTIVITY :
3462 $sql = "SELECT c.*
3463 FROM {course} c
3464 JOIN {course_modules} cm ON cm.course = c.id
3465 WHERE cm.id = :cmid";
3466 $params = array('cmid' => $this->instanceid);
3467 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3468 $modinfo = get_fast_modinfo($course);
3469 $cm = $modinfo->get_cm($this->instanceid);
3470 require_course_login($course, true, $cm, false, true);
3471 $this->page->set_context(context_module::instance($cm->id));
3472 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3473 $this->load_course_sections($course, $coursenode, null, $cm);
3474 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3475 if ($activitynode) {
3476 $modulenode = $this->load_activity($cm, $course, $activitynode);
3478 break;
3479 default:
3480 throw new Exception('Unknown type');
3481 return $this->expandable;
3484 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3485 $this->load_for_user(null, true);
3488 // Give the local plugins a chance to include some navigation if they want.
3489 $this->load_local_plugin_navigation();
3491 $this->find_expandable($this->expandable);
3492 return $this->expandable;
3496 * They've expanded the general 'courses' branch.
3498 protected function load_courses_other() {
3499 $this->load_all_courses();
3503 * Loads a single category into the AJAX navigation.
3505 * This function is special in that it doesn't concern itself with the parent of
3506 * the requested category or its siblings.
3507 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3508 * request that.
3510 * @global moodle_database $DB
3511 * @param int $categoryid id of category to load in navigation.
3512 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3513 * @return void.
3515 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3516 global $CFG, $DB;
3518 $limit = 20;
3519 if (!empty($CFG->navcourselimit)) {
3520 $limit = (int)$CFG->navcourselimit;
3523 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3524 $sql = "SELECT cc.*, $catcontextsql
3525 FROM {course_categories} cc
3526 JOIN {context} ctx ON cc.id = ctx.instanceid
3527 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3528 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3529 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3530 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3531 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3532 $categorylist = array();
3533 $subcategories = array();
3534 $basecategory = null;
3535 foreach ($categories as $category) {
3536 $categorylist[] = $category->id;
3537 context_helper::preload_from_record($category);
3538 if ($category->id == $categoryid) {
3539 $this->add_category($category, $this, $nodetype);
3540 $basecategory = $this->addedcategories[$category->id];
3541 } else {
3542 $subcategories[$category->id] = $category;
3545 $categories->close();
3548 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3549 // else show all courses.
3550 if ($nodetype === self::TYPE_MY_CATEGORY) {
3551 $courses = enrol_get_my_courses('*');
3552 $categoryids = array();
3554 // Only search for categories if basecategory was found.
3555 if (!is_null($basecategory)) {
3556 // Get course parent category ids.
3557 foreach ($courses as $course) {
3558 $categoryids[] = $course->category;
3561 // Get a unique list of category ids which a part of the path
3562 // to user's courses.
3563 $coursesubcategories = array();
3564 $addedsubcategories = array();
3566 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3567 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3569 foreach ($categories as $category){
3570 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3572 $categories->close();
3573 $coursesubcategories = array_unique($coursesubcategories);
3575 // Only add a subcategory if it is part of the path to user's course and
3576 // wasn't already added.
3577 foreach ($subcategories as $subid => $subcategory) {
3578 if (in_array($subid, $coursesubcategories) &&
3579 !in_array($subid, $addedsubcategories)) {
3580 $this->add_category($subcategory, $basecategory, $nodetype);
3581 $addedsubcategories[] = $subid;
3586 foreach ($courses as $course) {
3587 // Add course if it's in category.
3588 if (in_array($course->category, $categorylist)) {
3589 $this->add_course($course, true, self::COURSE_MY);
3592 } else {
3593 if (!is_null($basecategory)) {
3594 foreach ($subcategories as $key=>$category) {
3595 $this->add_category($category, $basecategory, $nodetype);
3598 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3599 foreach ($courses as $course) {
3600 $this->add_course($course);
3602 $courses->close();
3607 * Returns an array of expandable nodes
3608 * @return array
3610 public function get_expandable() {
3611 return $this->expandable;
3616 * Navbar class
3618 * This class is used to manage the navbar, which is initialised from the navigation
3619 * object held by PAGE
3621 * @package core
3622 * @category navigation
3623 * @copyright 2009 Sam Hemelryk
3624 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3626 class navbar extends navigation_node {
3627 /** @var bool A switch for whether the navbar is initialised or not */
3628 protected $initialised = false;
3629 /** @var mixed keys used to reference the nodes on the navbar */
3630 protected $keys = array();
3631 /** @var null|string content of the navbar */
3632 protected $content = null;
3633 /** @var moodle_page object the moodle page that this navbar belongs to */
3634 protected $page;
3635 /** @var bool A switch for whether to ignore the active navigation information */
3636 protected $ignoreactive = false;
3637 /** @var bool A switch to let us know if we are in the middle of an install */
3638 protected $duringinstall = false;
3639 /** @var bool A switch for whether the navbar has items */
3640 protected $hasitems = false;
3641 /** @var array An array of navigation nodes for the navbar */
3642 protected $items;
3643 /** @var array An array of child node objects */
3644 public $children = array();
3645 /** @var bool A switch for whether we want to include the root node in the navbar */
3646 public $includesettingsbase = false;
3647 /** @var breadcrumb_navigation_node[] $prependchildren */
3648 protected $prependchildren = array();
3651 * The almighty constructor
3653 * @param moodle_page $page
3655 public function __construct(moodle_page $page) {
3656 global $CFG;
3657 if (during_initial_install()) {
3658 $this->duringinstall = true;
3659 return false;
3661 $this->page = $page;
3662 $this->text = get_string('home');
3663 $this->shorttext = get_string('home');
3664 $this->action = new moodle_url($CFG->wwwroot);
3665 $this->nodetype = self::NODETYPE_BRANCH;
3666 $this->type = self::TYPE_SYSTEM;
3670 * Quick check to see if the navbar will have items in.
3672 * @return bool Returns true if the navbar will have items, false otherwise
3674 public function has_items() {
3675 if ($this->duringinstall) {
3676 return false;
3677 } else if ($this->hasitems !== false) {
3678 return true;
3680 $outcome = false;
3681 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3682 // There have been manually added items - there are definitely items.
3683 $outcome = true;
3684 } else if (!$this->ignoreactive) {
3685 // We will need to initialise the navigation structure to check if there are active items.
3686 $this->page->navigation->initialise($this->page);
3687 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3689 $this->hasitems = $outcome;
3690 return $outcome;
3694 * Turn on/off ignore active
3696 * @param bool $setting
3698 public function ignore_active($setting=true) {
3699 $this->ignoreactive = ($setting);
3703 * Gets a navigation node
3705 * @param string|int $key for referencing the navbar nodes
3706 * @param int $type breadcrumb_navigation_node::TYPE_*
3707 * @return breadcrumb_navigation_node|bool
3709 public function get($key, $type = null) {
3710 foreach ($this->children as &$child) {
3711 if ($child->key === $key && ($type == null || $type == $child->type)) {
3712 return $child;
3715 foreach ($this->prependchildren as &$child) {
3716 if ($child->key === $key && ($type == null || $type == $child->type)) {
3717 return $child;
3720 return false;
3723 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3725 * @return array
3727 public function get_items() {
3728 global $CFG;
3729 $items = array();
3730 // Make sure that navigation is initialised
3731 if (!$this->has_items()) {
3732 return $items;
3734 if ($this->items !== null) {
3735 return $this->items;
3738 if (count($this->children) > 0) {
3739 // Add the custom children.
3740 $items = array_reverse($this->children);
3743 // Check if navigation contains the active node
3744 if (!$this->ignoreactive) {
3745 // We will need to ensure the navigation has been initialised.
3746 $this->page->navigation->initialise($this->page);
3747 // Now find the active nodes on both the navigation and settings.
3748 $navigationactivenode = $this->page->navigation->find_active_node();
3749 $settingsactivenode = $this->page->settingsnav->find_active_node();
3751 if ($navigationactivenode && $settingsactivenode) {
3752 // Parse a combined navigation tree
3753 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3754 if (!$settingsactivenode->mainnavonly) {
3755 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3757 $settingsactivenode = $settingsactivenode->parent;
3759 if (!$this->includesettingsbase) {
3760 // Removes the first node from the settings (root node) from the list
3761 array_pop($items);
3763 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3764 if (!$navigationactivenode->mainnavonly) {
3765 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3767 if (!empty($CFG->navshowcategories) &&
3768 $navigationactivenode->type === self::TYPE_COURSE &&
3769 $navigationactivenode->parent->key === 'currentcourse') {
3770 foreach ($this->get_course_categories() as $item) {
3771 $items[] = new breadcrumb_navigation_node($item);
3774 $navigationactivenode = $navigationactivenode->parent;
3776 } else if ($navigationactivenode) {
3777 // Parse the navigation tree to get the active node
3778 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3779 if (!$navigationactivenode->mainnavonly) {
3780 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3782 if (!empty($CFG->navshowcategories) &&
3783 $navigationactivenode->type === self::TYPE_COURSE &&
3784 $navigationactivenode->parent->key === 'currentcourse') {
3785 foreach ($this->get_course_categories() as $item) {
3786 $items[] = new breadcrumb_navigation_node($item);
3789 $navigationactivenode = $navigationactivenode->parent;
3791 } else if ($settingsactivenode) {
3792 // Parse the settings navigation to get the active node
3793 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3794 if (!$settingsactivenode->mainnavonly) {
3795 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3797 $settingsactivenode = $settingsactivenode->parent;
3802 $items[] = new breadcrumb_navigation_node(array(
3803 'text' => $this->page->navigation->text,
3804 'shorttext' => $this->page->navigation->shorttext,
3805 'key' => $this->page->navigation->key,
3806 'action' => $this->page->navigation->action
3809 if (count($this->prependchildren) > 0) {
3810 // Add the custom children
3811 $items = array_merge($items, array_reverse($this->prependchildren));
3814 $last = reset($items);
3815 if ($last) {
3816 $last->set_last(true);
3818 $this->items = array_reverse($items);
3819 return $this->items;
3823 * Get the list of categories leading to this course.
3825 * This function is used by {@link navbar::get_items()} to add back the "courses"
3826 * node and category chain leading to the current course. Note that this is only ever
3827 * called for the current course, so we don't need to bother taking in any parameters.
3829 * @return array
3831 private function get_course_categories() {
3832 global $CFG;
3833 require_once($CFG->dirroot.'/course/lib.php');
3835 $categories = array();
3836 $cap = 'moodle/category:viewhiddencategories';
3837 $showcategories = !core_course_category::is_simple_site();
3839 if ($showcategories) {
3840 foreach ($this->page->categories as $category) {
3841 $context = context_coursecat::instance($category->id);
3842 if (!core_course_category::can_view_category($category)) {
3843 continue;
3846 $displaycontext = \context_helper::get_navigation_filter_context($context);
3847 $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]);
3848 $name = format_string($category->name, true, ['context' => $displaycontext]);
3849 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3850 if (!$category->visible) {
3851 $categorynode->hidden = true;
3853 $categories[] = $categorynode;
3857 // Don't show the 'course' node if enrolled in this course.
3858 $coursecontext = context_course::instance($this->page->course->id);
3859 if (!is_enrolled($coursecontext, null, '', true)) {
3860 $courses = $this->page->navigation->get('courses');
3861 if (!$courses) {
3862 // Courses node may not be present.
3863 $courses = breadcrumb_navigation_node::create(
3864 get_string('courses'),
3865 new moodle_url('/course/index.php'),
3866 self::TYPE_CONTAINER
3869 $categories[] = $courses;
3872 return $categories;
3876 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3878 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3879 * the way nodes get added to allow us to simply call add and have the node added to the
3880 * end of the navbar
3882 * @param string $text
3883 * @param string|moodle_url|action_link $action An action to associate with this node.
3884 * @param int $type One of navigation_node::TYPE_*
3885 * @param string $shorttext
3886 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3887 * @param pix_icon $icon An optional icon to use for this node.
3888 * @return navigation_node
3890 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3891 if ($this->content !== null) {
3892 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3895 // Properties array used when creating the new navigation node
3896 $itemarray = array(
3897 'text' => $text,
3898 'type' => $type
3900 // Set the action if one was provided
3901 if ($action!==null) {
3902 $itemarray['action'] = $action;
3904 // Set the shorttext if one was provided
3905 if ($shorttext!==null) {
3906 $itemarray['shorttext'] = $shorttext;
3908 // Set the icon if one was provided
3909 if ($icon!==null) {
3910 $itemarray['icon'] = $icon;
3912 // Default the key to the number of children if not provided
3913 if ($key === null) {
3914 $key = count($this->children);
3916 // Set the key
3917 $itemarray['key'] = $key;
3918 // Set the parent to this node
3919 $itemarray['parent'] = $this;
3920 // Add the child using the navigation_node_collections add method
3921 $this->children[] = new breadcrumb_navigation_node($itemarray);
3922 return $this;
3926 * Prepends a new navigation_node to the start of the navbar
3928 * @param string $text
3929 * @param string|moodle_url|action_link $action An action to associate with this node.
3930 * @param int $type One of navigation_node::TYPE_*
3931 * @param string $shorttext
3932 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3933 * @param pix_icon $icon An optional icon to use for this node.
3934 * @return navigation_node
3936 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3937 if ($this->content !== null) {
3938 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3940 // Properties array used when creating the new navigation node.
3941 $itemarray = array(
3942 'text' => $text,
3943 'type' => $type
3945 // Set the action if one was provided.
3946 if ($action!==null) {
3947 $itemarray['action'] = $action;
3949 // Set the shorttext if one was provided.
3950 if ($shorttext!==null) {
3951 $itemarray['shorttext'] = $shorttext;
3953 // Set the icon if one was provided.
3954 if ($icon!==null) {
3955 $itemarray['icon'] = $icon;
3957 // Default the key to the number of children if not provided.
3958 if ($key === null) {
3959 $key = count($this->children);
3961 // Set the key.
3962 $itemarray['key'] = $key;
3963 // Set the parent to this node.
3964 $itemarray['parent'] = $this;
3965 // Add the child node to the prepend list.
3966 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3967 return $this;
3972 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3973 * in particular adding extra metadata for search engine robots to leverage.
3975 * @package core
3976 * @category navigation
3977 * @copyright 2015 Brendan Heywood
3978 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3980 class breadcrumb_navigation_node extends navigation_node {
3982 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3983 private $last = false;
3986 * A proxy constructor
3988 * @param mixed $navnode A navigation_node or an array
3990 public function __construct($navnode) {
3991 if (is_array($navnode)) {
3992 parent::__construct($navnode);
3993 } else if ($navnode instanceof navigation_node) {
3995 // Just clone everything.
3996 $objvalues = get_object_vars($navnode);
3997 foreach ($objvalues as $key => $value) {
3998 $this->$key = $value;
4000 } else {
4001 throw new coding_exception('Not a valid breadcrumb_navigation_node');
4006 * Getter for "last"
4007 * @return boolean
4009 public function is_last() {
4010 return $this->last;
4014 * Setter for "last"
4015 * @param $val boolean
4017 public function set_last($val) {
4018 $this->last = $val;
4023 * Subclass of navigation_node allowing different rendering for the flat navigation
4024 * in particular allowing dividers and indents.
4026 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts
4027 * @package core
4028 * @category navigation
4029 * @copyright 2016 Damyon Wiese
4030 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4032 class flat_navigation_node extends navigation_node {
4034 /** @var $indent integer The indent level */
4035 private $indent = 0;
4037 /** @var $showdivider bool Show a divider before this element */
4038 private $showdivider = false;
4040 /** @var $collectionlabel string Label for a group of nodes */
4041 private $collectionlabel = '';
4044 * A proxy constructor
4046 * @param mixed $navnode A navigation_node or an array
4048 public function __construct($navnode, $indent) {
4049 debugging("Flat nav has been deprecated in favour of primary/secondary navigation concepts");
4050 if (is_array($navnode)) {
4051 parent::__construct($navnode);
4052 } else if ($navnode instanceof navigation_node) {
4054 // Just clone everything.
4055 $objvalues = get_object_vars($navnode);
4056 foreach ($objvalues as $key => $value) {
4057 $this->$key = $value;
4059 } else {
4060 throw new coding_exception('Not a valid flat_navigation_node');
4062 $this->indent = $indent;
4066 * Setter, a label is required for a flat navigation node that shows a divider.
4068 * @param string $label
4070 public function set_collectionlabel($label) {
4071 $this->collectionlabel = $label;
4075 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
4077 * @return string
4079 public function get_collectionlabel() {
4080 if (!empty($this->collectionlabel)) {
4081 return $this->collectionlabel;
4083 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) {
4084 return $this->parent->get_collectionlabel();
4086 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
4087 return '';
4091 * Does this node represent a course section link.
4092 * @return boolean
4094 public function is_section() {
4095 return $this->type == navigation_node::TYPE_SECTION;
4099 * In flat navigation - sections are active if we are looking at activities in the section.
4100 * @return boolean
4102 public function isactive() {
4103 global $PAGE;
4105 if ($this->is_section()) {
4106 $active = $PAGE->navigation->find_active_node();
4107 if ($active) {
4108 while ($active = $active->parent) {
4109 if ($active->key == $this->key && $active->type == $this->type) {
4110 return true;
4115 return $this->isactive;
4119 * Getter for "showdivider"
4120 * @return boolean
4122 public function showdivider() {
4123 return $this->showdivider;
4127 * Setter for "showdivider"
4128 * @param $val boolean
4129 * @param $label string Label for the group of nodes
4131 public function set_showdivider($val, $label = '') {
4132 $this->showdivider = $val;
4133 if ($this->showdivider && empty($label)) {
4134 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
4135 } else {
4136 $this->set_collectionlabel($label);
4141 * Getter for "indent"
4142 * @return boolean
4144 public function get_indent() {
4145 return $this->indent;
4149 * Setter for "indent"
4150 * @param $val boolean
4152 public function set_indent($val) {
4153 $this->indent = $val;
4158 * Class used to generate a collection of navigation nodes most closely related
4159 * to the current page.
4161 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts
4162 * @package core
4163 * @copyright 2016 Damyon Wiese
4164 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4166 class flat_navigation extends navigation_node_collection {
4167 /** @var moodle_page the moodle page that the navigation belongs to */
4168 protected $page;
4171 * Constructor.
4173 * @param moodle_page $page
4175 public function __construct(moodle_page &$page) {
4176 if (during_initial_install()) {
4177 return false;
4179 debugging("Flat navigation has been deprecated in favour of primary/secondary navigation concepts");
4180 $this->page = $page;
4184 * Build the list of navigation nodes based on the current navigation and settings trees.
4187 public function initialise() {
4188 global $PAGE, $USER, $OUTPUT, $CFG;
4189 if (during_initial_install()) {
4190 return;
4193 $current = false;
4195 $course = $PAGE->course;
4197 $this->page->navigation->initialise();
4199 // First walk the nav tree looking for "flat_navigation" nodes.
4200 if ($course->id > 1) {
4201 // It's a real course.
4202 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4204 $coursecontext = context_course::instance($course->id, MUST_EXIST);
4205 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext);
4206 // This is the name that will be shown for the course.
4207 $coursename = empty($CFG->navshowfullcoursenames) ?
4208 format_string($course->shortname, true, ['context' => $displaycontext]) :
4209 format_string($course->fullname, true, ['context' => $displaycontext]);
4211 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
4212 $flat->set_collectionlabel($coursename);
4213 $flat->key = 'coursehome';
4214 $flat->icon = new pix_icon('i/course', '');
4216 $courseformat = course_get_format($course);
4217 $coursenode = $PAGE->navigation->find_active_node();
4218 $targettype = navigation_node::TYPE_COURSE;
4220 // Single activity format has no course node - the course node is swapped for the activity node.
4221 if (!$courseformat->has_view_page()) {
4222 $targettype = navigation_node::TYPE_ACTIVITY;
4225 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
4226 $coursenode = $coursenode->parent;
4228 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4229 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4230 if ($coursenode && $coursenode->key != SITEID) {
4231 $this->add($flat);
4232 foreach ($coursenode->children as $child) {
4233 if ($child->action) {
4234 $flat = new flat_navigation_node($child, 0);
4235 $this->add($flat);
4240 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
4241 } else {
4242 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
4245 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
4246 if (!$admin) {
4247 // Try again - crazy nav tree!
4248 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
4250 if ($admin) {
4251 $flat = new flat_navigation_node($admin, 0);
4252 $flat->set_showdivider(true, get_string('sitesettings'));
4253 $flat->key = 'sitesettings';
4254 $flat->icon = new pix_icon('t/preferences', '');
4255 $this->add($flat);
4258 // Add-a-block in editing mode.
4259 if (isset($this->page->theme->addblockposition) &&
4260 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
4261 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) {
4262 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
4263 $addablock = navigation_node::create(get_string('addblock'), $url);
4264 $flat = new flat_navigation_node($addablock, 0);
4265 $flat->set_showdivider(true, get_string('blocksaddedit'));
4266 $flat->key = 'addblock';
4267 $flat->icon = new pix_icon('i/addblock', '');
4268 $this->add($flat);
4270 $addblockurl = "?{$url->get_query_string(false)}";
4272 $PAGE->requires->js_call_amd('core_block/add_modal', 'init',
4273 [$addblockurl, $this->page->get_edited_page_hash()]);
4278 * Override the parent so we can set a label for this collection if it has not been set yet.
4280 * @param navigation_node $node Node to add
4281 * @param string $beforekey If specified, adds before a node with this key,
4282 * otherwise adds at end
4283 * @return navigation_node Added node
4285 public function add(navigation_node $node, $beforekey=null) {
4286 $result = parent::add($node, $beforekey);
4287 // Extend the parent to get a name for the collection of nodes if required.
4288 if (empty($this->collectionlabel)) {
4289 if ($node instanceof flat_navigation_node) {
4290 $this->set_collectionlabel($node->get_collectionlabel());
4294 return $result;
4299 * Class used to manage the settings option for the current page
4301 * This class is used to manage the settings options in a tree format (recursively)
4302 * and was created initially for use with the settings blocks.
4304 * @package core
4305 * @category navigation
4306 * @copyright 2009 Sam Hemelryk
4307 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4309 class settings_navigation extends navigation_node {
4310 /** @var context the current context */
4311 protected $context;
4312 /** @var moodle_page the moodle page that the navigation belongs to */
4313 protected $page;
4314 /** @var string contains administration section navigation_nodes */
4315 protected $adminsection;
4316 /** @var bool A switch to see if the navigation node is initialised */
4317 protected $initialised = false;
4318 /** @var array An array of users that the nodes can extend for. */
4319 protected $userstoextendfor = array();
4320 /** @var navigation_cache **/
4321 protected $cache;
4324 * Sets up the object with basic settings and preparse it for use
4326 * @param moodle_page $page
4328 public function __construct(moodle_page &$page) {
4329 if (during_initial_install()) {
4330 return false;
4332 $this->page = $page;
4333 // Initialise the main navigation. It is most important that this is done
4334 // before we try anything
4335 $this->page->navigation->initialise();
4336 // Initialise the navigation cache
4337 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4338 $this->children = new navigation_node_collection();
4342 * Initialise the settings navigation based on the current context
4344 * This function initialises the settings navigation tree for a given context
4345 * by calling supporting functions to generate major parts of the tree.
4348 public function initialise() {
4349 global $DB, $SESSION, $SITE;
4351 if (during_initial_install()) {
4352 return false;
4353 } else if ($this->initialised) {
4354 return true;
4356 $this->id = 'settingsnav';
4357 $this->context = $this->page->context;
4359 $context = $this->context;
4360 if ($context->contextlevel == CONTEXT_BLOCK) {
4361 $this->load_block_settings();
4362 $context = $context->get_parent_context();
4363 $this->context = $context;
4365 switch ($context->contextlevel) {
4366 case CONTEXT_SYSTEM:
4367 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4368 $this->load_front_page_settings(($context->id == $this->context->id));
4370 break;
4371 case CONTEXT_COURSECAT:
4372 $this->load_category_settings();
4373 break;
4374 case CONTEXT_COURSE:
4375 if ($this->page->course->id != $SITE->id) {
4376 $this->load_course_settings(($context->id == $this->context->id));
4377 } else {
4378 $this->load_front_page_settings(($context->id == $this->context->id));
4380 break;
4381 case CONTEXT_MODULE:
4382 $this->load_module_settings();
4383 $this->load_course_settings();
4384 break;
4385 case CONTEXT_USER:
4386 if ($this->page->course->id != $SITE->id) {
4387 $this->load_course_settings();
4389 break;
4392 $usersettings = $this->load_user_settings($this->page->course->id);
4394 $adminsettings = false;
4395 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4396 $isadminpage = $this->is_admin_tree_needed();
4398 if (has_capability('moodle/site:configview', context_system::instance())) {
4399 if (has_capability('moodle/site:config', context_system::instance())) {
4400 // Make sure this works even if config capability changes on the fly
4401 // and also make it fast for admin right after login.
4402 $SESSION->load_navigation_admin = 1;
4403 if ($isadminpage) {
4404 $adminsettings = $this->load_administration_settings();
4407 } else if (!isset($SESSION->load_navigation_admin)) {
4408 $adminsettings = $this->load_administration_settings();
4409 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4411 } else if ($SESSION->load_navigation_admin) {
4412 if ($isadminpage) {
4413 $adminsettings = $this->load_administration_settings();
4417 // Print empty navigation node, if needed.
4418 if ($SESSION->load_navigation_admin && !$isadminpage) {
4419 if ($adminsettings) {
4420 // Do not print settings tree on pages that do not need it, this helps with performance.
4421 $adminsettings->remove();
4422 $adminsettings = false;
4424 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4425 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4426 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4427 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4428 $siteadminnode->requiresajaxloading = 'true';
4433 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4434 $adminsettings->force_open();
4435 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4436 $usersettings->force_open();
4439 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4440 $this->load_local_plugin_settings();
4442 foreach ($this->children as $key=>$node) {
4443 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4444 // Site administration is shown as link.
4445 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4446 continue;
4448 $node->remove();
4451 $this->initialised = true;
4454 * Override the parent function so that we can add preceeding hr's and set a
4455 * root node class against all first level element
4457 * It does this by first calling the parent's add method {@link navigation_node::add()}
4458 * and then proceeds to use the key to set class and hr
4460 * @param string $text text to be used for the link.
4461 * @param string|moodle_url $url url for the new node
4462 * @param int $type the type of node navigation_node::TYPE_*
4463 * @param string $shorttext
4464 * @param string|int $key a key to access the node by.
4465 * @param pix_icon $icon An icon that appears next to the node.
4466 * @return navigation_node with the new node added to it.
4468 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4469 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4470 $node->add_class('root_node');
4471 return $node;
4475 * This function allows the user to add something to the start of the settings
4476 * navigation, which means it will be at the top of the settings navigation block
4478 * @param string $text text to be used for the link.
4479 * @param string|moodle_url $url url for the new node
4480 * @param int $type the type of node navigation_node::TYPE_*
4481 * @param string $shorttext
4482 * @param string|int $key a key to access the node by.
4483 * @param pix_icon $icon An icon that appears next to the node.
4484 * @return navigation_node $node with the new node added to it.
4486 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4487 $children = $this->children;
4488 $childrenclass = get_class($children);
4489 $this->children = new $childrenclass;
4490 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4491 foreach ($children as $child) {
4492 $this->children->add($child);
4494 return $node;
4498 * Does this page require loading of full admin tree or is
4499 * it enough rely on AJAX?
4501 * @return bool
4503 protected function is_admin_tree_needed() {
4504 if (self::$loadadmintree) {
4505 // Usually external admin page or settings page.
4506 return true;
4509 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4510 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4511 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4512 return false;
4514 return true;
4517 return false;
4521 * Load the site administration tree
4523 * This function loads the site administration tree by using the lib/adminlib library functions
4525 * @param navigation_node $referencebranch A reference to a branch in the settings
4526 * navigation tree
4527 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4528 * tree and start at the beginning
4529 * @return mixed A key to access the admin tree by
4531 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4532 global $CFG;
4534 // Check if we are just starting to generate this navigation.
4535 if ($referencebranch === null) {
4537 // Require the admin lib then get an admin structure
4538 if (!function_exists('admin_get_root')) {
4539 require_once($CFG->dirroot.'/lib/adminlib.php');
4541 $adminroot = admin_get_root(false, false);
4542 // This is the active section identifier
4543 $this->adminsection = $this->page->url->param('section');
4545 // Disable the navigation from automatically finding the active node
4546 navigation_node::$autofindactive = false;
4547 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4548 foreach ($adminroot->children as $adminbranch) {
4549 $this->load_administration_settings($referencebranch, $adminbranch);
4551 navigation_node::$autofindactive = true;
4553 // Use the admin structure to locate the active page
4554 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4555 $currentnode = $this;
4556 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4557 $currentnode = $currentnode->get($pathkey);
4559 if ($currentnode) {
4560 $currentnode->make_active();
4562 } else {
4563 $this->scan_for_active_node($referencebranch);
4565 return $referencebranch;
4566 } else if ($adminbranch->check_access()) {
4567 // We have a reference branch that we can access and is not hidden `hurrah`
4568 // Now we need to display it and any children it may have
4569 $url = null;
4570 $icon = null;
4572 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) {
4573 if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4574 $url = null;
4575 } else {
4576 $url = $adminbranch->get_settings_page_url();
4580 // Add the branch
4581 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4583 if ($adminbranch->is_hidden()) {
4584 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4585 $reference->add_class('hidden');
4586 } else {
4587 $reference->display = false;
4591 // Check if we are generating the admin notifications and whether notificiations exist
4592 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4593 $reference->add_class('criticalnotification');
4595 // Check if this branch has children
4596 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4597 foreach ($adminbranch->children as $branch) {
4598 // Generate the child branches as well now using this branch as the reference
4599 $this->load_administration_settings($reference, $branch);
4601 } else {
4602 $reference->icon = new pix_icon('i/settings', '');
4608 * This function recursivily scans nodes until it finds the active node or there
4609 * are no more nodes.
4610 * @param navigation_node $node
4612 protected function scan_for_active_node(navigation_node $node) {
4613 if (!$node->check_if_active() && $node->children->count()>0) {
4614 foreach ($node->children as &$child) {
4615 $this->scan_for_active_node($child);
4621 * Gets a navigation node given an array of keys that represent the path to
4622 * the desired node.
4624 * @param array $path
4625 * @return navigation_node|false
4627 protected function get_by_path(array $path) {
4628 $node = $this->get(array_shift($path));
4629 foreach ($path as $key) {
4630 $node->get($key);
4632 return $node;
4636 * This function loads the course settings that are available for the user
4638 * @param bool $forceopen If set to true the course node will be forced open
4639 * @return navigation_node|false
4641 protected function load_course_settings($forceopen = false) {
4642 global $CFG, $USER;
4643 require_once($CFG->dirroot . '/course/lib.php');
4645 $course = $this->page->course;
4646 $coursecontext = context_course::instance($course->id);
4647 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4649 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4651 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4652 if ($forceopen) {
4653 $coursenode->force_open();
4656 // MoodleNet links.
4657 if ($this->page->user_is_editing()) {
4658 $this->page->requires->js_call_amd('core/moodlenet/mutations', 'init');
4660 $usercanshare = utilities::can_user_share($coursecontext, $USER->id, 'course');
4661 $issuerid = get_config('moodlenet', 'oauthservice');
4662 try {
4663 $issuer = \core\oauth2\api::get_issuer($issuerid);
4664 $isvalidinstance = utilities::is_valid_instance($issuer);
4665 if ($usercanshare && $isvalidinstance) {
4666 $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init');
4667 $action = new action_link(new moodle_url(''), '', null, [
4668 'data-action' => 'sendtomoodlenet',
4669 'data-type' => 'course',
4671 // Share course to MoodleNet link.
4672 $coursenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'),
4673 $action, self::TYPE_SETTING, null, 'exportcoursetomoodlenet')->set_force_into_more_menu(true);
4674 // MoodleNet share progress link.
4675 $url = new moodle_url('/moodlenet/shareprogress.php');
4676 $coursenode->add(get_string('moodlenet:shareprogress'),
4677 $url, self::TYPE_SETTING, null, 'moodlenetshareprogress')->set_force_into_more_menu(true);
4679 } catch (dml_missing_record_exception $e) {
4680 debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " .
4681 "This must be a valid issuer.");
4684 if ($adminoptions->update) {
4685 // Add the course settings link
4686 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4687 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null,
4688 'editsettings', new pix_icon('i/settings', ''));
4691 if ($adminoptions->editcompletion) {
4692 // Add the course completion settings link
4693 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4694 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion',
4695 new pix_icon('i/settings', ''));
4698 if (!$adminoptions->update && $adminoptions->tags) {
4699 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4700 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4701 $coursenode->get('coursetags')->set_force_into_more_menu();
4704 // add enrol nodes
4705 enrol_add_course_navigation($coursenode, $course);
4707 // Manage filters
4708 if ($adminoptions->filters) {
4709 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4710 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
4711 null, 'filtermanagement', new pix_icon('i/filter', ''));
4714 // View course reports.
4715 if ($adminoptions->reports) {
4716 $reportnav = $coursenode->add(get_string('reports'),
4717 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]),
4718 self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', ''));
4719 $coursereports = core_component::get_plugin_list('coursereport');
4720 foreach ($coursereports as $report => $dir) {
4721 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4722 if (file_exists($libfile)) {
4723 require_once($libfile);
4724 $reportfunction = $report.'_report_extend_navigation';
4725 if (function_exists($report.'_report_extend_navigation')) {
4726 $reportfunction($reportnav, $course, $coursecontext);
4731 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4732 foreach ($reports as $reportfunction) {
4733 $reportfunction($reportnav, $course, $coursecontext);
4736 if (!$reportnav->has_children()) {
4737 $reportnav->remove();
4741 // Check if we can view the gradebook's setup page.
4742 if ($adminoptions->gradebook) {
4743 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4744 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4745 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4748 // Add the context locking node.
4749 $this->add_context_locking_node($coursenode, $coursecontext);
4751 // Add outcome if permitted
4752 if ($adminoptions->outcomes) {
4753 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4754 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4757 //Add badges navigation
4758 if ($adminoptions->badges) {
4759 require_once($CFG->libdir .'/badgeslib.php');
4760 badges_add_course_navigation($coursenode, $course);
4763 // Questions
4764 require_once($CFG->libdir . '/questionlib.php');
4765 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4767 if ($adminoptions->update) {
4768 // Repository Instances
4769 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4770 require_once($CFG->dirroot . '/repository/lib.php');
4771 $editabletypes = repository::get_editable_types($coursecontext);
4772 $haseditabletypes = !empty($editabletypes);
4773 unset($editabletypes);
4774 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4775 } else {
4776 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4778 if ($haseditabletypes) {
4779 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4780 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4784 // Manage files
4785 if ($adminoptions->files) {
4786 // hidden in new courses and courses where legacy files were turned off
4787 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4788 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4792 // Let plugins hook into course navigation.
4793 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4794 foreach ($pluginsfunction as $plugintype => $plugins) {
4795 // Ignore the report plugin as it was already loaded above.
4796 if ($plugintype == 'report') {
4797 continue;
4799 foreach ($plugins as $pluginfunction) {
4800 $pluginfunction($coursenode, $course, $coursecontext);
4804 // Prepare data for course content download functionality if it is enabled.
4805 if (\core\content::can_export_context($coursecontext, $USER)) {
4806 $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext);
4807 $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes);
4809 $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download',
4810 new pix_icon('t/download', ''));
4811 $coursenode->get('download')->set_force_into_more_menu(true);
4814 // Course reuse options.
4815 if ($adminoptions->import
4816 || $adminoptions->backup
4817 || $adminoptions->restore
4818 || $adminoptions->copy
4819 || $adminoptions->reset) {
4820 $coursereusenav = $coursenode->add(
4821 get_string('coursereuse'),
4822 new moodle_url('/backup/view.php', ['id' => $course->id]),
4823 self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''),
4826 // Import data from other courses.
4827 if ($adminoptions->import) {
4828 $url = new moodle_url('/backup/import.php', ['id' => $course->id]);
4829 $coursereusenav->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4832 // Backup this course.
4833 if ($adminoptions->backup) {
4834 $url = new moodle_url('/backup/backup.php', ['id' => $course->id]);
4835 $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4838 // Restore to this course.
4839 if ($adminoptions->restore) {
4840 $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]);
4841 $coursereusenav->add(
4842 get_string('restore'),
4843 $url,
4844 self::TYPE_SETTING,
4845 null,
4846 'restore',
4847 new pix_icon('i/restore', ''),
4851 // Copy this course.
4852 if ($adminoptions->copy) {
4853 $url = new moodle_url('/backup/copy.php', ['id' => $course->id]);
4854 $coursereusenav->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', ''));
4857 // Reset this course.
4858 if ($adminoptions->reset) {
4859 $url = new moodle_url('/course/reset.php', ['id' => $course->id]);
4860 $coursereusenav->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4864 // Return we are done
4865 return $coursenode;
4869 * Get the moodle_page object associated to the current settings navigation.
4871 * @return moodle_page
4873 public function get_page(): moodle_page {
4874 return $this->page;
4878 * This function calls the module function to inject module settings into the
4879 * settings navigation tree.
4881 * This only gets called if there is a corrosponding function in the modules
4882 * lib file.
4884 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4886 * @return navigation_node|false
4888 protected function load_module_settings() {
4889 global $CFG, $USER;
4891 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4892 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4893 $this->page->set_cm($cm, $this->page->course);
4896 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4897 if (file_exists($file)) {
4898 require_once($file);
4901 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4902 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4903 $modulenode->force_open();
4905 // Settings for the module
4906 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4907 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4908 $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', ''));
4910 // Assign local roles
4911 if (count(get_assignable_roles($this->page->cm->context))>0) {
4912 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4913 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign',
4914 new pix_icon('i/role', ''));
4916 // Override roles
4917 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4918 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4919 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride',
4920 new pix_icon('i/permissions', ''));
4922 // Check role permissions
4923 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4924 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4925 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck',
4926 new pix_icon('i/checkpermissions', ''));
4929 // Add the context locking node.
4930 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4932 // Manage filters
4933 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4934 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4935 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage',
4936 new pix_icon('i/filter', ''));
4938 // Add reports
4939 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4940 foreach ($reports as $reportfunction) {
4941 $reportfunction($modulenode, $this->page->cm);
4943 // Add a backup link
4944 $featuresfunc = $this->page->activityname.'_supports';
4945 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4946 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4947 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4950 // Restore this activity
4951 $featuresfunc = $this->page->activityname.'_supports';
4952 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4953 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4954 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4957 // Allow the active advanced grading method plugin to append its settings
4958 $featuresfunc = $this->page->activityname.'_supports';
4959 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4960 require_once($CFG->dirroot.'/grade/grading/lib.php');
4961 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4962 $gradingman->extend_settings_navigation($this, $modulenode);
4965 $function = $this->page->activityname.'_extend_settings_navigation';
4966 if (function_exists($function)) {
4967 $function($this, $modulenode);
4970 // Send activity to MoodleNet.
4971 $usercanshare = utilities::can_user_share($this->context->get_course_context(), $USER->id);
4972 $issuerid = get_config('moodlenet', 'oauthservice');
4973 try {
4974 $issuer = \core\oauth2\api::get_issuer($issuerid);
4975 $isvalidinstance = utilities::is_valid_instance($issuer);
4976 if ($usercanshare && $isvalidinstance) {
4977 $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init');
4978 $action = new action_link(new moodle_url(''), '', null, [
4979 'data-action' => 'sendtomoodlenet',
4980 'data-type' => 'activity',
4982 $modulenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'),
4983 $action, self::TYPE_SETTING, null, 'exportmoodlenet')->set_force_into_more_menu(true);
4985 } catch (dml_missing_record_exception $e) {
4986 debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " .
4987 "This must be a valid issuer.");
4990 // Remove the module node if there are no children.
4991 if ($modulenode->children->count() <= 0) {
4992 $modulenode->remove();
4995 return $modulenode;
4999 * Loads the user settings block of the settings nav
5001 * This function is simply works out the userid and whether we need to load
5002 * just the current users profile settings, or the current user and the user the
5003 * current user is viewing.
5005 * This function has some very ugly code to work out the user, if anyone has
5006 * any bright ideas please feel free to intervene.
5008 * @param int $courseid The course id of the current course
5009 * @return navigation_node|false
5011 protected function load_user_settings($courseid = SITEID) {
5012 global $USER, $CFG;
5014 if (isguestuser() || !isloggedin()) {
5015 return false;
5018 $navusers = $this->page->navigation->get_extending_users();
5020 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
5021 $usernode = null;
5022 foreach ($this->userstoextendfor as $userid) {
5023 if ($userid == $USER->id) {
5024 continue;
5026 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
5027 if (is_null($usernode)) {
5028 $usernode = $node;
5031 foreach ($navusers as $user) {
5032 if ($user->id == $USER->id) {
5033 continue;
5035 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
5036 if (is_null($usernode)) {
5037 $usernode = $node;
5040 $this->generate_user_settings($courseid, $USER->id);
5041 } else {
5042 $usernode = $this->generate_user_settings($courseid, $USER->id);
5044 return $usernode;
5048 * Extends the settings navigation for the given user.
5050 * Note: This method gets called automatically if you call
5051 * $PAGE->navigation->extend_for_user($userid)
5053 * @param int $userid
5055 public function extend_for_user($userid) {
5056 global $CFG;
5058 if (!in_array($userid, $this->userstoextendfor)) {
5059 $this->userstoextendfor[] = $userid;
5060 if ($this->initialised) {
5061 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
5062 $children = array();
5063 foreach ($this->children as $child) {
5064 $children[] = $child;
5066 array_unshift($children, array_pop($children));
5067 $this->children = new navigation_node_collection();
5068 foreach ($children as $child) {
5069 $this->children->add($child);
5076 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
5077 * what can be shown/done
5079 * @param int $courseid The current course' id
5080 * @param int $userid The user id to load for
5081 * @param string $gstitle The string to pass to get_string for the branch title
5082 * @return navigation_node|false
5084 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
5085 global $DB, $CFG, $USER, $SITE;
5087 if ($courseid != $SITE->id) {
5088 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
5089 $course = $this->page->course;
5090 } else {
5091 $select = context_helper::get_preload_record_columns_sql('ctx');
5092 $sql = "SELECT c.*, $select
5093 FROM {course} c
5094 JOIN {context} ctx ON c.id = ctx.instanceid
5095 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
5096 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
5097 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
5098 context_helper::preload_from_record($course);
5100 } else {
5101 $course = $SITE;
5104 $coursecontext = context_course::instance($course->id); // Course context
5105 $systemcontext = context_system::instance();
5106 $currentuser = ($USER->id == $userid);
5108 if ($currentuser) {
5109 $user = $USER;
5110 $usercontext = context_user::instance($user->id); // User context
5111 } else {
5112 $select = context_helper::get_preload_record_columns_sql('ctx');
5113 $sql = "SELECT u.*, $select
5114 FROM {user} u
5115 JOIN {context} ctx ON u.id = ctx.instanceid
5116 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
5117 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
5118 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
5119 if (!$user) {
5120 return false;
5122 context_helper::preload_from_record($user);
5124 // Check that the user can view the profile
5125 $usercontext = context_user::instance($user->id); // User context
5126 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
5128 if ($course->id == $SITE->id) {
5129 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
5130 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
5131 return false;
5133 } else {
5134 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
5135 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
5136 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
5137 return false;
5139 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
5140 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
5141 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
5142 if ($courseid == $this->page->course->id) {
5143 $mygroups = get_fast_modinfo($this->page->course)->groups;
5144 } else {
5145 $mygroups = groups_get_user_groups($courseid);
5147 $usergroups = groups_get_user_groups($courseid, $userid);
5148 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
5149 return false;
5155 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
5157 $key = $gstitle;
5158 $prefurl = new moodle_url('/user/preferences.php');
5159 if ($gstitle != 'usercurrentsettings') {
5160 $key .= $userid;
5161 $prefurl->param('userid', $userid);
5164 // Add a user setting branch.
5165 if ($gstitle == 'usercurrentsettings') {
5166 $mainpage = $this->add(get_string('home'), new moodle_url('/'), self::TYPE_CONTAINER, null, 'site');
5168 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
5169 // breadcrumb.
5170 $mainpage->display = false;
5171 $homepage = get_home_page();
5172 if (($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES)) {
5173 $mainpage->mainnavonly = true;
5176 $iscurrentuser = ($user->id == $USER->id);
5178 $baseargs = array('id' => $user->id);
5179 if ($course->id != $SITE->id && !$iscurrentuser) {
5180 $baseargs['course'] = $course->id;
5181 $issitecourse = false;
5182 } else {
5183 // Load all categories and get the context for the system.
5184 $issitecourse = true;
5187 // Add the user profile to the dashboard.
5188 $profilenode = $mainpage->add(get_string('profile'), new moodle_url('/user/profile.php',
5189 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
5191 if (!empty($CFG->navadduserpostslinks)) {
5192 // Add nodes for forum posts and discussions if the user can view either or both
5193 // There are no capability checks here as the content of the page is based
5194 // purely on the forums the current user has access too.
5195 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
5196 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
5197 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
5198 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
5201 // Add blog nodes.
5202 if (!empty($CFG->enableblogs)) {
5203 if (!$this->cache->cached('userblogoptions'.$user->id)) {
5204 require_once($CFG->dirroot.'/blog/lib.php');
5205 // Get all options for the user.
5206 $options = blog_get_options_for_user($user);
5207 $this->cache->set('userblogoptions'.$user->id, $options);
5208 } else {
5209 $options = $this->cache->{'userblogoptions'.$user->id};
5212 if (count($options) > 0) {
5213 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
5214 foreach ($options as $type => $option) {
5215 if ($type == "rss") {
5216 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
5217 new pix_icon('i/rss', ''));
5218 } else {
5219 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
5225 // Add the messages link.
5226 // It is context based so can appear in the user's profile and in course participants information.
5227 if (!empty($CFG->messaging)) {
5228 $messageargs = array('user1' => $USER->id);
5229 if ($USER->id != $user->id) {
5230 $messageargs['user2'] = $user->id;
5232 $url = new moodle_url('/message/index.php', $messageargs);
5233 $mainpage->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
5236 // Add the "My private files" link.
5237 // This link doesn't have a unique display for course context so only display it under the user's profile.
5238 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
5239 $url = new moodle_url('/user/files.php');
5240 $mainpage->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
5243 // Add a node to view the users notes if permitted.
5244 if (!empty($CFG->enablenotes) &&
5245 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
5246 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
5247 if ($coursecontext->instanceid != SITEID) {
5248 $url->param('course', $coursecontext->instanceid);
5250 $profilenode->add(get_string('notes', 'notes'), $url);
5253 // Show the grades node.
5254 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
5255 require_once($CFG->dirroot . '/user/lib.php');
5256 // Set the grades node to link to the "Grades" page.
5257 if ($course->id == SITEID) {
5258 $url = user_mygrades_url($user->id, $course->id);
5259 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
5260 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
5262 $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
5265 // Let plugins hook into user navigation.
5266 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5267 foreach ($pluginsfunction as $plugintype => $plugins) {
5268 if ($plugintype != 'report') {
5269 foreach ($plugins as $pluginfunction) {
5270 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5275 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5276 $mainpage->add_node($usersetting);
5277 } else {
5278 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
5279 $usersetting->display = false;
5281 $usersetting->id = 'usersettings';
5283 // Check if the user has been deleted.
5284 if ($user->deleted) {
5285 if (!has_capability('moodle/user:update', $coursecontext)) {
5286 // We can't edit the user so just show the user deleted message.
5287 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
5288 } else {
5289 // We can edit the user so show the user deleted message and link it to the profile.
5290 if ($course->id == $SITE->id) {
5291 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
5292 } else {
5293 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
5295 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
5297 return true;
5300 $userauthplugin = false;
5301 if (!empty($user->auth)) {
5302 $userauthplugin = get_auth_plugin($user->auth);
5305 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
5307 // Add the profile edit link.
5308 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5309 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
5310 has_capability('moodle/user:update', $systemcontext)) {
5311 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
5312 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5313 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5314 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5315 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5316 $url = $userauthplugin->edit_profile_url();
5317 if (empty($url)) {
5318 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
5320 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5325 // Change password link.
5326 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
5327 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5328 $passwordchangeurl = $userauthplugin->change_password_url();
5329 if (empty($passwordchangeurl)) {
5330 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
5332 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
5335 // Default homepage.
5336 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER));
5337 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5338 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5339 has_capability('moodle/user:editprofile', $usercontext)) {
5340 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]);
5341 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser');
5345 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5346 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5347 has_capability('moodle/user:editprofile', $usercontext)) {
5348 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
5349 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
5352 $pluginmanager = core_plugin_manager::instance();
5353 $enabled = $pluginmanager->get_enabled_plugins('mod');
5354 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5355 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5356 has_capability('moodle/user:editprofile', $usercontext)) {
5357 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
5358 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
5361 $editors = editors_get_enabled();
5362 if (count($editors) > 1) {
5363 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5364 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5365 has_capability('moodle/user:editprofile', $usercontext)) {
5366 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
5367 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
5372 // Add "Calendar preferences" link.
5373 if (isloggedin() && !isguestuser($user)) {
5374 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5375 has_capability('moodle/user:editprofile', $usercontext)) {
5376 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
5377 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
5381 // Add "Content bank preferences" link.
5382 if (isloggedin() && !isguestuser($user)) {
5383 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5384 has_capability('moodle/user:editprofile', $usercontext)) {
5385 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]);
5386 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING,
5387 null, 'contentbankpreferences');
5391 // View the roles settings.
5392 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5393 'moodle/role:manage'], $usercontext)) {
5394 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
5396 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]);
5397 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
5399 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
5401 if (!empty($assignableroles)) {
5402 $url = new moodle_url('/admin/roles/assign.php',
5403 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5404 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
5407 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
5408 $url = new moodle_url('/admin/roles/permissions.php',
5409 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5410 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5413 $url = new moodle_url('/admin/roles/check.php',
5414 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5415 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5418 // Repositories.
5419 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5420 require_once($CFG->dirroot . '/repository/lib.php');
5421 $editabletypes = repository::get_editable_types($usercontext);
5422 $haseditabletypes = !empty($editabletypes);
5423 unset($editabletypes);
5424 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5425 } else {
5426 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5428 if ($haseditabletypes) {
5429 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5430 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5431 array('contextid' => $usercontext->id)));
5434 // Portfolio.
5435 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5436 require_once($CFG->libdir . '/portfoliolib.php');
5437 if (portfolio_has_visible_instances()) {
5438 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5440 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5441 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5443 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5444 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5448 $enablemanagetokens = false;
5449 if (!empty($CFG->enablerssfeeds)) {
5450 $enablemanagetokens = true;
5451 } else if (!is_siteadmin($USER->id)
5452 && !empty($CFG->enablewebservices)
5453 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5454 $enablemanagetokens = true;
5456 // Security keys.
5457 if ($currentuser && $enablemanagetokens) {
5458 $url = new moodle_url('/user/managetoken.php');
5459 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5462 // Messaging.
5463 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5464 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5465 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5466 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5467 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5468 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5471 // Blogs.
5472 if ($currentuser && !empty($CFG->enableblogs)) {
5473 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5474 if (has_capability('moodle/blog:view', $systemcontext)) {
5475 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5476 navigation_node::TYPE_SETTING);
5478 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5479 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5480 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5481 navigation_node::TYPE_SETTING);
5482 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5483 navigation_node::TYPE_SETTING);
5485 // Remove the blog node if empty.
5486 $blog->trim_if_empty();
5489 // Badges.
5490 if ($currentuser && !empty($CFG->enablebadges)) {
5491 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5492 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5493 $url = new moodle_url('/badges/mybadges.php');
5494 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5496 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5497 navigation_node::TYPE_SETTING);
5498 if (!empty($CFG->badges_allowexternalbackpack)) {
5499 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5500 navigation_node::TYPE_SETTING);
5504 // Let plugins hook into user settings navigation.
5505 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5506 foreach ($pluginsfunction as $plugintype => $plugins) {
5507 foreach ($plugins as $pluginfunction) {
5508 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5512 return $usersetting;
5516 * Loads block specific settings in the navigation
5518 * @return navigation_node
5520 protected function load_block_settings() {
5521 global $CFG;
5523 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5524 $blocknode->force_open();
5526 // Assign local roles
5527 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5528 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5529 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5530 'roles', new pix_icon('i/assignroles', ''));
5533 // Override roles
5534 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5535 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5536 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5537 'permissions', new pix_icon('i/permissions', ''));
5539 // Check role permissions
5540 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5541 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5542 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5543 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5546 // Add the context locking node.
5547 $this->add_context_locking_node($blocknode, $this->context);
5549 return $blocknode;
5553 * Loads category specific settings in the navigation
5555 * @return navigation_node
5557 protected function load_category_settings() {
5558 global $CFG;
5560 // We can land here while being in the context of a block, in which case we
5561 // should get the parent context which should be the category one. See self::initialise().
5562 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5563 $catcontext = $this->context->get_parent_context();
5564 } else {
5565 $catcontext = $this->context;
5568 // Let's make sure that we always have the right context when getting here.
5569 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5570 throw new coding_exception('Unexpected context while loading category settings.');
5573 $categorynodetype = navigation_node::TYPE_CONTAINER;
5574 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5575 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5576 $categorynode->force_open();
5578 if (can_edit_in_category($catcontext->instanceid)) {
5579 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5580 $editstring = get_string('managecategorythis');
5581 $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', ''));
5582 $node->set_show_in_secondary_navigation(false);
5585 if (has_capability('moodle/category:manage', $catcontext)) {
5586 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5587 $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5589 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5590 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null,
5591 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false);
5594 // Assign local roles
5595 $assignableroles = get_assignable_roles($catcontext);
5596 if (!empty($assignableroles)) {
5597 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5598 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5601 // Override roles
5602 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5603 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5604 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5606 // Check role permissions
5607 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5608 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5609 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5610 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', ''));
5613 // Add the context locking node.
5614 $this->add_context_locking_node($categorynode, $catcontext);
5616 // Cohorts
5617 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5618 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5619 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5622 // Manage filters
5623 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5624 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5625 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5628 // Restore.
5629 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5630 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5631 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5634 // Let plugins hook into category settings navigation.
5635 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5636 foreach ($pluginsfunction as $plugintype => $plugins) {
5637 foreach ($plugins as $pluginfunction) {
5638 $pluginfunction($categorynode, $catcontext);
5642 $cb = new contentbank();
5643 if ($cb->is_context_allowed($catcontext)
5644 && has_capability('moodle/contentbank:access', $catcontext)) {
5645 $url = new \moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id]);
5646 $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null,
5647 'contentbank', new \pix_icon('i/contentbank', ''));
5650 return $categorynode;
5654 * Determine whether the user is assuming another role
5656 * This function checks to see if the user is assuming another role by means of
5657 * role switching. In doing this we compare each RSW key (context path) against
5658 * the current context path. This ensures that we can provide the switching
5659 * options against both the course and any page shown under the course.
5661 * @return bool|int The role(int) if the user is in another role, false otherwise
5663 protected function in_alternative_role() {
5664 global $USER;
5665 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5666 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5667 return $USER->access['rsw'][$this->page->context->path];
5669 foreach ($USER->access['rsw'] as $key=>$role) {
5670 if (strpos($this->context->path,$key)===0) {
5671 return $role;
5675 return false;
5679 * This function loads all of the front page settings into the settings navigation.
5680 * This function is called when the user is on the front page, or $COURSE==$SITE
5681 * @param bool $forceopen (optional)
5682 * @return navigation_node
5684 protected function load_front_page_settings($forceopen = false) {
5685 global $SITE, $CFG;
5686 require_once($CFG->dirroot . '/course/lib.php');
5688 $course = clone($SITE);
5689 $coursecontext = context_course::instance($course->id); // Course context
5690 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5692 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5693 if ($forceopen) {
5694 $frontpage->force_open();
5696 $frontpage->id = 'frontpagesettings';
5698 if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) {
5700 // Add the turn on/off settings
5701 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5702 if ($this->page->user_is_editing()) {
5703 $url->param('edit', 'off');
5704 $editstring = get_string('turneditingoff');
5705 } else {
5706 $url->param('edit', 'on');
5707 $editstring = get_string('turneditingon');
5709 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5712 if ($adminoptions->update) {
5713 // Add the course settings link
5714 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5715 $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null,
5716 'editsettings', new pix_icon('i/settings', ''));
5719 // add enrol nodes
5720 enrol_add_course_navigation($frontpage, $course);
5722 // Manage filters
5723 if ($adminoptions->filters) {
5724 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5725 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING,
5726 null, 'filtermanagement', new pix_icon('i/filter', ''));
5729 // View course reports.
5730 if ($adminoptions->reports) {
5731 $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php',
5732 ['courseid' => $coursecontext->instanceid]),
5733 self::TYPE_CONTAINER, null, 'coursereports',
5734 new pix_icon('i/stats', ''));
5735 $coursereports = core_component::get_plugin_list('coursereport');
5736 foreach ($coursereports as $report=>$dir) {
5737 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5738 if (file_exists($libfile)) {
5739 require_once($libfile);
5740 $reportfunction = $report.'_report_extend_navigation';
5741 if (function_exists($report.'_report_extend_navigation')) {
5742 $reportfunction($frontpagenav, $course, $coursecontext);
5747 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5748 foreach ($reports as $reportfunction) {
5749 $reportfunction($frontpagenav, $course, $coursecontext);
5752 if (!$frontpagenav->has_children()) {
5753 $frontpagenav->remove();
5757 // Questions
5758 require_once($CFG->libdir . '/questionlib.php');
5759 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5761 // Manage files
5762 if ($adminoptions->files) {
5763 //hiden in new installs
5764 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5765 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5768 // Let plugins hook into frontpage navigation.
5769 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5770 foreach ($pluginsfunction as $plugintype => $plugins) {
5771 foreach ($plugins as $pluginfunction) {
5772 $pluginfunction($frontpage, $course, $coursecontext);
5776 // Course reuse options.
5777 if ($adminoptions->backup || $adminoptions->restore) {
5778 $coursereusenav = $frontpage->add(
5779 get_string('coursereuse'),
5780 new moodle_url('/backup/view.php', ['id' => $course->id]),
5781 self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''),
5784 // Backup this course.
5785 if ($adminoptions->backup) {
5786 $url = new moodle_url('/backup/backup.php', ['id' => $course->id]);
5787 $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
5790 // Restore to this course.
5791 if ($adminoptions->restore) {
5792 $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]);
5793 $coursereusenav->add(
5794 get_string('restore'),
5795 $url,
5796 self::TYPE_SETTING,
5797 null,
5798 'restore',
5799 new pix_icon('i/restore', ''),
5804 return $frontpage;
5808 * This function gives local plugins an opportunity to modify the settings navigation.
5810 protected function load_local_plugin_settings() {
5812 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5813 $function($this, $this->context);
5818 * This function marks the cache as volatile so it is cleared during shutdown
5820 public function clear_cache() {
5821 $this->cache->volatile();
5825 * Checks to see if there are child nodes available in the specific user's preference node.
5826 * If so, then they have the appropriate permissions view this user's preferences.
5828 * @since Moodle 2.9.3
5829 * @param int $userid The user's ID.
5830 * @return bool True if child nodes exist to view, otherwise false.
5832 public function can_view_user_preferences($userid) {
5833 if (is_siteadmin()) {
5834 return true;
5836 // See if any nodes are present in the preferences section for this user.
5837 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5838 if ($preferencenode && $preferencenode->has_children()) {
5839 // Run through each child node.
5840 foreach ($preferencenode->children as $childnode) {
5841 // If the child node has children then this user has access to a link in the preferences page.
5842 if ($childnode->has_children()) {
5843 return true;
5847 // No links found for the user to access on the preferences page.
5848 return false;
5853 * Class used to populate site admin navigation for ajax.
5855 * @package core
5856 * @category navigation
5857 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5860 class settings_navigation_ajax extends settings_navigation {
5862 * Constructs the navigation for use in an AJAX request
5864 * @param moodle_page $page
5866 public function __construct(moodle_page &$page) {
5867 $this->page = $page;
5868 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5869 $this->children = new navigation_node_collection();
5870 $this->initialise();
5874 * Initialise the site admin navigation.
5876 public function initialise() {
5877 if ($this->initialised || during_initial_install()) {
5878 return false;
5880 $this->context = $this->page->context;
5881 $this->load_administration_settings();
5883 // Check if local plugins is adding node to site admin.
5884 $this->load_local_plugin_settings();
5886 $this->initialised = true;
5891 * Simple class used to output a navigation branch in XML
5893 * @package core
5894 * @category navigation
5895 * @copyright 2009 Sam Hemelryk
5896 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5898 class navigation_json {
5899 /** @var array An array of different node types */
5900 protected $nodetype = array('node','branch');
5901 /** @var array An array of node keys and types */
5902 protected $expandable = array();
5904 * Turns a branch and all of its children into XML
5906 * @param navigation_node $branch
5907 * @return string XML string
5909 public function convert($branch) {
5910 $xml = $this->convert_child($branch);
5911 return $xml;
5914 * Set the expandable items in the array so that we have enough information
5915 * to attach AJAX events
5916 * @param array $expandable
5918 public function set_expandable($expandable) {
5919 foreach ($expandable as $node) {
5920 $this->expandable[$node['key'].':'.$node['type']] = $node;
5924 * Recusively converts a child node and its children to XML for output
5926 * @param navigation_node $child The child to convert
5927 * @param int $depth Pointlessly used to track the depth of the XML structure
5928 * @return string JSON
5930 protected function convert_child($child, $depth=1) {
5931 if (!$child->display) {
5932 return '';
5934 $attributes = array();
5935 $attributes['id'] = $child->id;
5936 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5937 $attributes['type'] = $child->type;
5938 $attributes['key'] = $child->key;
5939 $attributes['class'] = $child->get_css_type();
5940 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5942 if ($child->icon instanceof pix_icon) {
5943 $attributes['icon'] = array(
5944 'component' => $child->icon->component,
5945 'pix' => $child->icon->pix,
5947 foreach ($child->icon->attributes as $key=>$value) {
5948 if ($key == 'class') {
5949 $attributes['icon']['classes'] = explode(' ', $value);
5950 } else if (!array_key_exists($key, $attributes['icon'])) {
5951 $attributes['icon'][$key] = $value;
5955 } else if (!empty($child->icon)) {
5956 $attributes['icon'] = (string)$child->icon;
5959 if ($child->forcetitle || $child->title !== $child->text) {
5960 $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8');
5962 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5963 $attributes['expandable'] = $child->key;
5964 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5967 if (count($child->classes)>0) {
5968 $attributes['class'] .= ' '.join(' ',$child->classes);
5970 if (is_string($child->action)) {
5971 $attributes['link'] = $child->action;
5972 } else if ($child->action instanceof moodle_url) {
5973 $attributes['link'] = $child->action->out();
5974 } else if ($child->action instanceof action_link) {
5975 $attributes['link'] = $child->action->url->out();
5977 $attributes['hidden'] = ($child->hidden);
5978 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5979 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5981 if ($child->children->count() > 0) {
5982 $attributes['children'] = array();
5983 foreach ($child->children as $subchild) {
5984 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5988 if ($depth > 1) {
5989 return $attributes;
5990 } else {
5991 return json_encode($attributes);
5997 * The cache class used by global navigation and settings navigation.
5999 * It is basically an easy access point to session with a bit of smarts to make
6000 * sure that the information that is cached is valid still.
6002 * Example use:
6003 * <code php>
6004 * if (!$cache->viewdiscussion()) {
6005 * // Code to do stuff and produce cachable content
6006 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
6008 * $content = $cache->viewdiscussion;
6009 * </code>
6011 * @package core
6012 * @category navigation
6013 * @copyright 2009 Sam Hemelryk
6014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6016 class navigation_cache {
6017 /** @var int represents the time created */
6018 protected $creation;
6019 /** @var array An array of session keys */
6020 protected $session;
6022 * The string to use to segregate this particular cache. It can either be
6023 * unique to start a fresh cache or if you want to share a cache then make
6024 * it the string used in the original cache.
6025 * @var string
6027 protected $area;
6028 /** @var int a time that the information will time out */
6029 protected $timeout;
6030 /** @var stdClass The current context */
6031 protected $currentcontext;
6032 /** @var int cache time information */
6033 const CACHETIME = 0;
6034 /** @var int cache user id */
6035 const CACHEUSERID = 1;
6036 /** @var int cache value */
6037 const CACHEVALUE = 2;
6038 /** @var null|array An array of navigation cache areas to expire on shutdown */
6039 public static $volatilecaches;
6042 * Contructor for the cache. Requires two arguments
6044 * @param string $area The string to use to segregate this particular cache
6045 * it can either be unique to start a fresh cache or if you want
6046 * to share a cache then make it the string used in the original
6047 * cache
6048 * @param int $timeout The number of seconds to time the information out after
6050 public function __construct($area, $timeout=1800) {
6051 $this->creation = time();
6052 $this->area = $area;
6053 $this->timeout = time() - $timeout;
6054 if (rand(0,100) === 0) {
6055 $this->garbage_collection();
6060 * Used to set up the cache within the SESSION.
6062 * This is called for each access and ensure that we don't put anything into the session before
6063 * it is required.
6065 protected function ensure_session_cache_initialised() {
6066 global $SESSION;
6067 if (empty($this->session)) {
6068 if (!isset($SESSION->navcache)) {
6069 $SESSION->navcache = new stdClass;
6071 if (!isset($SESSION->navcache->{$this->area})) {
6072 $SESSION->navcache->{$this->area} = array();
6074 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
6079 * Magic Method to retrieve something by simply calling using = cache->key
6081 * @param mixed $key The identifier for the information you want out again
6082 * @return void|mixed Either void or what ever was put in
6084 public function __get($key) {
6085 if (!$this->cached($key)) {
6086 return;
6088 $information = $this->session[$key][self::CACHEVALUE];
6089 return unserialize($information);
6093 * Magic method that simply uses {@link set();} to store something in the cache
6095 * @param string|int $key
6096 * @param mixed $information
6098 public function __set($key, $information) {
6099 $this->set($key, $information);
6103 * Sets some information against the cache (session) for later retrieval
6105 * @param string|int $key
6106 * @param mixed $information
6108 public function set($key, $information) {
6109 global $USER;
6110 $this->ensure_session_cache_initialised();
6111 $information = serialize($information);
6112 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
6115 * Check the existence of the identifier in the cache
6117 * @param string|int $key
6118 * @return bool
6120 public function cached($key) {
6121 global $USER;
6122 $this->ensure_session_cache_initialised();
6123 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) {
6124 return false;
6126 return true;
6129 * Compare something to it's equivilant in the cache
6131 * @param string $key
6132 * @param mixed $value
6133 * @param bool $serialise Whether to serialise the value before comparison
6134 * this should only be set to false if the value is already
6135 * serialised
6136 * @return bool If the value is the same false if it is not set or doesn't match
6138 public function compare($key, $value, $serialise = true) {
6139 if ($this->cached($key)) {
6140 if ($serialise) {
6141 $value = serialize($value);
6143 if ($this->session[$key][self::CACHEVALUE] === $value) {
6144 return true;
6147 return false;
6150 * Wipes the entire cache, good to force regeneration
6152 public function clear() {
6153 global $SESSION;
6154 unset($SESSION->navcache);
6155 $this->session = null;
6158 * Checks all cache entries and removes any that have expired, good ole cleanup
6160 protected function garbage_collection() {
6161 if (empty($this->session)) {
6162 return true;
6164 foreach ($this->session as $key=>$cachedinfo) {
6165 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
6166 unset($this->session[$key]);
6172 * Marks the cache as being volatile (likely to change)
6174 * Any caches marked as volatile will be destroyed at the on shutdown by
6175 * {@link navigation_node::destroy_volatile_caches()} which is registered
6176 * as a shutdown function if any caches are marked as volatile.
6178 * @param bool $setting True to destroy the cache false not too
6180 public function volatile($setting = true) {
6181 if (self::$volatilecaches===null) {
6182 self::$volatilecaches = array();
6183 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
6186 if ($setting) {
6187 self::$volatilecaches[$this->area] = $this->area;
6188 } else if (array_key_exists($this->area, self::$volatilecaches)) {
6189 unset(self::$volatilecaches[$this->area]);
6194 * Destroys all caches marked as volatile
6196 * This function is static and works in conjunction with the static volatilecaches
6197 * property of navigation cache.
6198 * Because this function is static it manually resets the cached areas back to an
6199 * empty array.
6201 public static function destroy_volatile_caches() {
6202 global $SESSION;
6203 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
6204 foreach (self::$volatilecaches as $area) {
6205 $SESSION->navcache->{$area} = array();
6207 } else {
6208 $SESSION->navcache = new stdClass;