Merge branch 'MDL-64012' of https://github.com/timhunt/moodle
[moodle.git] / lib / navigationlib.php
blob93d32b5d2bdbf05e5e53d3343196b504c81d8524
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since Moodle 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
34 /**
35 * This class is used to represent a node in a navigation tree
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
43 * @package core
44 * @category navigation
45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF = 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH = 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN = null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY = 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
77 /** @var int Setting node type, used only within settings nav 80 */
78 const TYPE_USER = 80;
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE = 'courseindexpage';
90 /** @var int Parameter to aid the coder in tracking [optional] */
91 public $id = null;
92 /** @var string|int The identifier for the node, used to retrieve the node */
93 public $key = null;
94 /** @var string The text to use for the node */
95 public $text = null;
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
99 public $title = null;
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
102 /** @var moodle_url|action_link|null An action for the node (link) */
103 public $action = null;
104 /** @var pix_icon The path to an icon to use for this node */
105 public $icon = null;
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self::TYPE_UNKNOWN;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self::NODETYPE_LEAF;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
114 /** @var array An array of CSS classes for the node */
115 public $classes = array();
116 /** @var navigation_node_collection An array of child nodes */
117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
120 /** @var bool If set to true the node will be dimmed */
121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
131 public $parent = null;
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
136 /** @var array */
137 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
138 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
139 90 => 'container');
140 /** @var moodle_url */
141 protected static $fullmeurl = null;
142 /** @var bool toogles auto matching of active node */
143 public static $autofindactive = true;
144 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
145 protected static $loadadmintree = false;
146 /** @var mixed If set to an int, that section will be included even if it has no activities */
147 public $includesectionnum = false;
148 /** @var bool does the node need to be loaded via ajax */
149 public $requiresajaxloading = false;
150 /** @var bool If set to true this node will be added to the "flat" navigation */
151 public $showinflatnavigation = false;
154 * Constructs a new navigation_node
156 * @param array|string $properties Either an array of properties or a string to use
157 * as the text for the node
159 public function __construct($properties) {
160 if (is_array($properties)) {
161 // Check the array for each property that we allow to set at construction.
162 // text - The main content for the node
163 // shorttext - A short text if required for the node
164 // icon - The icon to display for the node
165 // type - The type of the node
166 // key - The key to use to identify the node
167 // parent - A reference to the nodes parent
168 // action - The action to attribute to this node, usually a URL to link to
169 if (array_key_exists('text', $properties)) {
170 $this->text = $properties['text'];
172 if (array_key_exists('shorttext', $properties)) {
173 $this->shorttext = $properties['shorttext'];
175 if (!array_key_exists('icon', $properties)) {
176 $properties['icon'] = new pix_icon('i/navigationitem', '');
178 $this->icon = $properties['icon'];
179 if ($this->icon instanceof pix_icon) {
180 if (empty($this->icon->attributes['class'])) {
181 $this->icon->attributes['class'] = 'navicon';
182 } else {
183 $this->icon->attributes['class'] .= ' navicon';
186 if (array_key_exists('type', $properties)) {
187 $this->type = $properties['type'];
188 } else {
189 $this->type = self::TYPE_CUSTOM;
191 if (array_key_exists('key', $properties)) {
192 $this->key = $properties['key'];
194 // This needs to happen last because of the check_if_active call that occurs
195 if (array_key_exists('action', $properties)) {
196 $this->action = $properties['action'];
197 if (is_string($this->action)) {
198 $this->action = new moodle_url($this->action);
200 if (self::$autofindactive) {
201 $this->check_if_active();
204 if (array_key_exists('parent', $properties)) {
205 $this->set_parent($properties['parent']);
207 } else if (is_string($properties)) {
208 $this->text = $properties;
210 if ($this->text === null) {
211 throw new coding_exception('You must set the text for the node when you create it.');
213 // Instantiate a new navigation node collection for this nodes children
214 $this->children = new navigation_node_collection();
218 * Checks if this node is the active node.
220 * This is determined by comparing the action for the node against the
221 * defined URL for the page. A match will see this node marked as active.
223 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
224 * @return bool
226 public function check_if_active($strength=URL_MATCH_EXACT) {
227 global $FULLME, $PAGE;
228 // Set fullmeurl if it hasn't already been set
229 if (self::$fullmeurl == null) {
230 if ($PAGE->has_set_url()) {
231 self::override_active_url(new moodle_url($PAGE->url));
232 } else {
233 self::override_active_url(new moodle_url($FULLME));
237 // Compare the action of this node against the fullmeurl
238 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
239 $this->make_active();
240 return true;
242 return false;
246 * True if this nav node has siblings in the tree.
248 * @return bool
250 public function has_siblings() {
251 if (empty($this->parent) || empty($this->parent->children)) {
252 return false;
254 if ($this->parent->children instanceof navigation_node_collection) {
255 $count = $this->parent->children->count();
256 } else {
257 $count = count($this->parent->children);
259 return ($count > 1);
263 * Get a list of sibling navigation nodes at the same level as this one.
265 * @return bool|array of navigation_node
267 public function get_siblings() {
268 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
269 // the in-page links or the breadcrumb links.
270 $siblings = false;
272 if ($this->has_siblings()) {
273 $siblings = [];
274 foreach ($this->parent->children as $child) {
275 if ($child->display) {
276 $siblings[] = $child;
280 return $siblings;
284 * This sets the URL that the URL of new nodes get compared to when locating
285 * the active node.
287 * The active node is the node that matches the URL set here. By default this
288 * is either $PAGE->url or if that hasn't been set $FULLME.
290 * @param moodle_url $url The url to use for the fullmeurl.
291 * @param bool $loadadmintree use true if the URL point to administration tree
293 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
294 // Clone the URL, in case the calling script changes their URL later.
295 self::$fullmeurl = new moodle_url($url);
296 // True means we do not want AJAX loaded admin tree, required for all admin pages.
297 if ($loadadmintree) {
298 // Do not change back to false if already set.
299 self::$loadadmintree = true;
304 * Use when page is linked from the admin tree,
305 * if not used navigation could not find the page using current URL
306 * because the tree is not fully loaded.
308 public static function require_admin_tree() {
309 self::$loadadmintree = true;
313 * Creates a navigation node, ready to add it as a child using add_node
314 * function. (The created node needs to be added before you can use it.)
315 * @param string $text
316 * @param moodle_url|action_link $action
317 * @param int $type
318 * @param string $shorttext
319 * @param string|int $key
320 * @param pix_icon $icon
321 * @return navigation_node
323 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
324 $shorttext=null, $key=null, pix_icon $icon=null) {
325 // Properties array used when creating the new navigation node
326 $itemarray = array(
327 'text' => $text,
328 'type' => $type
330 // Set the action if one was provided
331 if ($action!==null) {
332 $itemarray['action'] = $action;
334 // Set the shorttext if one was provided
335 if ($shorttext!==null) {
336 $itemarray['shorttext'] = $shorttext;
338 // Set the icon if one was provided
339 if ($icon!==null) {
340 $itemarray['icon'] = $icon;
342 // Set the key
343 $itemarray['key'] = $key;
344 // Construct and return
345 return new navigation_node($itemarray);
349 * Adds a navigation node as a child of this node.
351 * @param string $text
352 * @param moodle_url|action_link $action
353 * @param int $type
354 * @param string $shorttext
355 * @param string|int $key
356 * @param pix_icon $icon
357 * @return navigation_node
359 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
360 // Create child node
361 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
363 // Add the child to end and return
364 return $this->add_node($childnode);
368 * Adds a navigation node as a child of this one, given a $node object
369 * created using the create function.
370 * @param navigation_node $childnode Node to add
371 * @param string $beforekey
372 * @return navigation_node The added node
374 public function add_node(navigation_node $childnode, $beforekey=null) {
375 // First convert the nodetype for this node to a branch as it will now have children
376 if ($this->nodetype !== self::NODETYPE_BRANCH) {
377 $this->nodetype = self::NODETYPE_BRANCH;
379 // Set the parent to this node
380 $childnode->set_parent($this);
382 // Default the key to the number of children if not provided
383 if ($childnode->key === null) {
384 $childnode->key = $this->children->count();
387 // Add the child using the navigation_node_collections add method
388 $node = $this->children->add($childnode, $beforekey);
390 // If added node is a category node or the user is logged in and it's a course
391 // then mark added node as a branch (makes it expandable by AJAX)
392 $type = $childnode->type;
393 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
394 ($type === self::TYPE_SITE_ADMIN)) {
395 $node->nodetype = self::NODETYPE_BRANCH;
397 // If this node is hidden mark it's children as hidden also
398 if ($this->hidden) {
399 $node->hidden = true;
401 // Return added node (reference returned by $this->children->add()
402 return $node;
406 * Return a list of all the keys of all the child nodes.
407 * @return array the keys.
409 public function get_children_key_list() {
410 return $this->children->get_key_list();
414 * Searches for a node of the given type with the given key.
416 * This searches this node plus all of its children, and their children....
417 * If you know the node you are looking for is a child of this node then please
418 * use the get method instead.
420 * @param int|string $key The key of the node we are looking for
421 * @param int $type One of navigation_node::TYPE_*
422 * @return navigation_node|false
424 public function find($key, $type) {
425 return $this->children->find($key, $type);
429 * Walk the tree building up a list of all the flat navigation nodes.
431 * @param flat_navigation $nodes List of the found flat navigation nodes.
432 * @param boolean $showdivider Show a divider before the first node.
434 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false) {
435 if ($this->showinflatnavigation) {
436 $indent = 0;
437 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
438 $indent = 1;
440 $flat = new flat_navigation_node($this, $indent);
441 $flat->set_showdivider($showdivider);
442 $nodes->add($flat);
444 foreach ($this->children as $child) {
445 $child->build_flat_navigation_list($nodes, false);
450 * Get the child of this node that has the given key + (optional) type.
452 * If you are looking for a node and want to search all children + their children
453 * then please use the find method instead.
455 * @param int|string $key The key of the node we are looking for
456 * @param int $type One of navigation_node::TYPE_*
457 * @return navigation_node|false
459 public function get($key, $type=null) {
460 return $this->children->get($key, $type);
464 * Removes this node.
466 * @return bool
468 public function remove() {
469 return $this->parent->children->remove($this->key, $this->type);
473 * Checks if this node has or could have any children
475 * @return bool Returns true if it has children or could have (by AJAX expansion)
477 public function has_children() {
478 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
482 * Marks this node as active and forces it open.
484 * Important: If you are here because you need to mark a node active to get
485 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
486 * You can use it to specify a different URL to match the active navigation node on
487 * rather than having to locate and manually mark a node active.
489 public function make_active() {
490 $this->isactive = true;
491 $this->add_class('active_tree_node');
492 $this->force_open();
493 if ($this->parent !== null) {
494 $this->parent->make_inactive();
499 * Marks a node as inactive and recusised back to the base of the tree
500 * doing the same to all parents.
502 public function make_inactive() {
503 $this->isactive = false;
504 $this->remove_class('active_tree_node');
505 if ($this->parent !== null) {
506 $this->parent->make_inactive();
511 * Forces this node to be open and at the same time forces open all
512 * parents until the root node.
514 * Recursive.
516 public function force_open() {
517 $this->forceopen = true;
518 if ($this->parent !== null) {
519 $this->parent->force_open();
524 * Adds a CSS class to this node.
526 * @param string $class
527 * @return bool
529 public function add_class($class) {
530 if (!in_array($class, $this->classes)) {
531 $this->classes[] = $class;
533 return true;
537 * Removes a CSS class from this node.
539 * @param string $class
540 * @return bool True if the class was successfully removed.
542 public function remove_class($class) {
543 if (in_array($class, $this->classes)) {
544 $key = array_search($class,$this->classes);
545 if ($key!==false) {
546 unset($this->classes[$key]);
547 return true;
550 return false;
554 * Sets the title for this node and forces Moodle to utilise it.
555 * @param string $title
557 public function title($title) {
558 $this->title = $title;
559 $this->forcetitle = true;
563 * Resets the page specific information on this node if it is being unserialised.
565 public function __wakeup(){
566 $this->forceopen = false;
567 $this->isactive = false;
568 $this->remove_class('active_tree_node');
572 * Checks if this node or any of its children contain the active node.
574 * Recursive.
576 * @return bool
578 public function contains_active_node() {
579 if ($this->isactive) {
580 return true;
581 } else {
582 foreach ($this->children as $child) {
583 if ($child->isactive || $child->contains_active_node()) {
584 return true;
588 return false;
592 * To better balance the admin tree, we want to group all the short top branches together.
594 * This means < 8 nodes and no subtrees.
596 * @return bool
598 public function is_short_branch() {
599 $limit = 8;
600 if ($this->children->count() >= $limit) {
601 return false;
603 foreach ($this->children as $child) {
604 if ($child->has_children()) {
605 return false;
608 return true;
612 * Finds the active node.
614 * Searches this nodes children plus all of the children for the active node
615 * and returns it if found.
617 * Recursive.
619 * @return navigation_node|false
621 public function find_active_node() {
622 if ($this->isactive) {
623 return $this;
624 } else {
625 foreach ($this->children as &$child) {
626 $outcome = $child->find_active_node();
627 if ($outcome !== false) {
628 return $outcome;
632 return false;
636 * Searches all children for the best matching active node
637 * @return navigation_node|false
639 public function search_for_active_node() {
640 if ($this->check_if_active(URL_MATCH_BASE)) {
641 return $this;
642 } else {
643 foreach ($this->children as &$child) {
644 $outcome = $child->search_for_active_node();
645 if ($outcome !== false) {
646 return $outcome;
650 return false;
654 * Gets the content for this node.
656 * @param bool $shorttext If true shorttext is used rather than the normal text
657 * @return string
659 public function get_content($shorttext=false) {
660 if ($shorttext && $this->shorttext!==null) {
661 return format_string($this->shorttext);
662 } else {
663 return format_string($this->text);
668 * Gets the title to use for this node.
670 * @return string
672 public function get_title() {
673 if ($this->forcetitle || $this->action != null){
674 return $this->title;
675 } else {
676 return '';
681 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
683 * @return boolean
685 public function has_action() {
686 return !empty($this->action);
690 * Used to easily determine if this link in the breadcrumbs is hidden.
692 * @return boolean
694 public function is_hidden() {
695 return $this->hidden;
699 * Gets the CSS class to add to this node to describe its type
701 * @return string
703 public function get_css_type() {
704 if (array_key_exists($this->type, $this->namedtypes)) {
705 return 'type_'.$this->namedtypes[$this->type];
707 return 'type_unknown';
711 * Finds all nodes that are expandable by AJAX
713 * @param array $expandable An array by reference to populate with expandable nodes.
715 public function find_expandable(array &$expandable) {
716 foreach ($this->children as &$child) {
717 if ($child->display && $child->has_children() && $child->children->count() == 0) {
718 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
719 $this->add_class('canexpand');
720 $child->requiresajaxloading = true;
721 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
723 $child->find_expandable($expandable);
728 * Finds all nodes of a given type (recursive)
730 * @param int $type One of navigation_node::TYPE_*
731 * @return array
733 public function find_all_of_type($type) {
734 $nodes = $this->children->type($type);
735 foreach ($this->children as &$node) {
736 $childnodes = $node->find_all_of_type($type);
737 $nodes = array_merge($nodes, $childnodes);
739 return $nodes;
743 * Removes this node if it is empty
745 public function trim_if_empty() {
746 if ($this->children->count() == 0) {
747 $this->remove();
752 * Creates a tab representation of this nodes children that can be used
753 * with print_tabs to produce the tabs on a page.
755 * call_user_func_array('print_tabs', $node->get_tabs_array());
757 * @param array $inactive
758 * @param bool $return
759 * @return array Array (tabs, selected, inactive, activated, return)
761 public function get_tabs_array(array $inactive=array(), $return=false) {
762 $tabs = array();
763 $rows = array();
764 $selected = null;
765 $activated = array();
766 foreach ($this->children as $node) {
767 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
768 if ($node->contains_active_node()) {
769 if ($node->children->count() > 0) {
770 $activated[] = $node->key;
771 foreach ($node->children as $child) {
772 if ($child->contains_active_node()) {
773 $selected = $child->key;
775 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
777 } else {
778 $selected = $node->key;
782 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
786 * Sets the parent for this node and if this node is active ensures that the tree is properly
787 * adjusted as well.
789 * @param navigation_node $parent
791 public function set_parent(navigation_node $parent) {
792 // Set the parent (thats the easy part)
793 $this->parent = $parent;
794 // Check if this node is active (this is checked during construction)
795 if ($this->isactive) {
796 // Force all of the parent nodes open so you can see this node
797 $this->parent->force_open();
798 // Make all parents inactive so that its clear where we are.
799 $this->parent->make_inactive();
804 * Hides the node and any children it has.
806 * @since Moodle 2.5
807 * @param array $typestohide Optional. An array of node types that should be hidden.
808 * If null all nodes will be hidden.
809 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
810 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
812 public function hide(array $typestohide = null) {
813 if ($typestohide === null || in_array($this->type, $typestohide)) {
814 $this->display = false;
815 if ($this->has_children()) {
816 foreach ($this->children as $child) {
817 $child->hide($typestohide);
824 * Get the action url for this navigation node.
825 * Called from templates.
827 * @since Moodle 3.2
829 public function action() {
830 if ($this->action instanceof moodle_url) {
831 return $this->action;
832 } else if ($this->action instanceof action_link) {
833 return $this->action->url;
835 return $this->action;
839 * Add the menu item to handle locking and unlocking of a conext.
841 * @param \navigation_node $node Node to add
842 * @param \context $context The context to be locked
844 protected function add_context_locking_node(\navigation_node $node, \context $context) {
845 global $CFG;
846 // Manage context locking.
847 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
848 $parentcontext = $context->get_parent_context();
849 if (empty($parentcontext) || !$parentcontext->locked) {
850 if ($context->locked) {
851 $lockicon = 'i/unlock';
852 $lockstring = get_string('managecontextunlock', 'admin');
853 } else {
854 $lockicon = 'i/lock';
855 $lockstring = get_string('managecontextlock', 'admin');
857 $node->add(
858 $lockstring,
859 new moodle_url(
860 '/admin/lock.php',
862 'id' => $context->id,
865 self::TYPE_SETTING,
866 null,
867 'contextlocking',
868 new pix_icon($lockicon, '')
877 * Navigation node collection
879 * This class is responsible for managing a collection of navigation nodes.
880 * It is required because a node's unique identifier is a combination of both its
881 * key and its type.
883 * Originally an array was used with a string key that was a combination of the two
884 * however it was decided that a better solution would be to use a class that
885 * implements the standard IteratorAggregate interface.
887 * @package core
888 * @category navigation
889 * @copyright 2010 Sam Hemelryk
890 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
892 class navigation_node_collection implements IteratorAggregate, Countable {
894 * A multidimensional array to where the first key is the type and the second
895 * key is the nodes key.
896 * @var array
898 protected $collection = array();
900 * An array that contains references to nodes in the same order they were added.
901 * This is maintained as a progressive array.
902 * @var array
904 protected $orderedcollection = array();
906 * A reference to the last node that was added to the collection
907 * @var navigation_node
909 protected $last = null;
911 * The total number of items added to this array.
912 * @var int
914 protected $count = 0;
917 * Adds a navigation node to the collection
919 * @param navigation_node $node Node to add
920 * @param string $beforekey If specified, adds before a node with this key,
921 * otherwise adds at end
922 * @return navigation_node Added node
924 public function add(navigation_node $node, $beforekey=null) {
925 global $CFG;
926 $key = $node->key;
927 $type = $node->type;
929 // First check we have a 2nd dimension for this type
930 if (!array_key_exists($type, $this->orderedcollection)) {
931 $this->orderedcollection[$type] = array();
933 // Check for a collision and report if debugging is turned on
934 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
935 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
938 // Find the key to add before
939 $newindex = $this->count;
940 $last = true;
941 if ($beforekey !== null) {
942 foreach ($this->collection as $index => $othernode) {
943 if ($othernode->key === $beforekey) {
944 $newindex = $index;
945 $last = false;
946 break;
949 if ($newindex === $this->count) {
950 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
951 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
955 // Add the node to the appropriate place in the by-type structure (which
956 // is not ordered, despite the variable name)
957 $this->orderedcollection[$type][$key] = $node;
958 if (!$last) {
959 // Update existing references in the ordered collection (which is the
960 // one that isn't called 'ordered') to shuffle them along if required
961 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
962 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
965 // Add a reference to the node to the progressive collection.
966 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
967 // Update the last property to a reference to this new node.
968 $this->last = $this->orderedcollection[$type][$key];
970 // Reorder the array by index if needed
971 if (!$last) {
972 ksort($this->collection);
974 $this->count++;
975 // Return the reference to the now added node
976 return $node;
980 * Return a list of all the keys of all the nodes.
981 * @return array the keys.
983 public function get_key_list() {
984 $keys = array();
985 foreach ($this->collection as $node) {
986 $keys[] = $node->key;
988 return $keys;
992 * Fetches a node from this collection.
994 * @param string|int $key The key of the node we want to find.
995 * @param int $type One of navigation_node::TYPE_*.
996 * @return navigation_node|null
998 public function get($key, $type=null) {
999 if ($type !== null) {
1000 // If the type is known then we can simply check and fetch
1001 if (!empty($this->orderedcollection[$type][$key])) {
1002 return $this->orderedcollection[$type][$key];
1004 } else {
1005 // Because we don't know the type we look in the progressive array
1006 foreach ($this->collection as $node) {
1007 if ($node->key === $key) {
1008 return $node;
1012 return false;
1016 * Searches for a node with matching key and type.
1018 * This function searches both the nodes in this collection and all of
1019 * the nodes in each collection belonging to the nodes in this collection.
1021 * Recursive.
1023 * @param string|int $key The key of the node we want to find.
1024 * @param int $type One of navigation_node::TYPE_*.
1025 * @return navigation_node|null
1027 public function find($key, $type=null) {
1028 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1029 return $this->orderedcollection[$type][$key];
1030 } else {
1031 $nodes = $this->getIterator();
1032 // Search immediate children first
1033 foreach ($nodes as &$node) {
1034 if ($node->key === $key && ($type === null || $type === $node->type)) {
1035 return $node;
1038 // Now search each childs children
1039 foreach ($nodes as &$node) {
1040 $result = $node->children->find($key, $type);
1041 if ($result !== false) {
1042 return $result;
1046 return false;
1050 * Fetches the last node that was added to this collection
1052 * @return navigation_node
1054 public function last() {
1055 return $this->last;
1059 * Fetches all nodes of a given type from this collection
1061 * @param string|int $type node type being searched for.
1062 * @return array ordered collection
1064 public function type($type) {
1065 if (!array_key_exists($type, $this->orderedcollection)) {
1066 $this->orderedcollection[$type] = array();
1068 return $this->orderedcollection[$type];
1071 * Removes the node with the given key and type from the collection
1073 * @param string|int $key The key of the node we want to find.
1074 * @param int $type
1075 * @return bool
1077 public function remove($key, $type=null) {
1078 $child = $this->get($key, $type);
1079 if ($child !== false) {
1080 foreach ($this->collection as $colkey => $node) {
1081 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1082 unset($this->collection[$colkey]);
1083 $this->collection = array_values($this->collection);
1084 break;
1087 unset($this->orderedcollection[$child->type][$child->key]);
1088 $this->count--;
1089 return true;
1091 return false;
1095 * Gets the number of nodes in this collection
1097 * This option uses an internal count rather than counting the actual options to avoid
1098 * a performance hit through the count function.
1100 * @return int
1102 public function count() {
1103 return $this->count;
1106 * Gets an array iterator for the collection.
1108 * This is required by the IteratorAggregator interface and is used by routines
1109 * such as the foreach loop.
1111 * @return ArrayIterator
1113 public function getIterator() {
1114 return new ArrayIterator($this->collection);
1119 * The global navigation class used for... the global navigation
1121 * This class is used by PAGE to store the global navigation for the site
1122 * and is then used by the settings nav and navbar to save on processing and DB calls
1124 * See
1125 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1126 * {@link lib/ajax/getnavbranch.php} Called by ajax
1128 * @package core
1129 * @category navigation
1130 * @copyright 2009 Sam Hemelryk
1131 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1133 class global_navigation extends navigation_node {
1134 /** @var moodle_page The Moodle page this navigation object belongs to. */
1135 protected $page;
1136 /** @var bool switch to let us know if the navigation object is initialised*/
1137 protected $initialised = false;
1138 /** @var array An array of course information */
1139 protected $mycourses = array();
1140 /** @var navigation_node[] An array for containing root navigation nodes */
1141 protected $rootnodes = array();
1142 /** @var bool A switch for whether to show empty sections in the navigation */
1143 protected $showemptysections = true;
1144 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1145 protected $showcategories = null;
1146 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1147 protected $showmycategories = null;
1148 /** @var array An array of stdClasses for users that the navigation is extended for */
1149 protected $extendforuser = array();
1150 /** @var navigation_cache */
1151 protected $cache;
1152 /** @var array An array of course ids that are present in the navigation */
1153 protected $addedcourses = array();
1154 /** @var bool */
1155 protected $allcategoriesloaded = false;
1156 /** @var array An array of category ids that are included in the navigation */
1157 protected $addedcategories = array();
1158 /** @var int expansion limit */
1159 protected $expansionlimit = 0;
1160 /** @var int userid to allow parent to see child's profile page navigation */
1161 protected $useridtouseforparentchecks = 0;
1162 /** @var cache_session A cache that stores information on expanded courses */
1163 protected $cacheexpandcourse = null;
1165 /** Used when loading categories to load all top level categories [parent = 0] **/
1166 const LOAD_ROOT_CATEGORIES = 0;
1167 /** Used when loading categories to load all categories **/
1168 const LOAD_ALL_CATEGORIES = -1;
1171 * Constructs a new global navigation
1173 * @param moodle_page $page The page this navigation object belongs to
1175 public function __construct(moodle_page $page) {
1176 global $CFG, $SITE, $USER;
1178 if (during_initial_install()) {
1179 return;
1182 if (get_home_page() == HOMEPAGE_SITE) {
1183 // We are using the site home for the root element
1184 $properties = array(
1185 'key' => 'home',
1186 'type' => navigation_node::TYPE_SYSTEM,
1187 'text' => get_string('home'),
1188 'action' => new moodle_url('/'),
1189 'icon' => new pix_icon('i/home', '')
1191 } else {
1192 // We are using the users my moodle for the root element
1193 $properties = array(
1194 'key' => 'myhome',
1195 'type' => navigation_node::TYPE_SYSTEM,
1196 'text' => get_string('myhome'),
1197 'action' => new moodle_url('/my/'),
1198 'icon' => new pix_icon('i/dashboard', '')
1202 // Use the parents constructor.... good good reuse
1203 parent::__construct($properties);
1204 $this->showinflatnavigation = true;
1206 // Initalise and set defaults
1207 $this->page = $page;
1208 $this->forceopen = true;
1209 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1213 * Mutator to set userid to allow parent to see child's profile
1214 * page navigation. See MDL-25805 for initial issue. Linked to it
1215 * is an issue explaining why this is a REALLY UGLY HACK thats not
1216 * for you to use!
1218 * @param int $userid userid of profile page that parent wants to navigate around.
1220 public function set_userid_for_parent_checks($userid) {
1221 $this->useridtouseforparentchecks = $userid;
1226 * Initialises the navigation object.
1228 * This causes the navigation object to look at the current state of the page
1229 * that it is associated with and then load the appropriate content.
1231 * This should only occur the first time that the navigation structure is utilised
1232 * which will normally be either when the navbar is called to be displayed or
1233 * when a block makes use of it.
1235 * @return bool
1237 public function initialise() {
1238 global $CFG, $SITE, $USER;
1239 // Check if it has already been initialised
1240 if ($this->initialised || during_initial_install()) {
1241 return true;
1243 $this->initialised = true;
1245 // Set up the five base root nodes. These are nodes where we will put our
1246 // content and are as follows:
1247 // site: Navigation for the front page.
1248 // myprofile: User profile information goes here.
1249 // currentcourse: The course being currently viewed.
1250 // mycourses: The users courses get added here.
1251 // courses: Additional courses are added here.
1252 // users: Other users information loaded here.
1253 $this->rootnodes = array();
1254 if (get_home_page() == HOMEPAGE_SITE) {
1255 // The home element should be my moodle because the root element is the site
1256 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1257 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1258 self::TYPE_SETTING, null, 'home', new pix_icon('i/dashboard', ''));
1259 $this->rootnodes['home']->showinflatnavigation = true;
1261 } else {
1262 // The home element should be the site because the root node is my moodle
1263 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1264 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1265 $this->rootnodes['home']->showinflatnavigation = true;
1266 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1267 // We need to stop automatic redirection
1268 $this->rootnodes['home']->action->param('redirect', '0');
1271 $this->rootnodes['site'] = $this->add_course($SITE);
1272 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1273 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1274 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
1275 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1276 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1278 // We always load the frontpage course to ensure it is available without
1279 // JavaScript enabled.
1280 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1281 $this->load_course_sections($SITE, $this->rootnodes['site']);
1283 $course = $this->page->course;
1284 $this->load_courses_enrolled();
1286 // $issite gets set to true if the current pages course is the sites frontpage course
1287 $issite = ($this->page->course->id == $SITE->id);
1289 // Determine if the user is enrolled in any course.
1290 $enrolledinanycourse = enrol_user_sees_own_courses();
1292 $this->rootnodes['currentcourse']->mainnavonly = true;
1293 if ($enrolledinanycourse) {
1294 $this->rootnodes['mycourses']->isexpandable = true;
1295 $this->rootnodes['mycourses']->showinflatnavigation = true;
1296 if ($CFG->navshowallcourses) {
1297 // When we show all courses we need to show both the my courses and the regular courses branch.
1298 $this->rootnodes['courses']->isexpandable = true;
1300 } else {
1301 $this->rootnodes['courses']->isexpandable = true;
1303 $this->rootnodes['mycourses']->forceopen = true;
1305 $canviewcourseprofile = true;
1307 // Next load context specific content into the navigation
1308 switch ($this->page->context->contextlevel) {
1309 case CONTEXT_SYSTEM :
1310 // Nothing left to do here I feel.
1311 break;
1312 case CONTEXT_COURSECAT :
1313 // This is essential, we must load categories.
1314 $this->load_all_categories($this->page->context->instanceid, true);
1315 break;
1316 case CONTEXT_BLOCK :
1317 case CONTEXT_COURSE :
1318 if ($issite) {
1319 // Nothing left to do here.
1320 break;
1323 // Load the course associated with the current page into the navigation.
1324 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1325 // If the course wasn't added then don't try going any further.
1326 if (!$coursenode) {
1327 $canviewcourseprofile = false;
1328 break;
1331 // If the user is not enrolled then we only want to show the
1332 // course node and not populate it.
1334 // Not enrolled, can't view, and hasn't switched roles
1335 if (!can_access_course($course, null, '', true)) {
1336 if ($coursenode->isexpandable === true) {
1337 // Obviously the situation has changed, update the cache and adjust the node.
1338 // This occurs if the user access to a course has been revoked (one way or another) after
1339 // initially logging in for this session.
1340 $this->get_expand_course_cache()->set($course->id, 1);
1341 $coursenode->isexpandable = true;
1342 $coursenode->nodetype = self::NODETYPE_BRANCH;
1344 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1345 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1346 if (!$this->current_user_is_parent_role()) {
1347 $coursenode->make_active();
1348 $canviewcourseprofile = false;
1349 break;
1351 } else if ($coursenode->isexpandable === false) {
1352 // Obviously the situation has changed, update the cache and adjust the node.
1353 // This occurs if the user has been granted access to a course (one way or another) after initially
1354 // logging in for this session.
1355 $this->get_expand_course_cache()->set($course->id, 1);
1356 $coursenode->isexpandable = true;
1357 $coursenode->nodetype = self::NODETYPE_BRANCH;
1360 // Add the essentials such as reports etc...
1361 $this->add_course_essentials($coursenode, $course);
1362 // Extend course navigation with it's sections/activities
1363 $this->load_course_sections($course, $coursenode);
1364 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1365 $coursenode->make_active();
1368 break;
1369 case CONTEXT_MODULE :
1370 if ($issite) {
1371 // If this is the site course then most information will have
1372 // already been loaded.
1373 // However we need to check if there is more content that can
1374 // yet be loaded for the specific module instance.
1375 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1376 if ($activitynode) {
1377 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1379 break;
1382 $course = $this->page->course;
1383 $cm = $this->page->cm;
1385 // Load the course associated with the page into the navigation
1386 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1388 // If the course wasn't added then don't try going any further.
1389 if (!$coursenode) {
1390 $canviewcourseprofile = false;
1391 break;
1394 // If the user is not enrolled then we only want to show the
1395 // course node and not populate it.
1396 if (!can_access_course($course, null, '', true)) {
1397 $coursenode->make_active();
1398 $canviewcourseprofile = false;
1399 break;
1402 $this->add_course_essentials($coursenode, $course);
1404 // Load the course sections into the page
1405 $this->load_course_sections($course, $coursenode, null, $cm);
1406 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1407 if (!empty($activity)) {
1408 // Finally load the cm specific navigaton information
1409 $this->load_activity($cm, $course, $activity);
1410 // Check if we have an active ndoe
1411 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1412 // And make the activity node active.
1413 $activity->make_active();
1416 break;
1417 case CONTEXT_USER :
1418 if ($issite) {
1419 // The users profile information etc is already loaded
1420 // for the front page.
1421 break;
1423 $course = $this->page->course;
1424 // Load the course associated with the user into the navigation
1425 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1427 // If the course wasn't added then don't try going any further.
1428 if (!$coursenode) {
1429 $canviewcourseprofile = false;
1430 break;
1433 // If the user is not enrolled then we only want to show the
1434 // course node and not populate it.
1435 if (!can_access_course($course, null, '', true)) {
1436 $coursenode->make_active();
1437 $canviewcourseprofile = false;
1438 break;
1440 $this->add_course_essentials($coursenode, $course);
1441 $this->load_course_sections($course, $coursenode);
1442 break;
1445 // Load for the current user
1446 $this->load_for_user();
1447 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1448 $this->load_for_user(null, true);
1450 // Load each extending user into the navigation.
1451 foreach ($this->extendforuser as $user) {
1452 if ($user->id != $USER->id) {
1453 $this->load_for_user($user);
1457 // Give the local plugins a chance to include some navigation if they want.
1458 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1459 $function($this);
1462 // Remove any empty root nodes
1463 foreach ($this->rootnodes as $node) {
1464 // Dont remove the home node
1465 /** @var navigation_node $node */
1466 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1467 $node->remove();
1471 if (!$this->contains_active_node()) {
1472 $this->search_for_active_node();
1475 // If the user is not logged in modify the navigation structure as detailed
1476 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1477 if (!isloggedin()) {
1478 $activities = clone($this->rootnodes['site']->children);
1479 $this->rootnodes['site']->remove();
1480 $children = clone($this->children);
1481 $this->children = new navigation_node_collection();
1482 foreach ($activities as $child) {
1483 $this->children->add($child);
1485 foreach ($children as $child) {
1486 $this->children->add($child);
1489 return true;
1493 * Returns true if the current user is a parent of the user being currently viewed.
1495 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1496 * other user being viewed this function returns false.
1497 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1499 * @since Moodle 2.4
1500 * @return bool
1502 protected function current_user_is_parent_role() {
1503 global $USER, $DB;
1504 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1505 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1506 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1507 return false;
1509 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1510 return true;
1513 return false;
1517 * Returns true if courses should be shown within categories on the navigation.
1519 * @param bool $ismycourse Set to true if you are calculating this for a course.
1520 * @return bool
1522 protected function show_categories($ismycourse = false) {
1523 global $CFG, $DB;
1524 if ($ismycourse) {
1525 return $this->show_my_categories();
1527 if ($this->showcategories === null) {
1528 $show = false;
1529 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1530 $show = true;
1531 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1532 $show = true;
1534 $this->showcategories = $show;
1536 return $this->showcategories;
1540 * Returns true if we should show categories in the My Courses branch.
1541 * @return bool
1543 protected function show_my_categories() {
1544 global $CFG;
1545 if ($this->showmycategories === null) {
1546 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && core_course_category::count_all() > 1;
1548 return $this->showmycategories;
1552 * Loads the courses in Moodle into the navigation.
1554 * @global moodle_database $DB
1555 * @param string|array $categoryids An array containing categories to load courses
1556 * for, OR null to load courses for all categories.
1557 * @return array An array of navigation_nodes one for each course
1559 protected function load_all_courses($categoryids = null) {
1560 global $CFG, $DB, $SITE;
1562 // Work out the limit of courses.
1563 $limit = 20;
1564 if (!empty($CFG->navcourselimit)) {
1565 $limit = $CFG->navcourselimit;
1568 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1570 // If we are going to show all courses AND we are showing categories then
1571 // to save us repeated DB calls load all of the categories now
1572 if ($this->show_categories()) {
1573 $this->load_all_categories($toload);
1576 // Will be the return of our efforts
1577 $coursenodes = array();
1579 // Check if we need to show categories.
1580 if ($this->show_categories()) {
1581 // Hmmm we need to show categories... this is going to be painful.
1582 // We now need to fetch up to $limit courses for each category to
1583 // be displayed.
1584 if ($categoryids !== null) {
1585 if (!is_array($categoryids)) {
1586 $categoryids = array($categoryids);
1588 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1589 $categorywhere = 'WHERE cc.id '.$categorywhere;
1590 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1591 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1592 $categoryparams = array();
1593 } else {
1594 $categorywhere = '';
1595 $categoryparams = array();
1598 // First up we are going to get the categories that we are going to
1599 // need so that we can determine how best to load the courses from them.
1600 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1601 FROM {course_categories} cc
1602 LEFT JOIN {course} c ON c.category = cc.id
1603 {$categorywhere}
1604 GROUP BY cc.id";
1605 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1606 $fullfetch = array();
1607 $partfetch = array();
1608 foreach ($categories as $category) {
1609 if (!$this->can_add_more_courses_to_category($category->id)) {
1610 continue;
1612 if ($category->coursecount > $limit * 5) {
1613 $partfetch[] = $category->id;
1614 } else if ($category->coursecount > 0) {
1615 $fullfetch[] = $category->id;
1618 $categories->close();
1620 if (count($fullfetch)) {
1621 // First up fetch all of the courses in categories where we know that we are going to
1622 // need the majority of courses.
1623 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1624 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1625 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1626 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1627 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1628 FROM {course} c
1629 $ccjoin
1630 WHERE c.category {$categoryids}
1631 ORDER BY c.sortorder ASC";
1632 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1633 foreach ($coursesrs as $course) {
1634 if ($course->id == $SITE->id) {
1635 // This should not be necessary, frontpage is not in any category.
1636 continue;
1638 if (array_key_exists($course->id, $this->addedcourses)) {
1639 // It is probably better to not include the already loaded courses
1640 // directly in SQL because inequalities may confuse query optimisers
1641 // and may interfere with query caching.
1642 continue;
1644 if (!$this->can_add_more_courses_to_category($course->category)) {
1645 continue;
1647 context_helper::preload_from_record($course);
1648 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1649 continue;
1651 $coursenodes[$course->id] = $this->add_course($course);
1653 $coursesrs->close();
1656 if (count($partfetch)) {
1657 // Next we will work our way through the categories where we will likely only need a small
1658 // proportion of the courses.
1659 foreach ($partfetch as $categoryid) {
1660 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1661 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1662 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1663 FROM {course} c
1664 $ccjoin
1665 WHERE c.category = :categoryid
1666 ORDER BY c.sortorder ASC";
1667 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1668 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1669 foreach ($coursesrs as $course) {
1670 if ($course->id == $SITE->id) {
1671 // This should not be necessary, frontpage is not in any category.
1672 continue;
1674 if (array_key_exists($course->id, $this->addedcourses)) {
1675 // It is probably better to not include the already loaded courses
1676 // directly in SQL because inequalities may confuse query optimisers
1677 // and may interfere with query caching.
1678 // This also helps to respect expected $limit on repeated executions.
1679 continue;
1681 if (!$this->can_add_more_courses_to_category($course->category)) {
1682 break;
1684 context_helper::preload_from_record($course);
1685 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1686 continue;
1688 $coursenodes[$course->id] = $this->add_course($course);
1690 $coursesrs->close();
1693 } else {
1694 // Prepare the SQL to load the courses and their contexts
1695 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1696 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1697 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1698 $courseparams['contextlevel'] = CONTEXT_COURSE;
1699 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1700 FROM {course} c
1701 $ccjoin
1702 WHERE c.id {$courseids}
1703 ORDER BY c.sortorder ASC";
1704 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1705 foreach ($coursesrs as $course) {
1706 if ($course->id == $SITE->id) {
1707 // frotpage is not wanted here
1708 continue;
1710 if ($this->page->course && ($this->page->course->id == $course->id)) {
1711 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1712 continue;
1714 context_helper::preload_from_record($course);
1715 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1716 continue;
1718 $coursenodes[$course->id] = $this->add_course($course);
1719 if (count($coursenodes) >= $limit) {
1720 break;
1723 $coursesrs->close();
1726 return $coursenodes;
1730 * Returns true if more courses can be added to the provided category.
1732 * @param int|navigation_node|stdClass $category
1733 * @return bool
1735 protected function can_add_more_courses_to_category($category) {
1736 global $CFG;
1737 $limit = 20;
1738 if (!empty($CFG->navcourselimit)) {
1739 $limit = (int)$CFG->navcourselimit;
1741 if (is_numeric($category)) {
1742 if (!array_key_exists($category, $this->addedcategories)) {
1743 return true;
1745 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1746 } else if ($category instanceof navigation_node) {
1747 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1748 return false;
1750 $coursecount = count($category->children->type(self::TYPE_COURSE));
1751 } else if (is_object($category) && property_exists($category,'id')) {
1752 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1754 return ($coursecount <= $limit);
1758 * Loads all categories (top level or if an id is specified for that category)
1760 * @param int $categoryid The category id to load or null/0 to load all base level categories
1761 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1762 * as the requested category and any parent categories.
1763 * @return navigation_node|void returns a navigation node if a category has been loaded.
1765 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1766 global $CFG, $DB;
1768 // Check if this category has already been loaded
1769 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1770 return true;
1773 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1774 $sqlselect = "SELECT cc.*, $catcontextsql
1775 FROM {course_categories} cc
1776 JOIN {context} ctx ON cc.id = ctx.instanceid";
1777 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1778 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1779 $params = array();
1781 $categoriestoload = array();
1782 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1783 // We are going to load all categories regardless... prepare to fire
1784 // on the database server!
1785 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1786 // We are going to load all of the first level categories (categories without parents)
1787 $sqlwhere .= " AND cc.parent = 0";
1788 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1789 // The category itself has been loaded already so we just need to ensure its subcategories
1790 // have been loaded
1791 $addedcategories = $this->addedcategories;
1792 unset($addedcategories[$categoryid]);
1793 if (count($addedcategories) > 0) {
1794 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1795 if ($showbasecategories) {
1796 // We need to include categories with parent = 0 as well
1797 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1798 } else {
1799 // All we need is categories that match the parent
1800 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1803 $params['categoryid'] = $categoryid;
1804 } else {
1805 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1806 // and load this category plus all its parents and subcategories
1807 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1808 $categoriestoload = explode('/', trim($category->path, '/'));
1809 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1810 // We are going to use select twice so double the params
1811 $params = array_merge($params, $params);
1812 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1813 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1816 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1817 $categories = array();
1818 foreach ($categoriesrs as $category) {
1819 // Preload the context.. we'll need it when adding the category in order
1820 // to format the category name.
1821 context_helper::preload_from_record($category);
1822 if (array_key_exists($category->id, $this->addedcategories)) {
1823 // Do nothing, its already been added.
1824 } else if ($category->parent == '0') {
1825 // This is a root category lets add it immediately
1826 $this->add_category($category, $this->rootnodes['courses']);
1827 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1828 // This categories parent has already been added we can add this immediately
1829 $this->add_category($category, $this->addedcategories[$category->parent]);
1830 } else {
1831 $categories[] = $category;
1834 $categoriesrs->close();
1836 // Now we have an array of categories we need to add them to the navigation.
1837 while (!empty($categories)) {
1838 $category = reset($categories);
1839 if (array_key_exists($category->id, $this->addedcategories)) {
1840 // Do nothing
1841 } else if ($category->parent == '0') {
1842 $this->add_category($category, $this->rootnodes['courses']);
1843 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1844 $this->add_category($category, $this->addedcategories[$category->parent]);
1845 } else {
1846 // This category isn't in the navigation and niether is it's parent (yet).
1847 // We need to go through the category path and add all of its components in order.
1848 $path = explode('/', trim($category->path, '/'));
1849 foreach ($path as $catid) {
1850 if (!array_key_exists($catid, $this->addedcategories)) {
1851 // This category isn't in the navigation yet so add it.
1852 $subcategory = $categories[$catid];
1853 if ($subcategory->parent == '0') {
1854 // Yay we have a root category - this likely means we will now be able
1855 // to add categories without problems.
1856 $this->add_category($subcategory, $this->rootnodes['courses']);
1857 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1858 // The parent is in the category (as we'd expect) so add it now.
1859 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1860 // Remove the category from the categories array.
1861 unset($categories[$catid]);
1862 } else {
1863 // We should never ever arrive here - if we have then there is a bigger
1864 // problem at hand.
1865 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1870 // Remove the category from the categories array now that we know it has been added.
1871 unset($categories[$category->id]);
1873 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1874 $this->allcategoriesloaded = true;
1876 // Check if there are any categories to load.
1877 if (count($categoriestoload) > 0) {
1878 $readytoloadcourses = array();
1879 foreach ($categoriestoload as $category) {
1880 if ($this->can_add_more_courses_to_category($category)) {
1881 $readytoloadcourses[] = $category;
1884 if (count($readytoloadcourses)) {
1885 $this->load_all_courses($readytoloadcourses);
1889 // Look for all categories which have been loaded
1890 if (!empty($this->addedcategories)) {
1891 $categoryids = array();
1892 foreach ($this->addedcategories as $category) {
1893 if ($this->can_add_more_courses_to_category($category)) {
1894 $categoryids[] = $category->key;
1897 if ($categoryids) {
1898 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1899 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1900 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1901 FROM {course_categories} cc
1902 JOIN {course} c ON c.category = cc.id
1903 WHERE cc.id {$categoriessql}
1904 GROUP BY cc.id
1905 HAVING COUNT(c.id) > :limit";
1906 $excessivecategories = $DB->get_records_sql($sql, $params);
1907 foreach ($categories as &$category) {
1908 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1909 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1910 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1918 * Adds a structured category to the navigation in the correct order/place
1920 * @param stdClass $category category to be added in navigation.
1921 * @param navigation_node $parent parent navigation node
1922 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1923 * @return void.
1925 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1926 if (array_key_exists($category->id, $this->addedcategories)) {
1927 return;
1929 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1930 $context = context_coursecat::instance($category->id);
1931 $categoryname = format_string($category->name, true, array('context' => $context));
1932 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1933 if (empty($category->visible)) {
1934 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1935 $categorynode->hidden = true;
1936 } else {
1937 $categorynode->display = false;
1940 $this->addedcategories[$category->id] = $categorynode;
1944 * Loads the given course into the navigation
1946 * @param stdClass $course
1947 * @return navigation_node
1949 protected function load_course(stdClass $course) {
1950 global $SITE;
1951 if ($course->id == $SITE->id) {
1952 // This is always loaded during initialisation
1953 return $this->rootnodes['site'];
1954 } else if (array_key_exists($course->id, $this->addedcourses)) {
1955 // The course has already been loaded so return a reference
1956 return $this->addedcourses[$course->id];
1957 } else {
1958 // Add the course
1959 return $this->add_course($course);
1964 * Loads all of the courses section into the navigation.
1966 * This function calls method from current course format, see
1967 * {@link format_base::extend_course_navigation()}
1968 * If course module ($cm) is specified but course format failed to create the node,
1969 * the activity node is created anyway.
1971 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1973 * @param stdClass $course Database record for the course
1974 * @param navigation_node $coursenode The course node within the navigation
1975 * @param null|int $sectionnum If specified load the contents of section with this relative number
1976 * @param null|cm_info $cm If specified make sure that activity node is created (either
1977 * in containg section or by calling load_stealth_activity() )
1979 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1980 global $CFG, $SITE;
1981 require_once($CFG->dirroot.'/course/lib.php');
1982 if (isset($cm->sectionnum)) {
1983 $sectionnum = $cm->sectionnum;
1985 if ($sectionnum !== null) {
1986 $this->includesectionnum = $sectionnum;
1988 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1989 if (isset($cm->id)) {
1990 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1991 if (empty($activity)) {
1992 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1998 * Generates an array of sections and an array of activities for the given course.
2000 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2002 * @param stdClass $course
2003 * @return array Array($sections, $activities)
2005 protected function generate_sections_and_activities(stdClass $course) {
2006 global $CFG;
2007 require_once($CFG->dirroot.'/course/lib.php');
2009 $modinfo = get_fast_modinfo($course);
2010 $sections = $modinfo->get_section_info_all();
2012 // For course formats using 'numsections' trim the sections list
2013 $courseformatoptions = course_get_format($course)->get_format_options();
2014 if (isset($courseformatoptions['numsections'])) {
2015 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2018 $activities = array();
2020 foreach ($sections as $key => $section) {
2021 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2022 $sections[$key] = clone($section);
2023 unset($sections[$key]->summary);
2024 $sections[$key]->hasactivites = false;
2025 if (!array_key_exists($section->section, $modinfo->sections)) {
2026 continue;
2028 foreach ($modinfo->sections[$section->section] as $cmid) {
2029 $cm = $modinfo->cms[$cmid];
2030 $activity = new stdClass;
2031 $activity->id = $cm->id;
2032 $activity->course = $course->id;
2033 $activity->section = $section->section;
2034 $activity->name = $cm->name;
2035 $activity->icon = $cm->icon;
2036 $activity->iconcomponent = $cm->iconcomponent;
2037 $activity->hidden = (!$cm->visible);
2038 $activity->modname = $cm->modname;
2039 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2040 $activity->onclick = $cm->onclick;
2041 $url = $cm->url;
2042 if (!$url) {
2043 $activity->url = null;
2044 $activity->display = false;
2045 } else {
2046 $activity->url = $url->out();
2047 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2048 if (self::module_extends_navigation($cm->modname)) {
2049 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2052 $activities[$cmid] = $activity;
2053 if ($activity->display) {
2054 $sections[$key]->hasactivites = true;
2059 return array($sections, $activities);
2063 * Generically loads the course sections into the course's navigation.
2065 * @param stdClass $course
2066 * @param navigation_node $coursenode
2067 * @return array An array of course section nodes
2069 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2070 global $CFG, $DB, $USER, $SITE;
2071 require_once($CFG->dirroot.'/course/lib.php');
2073 list($sections, $activities) = $this->generate_sections_and_activities($course);
2075 $navigationsections = array();
2076 foreach ($sections as $sectionid => $section) {
2077 $section = clone($section);
2078 if ($course->id == $SITE->id) {
2079 $this->load_section_activities($coursenode, $section->section, $activities);
2080 } else {
2081 if (!$section->uservisible || (!$this->showemptysections &&
2082 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2083 continue;
2086 $sectionname = get_section_name($course, $section);
2087 $url = course_get_url($course, $section->section, array('navigation' => true));
2089 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2090 null, $section->id, new pix_icon('i/section', ''));
2091 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2092 $sectionnode->hidden = (!$section->visible || !$section->available);
2093 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2094 $this->load_section_activities($sectionnode, $section->section, $activities);
2096 $section->sectionnode = $sectionnode;
2097 $navigationsections[$sectionid] = $section;
2100 return $navigationsections;
2104 * Loads all of the activities for a section into the navigation structure.
2106 * @param navigation_node $sectionnode
2107 * @param int $sectionnumber
2108 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2109 * @param stdClass $course The course object the section and activities relate to.
2110 * @return array Array of activity nodes
2112 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2113 global $CFG, $SITE;
2114 // A static counter for JS function naming
2115 static $legacyonclickcounter = 0;
2117 $activitynodes = array();
2118 if (empty($activities)) {
2119 return $activitynodes;
2122 if (!is_object($course)) {
2123 $activity = reset($activities);
2124 $courseid = $activity->course;
2125 } else {
2126 $courseid = $course->id;
2128 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2130 foreach ($activities as $activity) {
2131 if ($activity->section != $sectionnumber) {
2132 continue;
2134 if ($activity->icon) {
2135 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2136 } else {
2137 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2140 // Prepare the default name and url for the node
2141 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2142 $action = new moodle_url($activity->url);
2144 // Check if the onclick property is set (puke!)
2145 if (!empty($activity->onclick)) {
2146 // Increment the counter so that we have a unique number.
2147 $legacyonclickcounter++;
2148 // Generate the function name we will use
2149 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2150 $propogrationhandler = '';
2151 // Check if we need to cancel propogation. Remember inline onclick
2152 // events would return false if they wanted to prevent propogation and the
2153 // default action.
2154 if (strpos($activity->onclick, 'return false')) {
2155 $propogrationhandler = 'e.halt();';
2157 // Decode the onclick - it has already been encoded for display (puke)
2158 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2159 // Build the JS function the click event will call
2160 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2161 $this->page->requires->js_amd_inline($jscode);
2162 // Override the default url with the new action link
2163 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2166 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2167 $activitynode->title(get_string('modulename', $activity->modname));
2168 $activitynode->hidden = $activity->hidden;
2169 $activitynode->display = $showactivities && $activity->display;
2170 $activitynode->nodetype = $activity->nodetype;
2171 $activitynodes[$activity->id] = $activitynode;
2174 return $activitynodes;
2177 * Loads a stealth module from unavailable section
2178 * @param navigation_node $coursenode
2179 * @param stdClass $modinfo
2180 * @return navigation_node or null if not accessible
2182 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2183 if (empty($modinfo->cms[$this->page->cm->id])) {
2184 return null;
2186 $cm = $modinfo->cms[$this->page->cm->id];
2187 if ($cm->icon) {
2188 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2189 } else {
2190 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2192 $url = $cm->url;
2193 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2194 $activitynode->title(get_string('modulename', $cm->modname));
2195 $activitynode->hidden = (!$cm->visible);
2196 if (!$cm->is_visible_on_course_page()) {
2197 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2198 // Also there may be no exception at all in case when teacher is logged in as student.
2199 $activitynode->display = false;
2200 } else if (!$url) {
2201 // Don't show activities that don't have links!
2202 $activitynode->display = false;
2203 } else if (self::module_extends_navigation($cm->modname)) {
2204 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2206 return $activitynode;
2209 * Loads the navigation structure for the given activity into the activities node.
2211 * This method utilises a callback within the modules lib.php file to load the
2212 * content specific to activity given.
2214 * The callback is a method: {modulename}_extend_navigation()
2215 * Examples:
2216 * * {@link forum_extend_navigation()}
2217 * * {@link workshop_extend_navigation()}
2219 * @param cm_info|stdClass $cm
2220 * @param stdClass $course
2221 * @param navigation_node $activity
2222 * @return bool
2224 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2225 global $CFG, $DB;
2227 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2228 if (!($cm instanceof cm_info)) {
2229 $modinfo = get_fast_modinfo($course);
2230 $cm = $modinfo->get_cm($cm->id);
2232 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2233 $activity->make_active();
2234 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2235 $function = $cm->modname.'_extend_navigation';
2237 if (file_exists($file)) {
2238 require_once($file);
2239 if (function_exists($function)) {
2240 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2241 $function($activity, $course, $activtyrecord, $cm);
2245 // Allow the active advanced grading method plugin to append module navigation
2246 $featuresfunc = $cm->modname.'_supports';
2247 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2248 require_once($CFG->dirroot.'/grade/grading/lib.php');
2249 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2250 $gradingman->extend_navigation($this, $activity);
2253 return $activity->has_children();
2256 * Loads user specific information into the navigation in the appropriate place.
2258 * If no user is provided the current user is assumed.
2260 * @param stdClass $user
2261 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2262 * @return bool
2264 protected function load_for_user($user=null, $forceforcontext=false) {
2265 global $DB, $CFG, $USER, $SITE;
2267 require_once($CFG->dirroot . '/course/lib.php');
2269 if ($user === null) {
2270 // We can't require login here but if the user isn't logged in we don't
2271 // want to show anything
2272 if (!isloggedin() || isguestuser()) {
2273 return false;
2275 $user = $USER;
2276 } else if (!is_object($user)) {
2277 // If the user is not an object then get them from the database
2278 $select = context_helper::get_preload_record_columns_sql('ctx');
2279 $sql = "SELECT u.*, $select
2280 FROM {user} u
2281 JOIN {context} ctx ON u.id = ctx.instanceid
2282 WHERE u.id = :userid AND
2283 ctx.contextlevel = :contextlevel";
2284 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2285 context_helper::preload_from_record($user);
2288 $iscurrentuser = ($user->id == $USER->id);
2290 $usercontext = context_user::instance($user->id);
2292 // Get the course set against the page, by default this will be the site
2293 $course = $this->page->course;
2294 $baseargs = array('id'=>$user->id);
2295 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2296 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2297 $baseargs['course'] = $course->id;
2298 $coursecontext = context_course::instance($course->id);
2299 $issitecourse = false;
2300 } else {
2301 // Load all categories and get the context for the system
2302 $coursecontext = context_system::instance();
2303 $issitecourse = true;
2306 // Create a node to add user information under.
2307 $usersnode = null;
2308 if (!$issitecourse) {
2309 // Not the current user so add it to the participants node for the current course.
2310 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2311 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2312 } else if ($USER->id != $user->id) {
2313 // This is the site so add a users node to the root branch.
2314 $usersnode = $this->rootnodes['users'];
2315 if (course_can_view_participants($coursecontext)) {
2316 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2318 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2320 if (!$usersnode) {
2321 // We should NEVER get here, if the course hasn't been populated
2322 // with a participants node then the navigaiton either wasn't generated
2323 // for it (you are missing a require_login or set_context call) or
2324 // you don't have access.... in the interests of no leaking informatin
2325 // we simply quit...
2326 return false;
2328 // Add a branch for the current user.
2329 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2330 $viewprofile = true;
2331 if (!$iscurrentuser) {
2332 require_once($CFG->dirroot . '/user/lib.php');
2333 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2334 $viewprofile = false;
2335 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2336 $viewprofile = false;
2338 if (!$viewprofile) {
2339 $viewprofile = user_can_view_profile($user, null, $usercontext);
2343 // Now, conditionally add the user node.
2344 if ($viewprofile) {
2345 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2346 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2347 } else {
2348 $usernode = $usersnode->add(get_string('user'));
2351 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2352 $usernode->make_active();
2355 // Add user information to the participants or user node.
2356 if ($issitecourse) {
2358 // If the user is the current user or has permission to view the details of the requested
2359 // user than add a view profile link.
2360 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2361 has_capability('moodle/user:viewdetails', $usercontext)) {
2362 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2363 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2364 } else {
2365 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2369 if (!empty($CFG->navadduserpostslinks)) {
2370 // Add nodes for forum posts and discussions if the user can view either or both
2371 // There are no capability checks here as the content of the page is based
2372 // purely on the forums the current user has access too.
2373 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2374 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2375 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2376 array_merge($baseargs, array('mode' => 'discussions'))));
2379 // Add blog nodes.
2380 if (!empty($CFG->enableblogs)) {
2381 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2382 require_once($CFG->dirroot.'/blog/lib.php');
2383 // Get all options for the user.
2384 $options = blog_get_options_for_user($user);
2385 $this->cache->set('userblogoptions'.$user->id, $options);
2386 } else {
2387 $options = $this->cache->{'userblogoptions'.$user->id};
2390 if (count($options) > 0) {
2391 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2392 foreach ($options as $type => $option) {
2393 if ($type == "rss") {
2394 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2395 new pix_icon('i/rss', ''));
2396 } else {
2397 $blogs->add($option['string'], $option['link']);
2403 // Add the messages link.
2404 // It is context based so can appear in the user's profile and in course participants information.
2405 if (!empty($CFG->messaging)) {
2406 $messageargs = array('user1' => $USER->id);
2407 if ($USER->id != $user->id) {
2408 $messageargs['user2'] = $user->id;
2410 $url = new moodle_url('/message/index.php', $messageargs);
2411 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2414 // Add the "My private files" link.
2415 // This link doesn't have a unique display for course context so only display it under the user's profile.
2416 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2417 $url = new moodle_url('/user/files.php');
2418 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2421 // Add a node to view the users notes if permitted.
2422 if (!empty($CFG->enablenotes) &&
2423 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2424 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2425 if ($coursecontext->instanceid != SITEID) {
2426 $url->param('course', $coursecontext->instanceid);
2428 $usernode->add(get_string('notes', 'notes'), $url);
2431 // Show the grades node.
2432 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2433 require_once($CFG->dirroot . '/user/lib.php');
2434 // Set the grades node to link to the "Grades" page.
2435 if ($course->id == SITEID) {
2436 $url = user_mygrades_url($user->id, $course->id);
2437 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2438 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2440 if ($USER->id != $user->id) {
2441 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2442 } else {
2443 $usernode->add(get_string('grades', 'grades'), $url);
2447 // If the user is the current user add the repositories for the current user.
2448 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2449 if (!$iscurrentuser &&
2450 $course->id == $SITE->id &&
2451 has_capability('moodle/user:viewdetails', $usercontext) &&
2452 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2454 // Add view grade report is permitted.
2455 $reports = core_component::get_plugin_list('gradereport');
2456 arsort($reports); // User is last, we want to test it first.
2458 $userscourses = enrol_get_users_courses($user->id, false, '*');
2459 $userscoursesnode = $usernode->add(get_string('courses'));
2461 $count = 0;
2462 foreach ($userscourses as $usercourse) {
2463 if ($count === (int)$CFG->navcourselimit) {
2464 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2465 $userscoursesnode->add(get_string('showallcourses'), $url);
2466 break;
2468 $count++;
2469 $usercoursecontext = context_course::instance($usercourse->id);
2470 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2471 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2472 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2474 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2475 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2476 foreach ($reports as $plugin => $plugindir) {
2477 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2478 // Stop when the first visible plugin is found.
2479 $gradeavailable = true;
2480 break;
2485 if ($gradeavailable) {
2486 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2487 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2488 new pix_icon('i/grades', ''));
2491 // Add a node to view the users notes if permitted.
2492 if (!empty($CFG->enablenotes) &&
2493 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2494 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2495 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2498 if (can_access_course($usercourse, $user->id, '', true)) {
2499 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2500 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2503 $reporttab = $usercoursenode->add(get_string('activityreports'));
2505 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2506 foreach ($reportfunctions as $reportfunction) {
2507 $reportfunction($reporttab, $user, $usercourse);
2510 $reporttab->trim_if_empty();
2514 // Let plugins hook into user navigation.
2515 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2516 foreach ($pluginsfunction as $plugintype => $plugins) {
2517 if ($plugintype != 'report') {
2518 foreach ($plugins as $pluginfunction) {
2519 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2524 return true;
2528 * This method simply checks to see if a given module can extend the navigation.
2530 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2532 * @param string $modname
2533 * @return bool
2535 public static function module_extends_navigation($modname) {
2536 global $CFG;
2537 static $extendingmodules = array();
2538 if (!array_key_exists($modname, $extendingmodules)) {
2539 $extendingmodules[$modname] = false;
2540 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2541 if (file_exists($file)) {
2542 $function = $modname.'_extend_navigation';
2543 require_once($file);
2544 $extendingmodules[$modname] = (function_exists($function));
2547 return $extendingmodules[$modname];
2550 * Extends the navigation for the given user.
2552 * @param stdClass $user A user from the database
2554 public function extend_for_user($user) {
2555 $this->extendforuser[] = $user;
2559 * Returns all of the users the navigation is being extended for
2561 * @return array An array of extending users.
2563 public function get_extending_users() {
2564 return $this->extendforuser;
2567 * Adds the given course to the navigation structure.
2569 * @param stdClass $course
2570 * @param bool $forcegeneric
2571 * @param bool $ismycourse
2572 * @return navigation_node
2574 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2575 global $CFG, $SITE;
2577 // We found the course... we can return it now :)
2578 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2579 return $this->addedcourses[$course->id];
2582 $coursecontext = context_course::instance($course->id);
2584 if ($course->id != $SITE->id && !$course->visible) {
2585 if (is_role_switched($course->id)) {
2586 // user has to be able to access course in order to switch, let's skip the visibility test here
2587 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2588 return false;
2592 $issite = ($course->id == $SITE->id);
2593 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2594 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2595 // This is the name that will be shown for the course.
2596 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2598 if ($coursetype == self::COURSE_CURRENT) {
2599 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2600 return $coursenode;
2601 } else {
2602 $coursetype = self::COURSE_OTHER;
2606 // Can the user expand the course to see its content.
2607 $canexpandcourse = true;
2608 if ($issite) {
2609 $parent = $this;
2610 $url = null;
2611 if (empty($CFG->usesitenameforsitepages)) {
2612 $coursename = get_string('sitepages');
2614 } else if ($coursetype == self::COURSE_CURRENT) {
2615 $parent = $this->rootnodes['currentcourse'];
2616 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2617 $canexpandcourse = $this->can_expand_course($course);
2618 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2619 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2620 // Nothing to do here the above statement set $parent to the category within mycourses.
2621 } else {
2622 $parent = $this->rootnodes['mycourses'];
2624 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2625 } else {
2626 $parent = $this->rootnodes['courses'];
2627 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2628 // They can only expand the course if they can access it.
2629 $canexpandcourse = $this->can_expand_course($course);
2630 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2631 if (!$this->is_category_fully_loaded($course->category)) {
2632 // We need to load the category structure for this course
2633 $this->load_all_categories($course->category, false);
2635 if (array_key_exists($course->category, $this->addedcategories)) {
2636 $parent = $this->addedcategories[$course->category];
2637 // This could lead to the course being created so we should check whether it is the case again
2638 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2639 return $this->addedcourses[$course->id];
2645 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2646 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2648 $coursenode->hidden = (!$course->visible);
2649 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2650 if ($canexpandcourse) {
2651 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2652 $coursenode->nodetype = self::NODETYPE_BRANCH;
2653 $coursenode->isexpandable = true;
2654 } else {
2655 $coursenode->nodetype = self::NODETYPE_LEAF;
2656 $coursenode->isexpandable = false;
2658 if (!$forcegeneric) {
2659 $this->addedcourses[$course->id] = $coursenode;
2662 return $coursenode;
2666 * Returns a cache instance to use for the expand course cache.
2667 * @return cache_session
2669 protected function get_expand_course_cache() {
2670 if ($this->cacheexpandcourse === null) {
2671 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2673 return $this->cacheexpandcourse;
2677 * Checks if a user can expand a course in the navigation.
2679 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2680 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2681 * permits stale data.
2682 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2683 * will be stale.
2684 * It is brought up to date in only one of two ways.
2685 * 1. The user logs out and in again.
2686 * 2. The user browses to the course they've just being given access to.
2688 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2690 * @param stdClass $course
2691 * @return bool
2693 protected function can_expand_course($course) {
2694 $cache = $this->get_expand_course_cache();
2695 $canexpand = $cache->get($course->id);
2696 if ($canexpand === false) {
2697 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2698 $canexpand = (int)$canexpand;
2699 $cache->set($course->id, $canexpand);
2701 return ($canexpand === 1);
2705 * Returns true if the category has already been loaded as have any child categories
2707 * @param int $categoryid
2708 * @return bool
2710 protected function is_category_fully_loaded($categoryid) {
2711 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2715 * Adds essential course nodes to the navigation for the given course.
2717 * This method adds nodes such as reports, blogs and participants
2719 * @param navigation_node $coursenode
2720 * @param stdClass $course
2721 * @return bool returns true on successful addition of a node.
2723 public function add_course_essentials($coursenode, stdClass $course) {
2724 global $CFG, $SITE;
2725 require_once($CFG->dirroot . '/course/lib.php');
2727 if ($course->id == $SITE->id) {
2728 return $this->add_front_page_course_essentials($coursenode, $course);
2731 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2732 return true;
2735 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2737 //Participants
2738 if ($navoptions->participants) {
2739 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2740 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2742 if ($navoptions->blogs) {
2743 $blogsurls = new moodle_url('/blog/index.php');
2744 if ($currentgroup = groups_get_course_group($course, true)) {
2745 $blogsurls->param('groupid', $currentgroup);
2746 } else {
2747 $blogsurls->param('courseid', $course->id);
2749 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2752 if ($navoptions->notes) {
2753 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2755 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2756 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2759 // Badges.
2760 if ($navoptions->badges) {
2761 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2763 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2764 navigation_node::TYPE_SETTING, null, 'badgesview',
2765 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2768 // Check access to the course and competencies page.
2769 if ($navoptions->competencies) {
2770 // Just a link to course competency.
2771 $title = get_string('competencies', 'core_competency');
2772 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2773 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2774 new pix_icon('i/competencies', ''));
2776 if ($navoptions->grades) {
2777 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2778 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2779 'grades', new pix_icon('i/grades', ''));
2780 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2781 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2782 $gradenode->make_active();
2786 return true;
2789 * This generates the structure of the course that won't be generated when
2790 * the modules and sections are added.
2792 * Things such as the reports branch, the participants branch, blogs... get
2793 * added to the course node by this method.
2795 * @param navigation_node $coursenode
2796 * @param stdClass $course
2797 * @return bool True for successfull generation
2799 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2800 global $CFG, $USER, $COURSE, $SITE;
2801 require_once($CFG->dirroot . '/course/lib.php');
2803 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2804 return true;
2807 $sitecontext = context_system::instance();
2808 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2810 // Hidden node that we use to determine if the front page navigation is loaded.
2811 // This required as there are not other guaranteed nodes that may be loaded.
2812 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2814 // Participants.
2815 if ($navoptions->participants) {
2816 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2819 // Blogs.
2820 if ($navoptions->blogs) {
2821 $blogsurls = new moodle_url('/blog/index.php');
2822 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2825 $filterselect = 0;
2827 // Badges.
2828 if ($navoptions->badges) {
2829 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2830 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2833 // Notes.
2834 if ($navoptions->notes) {
2835 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2836 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2839 // Tags
2840 if ($navoptions->tags) {
2841 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2842 self::TYPE_SETTING, null, 'tags');
2845 // Search.
2846 if ($navoptions->search) {
2847 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2848 self::TYPE_SETTING, null, 'search');
2851 if ($navoptions->calendar) {
2852 $courseid = $COURSE->id;
2853 $params = array('view' => 'month');
2854 if ($courseid != $SITE->id) {
2855 $params['course'] = $courseid;
2858 // Calendar
2859 $calendarurl = new moodle_url('/calendar/view.php', $params);
2860 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2861 self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
2862 $node->showinflatnavigation = true;
2865 if (isloggedin()) {
2866 $usercontext = context_user::instance($USER->id);
2867 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2868 $url = new moodle_url('/user/files.php');
2869 $node = $coursenode->add(get_string('privatefiles'), $url,
2870 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2871 $node->display = false;
2872 $node->showinflatnavigation = true;
2876 return true;
2880 * Clears the navigation cache
2882 public function clear_cache() {
2883 $this->cache->clear();
2887 * Sets an expansion limit for the navigation
2889 * The expansion limit is used to prevent the display of content that has a type
2890 * greater than the provided $type.
2892 * Can be used to ensure things such as activities or activity content don't get
2893 * shown on the navigation.
2894 * They are still generated in order to ensure the navbar still makes sense.
2896 * @param int $type One of navigation_node::TYPE_*
2897 * @return bool true when complete.
2899 public function set_expansion_limit($type) {
2900 global $SITE;
2901 $nodes = $this->find_all_of_type($type);
2903 // We only want to hide specific types of nodes.
2904 // Only nodes that represent "structure" in the navigation tree should be hidden.
2905 // If we hide all nodes then we risk hiding vital information.
2906 $typestohide = array(
2907 self::TYPE_CATEGORY,
2908 self::TYPE_COURSE,
2909 self::TYPE_SECTION,
2910 self::TYPE_ACTIVITY
2913 foreach ($nodes as $node) {
2914 // We need to generate the full site node
2915 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2916 continue;
2918 foreach ($node->children as $child) {
2919 $child->hide($typestohide);
2922 return true;
2925 * Attempts to get the navigation with the given key from this nodes children.
2927 * This function only looks at this nodes children, it does NOT look recursivily.
2928 * If the node can't be found then false is returned.
2930 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2932 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2933 * may be of more use to you.
2935 * @param string|int $key The key of the node you wish to receive.
2936 * @param int $type One of navigation_node::TYPE_*
2937 * @return navigation_node|false
2939 public function get($key, $type = null) {
2940 if (!$this->initialised) {
2941 $this->initialise();
2943 return parent::get($key, $type);
2947 * Searches this nodes children and their children to find a navigation node
2948 * with the matching key and type.
2950 * This method is recursive and searches children so until either a node is
2951 * found or there are no more nodes to search.
2953 * If you know that the node being searched for is a child of this node
2954 * then use the {@link global_navigation::get()} method instead.
2956 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2957 * may be of more use to you.
2959 * @param string|int $key The key of the node you wish to receive.
2960 * @param int $type One of navigation_node::TYPE_*
2961 * @return navigation_node|false
2963 public function find($key, $type) {
2964 if (!$this->initialised) {
2965 $this->initialise();
2967 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2968 return $this->rootnodes[$key];
2970 return parent::find($key, $type);
2974 * They've expanded the 'my courses' branch.
2976 protected function load_courses_enrolled() {
2977 global $CFG;
2979 $limit = (int) $CFG->navcourselimit;
2981 $courses = enrol_get_my_courses('*');
2982 $flatnavcourses = [];
2984 // Go through the courses and see which ones we want to display in the flatnav.
2985 foreach ($courses as $course) {
2986 $classify = course_classify_for_timeline($course);
2988 if ($classify == COURSE_TIMELINE_INPROGRESS) {
2989 $flatnavcourses[$course->id] = $course;
2993 // Get the number of courses that can be displayed in the nav block and in the flatnav.
2994 $numtotalcourses = count($courses);
2995 $numtotalflatnavcourses = count($flatnavcourses);
2997 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
2998 $courses = array_slice($courses, 0, $limit, true);
2999 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3001 // Get the number of courses we are going to show for each.
3002 $numshowncourses = count($courses);
3003 $numshownflatnavcourses = count($flatnavcourses);
3004 if ($numshowncourses && $this->show_my_categories()) {
3005 // Generate an array containing unique values of all the courses' categories.
3006 $categoryids = array();
3007 foreach ($courses as $course) {
3008 if (in_array($course->category, $categoryids)) {
3009 continue;
3011 $categoryids[] = $course->category;
3014 // Array of category IDs that include the categories of the user's courses and the related course categories.
3015 $fullpathcategoryids = [];
3016 // Get the course categories for the enrolled courses' category IDs.
3017 $mycoursecategories = core_course_category::get_many($categoryids);
3018 // Loop over each of these categories and build the category tree using each category's path.
3019 foreach ($mycoursecategories as $mycoursecat) {
3020 $pathcategoryids = explode('/', $mycoursecat->path);
3021 // First element of the exploded path is empty since paths begin with '/'.
3022 array_shift($pathcategoryids);
3023 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3024 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3027 // Fetch all of the categories related to the user's courses.
3028 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3029 // Loop over each of these categories and build the category tree.
3030 foreach ($pathcategories as $coursecat) {
3031 // No need to process categories that have already been added.
3032 if (isset($this->addedcategories[$coursecat->id])) {
3033 continue;
3036 // Get this course category's parent node.
3037 $parent = null;
3038 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3039 $parent = $this->addedcategories[$coursecat->parent];
3041 if (!$parent) {
3042 // If it has no parent, then it should be right under the My courses node.
3043 $parent = $this->rootnodes['mycourses'];
3046 // Build the category object based from the coursecat object.
3047 $mycategory = new stdClass();
3048 $mycategory->id = $coursecat->id;
3049 $mycategory->name = $coursecat->name;
3050 $mycategory->visible = $coursecat->visible;
3052 // Add this category to the nav tree.
3053 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3057 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3058 foreach ($courses as $course) {
3059 $node = $this->add_course($course, false, self::COURSE_MY);
3060 if ($node) {
3061 $node->showinflatnavigation = false;
3062 // Check if we should also add this to the flat nav as well.
3063 if (isset($flatnavcourses[$course->id])) {
3064 $node->showinflatnavigation = true;
3069 // Go through each course in the flatnav now.
3070 foreach ($flatnavcourses as $course) {
3071 // Check if we haven't already added it.
3072 if (!isset($courses[$course->id])) {
3073 // Ok, add it to the flatnav only.
3074 $node = $this->add_course($course, false, self::COURSE_MY);
3075 $node->display = false;
3076 $node->showinflatnavigation = true;
3080 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3081 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3082 // Show a link to the course page if there are more courses the user is enrolled in.
3083 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3084 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3085 $url = new moodle_url('/my/');
3086 $parent = $this->rootnodes['mycourses'];
3087 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3089 if ($showmorelinkinnav) {
3090 $coursenode->display = true;
3093 if ($showmorelinkinflatnav) {
3094 $coursenode->showinflatnavigation = true;
3101 * The global navigation class used especially for AJAX requests.
3103 * The primary methods that are used in the global navigation class have been overriden
3104 * to ensure that only the relevant branch is generated at the root of the tree.
3105 * This can be done because AJAX is only used when the backwards structure for the
3106 * requested branch exists.
3107 * This has been done only because it shortens the amounts of information that is generated
3108 * which of course will speed up the response time.. because no one likes laggy AJAX.
3110 * @package core
3111 * @category navigation
3112 * @copyright 2009 Sam Hemelryk
3113 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3115 class global_navigation_for_ajax extends global_navigation {
3117 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3118 protected $branchtype;
3120 /** @var int the instance id */
3121 protected $instanceid;
3123 /** @var array Holds an array of expandable nodes */
3124 protected $expandable = array();
3127 * Constructs the navigation for use in an AJAX request
3129 * @param moodle_page $page moodle_page object
3130 * @param int $branchtype
3131 * @param int $id
3133 public function __construct($page, $branchtype, $id) {
3134 $this->page = $page;
3135 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3136 $this->children = new navigation_node_collection();
3137 $this->branchtype = $branchtype;
3138 $this->instanceid = $id;
3139 $this->initialise();
3142 * Initialise the navigation given the type and id for the branch to expand.
3144 * @return array An array of the expandable nodes
3146 public function initialise() {
3147 global $DB, $SITE;
3149 if ($this->initialised || during_initial_install()) {
3150 return $this->expandable;
3152 $this->initialised = true;
3154 $this->rootnodes = array();
3155 $this->rootnodes['site'] = $this->add_course($SITE);
3156 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3157 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3158 // The courses branch is always displayed, and is always expandable (although may be empty).
3159 // This mimicks what is done during {@link global_navigation::initialise()}.
3160 $this->rootnodes['courses']->isexpandable = true;
3162 // Branchtype will be one of navigation_node::TYPE_*
3163 switch ($this->branchtype) {
3164 case 0:
3165 if ($this->instanceid === 'mycourses') {
3166 $this->load_courses_enrolled();
3167 } else if ($this->instanceid === 'courses') {
3168 $this->load_courses_other();
3170 break;
3171 case self::TYPE_CATEGORY :
3172 $this->load_category($this->instanceid);
3173 break;
3174 case self::TYPE_MY_CATEGORY :
3175 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3176 break;
3177 case self::TYPE_COURSE :
3178 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3179 if (!can_access_course($course, null, '', true)) {
3180 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3181 // add the course node and break. This leads to an empty node.
3182 $this->add_course($course);
3183 break;
3185 require_course_login($course, true, null, false, true);
3186 $this->page->set_context(context_course::instance($course->id));
3187 $coursenode = $this->add_course($course);
3188 $this->add_course_essentials($coursenode, $course);
3189 $this->load_course_sections($course, $coursenode);
3190 break;
3191 case self::TYPE_SECTION :
3192 $sql = 'SELECT c.*, cs.section AS sectionnumber
3193 FROM {course} c
3194 LEFT JOIN {course_sections} cs ON cs.course = c.id
3195 WHERE cs.id = ?';
3196 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3197 require_course_login($course, true, null, false, true);
3198 $this->page->set_context(context_course::instance($course->id));
3199 $coursenode = $this->add_course($course);
3200 $this->add_course_essentials($coursenode, $course);
3201 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3202 break;
3203 case self::TYPE_ACTIVITY :
3204 $sql = "SELECT c.*
3205 FROM {course} c
3206 JOIN {course_modules} cm ON cm.course = c.id
3207 WHERE cm.id = :cmid";
3208 $params = array('cmid' => $this->instanceid);
3209 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3210 $modinfo = get_fast_modinfo($course);
3211 $cm = $modinfo->get_cm($this->instanceid);
3212 require_course_login($course, true, $cm, false, true);
3213 $this->page->set_context(context_module::instance($cm->id));
3214 $coursenode = $this->load_course($course);
3215 $this->load_course_sections($course, $coursenode, null, $cm);
3216 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3217 if ($activitynode) {
3218 $modulenode = $this->load_activity($cm, $course, $activitynode);
3220 break;
3221 default:
3222 throw new Exception('Unknown type');
3223 return $this->expandable;
3226 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3227 $this->load_for_user(null, true);
3230 $this->find_expandable($this->expandable);
3231 return $this->expandable;
3235 * They've expanded the general 'courses' branch.
3237 protected function load_courses_other() {
3238 $this->load_all_courses();
3242 * Loads a single category into the AJAX navigation.
3244 * This function is special in that it doesn't concern itself with the parent of
3245 * the requested category or its siblings.
3246 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3247 * request that.
3249 * @global moodle_database $DB
3250 * @param int $categoryid id of category to load in navigation.
3251 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3252 * @return void.
3254 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3255 global $CFG, $DB;
3257 $limit = 20;
3258 if (!empty($CFG->navcourselimit)) {
3259 $limit = (int)$CFG->navcourselimit;
3262 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3263 $sql = "SELECT cc.*, $catcontextsql
3264 FROM {course_categories} cc
3265 JOIN {context} ctx ON cc.id = ctx.instanceid
3266 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3267 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3268 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3269 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3270 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3271 $categorylist = array();
3272 $subcategories = array();
3273 $basecategory = null;
3274 foreach ($categories as $category) {
3275 $categorylist[] = $category->id;
3276 context_helper::preload_from_record($category);
3277 if ($category->id == $categoryid) {
3278 $this->add_category($category, $this, $nodetype);
3279 $basecategory = $this->addedcategories[$category->id];
3280 } else {
3281 $subcategories[$category->id] = $category;
3284 $categories->close();
3287 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3288 // else show all courses.
3289 if ($nodetype === self::TYPE_MY_CATEGORY) {
3290 $courses = enrol_get_my_courses('*');
3291 $categoryids = array();
3293 // Only search for categories if basecategory was found.
3294 if (!is_null($basecategory)) {
3295 // Get course parent category ids.
3296 foreach ($courses as $course) {
3297 $categoryids[] = $course->category;
3300 // Get a unique list of category ids which a part of the path
3301 // to user's courses.
3302 $coursesubcategories = array();
3303 $addedsubcategories = array();
3305 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3306 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3308 foreach ($categories as $category){
3309 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3311 $categories->close();
3312 $coursesubcategories = array_unique($coursesubcategories);
3314 // Only add a subcategory if it is part of the path to user's course and
3315 // wasn't already added.
3316 foreach ($subcategories as $subid => $subcategory) {
3317 if (in_array($subid, $coursesubcategories) &&
3318 !in_array($subid, $addedsubcategories)) {
3319 $this->add_category($subcategory, $basecategory, $nodetype);
3320 $addedsubcategories[] = $subid;
3325 foreach ($courses as $course) {
3326 // Add course if it's in category.
3327 if (in_array($course->category, $categorylist)) {
3328 $this->add_course($course, true, self::COURSE_MY);
3331 } else {
3332 if (!is_null($basecategory)) {
3333 foreach ($subcategories as $key=>$category) {
3334 $this->add_category($category, $basecategory, $nodetype);
3337 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3338 foreach ($courses as $course) {
3339 $this->add_course($course);
3341 $courses->close();
3346 * Returns an array of expandable nodes
3347 * @return array
3349 public function get_expandable() {
3350 return $this->expandable;
3355 * Navbar class
3357 * This class is used to manage the navbar, which is initialised from the navigation
3358 * object held by PAGE
3360 * @package core
3361 * @category navigation
3362 * @copyright 2009 Sam Hemelryk
3363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3365 class navbar extends navigation_node {
3366 /** @var bool A switch for whether the navbar is initialised or not */
3367 protected $initialised = false;
3368 /** @var mixed keys used to reference the nodes on the navbar */
3369 protected $keys = array();
3370 /** @var null|string content of the navbar */
3371 protected $content = null;
3372 /** @var moodle_page object the moodle page that this navbar belongs to */
3373 protected $page;
3374 /** @var bool A switch for whether to ignore the active navigation information */
3375 protected $ignoreactive = false;
3376 /** @var bool A switch to let us know if we are in the middle of an install */
3377 protected $duringinstall = false;
3378 /** @var bool A switch for whether the navbar has items */
3379 protected $hasitems = false;
3380 /** @var array An array of navigation nodes for the navbar */
3381 protected $items;
3382 /** @var array An array of child node objects */
3383 public $children = array();
3384 /** @var bool A switch for whether we want to include the root node in the navbar */
3385 public $includesettingsbase = false;
3386 /** @var breadcrumb_navigation_node[] $prependchildren */
3387 protected $prependchildren = array();
3390 * The almighty constructor
3392 * @param moodle_page $page
3394 public function __construct(moodle_page $page) {
3395 global $CFG;
3396 if (during_initial_install()) {
3397 $this->duringinstall = true;
3398 return false;
3400 $this->page = $page;
3401 $this->text = get_string('home');
3402 $this->shorttext = get_string('home');
3403 $this->action = new moodle_url($CFG->wwwroot);
3404 $this->nodetype = self::NODETYPE_BRANCH;
3405 $this->type = self::TYPE_SYSTEM;
3409 * Quick check to see if the navbar will have items in.
3411 * @return bool Returns true if the navbar will have items, false otherwise
3413 public function has_items() {
3414 if ($this->duringinstall) {
3415 return false;
3416 } else if ($this->hasitems !== false) {
3417 return true;
3419 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3420 // There have been manually added items - there are definitely items.
3421 $outcome = true;
3422 } else if (!$this->ignoreactive) {
3423 // We will need to initialise the navigation structure to check if there are active items.
3424 $this->page->navigation->initialise($this->page);
3425 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3427 $this->hasitems = $outcome;
3428 return $outcome;
3432 * Turn on/off ignore active
3434 * @param bool $setting
3436 public function ignore_active($setting=true) {
3437 $this->ignoreactive = ($setting);
3441 * Gets a navigation node
3443 * @param string|int $key for referencing the navbar nodes
3444 * @param int $type breadcrumb_navigation_node::TYPE_*
3445 * @return breadcrumb_navigation_node|bool
3447 public function get($key, $type = null) {
3448 foreach ($this->children as &$child) {
3449 if ($child->key === $key && ($type == null || $type == $child->type)) {
3450 return $child;
3453 foreach ($this->prependchildren as &$child) {
3454 if ($child->key === $key && ($type == null || $type == $child->type)) {
3455 return $child;
3458 return false;
3461 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3463 * @return array
3465 public function get_items() {
3466 global $CFG;
3467 $items = array();
3468 // Make sure that navigation is initialised
3469 if (!$this->has_items()) {
3470 return $items;
3472 if ($this->items !== null) {
3473 return $this->items;
3476 if (count($this->children) > 0) {
3477 // Add the custom children.
3478 $items = array_reverse($this->children);
3481 // Check if navigation contains the active node
3482 if (!$this->ignoreactive) {
3483 // We will need to ensure the navigation has been initialised.
3484 $this->page->navigation->initialise($this->page);
3485 // Now find the active nodes on both the navigation and settings.
3486 $navigationactivenode = $this->page->navigation->find_active_node();
3487 $settingsactivenode = $this->page->settingsnav->find_active_node();
3489 if ($navigationactivenode && $settingsactivenode) {
3490 // Parse a combined navigation tree
3491 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3492 if (!$settingsactivenode->mainnavonly) {
3493 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3495 $settingsactivenode = $settingsactivenode->parent;
3497 if (!$this->includesettingsbase) {
3498 // Removes the first node from the settings (root node) from the list
3499 array_pop($items);
3501 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3502 if (!$navigationactivenode->mainnavonly) {
3503 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3505 if (!empty($CFG->navshowcategories) &&
3506 $navigationactivenode->type === self::TYPE_COURSE &&
3507 $navigationactivenode->parent->key === 'currentcourse') {
3508 foreach ($this->get_course_categories() as $item) {
3509 $items[] = new breadcrumb_navigation_node($item);
3512 $navigationactivenode = $navigationactivenode->parent;
3514 } else if ($navigationactivenode) {
3515 // Parse the navigation tree to get the active node
3516 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3517 if (!$navigationactivenode->mainnavonly) {
3518 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3520 if (!empty($CFG->navshowcategories) &&
3521 $navigationactivenode->type === self::TYPE_COURSE &&
3522 $navigationactivenode->parent->key === 'currentcourse') {
3523 foreach ($this->get_course_categories() as $item) {
3524 $items[] = new breadcrumb_navigation_node($item);
3527 $navigationactivenode = $navigationactivenode->parent;
3529 } else if ($settingsactivenode) {
3530 // Parse the settings navigation to get the active node
3531 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3532 if (!$settingsactivenode->mainnavonly) {
3533 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3535 $settingsactivenode = $settingsactivenode->parent;
3540 $items[] = new breadcrumb_navigation_node(array(
3541 'text' => $this->page->navigation->text,
3542 'shorttext' => $this->page->navigation->shorttext,
3543 'key' => $this->page->navigation->key,
3544 'action' => $this->page->navigation->action
3547 if (count($this->prependchildren) > 0) {
3548 // Add the custom children
3549 $items = array_merge($items, array_reverse($this->prependchildren));
3552 $last = reset($items);
3553 if ($last) {
3554 $last->set_last(true);
3556 $this->items = array_reverse($items);
3557 return $this->items;
3561 * Get the list of categories leading to this course.
3563 * This function is used by {@link navbar::get_items()} to add back the "courses"
3564 * node and category chain leading to the current course. Note that this is only ever
3565 * called for the current course, so we don't need to bother taking in any parameters.
3567 * @return array
3569 private function get_course_categories() {
3570 global $CFG;
3571 require_once($CFG->dirroot.'/course/lib.php');
3573 $categories = array();
3574 $cap = 'moodle/category:viewhiddencategories';
3575 $showcategories = core_course_category::count_all() > 1;
3577 if ($showcategories) {
3578 foreach ($this->page->categories as $category) {
3579 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3580 continue;
3582 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3583 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3584 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3585 if (!$category->visible) {
3586 $categorynode->hidden = true;
3588 $categories[] = $categorynode;
3592 // Don't show the 'course' node if enrolled in this course.
3593 if (!is_enrolled(context_course::instance($this->page->course->id, null, '', true))) {
3594 $courses = $this->page->navigation->get('courses');
3595 if (!$courses) {
3596 // Courses node may not be present.
3597 $courses = breadcrumb_navigation_node::create(
3598 get_string('courses'),
3599 new moodle_url('/course/index.php'),
3600 self::TYPE_CONTAINER
3603 $categories[] = $courses;
3606 return $categories;
3610 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3612 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3613 * the way nodes get added to allow us to simply call add and have the node added to the
3614 * end of the navbar
3616 * @param string $text
3617 * @param string|moodle_url|action_link $action An action to associate with this node.
3618 * @param int $type One of navigation_node::TYPE_*
3619 * @param string $shorttext
3620 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3621 * @param pix_icon $icon An optional icon to use for this node.
3622 * @return navigation_node
3624 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3625 if ($this->content !== null) {
3626 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3629 // Properties array used when creating the new navigation node
3630 $itemarray = array(
3631 'text' => $text,
3632 'type' => $type
3634 // Set the action if one was provided
3635 if ($action!==null) {
3636 $itemarray['action'] = $action;
3638 // Set the shorttext if one was provided
3639 if ($shorttext!==null) {
3640 $itemarray['shorttext'] = $shorttext;
3642 // Set the icon if one was provided
3643 if ($icon!==null) {
3644 $itemarray['icon'] = $icon;
3646 // Default the key to the number of children if not provided
3647 if ($key === null) {
3648 $key = count($this->children);
3650 // Set the key
3651 $itemarray['key'] = $key;
3652 // Set the parent to this node
3653 $itemarray['parent'] = $this;
3654 // Add the child using the navigation_node_collections add method
3655 $this->children[] = new breadcrumb_navigation_node($itemarray);
3656 return $this;
3660 * Prepends a new navigation_node to the start of the navbar
3662 * @param string $text
3663 * @param string|moodle_url|action_link $action An action to associate with this node.
3664 * @param int $type One of navigation_node::TYPE_*
3665 * @param string $shorttext
3666 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3667 * @param pix_icon $icon An optional icon to use for this node.
3668 * @return navigation_node
3670 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3671 if ($this->content !== null) {
3672 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3674 // Properties array used when creating the new navigation node.
3675 $itemarray = array(
3676 'text' => $text,
3677 'type' => $type
3679 // Set the action if one was provided.
3680 if ($action!==null) {
3681 $itemarray['action'] = $action;
3683 // Set the shorttext if one was provided.
3684 if ($shorttext!==null) {
3685 $itemarray['shorttext'] = $shorttext;
3687 // Set the icon if one was provided.
3688 if ($icon!==null) {
3689 $itemarray['icon'] = $icon;
3691 // Default the key to the number of children if not provided.
3692 if ($key === null) {
3693 $key = count($this->children);
3695 // Set the key.
3696 $itemarray['key'] = $key;
3697 // Set the parent to this node.
3698 $itemarray['parent'] = $this;
3699 // Add the child node to the prepend list.
3700 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3701 return $this;
3706 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3707 * in particular adding extra metadata for search engine robots to leverage.
3709 * @package core
3710 * @category navigation
3711 * @copyright 2015 Brendan Heywood
3712 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3714 class breadcrumb_navigation_node extends navigation_node {
3716 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3717 private $last = false;
3720 * A proxy constructor
3722 * @param mixed $navnode A navigation_node or an array
3724 public function __construct($navnode) {
3725 if (is_array($navnode)) {
3726 parent::__construct($navnode);
3727 } else if ($navnode instanceof navigation_node) {
3729 // Just clone everything.
3730 $objvalues = get_object_vars($navnode);
3731 foreach ($objvalues as $key => $value) {
3732 $this->$key = $value;
3734 } else {
3735 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3740 * Getter for "last"
3741 * @return boolean
3743 public function is_last() {
3744 return $this->last;
3748 * Setter for "last"
3749 * @param $val boolean
3751 public function set_last($val) {
3752 $this->last = $val;
3757 * Subclass of navigation_node allowing different rendering for the flat navigation
3758 * in particular allowing dividers and indents.
3760 * @package core
3761 * @category navigation
3762 * @copyright 2016 Damyon Wiese
3763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3765 class flat_navigation_node extends navigation_node {
3767 /** @var $indent integer The indent level */
3768 private $indent = 0;
3770 /** @var $showdivider bool Show a divider before this element */
3771 private $showdivider = false;
3774 * A proxy constructor
3776 * @param mixed $navnode A navigation_node or an array
3778 public function __construct($navnode, $indent) {
3779 if (is_array($navnode)) {
3780 parent::__construct($navnode);
3781 } else if ($navnode instanceof navigation_node) {
3783 // Just clone everything.
3784 $objvalues = get_object_vars($navnode);
3785 foreach ($objvalues as $key => $value) {
3786 $this->$key = $value;
3788 } else {
3789 throw new coding_exception('Not a valid flat_navigation_node');
3791 $this->indent = $indent;
3795 * Does this node represent a course section link.
3796 * @return boolean
3798 public function is_section() {
3799 return $this->type == navigation_node::TYPE_SECTION;
3803 * In flat navigation - sections are active if we are looking at activities in the section.
3804 * @return boolean
3806 public function isactive() {
3807 global $PAGE;
3809 if ($this->is_section()) {
3810 $active = $PAGE->navigation->find_active_node();
3811 while ($active = $active->parent) {
3812 if ($active->key == $this->key && $active->type == $this->type) {
3813 return true;
3817 return $this->isactive;
3821 * Getter for "showdivider"
3822 * @return boolean
3824 public function showdivider() {
3825 return $this->showdivider;
3829 * Setter for "showdivider"
3830 * @param $val boolean
3832 public function set_showdivider($val) {
3833 $this->showdivider = $val;
3837 * Getter for "indent"
3838 * @return boolean
3840 public function get_indent() {
3841 return $this->indent;
3845 * Setter for "indent"
3846 * @param $val boolean
3848 public function set_indent($val) {
3849 $this->indent = $val;
3855 * Class used to generate a collection of navigation nodes most closely related
3856 * to the current page.
3858 * @package core
3859 * @copyright 2016 Damyon Wiese
3860 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3862 class flat_navigation extends navigation_node_collection {
3863 /** @var moodle_page the moodle page that the navigation belongs to */
3864 protected $page;
3867 * Constructor.
3869 * @param moodle_page $page
3871 public function __construct(moodle_page &$page) {
3872 if (during_initial_install()) {
3873 return false;
3875 $this->page = $page;
3879 * Build the list of navigation nodes based on the current navigation and settings trees.
3882 public function initialise() {
3883 global $PAGE, $USER, $OUTPUT, $CFG;
3884 if (during_initial_install()) {
3885 return;
3888 $current = false;
3890 $course = $PAGE->course;
3892 $this->page->navigation->initialise();
3894 // First walk the nav tree looking for "flat_navigation" nodes.
3895 if ($course->id > 1) {
3896 // It's a real course.
3897 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3899 $coursecontext = context_course::instance($course->id, MUST_EXIST);
3900 // This is the name that will be shown for the course.
3901 $coursename = empty($CFG->navshowfullcoursenames) ?
3902 format_string($course->shortname, true, array('context' => $coursecontext)) :
3903 format_string($course->fullname, true, array('context' => $coursecontext));
3905 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
3906 $flat->key = 'coursehome';
3907 $flat->icon = new pix_icon('i/course', '');
3909 $courseformat = course_get_format($course);
3910 $coursenode = $PAGE->navigation->find_active_node();
3911 $targettype = navigation_node::TYPE_COURSE;
3913 // Single activity format has no course node - the course node is swapped for the activity node.
3914 if (!$courseformat->has_view_page()) {
3915 $targettype = navigation_node::TYPE_ACTIVITY;
3918 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
3919 $coursenode = $coursenode->parent;
3921 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
3922 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
3923 if ($coursenode && $coursenode->key != SITEID) {
3924 $this->add($flat);
3925 foreach ($coursenode->children as $child) {
3926 if ($child->action) {
3927 $flat = new flat_navigation_node($child, 0);
3928 $this->add($flat);
3933 $this->page->navigation->build_flat_navigation_list($this, true);
3934 } else {
3935 $this->page->navigation->build_flat_navigation_list($this, false);
3938 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
3939 if (!$admin) {
3940 // Try again - crazy nav tree!
3941 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
3943 if ($admin) {
3944 $flat = new flat_navigation_node($admin, 0);
3945 $flat->set_showdivider(true);
3946 $flat->key = 'sitesettings';
3947 $flat->icon = new pix_icon('t/preferences', '');
3948 $this->add($flat);
3951 // Add-a-block in editing mode.
3952 if (isset($this->page->theme->addblockposition) &&
3953 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
3954 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
3955 ($addable = $PAGE->blocks->get_addable_blocks())) {
3956 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
3957 $addablock = navigation_node::create(get_string('addblock'), $url);
3958 $flat = new flat_navigation_node($addablock, 0);
3959 $flat->set_showdivider(true);
3960 $flat->key = 'addblock';
3961 $flat->icon = new pix_icon('i/addblock', '');
3962 $this->add($flat);
3963 $blocks = [];
3964 foreach ($addable as $block) {
3965 $blocks[] = $block->name;
3967 $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
3968 $PAGE->requires->js_call_amd('core/addblockmodal', 'init', array($params));
3975 * Class used to manage the settings option for the current page
3977 * This class is used to manage the settings options in a tree format (recursively)
3978 * and was created initially for use with the settings blocks.
3980 * @package core
3981 * @category navigation
3982 * @copyright 2009 Sam Hemelryk
3983 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3985 class settings_navigation extends navigation_node {
3986 /** @var stdClass the current context */
3987 protected $context;
3988 /** @var moodle_page the moodle page that the navigation belongs to */
3989 protected $page;
3990 /** @var string contains administration section navigation_nodes */
3991 protected $adminsection;
3992 /** @var bool A switch to see if the navigation node is initialised */
3993 protected $initialised = false;
3994 /** @var array An array of users that the nodes can extend for. */
3995 protected $userstoextendfor = array();
3996 /** @var navigation_cache **/
3997 protected $cache;
4000 * Sets up the object with basic settings and preparse it for use
4002 * @param moodle_page $page
4004 public function __construct(moodle_page &$page) {
4005 if (during_initial_install()) {
4006 return false;
4008 $this->page = $page;
4009 // Initialise the main navigation. It is most important that this is done
4010 // before we try anything
4011 $this->page->navigation->initialise();
4012 // Initialise the navigation cache
4013 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4014 $this->children = new navigation_node_collection();
4018 * Initialise the settings navigation based on the current context
4020 * This function initialises the settings navigation tree for a given context
4021 * by calling supporting functions to generate major parts of the tree.
4024 public function initialise() {
4025 global $DB, $SESSION, $SITE;
4027 if (during_initial_install()) {
4028 return false;
4029 } else if ($this->initialised) {
4030 return true;
4032 $this->id = 'settingsnav';
4033 $this->context = $this->page->context;
4035 $context = $this->context;
4036 if ($context->contextlevel == CONTEXT_BLOCK) {
4037 $this->load_block_settings();
4038 $context = $context->get_parent_context();
4039 $this->context = $context;
4041 switch ($context->contextlevel) {
4042 case CONTEXT_SYSTEM:
4043 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4044 $this->load_front_page_settings(($context->id == $this->context->id));
4046 break;
4047 case CONTEXT_COURSECAT:
4048 $this->load_category_settings();
4049 break;
4050 case CONTEXT_COURSE:
4051 if ($this->page->course->id != $SITE->id) {
4052 $this->load_course_settings(($context->id == $this->context->id));
4053 } else {
4054 $this->load_front_page_settings(($context->id == $this->context->id));
4056 break;
4057 case CONTEXT_MODULE:
4058 $this->load_module_settings();
4059 $this->load_course_settings();
4060 break;
4061 case CONTEXT_USER:
4062 if ($this->page->course->id != $SITE->id) {
4063 $this->load_course_settings();
4065 break;
4068 $usersettings = $this->load_user_settings($this->page->course->id);
4070 $adminsettings = false;
4071 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4072 $isadminpage = $this->is_admin_tree_needed();
4074 if (has_capability('moodle/site:configview', context_system::instance())) {
4075 if (has_capability('moodle/site:config', context_system::instance())) {
4076 // Make sure this works even if config capability changes on the fly
4077 // and also make it fast for admin right after login.
4078 $SESSION->load_navigation_admin = 1;
4079 if ($isadminpage) {
4080 $adminsettings = $this->load_administration_settings();
4083 } else if (!isset($SESSION->load_navigation_admin)) {
4084 $adminsettings = $this->load_administration_settings();
4085 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4087 } else if ($SESSION->load_navigation_admin) {
4088 if ($isadminpage) {
4089 $adminsettings = $this->load_administration_settings();
4093 // Print empty navigation node, if needed.
4094 if ($SESSION->load_navigation_admin && !$isadminpage) {
4095 if ($adminsettings) {
4096 // Do not print settings tree on pages that do not need it, this helps with performance.
4097 $adminsettings->remove();
4098 $adminsettings = false;
4100 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4101 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4102 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4103 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4104 $siteadminnode->requiresajaxloading = 'true';
4109 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4110 $adminsettings->force_open();
4111 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4112 $usersettings->force_open();
4115 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4116 $this->load_local_plugin_settings();
4118 foreach ($this->children as $key=>$node) {
4119 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4120 // Site administration is shown as link.
4121 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4122 continue;
4124 $node->remove();
4127 $this->initialised = true;
4130 * Override the parent function so that we can add preceeding hr's and set a
4131 * root node class against all first level element
4133 * It does this by first calling the parent's add method {@link navigation_node::add()}
4134 * and then proceeds to use the key to set class and hr
4136 * @param string $text text to be used for the link.
4137 * @param string|moodle_url $url url for the new node
4138 * @param int $type the type of node navigation_node::TYPE_*
4139 * @param string $shorttext
4140 * @param string|int $key a key to access the node by.
4141 * @param pix_icon $icon An icon that appears next to the node.
4142 * @return navigation_node with the new node added to it.
4144 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4145 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4146 $node->add_class('root_node');
4147 return $node;
4151 * This function allows the user to add something to the start of the settings
4152 * navigation, which means it will be at the top of the settings navigation block
4154 * @param string $text text to be used for the link.
4155 * @param string|moodle_url $url url for the new node
4156 * @param int $type the type of node navigation_node::TYPE_*
4157 * @param string $shorttext
4158 * @param string|int $key a key to access the node by.
4159 * @param pix_icon $icon An icon that appears next to the node.
4160 * @return navigation_node $node with the new node added to it.
4162 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4163 $children = $this->children;
4164 $childrenclass = get_class($children);
4165 $this->children = new $childrenclass;
4166 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4167 foreach ($children as $child) {
4168 $this->children->add($child);
4170 return $node;
4174 * Does this page require loading of full admin tree or is
4175 * it enough rely on AJAX?
4177 * @return bool
4179 protected function is_admin_tree_needed() {
4180 if (self::$loadadmintree) {
4181 // Usually external admin page or settings page.
4182 return true;
4185 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4186 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4187 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4188 return false;
4190 return true;
4193 return false;
4197 * Load the site administration tree
4199 * This function loads the site administration tree by using the lib/adminlib library functions
4201 * @param navigation_node $referencebranch A reference to a branch in the settings
4202 * navigation tree
4203 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4204 * tree and start at the beginning
4205 * @return mixed A key to access the admin tree by
4207 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4208 global $CFG;
4210 // Check if we are just starting to generate this navigation.
4211 if ($referencebranch === null) {
4213 // Require the admin lib then get an admin structure
4214 if (!function_exists('admin_get_root')) {
4215 require_once($CFG->dirroot.'/lib/adminlib.php');
4217 $adminroot = admin_get_root(false, false);
4218 // This is the active section identifier
4219 $this->adminsection = $this->page->url->param('section');
4221 // Disable the navigation from automatically finding the active node
4222 navigation_node::$autofindactive = false;
4223 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4224 foreach ($adminroot->children as $adminbranch) {
4225 $this->load_administration_settings($referencebranch, $adminbranch);
4227 navigation_node::$autofindactive = true;
4229 // Use the admin structure to locate the active page
4230 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4231 $currentnode = $this;
4232 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4233 $currentnode = $currentnode->get($pathkey);
4235 if ($currentnode) {
4236 $currentnode->make_active();
4238 } else {
4239 $this->scan_for_active_node($referencebranch);
4241 return $referencebranch;
4242 } else if ($adminbranch->check_access()) {
4243 // We have a reference branch that we can access and is not hidden `hurrah`
4244 // Now we need to display it and any children it may have
4245 $url = null;
4246 $icon = null;
4247 if ($adminbranch instanceof admin_settingpage) {
4248 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
4249 } else if ($adminbranch instanceof admin_externalpage) {
4250 $url = $adminbranch->url;
4251 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4252 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
4255 // Add the branch
4256 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4258 if ($adminbranch->is_hidden()) {
4259 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4260 $reference->add_class('hidden');
4261 } else {
4262 $reference->display = false;
4266 // Check if we are generating the admin notifications and whether notificiations exist
4267 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4268 $reference->add_class('criticalnotification');
4270 // Check if this branch has children
4271 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4272 foreach ($adminbranch->children as $branch) {
4273 // Generate the child branches as well now using this branch as the reference
4274 $this->load_administration_settings($reference, $branch);
4276 } else {
4277 $reference->icon = new pix_icon('i/settings', '');
4283 * This function recursivily scans nodes until it finds the active node or there
4284 * are no more nodes.
4285 * @param navigation_node $node
4287 protected function scan_for_active_node(navigation_node $node) {
4288 if (!$node->check_if_active() && $node->children->count()>0) {
4289 foreach ($node->children as &$child) {
4290 $this->scan_for_active_node($child);
4296 * Gets a navigation node given an array of keys that represent the path to
4297 * the desired node.
4299 * @param array $path
4300 * @return navigation_node|false
4302 protected function get_by_path(array $path) {
4303 $node = $this->get(array_shift($path));
4304 foreach ($path as $key) {
4305 $node->get($key);
4307 return $node;
4311 * This function loads the course settings that are available for the user
4313 * @param bool $forceopen If set to true the course node will be forced open
4314 * @return navigation_node|false
4316 protected function load_course_settings($forceopen = false) {
4317 global $CFG;
4318 require_once($CFG->dirroot . '/course/lib.php');
4320 $course = $this->page->course;
4321 $coursecontext = context_course::instance($course->id);
4322 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4324 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4326 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4327 if ($forceopen) {
4328 $coursenode->force_open();
4332 if ($adminoptions->update) {
4333 // Add the course settings link
4334 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4335 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
4338 if ($this->page->user_allowed_editing()) {
4339 // Add the turn on/off settings
4341 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
4342 // We are on the course page, retain the current page params e.g. section.
4343 $baseurl = clone($this->page->url);
4344 $baseurl->param('sesskey', sesskey());
4345 } else {
4346 // Edit on the main course page.
4347 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
4350 $editurl = clone($baseurl);
4351 if ($this->page->user_is_editing()) {
4352 $editurl->param('edit', 'off');
4353 $editstring = get_string('turneditingoff');
4354 } else {
4355 $editurl->param('edit', 'on');
4356 $editstring = get_string('turneditingon');
4358 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
4361 if ($adminoptions->editcompletion) {
4362 // Add the course completion settings link
4363 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4364 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null,
4365 new pix_icon('i/settings', ''));
4368 if (!$adminoptions->update && $adminoptions->tags) {
4369 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4370 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4373 // add enrol nodes
4374 enrol_add_course_navigation($coursenode, $course);
4376 // Manage filters
4377 if ($adminoptions->filters) {
4378 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4379 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4382 // View course reports.
4383 if ($adminoptions->reports) {
4384 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'coursereports',
4385 new pix_icon('i/stats', ''));
4386 $coursereports = core_component::get_plugin_list('coursereport');
4387 foreach ($coursereports as $report => $dir) {
4388 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4389 if (file_exists($libfile)) {
4390 require_once($libfile);
4391 $reportfunction = $report.'_report_extend_navigation';
4392 if (function_exists($report.'_report_extend_navigation')) {
4393 $reportfunction($reportnav, $course, $coursecontext);
4398 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4399 foreach ($reports as $reportfunction) {
4400 $reportfunction($reportnav, $course, $coursecontext);
4404 // Check if we can view the gradebook's setup page.
4405 if ($adminoptions->gradebook) {
4406 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4407 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4408 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4411 // Add the context locking node.
4412 $this->add_context_locking_node($coursenode, $coursecontext);
4414 // Add outcome if permitted
4415 if ($adminoptions->outcomes) {
4416 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4417 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4420 //Add badges navigation
4421 if ($adminoptions->badges) {
4422 require_once($CFG->libdir .'/badgeslib.php');
4423 badges_add_course_navigation($coursenode, $course);
4426 // Backup this course
4427 if ($adminoptions->backup) {
4428 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4429 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4432 // Restore to this course
4433 if ($adminoptions->restore) {
4434 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4435 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4438 // Import data from other courses
4439 if ($adminoptions->import) {
4440 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
4441 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4444 // Publish course on a hub
4445 if ($adminoptions->publish) {
4446 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
4447 $coursenode->add(get_string('publish', 'core_hub'), $url, self::TYPE_SETTING, null, 'publish',
4448 new pix_icon('i/publish', ''));
4451 // Reset this course
4452 if ($adminoptions->reset) {
4453 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4454 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4457 // Questions
4458 require_once($CFG->libdir . '/questionlib.php');
4459 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4461 if ($adminoptions->update) {
4462 // Repository Instances
4463 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4464 require_once($CFG->dirroot . '/repository/lib.php');
4465 $editabletypes = repository::get_editable_types($coursecontext);
4466 $haseditabletypes = !empty($editabletypes);
4467 unset($editabletypes);
4468 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4469 } else {
4470 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4472 if ($haseditabletypes) {
4473 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4474 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4478 // Manage files
4479 if ($adminoptions->files) {
4480 // hidden in new courses and courses where legacy files were turned off
4481 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4482 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4486 // Let plugins hook into course navigation.
4487 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4488 foreach ($pluginsfunction as $plugintype => $plugins) {
4489 // Ignore the report plugin as it was already loaded above.
4490 if ($plugintype == 'report') {
4491 continue;
4493 foreach ($plugins as $pluginfunction) {
4494 $pluginfunction($coursenode, $course, $coursecontext);
4498 // Return we are done
4499 return $coursenode;
4503 * This function calls the module function to inject module settings into the
4504 * settings navigation tree.
4506 * This only gets called if there is a corrosponding function in the modules
4507 * lib file.
4509 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4511 * @return navigation_node|false
4513 protected function load_module_settings() {
4514 global $CFG;
4516 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4517 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4518 $this->page->set_cm($cm, $this->page->course);
4521 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4522 if (file_exists($file)) {
4523 require_once($file);
4526 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4527 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4528 $modulenode->force_open();
4530 // Settings for the module
4531 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4532 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4533 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
4535 // Assign local roles
4536 if (count(get_assignable_roles($this->page->cm->context))>0) {
4537 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4538 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
4540 // Override roles
4541 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4542 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4543 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
4545 // Check role permissions
4546 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4547 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4548 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
4551 // Add the context locking node.
4552 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4554 // Manage filters
4555 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4556 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4557 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
4559 // Add reports
4560 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4561 foreach ($reports as $reportfunction) {
4562 $reportfunction($modulenode, $this->page->cm);
4564 // Add a backup link
4565 $featuresfunc = $this->page->activityname.'_supports';
4566 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4567 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4568 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4571 // Restore this activity
4572 $featuresfunc = $this->page->activityname.'_supports';
4573 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4574 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4575 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4578 // Allow the active advanced grading method plugin to append its settings
4579 $featuresfunc = $this->page->activityname.'_supports';
4580 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4581 require_once($CFG->dirroot.'/grade/grading/lib.php');
4582 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4583 $gradingman->extend_settings_navigation($this, $modulenode);
4586 $function = $this->page->activityname.'_extend_settings_navigation';
4587 if (function_exists($function)) {
4588 $function($this, $modulenode);
4591 // Remove the module node if there are no children.
4592 if ($modulenode->children->count() <= 0) {
4593 $modulenode->remove();
4596 return $modulenode;
4600 * Loads the user settings block of the settings nav
4602 * This function is simply works out the userid and whether we need to load
4603 * just the current users profile settings, or the current user and the user the
4604 * current user is viewing.
4606 * This function has some very ugly code to work out the user, if anyone has
4607 * any bright ideas please feel free to intervene.
4609 * @param int $courseid The course id of the current course
4610 * @return navigation_node|false
4612 protected function load_user_settings($courseid = SITEID) {
4613 global $USER, $CFG;
4615 if (isguestuser() || !isloggedin()) {
4616 return false;
4619 $navusers = $this->page->navigation->get_extending_users();
4621 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4622 $usernode = null;
4623 foreach ($this->userstoextendfor as $userid) {
4624 if ($userid == $USER->id) {
4625 continue;
4627 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4628 if (is_null($usernode)) {
4629 $usernode = $node;
4632 foreach ($navusers as $user) {
4633 if ($user->id == $USER->id) {
4634 continue;
4636 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4637 if (is_null($usernode)) {
4638 $usernode = $node;
4641 $this->generate_user_settings($courseid, $USER->id);
4642 } else {
4643 $usernode = $this->generate_user_settings($courseid, $USER->id);
4645 return $usernode;
4649 * Extends the settings navigation for the given user.
4651 * Note: This method gets called automatically if you call
4652 * $PAGE->navigation->extend_for_user($userid)
4654 * @param int $userid
4656 public function extend_for_user($userid) {
4657 global $CFG;
4659 if (!in_array($userid, $this->userstoextendfor)) {
4660 $this->userstoextendfor[] = $userid;
4661 if ($this->initialised) {
4662 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4663 $children = array();
4664 foreach ($this->children as $child) {
4665 $children[] = $child;
4667 array_unshift($children, array_pop($children));
4668 $this->children = new navigation_node_collection();
4669 foreach ($children as $child) {
4670 $this->children->add($child);
4677 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4678 * what can be shown/done
4680 * @param int $courseid The current course' id
4681 * @param int $userid The user id to load for
4682 * @param string $gstitle The string to pass to get_string for the branch title
4683 * @return navigation_node|false
4685 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4686 global $DB, $CFG, $USER, $SITE;
4688 if ($courseid != $SITE->id) {
4689 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4690 $course = $this->page->course;
4691 } else {
4692 $select = context_helper::get_preload_record_columns_sql('ctx');
4693 $sql = "SELECT c.*, $select
4694 FROM {course} c
4695 JOIN {context} ctx ON c.id = ctx.instanceid
4696 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4697 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4698 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4699 context_helper::preload_from_record($course);
4701 } else {
4702 $course = $SITE;
4705 $coursecontext = context_course::instance($course->id); // Course context
4706 $systemcontext = context_system::instance();
4707 $currentuser = ($USER->id == $userid);
4709 if ($currentuser) {
4710 $user = $USER;
4711 $usercontext = context_user::instance($user->id); // User context
4712 } else {
4713 $select = context_helper::get_preload_record_columns_sql('ctx');
4714 $sql = "SELECT u.*, $select
4715 FROM {user} u
4716 JOIN {context} ctx ON u.id = ctx.instanceid
4717 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4718 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4719 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4720 if (!$user) {
4721 return false;
4723 context_helper::preload_from_record($user);
4725 // Check that the user can view the profile
4726 $usercontext = context_user::instance($user->id); // User context
4727 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4729 if ($course->id == $SITE->id) {
4730 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4731 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4732 return false;
4734 } else {
4735 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4736 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4737 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4738 return false;
4740 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4741 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4742 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4743 if ($courseid == $this->page->course->id) {
4744 $mygroups = get_fast_modinfo($this->page->course)->groups;
4745 } else {
4746 $mygroups = groups_get_user_groups($courseid);
4748 $usergroups = groups_get_user_groups($courseid, $userid);
4749 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4750 return false;
4756 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4758 $key = $gstitle;
4759 $prefurl = new moodle_url('/user/preferences.php');
4760 if ($gstitle != 'usercurrentsettings') {
4761 $key .= $userid;
4762 $prefurl->param('userid', $userid);
4765 // Add a user setting branch.
4766 if ($gstitle == 'usercurrentsettings') {
4767 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4768 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4769 // breadcrumb.
4770 $dashboard->display = false;
4771 if (get_home_page() == HOMEPAGE_MY) {
4772 $dashboard->mainnavonly = true;
4775 $iscurrentuser = ($user->id == $USER->id);
4777 $baseargs = array('id' => $user->id);
4778 if ($course->id != $SITE->id && !$iscurrentuser) {
4779 $baseargs['course'] = $course->id;
4780 $issitecourse = false;
4781 } else {
4782 // Load all categories and get the context for the system.
4783 $issitecourse = true;
4786 // Add the user profile to the dashboard.
4787 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4788 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4790 if (!empty($CFG->navadduserpostslinks)) {
4791 // Add nodes for forum posts and discussions if the user can view either or both
4792 // There are no capability checks here as the content of the page is based
4793 // purely on the forums the current user has access too.
4794 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4795 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4796 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4797 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4800 // Add blog nodes.
4801 if (!empty($CFG->enableblogs)) {
4802 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4803 require_once($CFG->dirroot.'/blog/lib.php');
4804 // Get all options for the user.
4805 $options = blog_get_options_for_user($user);
4806 $this->cache->set('userblogoptions'.$user->id, $options);
4807 } else {
4808 $options = $this->cache->{'userblogoptions'.$user->id};
4811 if (count($options) > 0) {
4812 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4813 foreach ($options as $type => $option) {
4814 if ($type == "rss") {
4815 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4816 new pix_icon('i/rss', ''));
4817 } else {
4818 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4824 // Add the messages link.
4825 // It is context based so can appear in the user's profile and in course participants information.
4826 if (!empty($CFG->messaging)) {
4827 $messageargs = array('user1' => $USER->id);
4828 if ($USER->id != $user->id) {
4829 $messageargs['user2'] = $user->id;
4831 $url = new moodle_url('/message/index.php', $messageargs);
4832 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4835 // Add the "My private files" link.
4836 // This link doesn't have a unique display for course context so only display it under the user's profile.
4837 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4838 $url = new moodle_url('/user/files.php');
4839 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
4842 // Add a node to view the users notes if permitted.
4843 if (!empty($CFG->enablenotes) &&
4844 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4845 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4846 if ($coursecontext->instanceid != SITEID) {
4847 $url->param('course', $coursecontext->instanceid);
4849 $profilenode->add(get_string('notes', 'notes'), $url);
4852 // Show the grades node.
4853 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
4854 require_once($CFG->dirroot . '/user/lib.php');
4855 // Set the grades node to link to the "Grades" page.
4856 if ($course->id == SITEID) {
4857 $url = user_mygrades_url($user->id, $course->id);
4858 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4859 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
4861 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
4864 // Let plugins hook into user navigation.
4865 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
4866 foreach ($pluginsfunction as $plugintype => $plugins) {
4867 if ($plugintype != 'report') {
4868 foreach ($plugins as $pluginfunction) {
4869 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
4874 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4875 $dashboard->add_node($usersetting);
4876 } else {
4877 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4878 $usersetting->display = false;
4880 $usersetting->id = 'usersettings';
4882 // Check if the user has been deleted.
4883 if ($user->deleted) {
4884 if (!has_capability('moodle/user:update', $coursecontext)) {
4885 // We can't edit the user so just show the user deleted message.
4886 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4887 } else {
4888 // We can edit the user so show the user deleted message and link it to the profile.
4889 if ($course->id == $SITE->id) {
4890 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4891 } else {
4892 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4894 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4896 return true;
4899 $userauthplugin = false;
4900 if (!empty($user->auth)) {
4901 $userauthplugin = get_auth_plugin($user->auth);
4904 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
4906 // Add the profile edit link.
4907 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4908 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
4909 has_capability('moodle/user:update', $systemcontext)) {
4910 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4911 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4912 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4913 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4914 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4915 $url = $userauthplugin->edit_profile_url();
4916 if (empty($url)) {
4917 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4919 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4924 // Change password link.
4925 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
4926 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4927 $passwordchangeurl = $userauthplugin->change_password_url();
4928 if (empty($passwordchangeurl)) {
4929 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4931 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
4934 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4935 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4936 has_capability('moodle/user:editprofile', $usercontext)) {
4937 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
4938 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
4941 $pluginmanager = core_plugin_manager::instance();
4942 $enabled = $pluginmanager->get_enabled_plugins('mod');
4943 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4944 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4945 has_capability('moodle/user:editprofile', $usercontext)) {
4946 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
4947 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
4950 $editors = editors_get_enabled();
4951 if (count($editors) > 1) {
4952 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4953 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4954 has_capability('moodle/user:editprofile', $usercontext)) {
4955 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
4956 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
4961 // Add "Course preferences" link.
4962 if (isloggedin() && !isguestuser($user)) {
4963 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4964 has_capability('moodle/user:editprofile', $usercontext)) {
4965 $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
4966 $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
4970 // Add "Calendar preferences" link.
4971 if (isloggedin() && !isguestuser($user)) {
4972 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4973 has_capability('moodle/user:editprofile', $usercontext)) {
4974 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
4975 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
4979 // View the roles settings.
4980 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
4981 'moodle/role:manage'), $usercontext)) {
4982 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4984 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4985 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4987 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4989 if (!empty($assignableroles)) {
4990 $url = new moodle_url('/admin/roles/assign.php',
4991 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4992 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4995 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4996 $url = new moodle_url('/admin/roles/permissions.php',
4997 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4998 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5001 $url = new moodle_url('/admin/roles/check.php',
5002 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5003 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5006 // Repositories.
5007 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5008 require_once($CFG->dirroot . '/repository/lib.php');
5009 $editabletypes = repository::get_editable_types($usercontext);
5010 $haseditabletypes = !empty($editabletypes);
5011 unset($editabletypes);
5012 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5013 } else {
5014 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5016 if ($haseditabletypes) {
5017 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5018 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5019 array('contextid' => $usercontext->id)));
5022 // Portfolio.
5023 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5024 require_once($CFG->libdir . '/portfoliolib.php');
5025 if (portfolio_has_visible_instances()) {
5026 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5028 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5029 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5031 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5032 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5036 $enablemanagetokens = false;
5037 if (!empty($CFG->enablerssfeeds)) {
5038 $enablemanagetokens = true;
5039 } else if (!is_siteadmin($USER->id)
5040 && !empty($CFG->enablewebservices)
5041 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5042 $enablemanagetokens = true;
5044 // Security keys.
5045 if ($currentuser && $enablemanagetokens) {
5046 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
5047 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5050 // Messaging.
5051 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5052 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5053 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5054 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5055 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5056 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5059 // Blogs.
5060 if ($currentuser && !empty($CFG->enableblogs)) {
5061 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5062 if (has_capability('moodle/blog:view', $systemcontext)) {
5063 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5064 navigation_node::TYPE_SETTING);
5066 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5067 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5068 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5069 navigation_node::TYPE_SETTING);
5070 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5071 navigation_node::TYPE_SETTING);
5073 // Remove the blog node if empty.
5074 $blog->trim_if_empty();
5077 // Badges.
5078 if ($currentuser && !empty($CFG->enablebadges)) {
5079 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5080 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5081 $url = new moodle_url('/badges/mybadges.php');
5082 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5084 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5085 navigation_node::TYPE_SETTING);
5086 if (!empty($CFG->badges_allowexternalbackpack)) {
5087 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5088 navigation_node::TYPE_SETTING);
5092 // Let plugins hook into user settings navigation.
5093 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5094 foreach ($pluginsfunction as $plugintype => $plugins) {
5095 foreach ($plugins as $pluginfunction) {
5096 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5100 return $usersetting;
5104 * Loads block specific settings in the navigation
5106 * @return navigation_node
5108 protected function load_block_settings() {
5109 global $CFG;
5111 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5112 $blocknode->force_open();
5114 // Assign local roles
5115 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5116 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5117 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5118 'roles', new pix_icon('i/assignroles', ''));
5121 // Override roles
5122 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5123 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5124 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5125 'permissions', new pix_icon('i/permissions', ''));
5127 // Check role permissions
5128 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5129 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5130 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5131 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5134 // Add the context locking node.
5135 $this->add_context_locking_node($blocknode, $this->context);
5137 return $blocknode;
5141 * Loads category specific settings in the navigation
5143 * @return navigation_node
5145 protected function load_category_settings() {
5146 global $CFG;
5148 // We can land here while being in the context of a block, in which case we
5149 // should get the parent context which should be the category one. See self::initialise().
5150 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5151 $catcontext = $this->context->get_parent_context();
5152 } else {
5153 $catcontext = $this->context;
5156 // Let's make sure that we always have the right context when getting here.
5157 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5158 throw new coding_exception('Unexpected context while loading category settings.');
5161 $categorynodetype = navigation_node::TYPE_CONTAINER;
5162 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5163 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5164 $categorynode->force_open();
5166 if (can_edit_in_category($catcontext->instanceid)) {
5167 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5168 $editstring = get_string('managecategorythis');
5169 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5172 if (has_capability('moodle/category:manage', $catcontext)) {
5173 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5174 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5176 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5177 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5180 // Assign local roles
5181 $assignableroles = get_assignable_roles($catcontext);
5182 if (!empty($assignableroles)) {
5183 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5184 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5187 // Override roles
5188 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5189 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5190 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5192 // Check role permissions
5193 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5194 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5195 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5196 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5199 // Add the context locking node.
5200 $this->add_context_locking_node($categorynode, $catcontext);
5202 // Cohorts
5203 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5204 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5205 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5208 // Manage filters
5209 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5210 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5211 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5214 // Restore.
5215 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5216 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5217 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5220 // Let plugins hook into category settings navigation.
5221 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5222 foreach ($pluginsfunction as $plugintype => $plugins) {
5223 foreach ($plugins as $pluginfunction) {
5224 $pluginfunction($categorynode, $catcontext);
5228 return $categorynode;
5232 * Determine whether the user is assuming another role
5234 * This function checks to see if the user is assuming another role by means of
5235 * role switching. In doing this we compare each RSW key (context path) against
5236 * the current context path. This ensures that we can provide the switching
5237 * options against both the course and any page shown under the course.
5239 * @return bool|int The role(int) if the user is in another role, false otherwise
5241 protected function in_alternative_role() {
5242 global $USER;
5243 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5244 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5245 return $USER->access['rsw'][$this->page->context->path];
5247 foreach ($USER->access['rsw'] as $key=>$role) {
5248 if (strpos($this->context->path,$key)===0) {
5249 return $role;
5253 return false;
5257 * This function loads all of the front page settings into the settings navigation.
5258 * This function is called when the user is on the front page, or $COURSE==$SITE
5259 * @param bool $forceopen (optional)
5260 * @return navigation_node
5262 protected function load_front_page_settings($forceopen = false) {
5263 global $SITE, $CFG;
5264 require_once($CFG->dirroot . '/course/lib.php');
5266 $course = clone($SITE);
5267 $coursecontext = context_course::instance($course->id); // Course context
5268 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5270 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5271 if ($forceopen) {
5272 $frontpage->force_open();
5274 $frontpage->id = 'frontpagesettings';
5276 if ($this->page->user_allowed_editing()) {
5278 // Add the turn on/off settings
5279 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5280 if ($this->page->user_is_editing()) {
5281 $url->param('edit', 'off');
5282 $editstring = get_string('turneditingoff');
5283 } else {
5284 $url->param('edit', 'on');
5285 $editstring = get_string('turneditingon');
5287 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5290 if ($adminoptions->update) {
5291 // Add the course settings link
5292 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5293 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5296 // add enrol nodes
5297 enrol_add_course_navigation($frontpage, $course);
5299 // Manage filters
5300 if ($adminoptions->filters) {
5301 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5302 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5305 // View course reports.
5306 if ($adminoptions->reports) {
5307 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5308 new pix_icon('i/stats', ''));
5309 $coursereports = core_component::get_plugin_list('coursereport');
5310 foreach ($coursereports as $report=>$dir) {
5311 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5312 if (file_exists($libfile)) {
5313 require_once($libfile);
5314 $reportfunction = $report.'_report_extend_navigation';
5315 if (function_exists($report.'_report_extend_navigation')) {
5316 $reportfunction($frontpagenav, $course, $coursecontext);
5321 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5322 foreach ($reports as $reportfunction) {
5323 $reportfunction($frontpagenav, $course, $coursecontext);
5327 // Backup this course
5328 if ($adminoptions->backup) {
5329 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5330 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5333 // Restore to this course
5334 if ($adminoptions->restore) {
5335 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5336 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5339 // Questions
5340 require_once($CFG->libdir . '/questionlib.php');
5341 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5343 // Manage files
5344 if ($adminoptions->files) {
5345 //hiden in new installs
5346 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5347 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5350 // Let plugins hook into frontpage navigation.
5351 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5352 foreach ($pluginsfunction as $plugintype => $plugins) {
5353 foreach ($plugins as $pluginfunction) {
5354 $pluginfunction($frontpage, $course, $coursecontext);
5358 return $frontpage;
5362 * This function gives local plugins an opportunity to modify the settings navigation.
5364 protected function load_local_plugin_settings() {
5366 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5367 $function($this, $this->context);
5372 * This function marks the cache as volatile so it is cleared during shutdown
5374 public function clear_cache() {
5375 $this->cache->volatile();
5379 * Checks to see if there are child nodes available in the specific user's preference node.
5380 * If so, then they have the appropriate permissions view this user's preferences.
5382 * @since Moodle 2.9.3
5383 * @param int $userid The user's ID.
5384 * @return bool True if child nodes exist to view, otherwise false.
5386 public function can_view_user_preferences($userid) {
5387 if (is_siteadmin()) {
5388 return true;
5390 // See if any nodes are present in the preferences section for this user.
5391 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5392 if ($preferencenode && $preferencenode->has_children()) {
5393 // Run through each child node.
5394 foreach ($preferencenode->children as $childnode) {
5395 // If the child node has children then this user has access to a link in the preferences page.
5396 if ($childnode->has_children()) {
5397 return true;
5401 // No links found for the user to access on the preferences page.
5402 return false;
5407 * Class used to populate site admin navigation for ajax.
5409 * @package core
5410 * @category navigation
5411 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5414 class settings_navigation_ajax extends settings_navigation {
5416 * Constructs the navigation for use in an AJAX request
5418 * @param moodle_page $page
5420 public function __construct(moodle_page &$page) {
5421 $this->page = $page;
5422 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5423 $this->children = new navigation_node_collection();
5424 $this->initialise();
5428 * Initialise the site admin navigation.
5430 * @return array An array of the expandable nodes
5432 public function initialise() {
5433 if ($this->initialised || during_initial_install()) {
5434 return false;
5436 $this->context = $this->page->context;
5437 $this->load_administration_settings();
5439 // Check if local plugins is adding node to site admin.
5440 $this->load_local_plugin_settings();
5442 $this->initialised = true;
5447 * Simple class used to output a navigation branch in XML
5449 * @package core
5450 * @category navigation
5451 * @copyright 2009 Sam Hemelryk
5452 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5454 class navigation_json {
5455 /** @var array An array of different node types */
5456 protected $nodetype = array('node','branch');
5457 /** @var array An array of node keys and types */
5458 protected $expandable = array();
5460 * Turns a branch and all of its children into XML
5462 * @param navigation_node $branch
5463 * @return string XML string
5465 public function convert($branch) {
5466 $xml = $this->convert_child($branch);
5467 return $xml;
5470 * Set the expandable items in the array so that we have enough information
5471 * to attach AJAX events
5472 * @param array $expandable
5474 public function set_expandable($expandable) {
5475 foreach ($expandable as $node) {
5476 $this->expandable[$node['key'].':'.$node['type']] = $node;
5480 * Recusively converts a child node and its children to XML for output
5482 * @param navigation_node $child The child to convert
5483 * @param int $depth Pointlessly used to track the depth of the XML structure
5484 * @return string JSON
5486 protected function convert_child($child, $depth=1) {
5487 if (!$child->display) {
5488 return '';
5490 $attributes = array();
5491 $attributes['id'] = $child->id;
5492 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5493 $attributes['type'] = $child->type;
5494 $attributes['key'] = $child->key;
5495 $attributes['class'] = $child->get_css_type();
5496 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5498 if ($child->icon instanceof pix_icon) {
5499 $attributes['icon'] = array(
5500 'component' => $child->icon->component,
5501 'pix' => $child->icon->pix,
5503 foreach ($child->icon->attributes as $key=>$value) {
5504 if ($key == 'class') {
5505 $attributes['icon']['classes'] = explode(' ', $value);
5506 } else if (!array_key_exists($key, $attributes['icon'])) {
5507 $attributes['icon'][$key] = $value;
5511 } else if (!empty($child->icon)) {
5512 $attributes['icon'] = (string)$child->icon;
5515 if ($child->forcetitle || $child->title !== $child->text) {
5516 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5518 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5519 $attributes['expandable'] = $child->key;
5520 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5523 if (count($child->classes)>0) {
5524 $attributes['class'] .= ' '.join(' ',$child->classes);
5526 if (is_string($child->action)) {
5527 $attributes['link'] = $child->action;
5528 } else if ($child->action instanceof moodle_url) {
5529 $attributes['link'] = $child->action->out();
5530 } else if ($child->action instanceof action_link) {
5531 $attributes['link'] = $child->action->url->out();
5533 $attributes['hidden'] = ($child->hidden);
5534 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5535 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5537 if ($child->children->count() > 0) {
5538 $attributes['children'] = array();
5539 foreach ($child->children as $subchild) {
5540 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5544 if ($depth > 1) {
5545 return $attributes;
5546 } else {
5547 return json_encode($attributes);
5553 * The cache class used by global navigation and settings navigation.
5555 * It is basically an easy access point to session with a bit of smarts to make
5556 * sure that the information that is cached is valid still.
5558 * Example use:
5559 * <code php>
5560 * if (!$cache->viewdiscussion()) {
5561 * // Code to do stuff and produce cachable content
5562 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5564 * $content = $cache->viewdiscussion;
5565 * </code>
5567 * @package core
5568 * @category navigation
5569 * @copyright 2009 Sam Hemelryk
5570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5572 class navigation_cache {
5573 /** @var int represents the time created */
5574 protected $creation;
5575 /** @var array An array of session keys */
5576 protected $session;
5578 * The string to use to segregate this particular cache. It can either be
5579 * unique to start a fresh cache or if you want to share a cache then make
5580 * it the string used in the original cache.
5581 * @var string
5583 protected $area;
5584 /** @var int a time that the information will time out */
5585 protected $timeout;
5586 /** @var stdClass The current context */
5587 protected $currentcontext;
5588 /** @var int cache time information */
5589 const CACHETIME = 0;
5590 /** @var int cache user id */
5591 const CACHEUSERID = 1;
5592 /** @var int cache value */
5593 const CACHEVALUE = 2;
5594 /** @var null|array An array of navigation cache areas to expire on shutdown */
5595 public static $volatilecaches;
5598 * Contructor for the cache. Requires two arguments
5600 * @param string $area The string to use to segregate this particular cache
5601 * it can either be unique to start a fresh cache or if you want
5602 * to share a cache then make it the string used in the original
5603 * cache
5604 * @param int $timeout The number of seconds to time the information out after
5606 public function __construct($area, $timeout=1800) {
5607 $this->creation = time();
5608 $this->area = $area;
5609 $this->timeout = time() - $timeout;
5610 if (rand(0,100) === 0) {
5611 $this->garbage_collection();
5616 * Used to set up the cache within the SESSION.
5618 * This is called for each access and ensure that we don't put anything into the session before
5619 * it is required.
5621 protected function ensure_session_cache_initialised() {
5622 global $SESSION;
5623 if (empty($this->session)) {
5624 if (!isset($SESSION->navcache)) {
5625 $SESSION->navcache = new stdClass;
5627 if (!isset($SESSION->navcache->{$this->area})) {
5628 $SESSION->navcache->{$this->area} = array();
5630 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5635 * Magic Method to retrieve something by simply calling using = cache->key
5637 * @param mixed $key The identifier for the information you want out again
5638 * @return void|mixed Either void or what ever was put in
5640 public function __get($key) {
5641 if (!$this->cached($key)) {
5642 return;
5644 $information = $this->session[$key][self::CACHEVALUE];
5645 return unserialize($information);
5649 * Magic method that simply uses {@link set();} to store something in the cache
5651 * @param string|int $key
5652 * @param mixed $information
5654 public function __set($key, $information) {
5655 $this->set($key, $information);
5659 * Sets some information against the cache (session) for later retrieval
5661 * @param string|int $key
5662 * @param mixed $information
5664 public function set($key, $information) {
5665 global $USER;
5666 $this->ensure_session_cache_initialised();
5667 $information = serialize($information);
5668 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5671 * Check the existence of the identifier in the cache
5673 * @param string|int $key
5674 * @return bool
5676 public function cached($key) {
5677 global $USER;
5678 $this->ensure_session_cache_initialised();
5679 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) {
5680 return false;
5682 return true;
5685 * Compare something to it's equivilant in the cache
5687 * @param string $key
5688 * @param mixed $value
5689 * @param bool $serialise Whether to serialise the value before comparison
5690 * this should only be set to false if the value is already
5691 * serialised
5692 * @return bool If the value is the same false if it is not set or doesn't match
5694 public function compare($key, $value, $serialise = true) {
5695 if ($this->cached($key)) {
5696 if ($serialise) {
5697 $value = serialize($value);
5699 if ($this->session[$key][self::CACHEVALUE] === $value) {
5700 return true;
5703 return false;
5706 * Wipes the entire cache, good to force regeneration
5708 public function clear() {
5709 global $SESSION;
5710 unset($SESSION->navcache);
5711 $this->session = null;
5714 * Checks all cache entries and removes any that have expired, good ole cleanup
5716 protected function garbage_collection() {
5717 if (empty($this->session)) {
5718 return true;
5720 foreach ($this->session as $key=>$cachedinfo) {
5721 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5722 unset($this->session[$key]);
5728 * Marks the cache as being volatile (likely to change)
5730 * Any caches marked as volatile will be destroyed at the on shutdown by
5731 * {@link navigation_node::destroy_volatile_caches()} which is registered
5732 * as a shutdown function if any caches are marked as volatile.
5734 * @param bool $setting True to destroy the cache false not too
5736 public function volatile($setting = true) {
5737 if (self::$volatilecaches===null) {
5738 self::$volatilecaches = array();
5739 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5742 if ($setting) {
5743 self::$volatilecaches[$this->area] = $this->area;
5744 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5745 unset(self::$volatilecaches[$this->area]);
5750 * Destroys all caches marked as volatile
5752 * This function is static and works in conjunction with the static volatilecaches
5753 * property of navigation cache.
5754 * Because this function is static it manually resets the cached areas back to an
5755 * empty array.
5757 public static function destroy_volatile_caches() {
5758 global $SESSION;
5759 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5760 foreach (self::$volatilecaches as $area) {
5761 $SESSION->navcache->{$area} = array();
5763 } else {
5764 $SESSION->navcache = new stdClass;