MDL-63050 cachestore_redis: Update hExists to check empty
[moodle.git] / lib / navigationlib.php
blob4a1f7d79b75ee1a99cdd6b7e9105e206068608f8
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 * Gets the CSS class to add to this node to describe its type
692 * @return string
694 public function get_css_type() {
695 if (array_key_exists($this->type, $this->namedtypes)) {
696 return 'type_'.$this->namedtypes[$this->type];
698 return 'type_unknown';
702 * Finds all nodes that are expandable by AJAX
704 * @param array $expandable An array by reference to populate with expandable nodes.
706 public function find_expandable(array &$expandable) {
707 foreach ($this->children as &$child) {
708 if ($child->display && $child->has_children() && $child->children->count() == 0) {
709 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
710 $this->add_class('canexpand');
711 $child->requiresajaxloading = true;
712 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
714 $child->find_expandable($expandable);
719 * Finds all nodes of a given type (recursive)
721 * @param int $type One of navigation_node::TYPE_*
722 * @return array
724 public function find_all_of_type($type) {
725 $nodes = $this->children->type($type);
726 foreach ($this->children as &$node) {
727 $childnodes = $node->find_all_of_type($type);
728 $nodes = array_merge($nodes, $childnodes);
730 return $nodes;
734 * Removes this node if it is empty
736 public function trim_if_empty() {
737 if ($this->children->count() == 0) {
738 $this->remove();
743 * Creates a tab representation of this nodes children that can be used
744 * with print_tabs to produce the tabs on a page.
746 * call_user_func_array('print_tabs', $node->get_tabs_array());
748 * @param array $inactive
749 * @param bool $return
750 * @return array Array (tabs, selected, inactive, activated, return)
752 public function get_tabs_array(array $inactive=array(), $return=false) {
753 $tabs = array();
754 $rows = array();
755 $selected = null;
756 $activated = array();
757 foreach ($this->children as $node) {
758 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
759 if ($node->contains_active_node()) {
760 if ($node->children->count() > 0) {
761 $activated[] = $node->key;
762 foreach ($node->children as $child) {
763 if ($child->contains_active_node()) {
764 $selected = $child->key;
766 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
768 } else {
769 $selected = $node->key;
773 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
777 * Sets the parent for this node and if this node is active ensures that the tree is properly
778 * adjusted as well.
780 * @param navigation_node $parent
782 public function set_parent(navigation_node $parent) {
783 // Set the parent (thats the easy part)
784 $this->parent = $parent;
785 // Check if this node is active (this is checked during construction)
786 if ($this->isactive) {
787 // Force all of the parent nodes open so you can see this node
788 $this->parent->force_open();
789 // Make all parents inactive so that its clear where we are.
790 $this->parent->make_inactive();
795 * Hides the node and any children it has.
797 * @since Moodle 2.5
798 * @param array $typestohide Optional. An array of node types that should be hidden.
799 * If null all nodes will be hidden.
800 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
801 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
803 public function hide(array $typestohide = null) {
804 if ($typestohide === null || in_array($this->type, $typestohide)) {
805 $this->display = false;
806 if ($this->has_children()) {
807 foreach ($this->children as $child) {
808 $child->hide($typestohide);
815 * Get the action url for this navigation node.
816 * Called from templates.
818 * @since Moodle 3.2
820 public function action() {
821 if ($this->action instanceof moodle_url) {
822 return $this->action;
823 } else if ($this->action instanceof action_link) {
824 return $this->action->url;
826 return $this->action;
831 * Navigation node collection
833 * This class is responsible for managing a collection of navigation nodes.
834 * It is required because a node's unique identifier is a combination of both its
835 * key and its type.
837 * Originally an array was used with a string key that was a combination of the two
838 * however it was decided that a better solution would be to use a class that
839 * implements the standard IteratorAggregate interface.
841 * @package core
842 * @category navigation
843 * @copyright 2010 Sam Hemelryk
844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
846 class navigation_node_collection implements IteratorAggregate, Countable {
848 * A multidimensional array to where the first key is the type and the second
849 * key is the nodes key.
850 * @var array
852 protected $collection = array();
854 * An array that contains references to nodes in the same order they were added.
855 * This is maintained as a progressive array.
856 * @var array
858 protected $orderedcollection = array();
860 * A reference to the last node that was added to the collection
861 * @var navigation_node
863 protected $last = null;
865 * The total number of items added to this array.
866 * @var int
868 protected $count = 0;
871 * Adds a navigation node to the collection
873 * @param navigation_node $node Node to add
874 * @param string $beforekey If specified, adds before a node with this key,
875 * otherwise adds at end
876 * @return navigation_node Added node
878 public function add(navigation_node $node, $beforekey=null) {
879 global $CFG;
880 $key = $node->key;
881 $type = $node->type;
883 // First check we have a 2nd dimension for this type
884 if (!array_key_exists($type, $this->orderedcollection)) {
885 $this->orderedcollection[$type] = array();
887 // Check for a collision and report if debugging is turned on
888 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
889 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
892 // Find the key to add before
893 $newindex = $this->count;
894 $last = true;
895 if ($beforekey !== null) {
896 foreach ($this->collection as $index => $othernode) {
897 if ($othernode->key === $beforekey) {
898 $newindex = $index;
899 $last = false;
900 break;
903 if ($newindex === $this->count) {
904 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
905 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
909 // Add the node to the appropriate place in the by-type structure (which
910 // is not ordered, despite the variable name)
911 $this->orderedcollection[$type][$key] = $node;
912 if (!$last) {
913 // Update existing references in the ordered collection (which is the
914 // one that isn't called 'ordered') to shuffle them along if required
915 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
916 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
919 // Add a reference to the node to the progressive collection.
920 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
921 // Update the last property to a reference to this new node.
922 $this->last = $this->orderedcollection[$type][$key];
924 // Reorder the array by index if needed
925 if (!$last) {
926 ksort($this->collection);
928 $this->count++;
929 // Return the reference to the now added node
930 return $node;
934 * Return a list of all the keys of all the nodes.
935 * @return array the keys.
937 public function get_key_list() {
938 $keys = array();
939 foreach ($this->collection as $node) {
940 $keys[] = $node->key;
942 return $keys;
946 * Fetches a node from this collection.
948 * @param string|int $key The key of the node we want to find.
949 * @param int $type One of navigation_node::TYPE_*.
950 * @return navigation_node|null
952 public function get($key, $type=null) {
953 if ($type !== null) {
954 // If the type is known then we can simply check and fetch
955 if (!empty($this->orderedcollection[$type][$key])) {
956 return $this->orderedcollection[$type][$key];
958 } else {
959 // Because we don't know the type we look in the progressive array
960 foreach ($this->collection as $node) {
961 if ($node->key === $key) {
962 return $node;
966 return false;
970 * Searches for a node with matching key and type.
972 * This function searches both the nodes in this collection and all of
973 * the nodes in each collection belonging to the nodes in this collection.
975 * Recursive.
977 * @param string|int $key The key of the node we want to find.
978 * @param int $type One of navigation_node::TYPE_*.
979 * @return navigation_node|null
981 public function find($key, $type=null) {
982 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
983 return $this->orderedcollection[$type][$key];
984 } else {
985 $nodes = $this->getIterator();
986 // Search immediate children first
987 foreach ($nodes as &$node) {
988 if ($node->key === $key && ($type === null || $type === $node->type)) {
989 return $node;
992 // Now search each childs children
993 foreach ($nodes as &$node) {
994 $result = $node->children->find($key, $type);
995 if ($result !== false) {
996 return $result;
1000 return false;
1004 * Fetches the last node that was added to this collection
1006 * @return navigation_node
1008 public function last() {
1009 return $this->last;
1013 * Fetches all nodes of a given type from this collection
1015 * @param string|int $type node type being searched for.
1016 * @return array ordered collection
1018 public function type($type) {
1019 if (!array_key_exists($type, $this->orderedcollection)) {
1020 $this->orderedcollection[$type] = array();
1022 return $this->orderedcollection[$type];
1025 * Removes the node with the given key and type from the collection
1027 * @param string|int $key The key of the node we want to find.
1028 * @param int $type
1029 * @return bool
1031 public function remove($key, $type=null) {
1032 $child = $this->get($key, $type);
1033 if ($child !== false) {
1034 foreach ($this->collection as $colkey => $node) {
1035 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1036 unset($this->collection[$colkey]);
1037 $this->collection = array_values($this->collection);
1038 break;
1041 unset($this->orderedcollection[$child->type][$child->key]);
1042 $this->count--;
1043 return true;
1045 return false;
1049 * Gets the number of nodes in this collection
1051 * This option uses an internal count rather than counting the actual options to avoid
1052 * a performance hit through the count function.
1054 * @return int
1056 public function count() {
1057 return $this->count;
1060 * Gets an array iterator for the collection.
1062 * This is required by the IteratorAggregator interface and is used by routines
1063 * such as the foreach loop.
1065 * @return ArrayIterator
1067 public function getIterator() {
1068 return new ArrayIterator($this->collection);
1073 * The global navigation class used for... the global navigation
1075 * This class is used by PAGE to store the global navigation for the site
1076 * and is then used by the settings nav and navbar to save on processing and DB calls
1078 * See
1079 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1080 * {@link lib/ajax/getnavbranch.php} Called by ajax
1082 * @package core
1083 * @category navigation
1084 * @copyright 2009 Sam Hemelryk
1085 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1087 class global_navigation extends navigation_node {
1088 /** @var moodle_page The Moodle page this navigation object belongs to. */
1089 protected $page;
1090 /** @var bool switch to let us know if the navigation object is initialised*/
1091 protected $initialised = false;
1092 /** @var array An array of course information */
1093 protected $mycourses = array();
1094 /** @var navigation_node[] An array for containing root navigation nodes */
1095 protected $rootnodes = array();
1096 /** @var bool A switch for whether to show empty sections in the navigation */
1097 protected $showemptysections = true;
1098 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1099 protected $showcategories = null;
1100 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1101 protected $showmycategories = null;
1102 /** @var array An array of stdClasses for users that the navigation is extended for */
1103 protected $extendforuser = array();
1104 /** @var navigation_cache */
1105 protected $cache;
1106 /** @var array An array of course ids that are present in the navigation */
1107 protected $addedcourses = array();
1108 /** @var bool */
1109 protected $allcategoriesloaded = false;
1110 /** @var array An array of category ids that are included in the navigation */
1111 protected $addedcategories = array();
1112 /** @var int expansion limit */
1113 protected $expansionlimit = 0;
1114 /** @var int userid to allow parent to see child's profile page navigation */
1115 protected $useridtouseforparentchecks = 0;
1116 /** @var cache_session A cache that stores information on expanded courses */
1117 protected $cacheexpandcourse = null;
1119 /** Used when loading categories to load all top level categories [parent = 0] **/
1120 const LOAD_ROOT_CATEGORIES = 0;
1121 /** Used when loading categories to load all categories **/
1122 const LOAD_ALL_CATEGORIES = -1;
1125 * Constructs a new global navigation
1127 * @param moodle_page $page The page this navigation object belongs to
1129 public function __construct(moodle_page $page) {
1130 global $CFG, $SITE, $USER;
1132 if (during_initial_install()) {
1133 return;
1136 if (get_home_page() == HOMEPAGE_SITE) {
1137 // We are using the site home for the root element
1138 $properties = array(
1139 'key' => 'home',
1140 'type' => navigation_node::TYPE_SYSTEM,
1141 'text' => get_string('home'),
1142 'action' => new moodle_url('/'),
1143 'icon' => new pix_icon('i/home', '')
1145 } else {
1146 // We are using the users my moodle for the root element
1147 $properties = array(
1148 'key' => 'myhome',
1149 'type' => navigation_node::TYPE_SYSTEM,
1150 'text' => get_string('myhome'),
1151 'action' => new moodle_url('/my/'),
1152 'icon' => new pix_icon('i/dashboard', '')
1156 // Use the parents constructor.... good good reuse
1157 parent::__construct($properties);
1158 $this->showinflatnavigation = true;
1160 // Initalise and set defaults
1161 $this->page = $page;
1162 $this->forceopen = true;
1163 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1167 * Mutator to set userid to allow parent to see child's profile
1168 * page navigation. See MDL-25805 for initial issue. Linked to it
1169 * is an issue explaining why this is a REALLY UGLY HACK thats not
1170 * for you to use!
1172 * @param int $userid userid of profile page that parent wants to navigate around.
1174 public function set_userid_for_parent_checks($userid) {
1175 $this->useridtouseforparentchecks = $userid;
1180 * Initialises the navigation object.
1182 * This causes the navigation object to look at the current state of the page
1183 * that it is associated with and then load the appropriate content.
1185 * This should only occur the first time that the navigation structure is utilised
1186 * which will normally be either when the navbar is called to be displayed or
1187 * when a block makes use of it.
1189 * @return bool
1191 public function initialise() {
1192 global $CFG, $SITE, $USER;
1193 // Check if it has already been initialised
1194 if ($this->initialised || during_initial_install()) {
1195 return true;
1197 $this->initialised = true;
1199 // Set up the five base root nodes. These are nodes where we will put our
1200 // content and are as follows:
1201 // site: Navigation for the front page.
1202 // myprofile: User profile information goes here.
1203 // currentcourse: The course being currently viewed.
1204 // mycourses: The users courses get added here.
1205 // courses: Additional courses are added here.
1206 // users: Other users information loaded here.
1207 $this->rootnodes = array();
1208 if (get_home_page() == HOMEPAGE_SITE) {
1209 // The home element should be my moodle because the root element is the site
1210 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1211 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1212 self::TYPE_SETTING, null, 'home', new pix_icon('i/dashboard', ''));
1213 $this->rootnodes['home']->showinflatnavigation = true;
1215 } else {
1216 // The home element should be the site because the root node is my moodle
1217 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1218 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1219 $this->rootnodes['home']->showinflatnavigation = true;
1220 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1221 // We need to stop automatic redirection
1222 $this->rootnodes['home']->action->param('redirect', '0');
1225 $this->rootnodes['site'] = $this->add_course($SITE);
1226 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1227 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1228 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
1229 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1230 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1232 // We always load the frontpage course to ensure it is available without
1233 // JavaScript enabled.
1234 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1235 $this->load_course_sections($SITE, $this->rootnodes['site']);
1237 $course = $this->page->course;
1238 $this->load_courses_enrolled();
1240 // $issite gets set to true if the current pages course is the sites frontpage course
1241 $issite = ($this->page->course->id == $SITE->id);
1243 // Determine if the user is enrolled in any course.
1244 $enrolledinanycourse = enrol_user_sees_own_courses();
1246 $this->rootnodes['currentcourse']->mainnavonly = true;
1247 if ($enrolledinanycourse) {
1248 $this->rootnodes['mycourses']->isexpandable = true;
1249 $this->rootnodes['mycourses']->showinflatnavigation = true;
1250 if ($CFG->navshowallcourses) {
1251 // When we show all courses we need to show both the my courses and the regular courses branch.
1252 $this->rootnodes['courses']->isexpandable = true;
1254 } else {
1255 $this->rootnodes['courses']->isexpandable = true;
1257 $this->rootnodes['mycourses']->forceopen = true;
1259 $canviewcourseprofile = true;
1261 // Next load context specific content into the navigation
1262 switch ($this->page->context->contextlevel) {
1263 case CONTEXT_SYSTEM :
1264 // Nothing left to do here I feel.
1265 break;
1266 case CONTEXT_COURSECAT :
1267 // This is essential, we must load categories.
1268 $this->load_all_categories($this->page->context->instanceid, true);
1269 break;
1270 case CONTEXT_BLOCK :
1271 case CONTEXT_COURSE :
1272 if ($issite) {
1273 // Nothing left to do here.
1274 break;
1277 // Load the course associated with the current page into the navigation.
1278 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1279 // If the course wasn't added then don't try going any further.
1280 if (!$coursenode) {
1281 $canviewcourseprofile = false;
1282 break;
1285 // If the user is not enrolled then we only want to show the
1286 // course node and not populate it.
1288 // Not enrolled, can't view, and hasn't switched roles
1289 if (!can_access_course($course, null, '', true)) {
1290 if ($coursenode->isexpandable === true) {
1291 // Obviously the situation has changed, update the cache and adjust the node.
1292 // This occurs if the user access to a course has been revoked (one way or another) after
1293 // initially logging in for this session.
1294 $this->get_expand_course_cache()->set($course->id, 1);
1295 $coursenode->isexpandable = true;
1296 $coursenode->nodetype = self::NODETYPE_BRANCH;
1298 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1299 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1300 if (!$this->current_user_is_parent_role()) {
1301 $coursenode->make_active();
1302 $canviewcourseprofile = false;
1303 break;
1305 } else if ($coursenode->isexpandable === false) {
1306 // Obviously the situation has changed, update the cache and adjust the node.
1307 // This occurs if the user has been granted access to a course (one way or another) after initially
1308 // logging in for this session.
1309 $this->get_expand_course_cache()->set($course->id, 1);
1310 $coursenode->isexpandable = true;
1311 $coursenode->nodetype = self::NODETYPE_BRANCH;
1314 // Add the essentials such as reports etc...
1315 $this->add_course_essentials($coursenode, $course);
1316 // Extend course navigation with it's sections/activities
1317 $this->load_course_sections($course, $coursenode);
1318 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1319 $coursenode->make_active();
1322 break;
1323 case CONTEXT_MODULE :
1324 if ($issite) {
1325 // If this is the site course then most information will have
1326 // already been loaded.
1327 // However we need to check if there is more content that can
1328 // yet be loaded for the specific module instance.
1329 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1330 if ($activitynode) {
1331 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1333 break;
1336 $course = $this->page->course;
1337 $cm = $this->page->cm;
1339 // Load the course associated with the page into the navigation
1340 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1342 // If the course wasn't added then don't try going any further.
1343 if (!$coursenode) {
1344 $canviewcourseprofile = false;
1345 break;
1348 // If the user is not enrolled then we only want to show the
1349 // course node and not populate it.
1350 if (!can_access_course($course, null, '', true)) {
1351 $coursenode->make_active();
1352 $canviewcourseprofile = false;
1353 break;
1356 $this->add_course_essentials($coursenode, $course);
1358 // Load the course sections into the page
1359 $this->load_course_sections($course, $coursenode, null, $cm);
1360 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1361 if (!empty($activity)) {
1362 // Finally load the cm specific navigaton information
1363 $this->load_activity($cm, $course, $activity);
1364 // Check if we have an active ndoe
1365 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1366 // And make the activity node active.
1367 $activity->make_active();
1370 break;
1371 case CONTEXT_USER :
1372 if ($issite) {
1373 // The users profile information etc is already loaded
1374 // for the front page.
1375 break;
1377 $course = $this->page->course;
1378 // Load the course associated with the user into the navigation
1379 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1381 // If the course wasn't added then don't try going any further.
1382 if (!$coursenode) {
1383 $canviewcourseprofile = false;
1384 break;
1387 // If the user is not enrolled then we only want to show the
1388 // course node and not populate it.
1389 if (!can_access_course($course, null, '', true)) {
1390 $coursenode->make_active();
1391 $canviewcourseprofile = false;
1392 break;
1394 $this->add_course_essentials($coursenode, $course);
1395 $this->load_course_sections($course, $coursenode);
1396 break;
1399 // Load for the current user
1400 $this->load_for_user();
1401 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1402 $this->load_for_user(null, true);
1404 // Load each extending user into the navigation.
1405 foreach ($this->extendforuser as $user) {
1406 if ($user->id != $USER->id) {
1407 $this->load_for_user($user);
1411 // Give the local plugins a chance to include some navigation if they want.
1412 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1413 $function($this);
1416 // Remove any empty root nodes
1417 foreach ($this->rootnodes as $node) {
1418 // Dont remove the home node
1419 /** @var navigation_node $node */
1420 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1421 $node->remove();
1425 if (!$this->contains_active_node()) {
1426 $this->search_for_active_node();
1429 // If the user is not logged in modify the navigation structure as detailed
1430 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1431 if (!isloggedin()) {
1432 $activities = clone($this->rootnodes['site']->children);
1433 $this->rootnodes['site']->remove();
1434 $children = clone($this->children);
1435 $this->children = new navigation_node_collection();
1436 foreach ($activities as $child) {
1437 $this->children->add($child);
1439 foreach ($children as $child) {
1440 $this->children->add($child);
1443 return true;
1447 * Returns true if the current user is a parent of the user being currently viewed.
1449 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1450 * other user being viewed this function returns false.
1451 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1453 * @since Moodle 2.4
1454 * @return bool
1456 protected function current_user_is_parent_role() {
1457 global $USER, $DB;
1458 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1459 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1460 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1461 return false;
1463 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1464 return true;
1467 return false;
1471 * Returns true if courses should be shown within categories on the navigation.
1473 * @param bool $ismycourse Set to true if you are calculating this for a course.
1474 * @return bool
1476 protected function show_categories($ismycourse = false) {
1477 global $CFG, $DB;
1478 if ($ismycourse) {
1479 return $this->show_my_categories();
1481 if ($this->showcategories === null) {
1482 $show = false;
1483 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1484 $show = true;
1485 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1486 $show = true;
1488 $this->showcategories = $show;
1490 return $this->showcategories;
1494 * Returns true if we should show categories in the My Courses branch.
1495 * @return bool
1497 protected function show_my_categories() {
1498 global $CFG;
1499 if ($this->showmycategories === null) {
1500 require_once('coursecatlib.php');
1501 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && coursecat::count_all() > 1;
1503 return $this->showmycategories;
1507 * Loads the courses in Moodle into the navigation.
1509 * @global moodle_database $DB
1510 * @param string|array $categoryids An array containing categories to load courses
1511 * for, OR null to load courses for all categories.
1512 * @return array An array of navigation_nodes one for each course
1514 protected function load_all_courses($categoryids = null) {
1515 global $CFG, $DB, $SITE;
1517 // Work out the limit of courses.
1518 $limit = 20;
1519 if (!empty($CFG->navcourselimit)) {
1520 $limit = $CFG->navcourselimit;
1523 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1525 // If we are going to show all courses AND we are showing categories then
1526 // to save us repeated DB calls load all of the categories now
1527 if ($this->show_categories()) {
1528 $this->load_all_categories($toload);
1531 // Will be the return of our efforts
1532 $coursenodes = array();
1534 // Check if we need to show categories.
1535 if ($this->show_categories()) {
1536 // Hmmm we need to show categories... this is going to be painful.
1537 // We now need to fetch up to $limit courses for each category to
1538 // be displayed.
1539 if ($categoryids !== null) {
1540 if (!is_array($categoryids)) {
1541 $categoryids = array($categoryids);
1543 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1544 $categorywhere = 'WHERE cc.id '.$categorywhere;
1545 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1546 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1547 $categoryparams = array();
1548 } else {
1549 $categorywhere = '';
1550 $categoryparams = array();
1553 // First up we are going to get the categories that we are going to
1554 // need so that we can determine how best to load the courses from them.
1555 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1556 FROM {course_categories} cc
1557 LEFT JOIN {course} c ON c.category = cc.id
1558 {$categorywhere}
1559 GROUP BY cc.id";
1560 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1561 $fullfetch = array();
1562 $partfetch = array();
1563 foreach ($categories as $category) {
1564 if (!$this->can_add_more_courses_to_category($category->id)) {
1565 continue;
1567 if ($category->coursecount > $limit * 5) {
1568 $partfetch[] = $category->id;
1569 } else if ($category->coursecount > 0) {
1570 $fullfetch[] = $category->id;
1573 $categories->close();
1575 if (count($fullfetch)) {
1576 // First up fetch all of the courses in categories where we know that we are going to
1577 // need the majority of courses.
1578 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1579 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1580 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1581 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1582 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1583 FROM {course} c
1584 $ccjoin
1585 WHERE c.category {$categoryids}
1586 ORDER BY c.sortorder ASC";
1587 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1588 foreach ($coursesrs as $course) {
1589 if ($course->id == $SITE->id) {
1590 // This should not be necessary, frontpage is not in any category.
1591 continue;
1593 if (array_key_exists($course->id, $this->addedcourses)) {
1594 // It is probably better to not include the already loaded courses
1595 // directly in SQL because inequalities may confuse query optimisers
1596 // and may interfere with query caching.
1597 continue;
1599 if (!$this->can_add_more_courses_to_category($course->category)) {
1600 continue;
1602 context_helper::preload_from_record($course);
1603 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1604 continue;
1606 $coursenodes[$course->id] = $this->add_course($course);
1608 $coursesrs->close();
1611 if (count($partfetch)) {
1612 // Next we will work our way through the categories where we will likely only need a small
1613 // proportion of the courses.
1614 foreach ($partfetch as $categoryid) {
1615 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1616 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1617 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1618 FROM {course} c
1619 $ccjoin
1620 WHERE c.category = :categoryid
1621 ORDER BY c.sortorder ASC";
1622 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1623 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1624 foreach ($coursesrs as $course) {
1625 if ($course->id == $SITE->id) {
1626 // This should not be necessary, frontpage is not in any category.
1627 continue;
1629 if (array_key_exists($course->id, $this->addedcourses)) {
1630 // It is probably better to not include the already loaded courses
1631 // directly in SQL because inequalities may confuse query optimisers
1632 // and may interfere with query caching.
1633 // This also helps to respect expected $limit on repeated executions.
1634 continue;
1636 if (!$this->can_add_more_courses_to_category($course->category)) {
1637 break;
1639 context_helper::preload_from_record($course);
1640 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1641 continue;
1643 $coursenodes[$course->id] = $this->add_course($course);
1645 $coursesrs->close();
1648 } else {
1649 // Prepare the SQL to load the courses and their contexts
1650 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1651 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1652 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1653 $courseparams['contextlevel'] = CONTEXT_COURSE;
1654 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1655 FROM {course} c
1656 $ccjoin
1657 WHERE c.id {$courseids}
1658 ORDER BY c.sortorder ASC";
1659 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1660 foreach ($coursesrs as $course) {
1661 if ($course->id == $SITE->id) {
1662 // frotpage is not wanted here
1663 continue;
1665 if ($this->page->course && ($this->page->course->id == $course->id)) {
1666 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1667 continue;
1669 context_helper::preload_from_record($course);
1670 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1671 continue;
1673 $coursenodes[$course->id] = $this->add_course($course);
1674 if (count($coursenodes) >= $limit) {
1675 break;
1678 $coursesrs->close();
1681 return $coursenodes;
1685 * Returns true if more courses can be added to the provided category.
1687 * @param int|navigation_node|stdClass $category
1688 * @return bool
1690 protected function can_add_more_courses_to_category($category) {
1691 global $CFG;
1692 $limit = 20;
1693 if (!empty($CFG->navcourselimit)) {
1694 $limit = (int)$CFG->navcourselimit;
1696 if (is_numeric($category)) {
1697 if (!array_key_exists($category, $this->addedcategories)) {
1698 return true;
1700 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1701 } else if ($category instanceof navigation_node) {
1702 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1703 return false;
1705 $coursecount = count($category->children->type(self::TYPE_COURSE));
1706 } else if (is_object($category) && property_exists($category,'id')) {
1707 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1709 return ($coursecount <= $limit);
1713 * Loads all categories (top level or if an id is specified for that category)
1715 * @param int $categoryid The category id to load or null/0 to load all base level categories
1716 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1717 * as the requested category and any parent categories.
1718 * @return navigation_node|void returns a navigation node if a category has been loaded.
1720 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1721 global $CFG, $DB;
1723 // Check if this category has already been loaded
1724 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1725 return true;
1728 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1729 $sqlselect = "SELECT cc.*, $catcontextsql
1730 FROM {course_categories} cc
1731 JOIN {context} ctx ON cc.id = ctx.instanceid";
1732 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1733 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1734 $params = array();
1736 $categoriestoload = array();
1737 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1738 // We are going to load all categories regardless... prepare to fire
1739 // on the database server!
1740 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1741 // We are going to load all of the first level categories (categories without parents)
1742 $sqlwhere .= " AND cc.parent = 0";
1743 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1744 // The category itself has been loaded already so we just need to ensure its subcategories
1745 // have been loaded
1746 $addedcategories = $this->addedcategories;
1747 unset($addedcategories[$categoryid]);
1748 if (count($addedcategories) > 0) {
1749 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1750 if ($showbasecategories) {
1751 // We need to include categories with parent = 0 as well
1752 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1753 } else {
1754 // All we need is categories that match the parent
1755 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1758 $params['categoryid'] = $categoryid;
1759 } else {
1760 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1761 // and load this category plus all its parents and subcategories
1762 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1763 $categoriestoload = explode('/', trim($category->path, '/'));
1764 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1765 // We are going to use select twice so double the params
1766 $params = array_merge($params, $params);
1767 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1768 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1771 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1772 $categories = array();
1773 foreach ($categoriesrs as $category) {
1774 // Preload the context.. we'll need it when adding the category in order
1775 // to format the category name.
1776 context_helper::preload_from_record($category);
1777 if (array_key_exists($category->id, $this->addedcategories)) {
1778 // Do nothing, its already been added.
1779 } else if ($category->parent == '0') {
1780 // This is a root category lets add it immediately
1781 $this->add_category($category, $this->rootnodes['courses']);
1782 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1783 // This categories parent has already been added we can add this immediately
1784 $this->add_category($category, $this->addedcategories[$category->parent]);
1785 } else {
1786 $categories[] = $category;
1789 $categoriesrs->close();
1791 // Now we have an array of categories we need to add them to the navigation.
1792 while (!empty($categories)) {
1793 $category = reset($categories);
1794 if (array_key_exists($category->id, $this->addedcategories)) {
1795 // Do nothing
1796 } else if ($category->parent == '0') {
1797 $this->add_category($category, $this->rootnodes['courses']);
1798 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1799 $this->add_category($category, $this->addedcategories[$category->parent]);
1800 } else {
1801 // This category isn't in the navigation and niether is it's parent (yet).
1802 // We need to go through the category path and add all of its components in order.
1803 $path = explode('/', trim($category->path, '/'));
1804 foreach ($path as $catid) {
1805 if (!array_key_exists($catid, $this->addedcategories)) {
1806 // This category isn't in the navigation yet so add it.
1807 $subcategory = $categories[$catid];
1808 if ($subcategory->parent == '0') {
1809 // Yay we have a root category - this likely means we will now be able
1810 // to add categories without problems.
1811 $this->add_category($subcategory, $this->rootnodes['courses']);
1812 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1813 // The parent is in the category (as we'd expect) so add it now.
1814 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1815 // Remove the category from the categories array.
1816 unset($categories[$catid]);
1817 } else {
1818 // We should never ever arrive here - if we have then there is a bigger
1819 // problem at hand.
1820 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1825 // Remove the category from the categories array now that we know it has been added.
1826 unset($categories[$category->id]);
1828 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1829 $this->allcategoriesloaded = true;
1831 // Check if there are any categories to load.
1832 if (count($categoriestoload) > 0) {
1833 $readytoloadcourses = array();
1834 foreach ($categoriestoload as $category) {
1835 if ($this->can_add_more_courses_to_category($category)) {
1836 $readytoloadcourses[] = $category;
1839 if (count($readytoloadcourses)) {
1840 $this->load_all_courses($readytoloadcourses);
1844 // Look for all categories which have been loaded
1845 if (!empty($this->addedcategories)) {
1846 $categoryids = array();
1847 foreach ($this->addedcategories as $category) {
1848 if ($this->can_add_more_courses_to_category($category)) {
1849 $categoryids[] = $category->key;
1852 if ($categoryids) {
1853 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1854 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1855 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1856 FROM {course_categories} cc
1857 JOIN {course} c ON c.category = cc.id
1858 WHERE cc.id {$categoriessql}
1859 GROUP BY cc.id
1860 HAVING COUNT(c.id) > :limit";
1861 $excessivecategories = $DB->get_records_sql($sql, $params);
1862 foreach ($categories as &$category) {
1863 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1864 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1865 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1873 * Adds a structured category to the navigation in the correct order/place
1875 * @param stdClass $category category to be added in navigation.
1876 * @param navigation_node $parent parent navigation node
1877 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1878 * @return void.
1880 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1881 if (array_key_exists($category->id, $this->addedcategories)) {
1882 return;
1884 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1885 $context = context_coursecat::instance($category->id);
1886 $categoryname = format_string($category->name, true, array('context' => $context));
1887 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1888 if (empty($category->visible)) {
1889 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1890 $categorynode->hidden = true;
1891 } else {
1892 $categorynode->display = false;
1895 $this->addedcategories[$category->id] = $categorynode;
1899 * Loads the given course into the navigation
1901 * @param stdClass $course
1902 * @return navigation_node
1904 protected function load_course(stdClass $course) {
1905 global $SITE;
1906 if ($course->id == $SITE->id) {
1907 // This is always loaded during initialisation
1908 return $this->rootnodes['site'];
1909 } else if (array_key_exists($course->id, $this->addedcourses)) {
1910 // The course has already been loaded so return a reference
1911 return $this->addedcourses[$course->id];
1912 } else {
1913 // Add the course
1914 return $this->add_course($course);
1919 * Loads all of the courses section into the navigation.
1921 * This function calls method from current course format, see
1922 * {@link format_base::extend_course_navigation()}
1923 * If course module ($cm) is specified but course format failed to create the node,
1924 * the activity node is created anyway.
1926 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1928 * @param stdClass $course Database record for the course
1929 * @param navigation_node $coursenode The course node within the navigation
1930 * @param null|int $sectionnum If specified load the contents of section with this relative number
1931 * @param null|cm_info $cm If specified make sure that activity node is created (either
1932 * in containg section or by calling load_stealth_activity() )
1934 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1935 global $CFG, $SITE;
1936 require_once($CFG->dirroot.'/course/lib.php');
1937 if (isset($cm->sectionnum)) {
1938 $sectionnum = $cm->sectionnum;
1940 if ($sectionnum !== null) {
1941 $this->includesectionnum = $sectionnum;
1943 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1944 if (isset($cm->id)) {
1945 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1946 if (empty($activity)) {
1947 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1953 * Generates an array of sections and an array of activities for the given course.
1955 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1957 * @param stdClass $course
1958 * @return array Array($sections, $activities)
1960 protected function generate_sections_and_activities(stdClass $course) {
1961 global $CFG;
1962 require_once($CFG->dirroot.'/course/lib.php');
1964 $modinfo = get_fast_modinfo($course);
1965 $sections = $modinfo->get_section_info_all();
1967 // For course formats using 'numsections' trim the sections list
1968 $courseformatoptions = course_get_format($course)->get_format_options();
1969 if (isset($courseformatoptions['numsections'])) {
1970 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1973 $activities = array();
1975 foreach ($sections as $key => $section) {
1976 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1977 $sections[$key] = clone($section);
1978 unset($sections[$key]->summary);
1979 $sections[$key]->hasactivites = false;
1980 if (!array_key_exists($section->section, $modinfo->sections)) {
1981 continue;
1983 foreach ($modinfo->sections[$section->section] as $cmid) {
1984 $cm = $modinfo->cms[$cmid];
1985 $activity = new stdClass;
1986 $activity->id = $cm->id;
1987 $activity->course = $course->id;
1988 $activity->section = $section->section;
1989 $activity->name = $cm->name;
1990 $activity->icon = $cm->icon;
1991 $activity->iconcomponent = $cm->iconcomponent;
1992 $activity->hidden = (!$cm->visible);
1993 $activity->modname = $cm->modname;
1994 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1995 $activity->onclick = $cm->onclick;
1996 $url = $cm->url;
1997 if (!$url) {
1998 $activity->url = null;
1999 $activity->display = false;
2000 } else {
2001 $activity->url = $url->out();
2002 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2003 if (self::module_extends_navigation($cm->modname)) {
2004 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2007 $activities[$cmid] = $activity;
2008 if ($activity->display) {
2009 $sections[$key]->hasactivites = true;
2014 return array($sections, $activities);
2018 * Generically loads the course sections into the course's navigation.
2020 * @param stdClass $course
2021 * @param navigation_node $coursenode
2022 * @return array An array of course section nodes
2024 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2025 global $CFG, $DB, $USER, $SITE;
2026 require_once($CFG->dirroot.'/course/lib.php');
2028 list($sections, $activities) = $this->generate_sections_and_activities($course);
2030 $navigationsections = array();
2031 foreach ($sections as $sectionid => $section) {
2032 $section = clone($section);
2033 if ($course->id == $SITE->id) {
2034 $this->load_section_activities($coursenode, $section->section, $activities);
2035 } else {
2036 if (!$section->uservisible || (!$this->showemptysections &&
2037 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2038 continue;
2041 $sectionname = get_section_name($course, $section);
2042 $url = course_get_url($course, $section->section, array('navigation' => true));
2044 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2045 null, $section->id, new pix_icon('i/section', ''));
2046 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2047 $sectionnode->hidden = (!$section->visible || !$section->available);
2048 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2049 $this->load_section_activities($sectionnode, $section->section, $activities);
2051 $section->sectionnode = $sectionnode;
2052 $navigationsections[$sectionid] = $section;
2055 return $navigationsections;
2059 * Loads all of the activities for a section into the navigation structure.
2061 * @param navigation_node $sectionnode
2062 * @param int $sectionnumber
2063 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2064 * @param stdClass $course The course object the section and activities relate to.
2065 * @return array Array of activity nodes
2067 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2068 global $CFG, $SITE;
2069 // A static counter for JS function naming
2070 static $legacyonclickcounter = 0;
2072 $activitynodes = array();
2073 if (empty($activities)) {
2074 return $activitynodes;
2077 if (!is_object($course)) {
2078 $activity = reset($activities);
2079 $courseid = $activity->course;
2080 } else {
2081 $courseid = $course->id;
2083 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2085 foreach ($activities as $activity) {
2086 if ($activity->section != $sectionnumber) {
2087 continue;
2089 if ($activity->icon) {
2090 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2091 } else {
2092 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2095 // Prepare the default name and url for the node
2096 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2097 $action = new moodle_url($activity->url);
2099 // Check if the onclick property is set (puke!)
2100 if (!empty($activity->onclick)) {
2101 // Increment the counter so that we have a unique number.
2102 $legacyonclickcounter++;
2103 // Generate the function name we will use
2104 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2105 $propogrationhandler = '';
2106 // Check if we need to cancel propogation. Remember inline onclick
2107 // events would return false if they wanted to prevent propogation and the
2108 // default action.
2109 if (strpos($activity->onclick, 'return false')) {
2110 $propogrationhandler = 'e.halt();';
2112 // Decode the onclick - it has already been encoded for display (puke)
2113 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2114 // Build the JS function the click event will call
2115 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2116 $this->page->requires->js_amd_inline($jscode);
2117 // Override the default url with the new action link
2118 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2121 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2122 $activitynode->title(get_string('modulename', $activity->modname));
2123 $activitynode->hidden = $activity->hidden;
2124 $activitynode->display = $showactivities && $activity->display;
2125 $activitynode->nodetype = $activity->nodetype;
2126 $activitynodes[$activity->id] = $activitynode;
2129 return $activitynodes;
2132 * Loads a stealth module from unavailable section
2133 * @param navigation_node $coursenode
2134 * @param stdClass $modinfo
2135 * @return navigation_node or null if not accessible
2137 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2138 if (empty($modinfo->cms[$this->page->cm->id])) {
2139 return null;
2141 $cm = $modinfo->cms[$this->page->cm->id];
2142 if ($cm->icon) {
2143 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2144 } else {
2145 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2147 $url = $cm->url;
2148 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2149 $activitynode->title(get_string('modulename', $cm->modname));
2150 $activitynode->hidden = (!$cm->visible);
2151 if (!$cm->is_visible_on_course_page()) {
2152 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2153 // Also there may be no exception at all in case when teacher is logged in as student.
2154 $activitynode->display = false;
2155 } else if (!$url) {
2156 // Don't show activities that don't have links!
2157 $activitynode->display = false;
2158 } else if (self::module_extends_navigation($cm->modname)) {
2159 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2161 return $activitynode;
2164 * Loads the navigation structure for the given activity into the activities node.
2166 * This method utilises a callback within the modules lib.php file to load the
2167 * content specific to activity given.
2169 * The callback is a method: {modulename}_extend_navigation()
2170 * Examples:
2171 * * {@link forum_extend_navigation()}
2172 * * {@link workshop_extend_navigation()}
2174 * @param cm_info|stdClass $cm
2175 * @param stdClass $course
2176 * @param navigation_node $activity
2177 * @return bool
2179 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2180 global $CFG, $DB;
2182 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2183 if (!($cm instanceof cm_info)) {
2184 $modinfo = get_fast_modinfo($course);
2185 $cm = $modinfo->get_cm($cm->id);
2187 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2188 $activity->make_active();
2189 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2190 $function = $cm->modname.'_extend_navigation';
2192 if (file_exists($file)) {
2193 require_once($file);
2194 if (function_exists($function)) {
2195 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2196 $function($activity, $course, $activtyrecord, $cm);
2200 // Allow the active advanced grading method plugin to append module navigation
2201 $featuresfunc = $cm->modname.'_supports';
2202 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2203 require_once($CFG->dirroot.'/grade/grading/lib.php');
2204 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2205 $gradingman->extend_navigation($this, $activity);
2208 return $activity->has_children();
2211 * Loads user specific information into the navigation in the appropriate place.
2213 * If no user is provided the current user is assumed.
2215 * @param stdClass $user
2216 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2217 * @return bool
2219 protected function load_for_user($user=null, $forceforcontext=false) {
2220 global $DB, $CFG, $USER, $SITE;
2222 require_once($CFG->dirroot . '/course/lib.php');
2224 if ($user === null) {
2225 // We can't require login here but if the user isn't logged in we don't
2226 // want to show anything
2227 if (!isloggedin() || isguestuser()) {
2228 return false;
2230 $user = $USER;
2231 } else if (!is_object($user)) {
2232 // If the user is not an object then get them from the database
2233 $select = context_helper::get_preload_record_columns_sql('ctx');
2234 $sql = "SELECT u.*, $select
2235 FROM {user} u
2236 JOIN {context} ctx ON u.id = ctx.instanceid
2237 WHERE u.id = :userid AND
2238 ctx.contextlevel = :contextlevel";
2239 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2240 context_helper::preload_from_record($user);
2243 $iscurrentuser = ($user->id == $USER->id);
2245 $usercontext = context_user::instance($user->id);
2247 // Get the course set against the page, by default this will be the site
2248 $course = $this->page->course;
2249 $baseargs = array('id'=>$user->id);
2250 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2251 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2252 $baseargs['course'] = $course->id;
2253 $coursecontext = context_course::instance($course->id);
2254 $issitecourse = false;
2255 } else {
2256 // Load all categories and get the context for the system
2257 $coursecontext = context_system::instance();
2258 $issitecourse = true;
2261 // Create a node to add user information under.
2262 $usersnode = null;
2263 if (!$issitecourse) {
2264 // Not the current user so add it to the participants node for the current course.
2265 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2266 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2267 } else if ($USER->id != $user->id) {
2268 // This is the site so add a users node to the root branch.
2269 $usersnode = $this->rootnodes['users'];
2270 if (course_can_view_participants($coursecontext)) {
2271 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2273 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2275 if (!$usersnode) {
2276 // We should NEVER get here, if the course hasn't been populated
2277 // with a participants node then the navigaiton either wasn't generated
2278 // for it (you are missing a require_login or set_context call) or
2279 // you don't have access.... in the interests of no leaking informatin
2280 // we simply quit...
2281 return false;
2283 // Add a branch for the current user.
2284 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2285 $viewprofile = true;
2286 if (!$iscurrentuser) {
2287 require_once($CFG->dirroot . '/user/lib.php');
2288 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2289 $viewprofile = false;
2290 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2291 $viewprofile = false;
2293 if (!$viewprofile) {
2294 $viewprofile = user_can_view_profile($user, null, $usercontext);
2298 // Now, conditionally add the user node.
2299 if ($viewprofile) {
2300 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2301 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2302 } else {
2303 $usernode = $usersnode->add(get_string('user'));
2306 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2307 $usernode->make_active();
2310 // Add user information to the participants or user node.
2311 if ($issitecourse) {
2313 // If the user is the current user or has permission to view the details of the requested
2314 // user than add a view profile link.
2315 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2316 has_capability('moodle/user:viewdetails', $usercontext)) {
2317 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2318 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2319 } else {
2320 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2324 if (!empty($CFG->navadduserpostslinks)) {
2325 // Add nodes for forum posts and discussions if the user can view either or both
2326 // There are no capability checks here as the content of the page is based
2327 // purely on the forums the current user has access too.
2328 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2329 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2330 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2331 array_merge($baseargs, array('mode' => 'discussions'))));
2334 // Add blog nodes.
2335 if (!empty($CFG->enableblogs)) {
2336 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2337 require_once($CFG->dirroot.'/blog/lib.php');
2338 // Get all options for the user.
2339 $options = blog_get_options_for_user($user);
2340 $this->cache->set('userblogoptions'.$user->id, $options);
2341 } else {
2342 $options = $this->cache->{'userblogoptions'.$user->id};
2345 if (count($options) > 0) {
2346 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2347 foreach ($options as $type => $option) {
2348 if ($type == "rss") {
2349 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2350 new pix_icon('i/rss', ''));
2351 } else {
2352 $blogs->add($option['string'], $option['link']);
2358 // Add the messages link.
2359 // It is context based so can appear in the user's profile and in course participants information.
2360 if (!empty($CFG->messaging)) {
2361 $messageargs = array('user1' => $USER->id);
2362 if ($USER->id != $user->id) {
2363 $messageargs['user2'] = $user->id;
2365 $url = new moodle_url('/message/index.php', $messageargs);
2366 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2369 // Add the "My private files" link.
2370 // This link doesn't have a unique display for course context so only display it under the user's profile.
2371 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2372 $url = new moodle_url('/user/files.php');
2373 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2376 // Add a node to view the users notes if permitted.
2377 if (!empty($CFG->enablenotes) &&
2378 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2379 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2380 if ($coursecontext->instanceid != SITEID) {
2381 $url->param('course', $coursecontext->instanceid);
2383 $usernode->add(get_string('notes', 'notes'), $url);
2386 // Show the grades node.
2387 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2388 require_once($CFG->dirroot . '/user/lib.php');
2389 // Set the grades node to link to the "Grades" page.
2390 if ($course->id == SITEID) {
2391 $url = user_mygrades_url($user->id, $course->id);
2392 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2393 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2395 if ($USER->id != $user->id) {
2396 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2397 } else {
2398 $usernode->add(get_string('grades', 'grades'), $url);
2402 // If the user is the current user add the repositories for the current user.
2403 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2404 if (!$iscurrentuser &&
2405 $course->id == $SITE->id &&
2406 has_capability('moodle/user:viewdetails', $usercontext) &&
2407 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2409 // Add view grade report is permitted.
2410 $reports = core_component::get_plugin_list('gradereport');
2411 arsort($reports); // User is last, we want to test it first.
2413 $userscourses = enrol_get_users_courses($user->id, false, '*');
2414 $userscoursesnode = $usernode->add(get_string('courses'));
2416 $count = 0;
2417 foreach ($userscourses as $usercourse) {
2418 if ($count === (int)$CFG->navcourselimit) {
2419 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2420 $userscoursesnode->add(get_string('showallcourses'), $url);
2421 break;
2423 $count++;
2424 $usercoursecontext = context_course::instance($usercourse->id);
2425 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2426 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2427 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2429 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2430 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2431 foreach ($reports as $plugin => $plugindir) {
2432 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2433 // Stop when the first visible plugin is found.
2434 $gradeavailable = true;
2435 break;
2440 if ($gradeavailable) {
2441 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2442 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2443 new pix_icon('i/grades', ''));
2446 // Add a node to view the users notes if permitted.
2447 if (!empty($CFG->enablenotes) &&
2448 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2449 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2450 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2453 if (can_access_course($usercourse, $user->id, '', true)) {
2454 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2455 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2458 $reporttab = $usercoursenode->add(get_string('activityreports'));
2460 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2461 foreach ($reportfunctions as $reportfunction) {
2462 $reportfunction($reporttab, $user, $usercourse);
2465 $reporttab->trim_if_empty();
2469 // Let plugins hook into user navigation.
2470 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2471 foreach ($pluginsfunction as $plugintype => $plugins) {
2472 if ($plugintype != 'report') {
2473 foreach ($plugins as $pluginfunction) {
2474 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2479 return true;
2483 * This method simply checks to see if a given module can extend the navigation.
2485 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2487 * @param string $modname
2488 * @return bool
2490 public static function module_extends_navigation($modname) {
2491 global $CFG;
2492 static $extendingmodules = array();
2493 if (!array_key_exists($modname, $extendingmodules)) {
2494 $extendingmodules[$modname] = false;
2495 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2496 if (file_exists($file)) {
2497 $function = $modname.'_extend_navigation';
2498 require_once($file);
2499 $extendingmodules[$modname] = (function_exists($function));
2502 return $extendingmodules[$modname];
2505 * Extends the navigation for the given user.
2507 * @param stdClass $user A user from the database
2509 public function extend_for_user($user) {
2510 $this->extendforuser[] = $user;
2514 * Returns all of the users the navigation is being extended for
2516 * @return array An array of extending users.
2518 public function get_extending_users() {
2519 return $this->extendforuser;
2522 * Adds the given course to the navigation structure.
2524 * @param stdClass $course
2525 * @param bool $forcegeneric
2526 * @param bool $ismycourse
2527 * @return navigation_node
2529 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2530 global $CFG, $SITE;
2532 // We found the course... we can return it now :)
2533 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2534 return $this->addedcourses[$course->id];
2537 $coursecontext = context_course::instance($course->id);
2539 if ($course->id != $SITE->id && !$course->visible) {
2540 if (is_role_switched($course->id)) {
2541 // user has to be able to access course in order to switch, let's skip the visibility test here
2542 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2543 return false;
2547 $issite = ($course->id == $SITE->id);
2548 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2549 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2550 // This is the name that will be shown for the course.
2551 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2553 if ($coursetype == self::COURSE_CURRENT) {
2554 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2555 return $coursenode;
2556 } else {
2557 $coursetype = self::COURSE_OTHER;
2561 // Can the user expand the course to see its content.
2562 $canexpandcourse = true;
2563 if ($issite) {
2564 $parent = $this;
2565 $url = null;
2566 if (empty($CFG->usesitenameforsitepages)) {
2567 $coursename = get_string('sitepages');
2569 } else if ($coursetype == self::COURSE_CURRENT) {
2570 $parent = $this->rootnodes['currentcourse'];
2571 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2572 $canexpandcourse = $this->can_expand_course($course);
2573 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2574 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2575 // Nothing to do here the above statement set $parent to the category within mycourses.
2576 } else {
2577 $parent = $this->rootnodes['mycourses'];
2579 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2580 } else {
2581 $parent = $this->rootnodes['courses'];
2582 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2583 // They can only expand the course if they can access it.
2584 $canexpandcourse = $this->can_expand_course($course);
2585 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2586 if (!$this->is_category_fully_loaded($course->category)) {
2587 // We need to load the category structure for this course
2588 $this->load_all_categories($course->category, false);
2590 if (array_key_exists($course->category, $this->addedcategories)) {
2591 $parent = $this->addedcategories[$course->category];
2592 // This could lead to the course being created so we should check whether it is the case again
2593 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2594 return $this->addedcourses[$course->id];
2600 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2601 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2603 $coursenode->hidden = (!$course->visible);
2604 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2605 if ($canexpandcourse) {
2606 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2607 $coursenode->nodetype = self::NODETYPE_BRANCH;
2608 $coursenode->isexpandable = true;
2609 } else {
2610 $coursenode->nodetype = self::NODETYPE_LEAF;
2611 $coursenode->isexpandable = false;
2613 if (!$forcegeneric) {
2614 $this->addedcourses[$course->id] = $coursenode;
2617 return $coursenode;
2621 * Returns a cache instance to use for the expand course cache.
2622 * @return cache_session
2624 protected function get_expand_course_cache() {
2625 if ($this->cacheexpandcourse === null) {
2626 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2628 return $this->cacheexpandcourse;
2632 * Checks if a user can expand a course in the navigation.
2634 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2635 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2636 * permits stale data.
2637 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2638 * will be stale.
2639 * It is brought up to date in only one of two ways.
2640 * 1. The user logs out and in again.
2641 * 2. The user browses to the course they've just being given access to.
2643 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2645 * @param stdClass $course
2646 * @return bool
2648 protected function can_expand_course($course) {
2649 $cache = $this->get_expand_course_cache();
2650 $canexpand = $cache->get($course->id);
2651 if ($canexpand === false) {
2652 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2653 $canexpand = (int)$canexpand;
2654 $cache->set($course->id, $canexpand);
2656 return ($canexpand === 1);
2660 * Returns true if the category has already been loaded as have any child categories
2662 * @param int $categoryid
2663 * @return bool
2665 protected function is_category_fully_loaded($categoryid) {
2666 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2670 * Adds essential course nodes to the navigation for the given course.
2672 * This method adds nodes such as reports, blogs and participants
2674 * @param navigation_node $coursenode
2675 * @param stdClass $course
2676 * @return bool returns true on successful addition of a node.
2678 public function add_course_essentials($coursenode, stdClass $course) {
2679 global $CFG, $SITE;
2680 require_once($CFG->dirroot . '/course/lib.php');
2682 if ($course->id == $SITE->id) {
2683 return $this->add_front_page_course_essentials($coursenode, $course);
2686 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2687 return true;
2690 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2692 //Participants
2693 if ($navoptions->participants) {
2694 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2695 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2697 if ($navoptions->blogs) {
2698 $blogsurls = new moodle_url('/blog/index.php');
2699 if ($currentgroup = groups_get_course_group($course, true)) {
2700 $blogsurls->param('groupid', $currentgroup);
2701 } else {
2702 $blogsurls->param('courseid', $course->id);
2704 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2707 if ($navoptions->notes) {
2708 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2710 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2711 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2714 // Badges.
2715 if ($navoptions->badges) {
2716 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2718 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2719 navigation_node::TYPE_SETTING, null, 'badgesview',
2720 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2723 // Check access to the course and competencies page.
2724 if ($navoptions->competencies) {
2725 // Just a link to course competency.
2726 $title = get_string('competencies', 'core_competency');
2727 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2728 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2729 new pix_icon('i/competencies', ''));
2731 if ($navoptions->grades) {
2732 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2733 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2734 'grades', new pix_icon('i/grades', ''));
2735 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2736 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2737 $gradenode->make_active();
2741 return true;
2744 * This generates the structure of the course that won't be generated when
2745 * the modules and sections are added.
2747 * Things such as the reports branch, the participants branch, blogs... get
2748 * added to the course node by this method.
2750 * @param navigation_node $coursenode
2751 * @param stdClass $course
2752 * @return bool True for successfull generation
2754 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2755 global $CFG, $USER, $COURSE, $SITE;
2756 require_once($CFG->dirroot . '/course/lib.php');
2758 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2759 return true;
2762 $sitecontext = context_system::instance();
2763 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2765 // Hidden node that we use to determine if the front page navigation is loaded.
2766 // This required as there are not other guaranteed nodes that may be loaded.
2767 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2769 // Participants.
2770 if ($navoptions->participants) {
2771 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2774 // Blogs.
2775 if ($navoptions->blogs) {
2776 $blogsurls = new moodle_url('/blog/index.php');
2777 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2780 $filterselect = 0;
2782 // Badges.
2783 if ($navoptions->badges) {
2784 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2785 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2788 // Notes.
2789 if ($navoptions->notes) {
2790 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2791 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2794 // Tags
2795 if ($navoptions->tags) {
2796 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2797 self::TYPE_SETTING, null, 'tags');
2800 // Search.
2801 if ($navoptions->search) {
2802 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2803 self::TYPE_SETTING, null, 'search');
2806 if ($navoptions->calendar) {
2807 $courseid = $COURSE->id;
2808 $params = array('view' => 'month');
2809 if ($courseid != $SITE->id) {
2810 $params['course'] = $courseid;
2813 // Calendar
2814 $calendarurl = new moodle_url('/calendar/view.php', $params);
2815 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2816 self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
2817 $node->showinflatnavigation = true;
2820 if (isloggedin()) {
2821 $usercontext = context_user::instance($USER->id);
2822 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2823 $url = new moodle_url('/user/files.php');
2824 $node = $coursenode->add(get_string('privatefiles'), $url,
2825 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2826 $node->display = false;
2827 $node->showinflatnavigation = true;
2831 return true;
2835 * Clears the navigation cache
2837 public function clear_cache() {
2838 $this->cache->clear();
2842 * Sets an expansion limit for the navigation
2844 * The expansion limit is used to prevent the display of content that has a type
2845 * greater than the provided $type.
2847 * Can be used to ensure things such as activities or activity content don't get
2848 * shown on the navigation.
2849 * They are still generated in order to ensure the navbar still makes sense.
2851 * @param int $type One of navigation_node::TYPE_*
2852 * @return bool true when complete.
2854 public function set_expansion_limit($type) {
2855 global $SITE;
2856 $nodes = $this->find_all_of_type($type);
2858 // We only want to hide specific types of nodes.
2859 // Only nodes that represent "structure" in the navigation tree should be hidden.
2860 // If we hide all nodes then we risk hiding vital information.
2861 $typestohide = array(
2862 self::TYPE_CATEGORY,
2863 self::TYPE_COURSE,
2864 self::TYPE_SECTION,
2865 self::TYPE_ACTIVITY
2868 foreach ($nodes as $node) {
2869 // We need to generate the full site node
2870 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2871 continue;
2873 foreach ($node->children as $child) {
2874 $child->hide($typestohide);
2877 return true;
2880 * Attempts to get the navigation with the given key from this nodes children.
2882 * This function only looks at this nodes children, it does NOT look recursivily.
2883 * If the node can't be found then false is returned.
2885 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2887 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2888 * may be of more use to you.
2890 * @param string|int $key The key of the node you wish to receive.
2891 * @param int $type One of navigation_node::TYPE_*
2892 * @return navigation_node|false
2894 public function get($key, $type = null) {
2895 if (!$this->initialised) {
2896 $this->initialise();
2898 return parent::get($key, $type);
2902 * Searches this nodes children and their children to find a navigation node
2903 * with the matching key and type.
2905 * This method is recursive and searches children so until either a node is
2906 * found or there are no more nodes to search.
2908 * If you know that the node being searched for is a child of this node
2909 * then use the {@link global_navigation::get()} method instead.
2911 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2912 * may be of more use to you.
2914 * @param string|int $key The key of the node you wish to receive.
2915 * @param int $type One of navigation_node::TYPE_*
2916 * @return navigation_node|false
2918 public function find($key, $type) {
2919 if (!$this->initialised) {
2920 $this->initialise();
2922 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2923 return $this->rootnodes[$key];
2925 return parent::find($key, $type);
2929 * They've expanded the 'my courses' branch.
2931 protected function load_courses_enrolled() {
2932 global $CFG;
2934 $limit = (int) $CFG->navcourselimit;
2936 $courses = enrol_get_my_courses('*');
2937 $flatnavcourses = [];
2939 // Go through the courses and see which ones we want to display in the flatnav.
2940 foreach ($courses as $course) {
2941 $classify = course_classify_for_timeline($course);
2943 if ($classify == COURSE_TIMELINE_INPROGRESS) {
2944 $flatnavcourses[$course->id] = $course;
2948 // Get the number of courses that can be displayed in the nav block and in the flatnav.
2949 $numtotalcourses = count($courses);
2950 $numtotalflatnavcourses = count($flatnavcourses);
2952 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
2953 $courses = array_slice($courses, 0, $limit, true);
2954 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
2956 // Get the number of courses we are going to show for each.
2957 $numshowncourses = count($courses);
2958 $numshownflatnavcourses = count($flatnavcourses);
2959 if ($numshowncourses && $this->show_my_categories()) {
2960 // Generate an array containing unique values of all the courses' categories.
2961 $categoryids = array();
2962 foreach ($courses as $course) {
2963 if (in_array($course->category, $categoryids)) {
2964 continue;
2966 $categoryids[] = $course->category;
2969 // Array of category IDs that include the categories of the user's courses and the related course categories.
2970 $fullpathcategoryids = [];
2971 // Get the course categories for the enrolled courses' category IDs.
2972 require_once('coursecatlib.php');
2973 $mycoursecategories = coursecat::get_many($categoryids);
2974 // Loop over each of these categories and build the category tree using each category's path.
2975 foreach ($mycoursecategories as $mycoursecat) {
2976 $pathcategoryids = explode('/', $mycoursecat->path);
2977 // First element of the exploded path is empty since paths begin with '/'.
2978 array_shift($pathcategoryids);
2979 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
2980 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
2983 // Fetch all of the categories related to the user's courses.
2984 $pathcategories = coursecat::get_many($fullpathcategoryids);
2985 // Loop over each of these categories and build the category tree.
2986 foreach ($pathcategories as $coursecat) {
2987 // No need to process categories that have already been added.
2988 if (isset($this->addedcategories[$coursecat->id])) {
2989 continue;
2992 // Get this course category's parent node.
2993 $parent = null;
2994 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
2995 $parent = $this->addedcategories[$coursecat->parent];
2997 if (!$parent) {
2998 // If it has no parent, then it should be right under the My courses node.
2999 $parent = $this->rootnodes['mycourses'];
3002 // Build the category object based from the coursecat object.
3003 $mycategory = new stdClass();
3004 $mycategory->id = $coursecat->id;
3005 $mycategory->name = $coursecat->name;
3006 $mycategory->visible = $coursecat->visible;
3008 // Add this category to the nav tree.
3009 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3013 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3014 foreach ($courses as $course) {
3015 $node = $this->add_course($course, false, self::COURSE_MY);
3016 if ($node) {
3017 $node->showinflatnavigation = false;
3018 // Check if we should also add this to the flat nav as well.
3019 if (isset($flatnavcourses[$course->id])) {
3020 $node->showinflatnavigation = true;
3025 // Go through each course in the flatnav now.
3026 foreach ($flatnavcourses as $course) {
3027 // Check if we haven't already added it.
3028 if (!isset($courses[$course->id])) {
3029 // Ok, add it to the flatnav only.
3030 $node = $this->add_course($course, false, self::COURSE_MY);
3031 $node->display = false;
3032 $node->showinflatnavigation = true;
3036 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3037 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3038 // Show a link to the course page if there are more courses the user is enrolled in.
3039 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3040 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3041 $url = new moodle_url('/my/?myoverviewtab=courses');
3042 $parent = $this->rootnodes['mycourses'];
3043 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3045 if ($showmorelinkinnav) {
3046 $coursenode->display = true;
3049 if ($showmorelinkinflatnav) {
3050 $coursenode->showinflatnavigation = true;
3057 * The global navigation class used especially for AJAX requests.
3059 * The primary methods that are used in the global navigation class have been overriden
3060 * to ensure that only the relevant branch is generated at the root of the tree.
3061 * This can be done because AJAX is only used when the backwards structure for the
3062 * requested branch exists.
3063 * This has been done only because it shortens the amounts of information that is generated
3064 * which of course will speed up the response time.. because no one likes laggy AJAX.
3066 * @package core
3067 * @category navigation
3068 * @copyright 2009 Sam Hemelryk
3069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3071 class global_navigation_for_ajax extends global_navigation {
3073 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3074 protected $branchtype;
3076 /** @var int the instance id */
3077 protected $instanceid;
3079 /** @var array Holds an array of expandable nodes */
3080 protected $expandable = array();
3083 * Constructs the navigation for use in an AJAX request
3085 * @param moodle_page $page moodle_page object
3086 * @param int $branchtype
3087 * @param int $id
3089 public function __construct($page, $branchtype, $id) {
3090 $this->page = $page;
3091 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3092 $this->children = new navigation_node_collection();
3093 $this->branchtype = $branchtype;
3094 $this->instanceid = $id;
3095 $this->initialise();
3098 * Initialise the navigation given the type and id for the branch to expand.
3100 * @return array An array of the expandable nodes
3102 public function initialise() {
3103 global $DB, $SITE;
3105 if ($this->initialised || during_initial_install()) {
3106 return $this->expandable;
3108 $this->initialised = true;
3110 $this->rootnodes = array();
3111 $this->rootnodes['site'] = $this->add_course($SITE);
3112 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3113 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3114 // The courses branch is always displayed, and is always expandable (although may be empty).
3115 // This mimicks what is done during {@link global_navigation::initialise()}.
3116 $this->rootnodes['courses']->isexpandable = true;
3118 // Branchtype will be one of navigation_node::TYPE_*
3119 switch ($this->branchtype) {
3120 case 0:
3121 if ($this->instanceid === 'mycourses') {
3122 $this->load_courses_enrolled();
3123 } else if ($this->instanceid === 'courses') {
3124 $this->load_courses_other();
3126 break;
3127 case self::TYPE_CATEGORY :
3128 $this->load_category($this->instanceid);
3129 break;
3130 case self::TYPE_MY_CATEGORY :
3131 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3132 break;
3133 case self::TYPE_COURSE :
3134 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3135 if (!can_access_course($course, null, '', true)) {
3136 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3137 // add the course node and break. This leads to an empty node.
3138 $this->add_course($course);
3139 break;
3141 require_course_login($course, true, null, false, true);
3142 $this->page->set_context(context_course::instance($course->id));
3143 $coursenode = $this->add_course($course);
3144 $this->add_course_essentials($coursenode, $course);
3145 $this->load_course_sections($course, $coursenode);
3146 break;
3147 case self::TYPE_SECTION :
3148 $sql = 'SELECT c.*, cs.section AS sectionnumber
3149 FROM {course} c
3150 LEFT JOIN {course_sections} cs ON cs.course = c.id
3151 WHERE cs.id = ?';
3152 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3153 require_course_login($course, true, null, false, true);
3154 $this->page->set_context(context_course::instance($course->id));
3155 $coursenode = $this->add_course($course);
3156 $this->add_course_essentials($coursenode, $course);
3157 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3158 break;
3159 case self::TYPE_ACTIVITY :
3160 $sql = "SELECT c.*
3161 FROM {course} c
3162 JOIN {course_modules} cm ON cm.course = c.id
3163 WHERE cm.id = :cmid";
3164 $params = array('cmid' => $this->instanceid);
3165 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3166 $modinfo = get_fast_modinfo($course);
3167 $cm = $modinfo->get_cm($this->instanceid);
3168 require_course_login($course, true, $cm, false, true);
3169 $this->page->set_context(context_module::instance($cm->id));
3170 $coursenode = $this->load_course($course);
3171 $this->load_course_sections($course, $coursenode, null, $cm);
3172 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3173 if ($activitynode) {
3174 $modulenode = $this->load_activity($cm, $course, $activitynode);
3176 break;
3177 default:
3178 throw new Exception('Unknown type');
3179 return $this->expandable;
3182 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3183 $this->load_for_user(null, true);
3186 $this->find_expandable($this->expandable);
3187 return $this->expandable;
3191 * They've expanded the general 'courses' branch.
3193 protected function load_courses_other() {
3194 $this->load_all_courses();
3198 * Loads a single category into the AJAX navigation.
3200 * This function is special in that it doesn't concern itself with the parent of
3201 * the requested category or its siblings.
3202 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3203 * request that.
3205 * @global moodle_database $DB
3206 * @param int $categoryid id of category to load in navigation.
3207 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3208 * @return void.
3210 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3211 global $CFG, $DB;
3213 $limit = 20;
3214 if (!empty($CFG->navcourselimit)) {
3215 $limit = (int)$CFG->navcourselimit;
3218 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3219 $sql = "SELECT cc.*, $catcontextsql
3220 FROM {course_categories} cc
3221 JOIN {context} ctx ON cc.id = ctx.instanceid
3222 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3223 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3224 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3225 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3226 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3227 $categorylist = array();
3228 $subcategories = array();
3229 $basecategory = null;
3230 foreach ($categories as $category) {
3231 $categorylist[] = $category->id;
3232 context_helper::preload_from_record($category);
3233 if ($category->id == $categoryid) {
3234 $this->add_category($category, $this, $nodetype);
3235 $basecategory = $this->addedcategories[$category->id];
3236 } else {
3237 $subcategories[$category->id] = $category;
3240 $categories->close();
3243 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3244 // else show all courses.
3245 if ($nodetype === self::TYPE_MY_CATEGORY) {
3246 $courses = enrol_get_my_courses('*');
3247 $categoryids = array();
3249 // Only search for categories if basecategory was found.
3250 if (!is_null($basecategory)) {
3251 // Get course parent category ids.
3252 foreach ($courses as $course) {
3253 $categoryids[] = $course->category;
3256 // Get a unique list of category ids which a part of the path
3257 // to user's courses.
3258 $coursesubcategories = array();
3259 $addedsubcategories = array();
3261 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3262 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3264 foreach ($categories as $category){
3265 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3267 $categories->close();
3268 $coursesubcategories = array_unique($coursesubcategories);
3270 // Only add a subcategory if it is part of the path to user's course and
3271 // wasn't already added.
3272 foreach ($subcategories as $subid => $subcategory) {
3273 if (in_array($subid, $coursesubcategories) &&
3274 !in_array($subid, $addedsubcategories)) {
3275 $this->add_category($subcategory, $basecategory, $nodetype);
3276 $addedsubcategories[] = $subid;
3281 foreach ($courses as $course) {
3282 // Add course if it's in category.
3283 if (in_array($course->category, $categorylist)) {
3284 $this->add_course($course, true, self::COURSE_MY);
3287 } else {
3288 if (!is_null($basecategory)) {
3289 foreach ($subcategories as $key=>$category) {
3290 $this->add_category($category, $basecategory, $nodetype);
3293 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3294 foreach ($courses as $course) {
3295 $this->add_course($course);
3297 $courses->close();
3302 * Returns an array of expandable nodes
3303 * @return array
3305 public function get_expandable() {
3306 return $this->expandable;
3311 * Navbar class
3313 * This class is used to manage the navbar, which is initialised from the navigation
3314 * object held by PAGE
3316 * @package core
3317 * @category navigation
3318 * @copyright 2009 Sam Hemelryk
3319 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3321 class navbar extends navigation_node {
3322 /** @var bool A switch for whether the navbar is initialised or not */
3323 protected $initialised = false;
3324 /** @var mixed keys used to reference the nodes on the navbar */
3325 protected $keys = array();
3326 /** @var null|string content of the navbar */
3327 protected $content = null;
3328 /** @var moodle_page object the moodle page that this navbar belongs to */
3329 protected $page;
3330 /** @var bool A switch for whether to ignore the active navigation information */
3331 protected $ignoreactive = false;
3332 /** @var bool A switch to let us know if we are in the middle of an install */
3333 protected $duringinstall = false;
3334 /** @var bool A switch for whether the navbar has items */
3335 protected $hasitems = false;
3336 /** @var array An array of navigation nodes for the navbar */
3337 protected $items;
3338 /** @var array An array of child node objects */
3339 public $children = array();
3340 /** @var bool A switch for whether we want to include the root node in the navbar */
3341 public $includesettingsbase = false;
3342 /** @var breadcrumb_navigation_node[] $prependchildren */
3343 protected $prependchildren = array();
3346 * The almighty constructor
3348 * @param moodle_page $page
3350 public function __construct(moodle_page $page) {
3351 global $CFG;
3352 if (during_initial_install()) {
3353 $this->duringinstall = true;
3354 return false;
3356 $this->page = $page;
3357 $this->text = get_string('home');
3358 $this->shorttext = get_string('home');
3359 $this->action = new moodle_url($CFG->wwwroot);
3360 $this->nodetype = self::NODETYPE_BRANCH;
3361 $this->type = self::TYPE_SYSTEM;
3365 * Quick check to see if the navbar will have items in.
3367 * @return bool Returns true if the navbar will have items, false otherwise
3369 public function has_items() {
3370 if ($this->duringinstall) {
3371 return false;
3372 } else if ($this->hasitems !== false) {
3373 return true;
3375 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3376 // There have been manually added items - there are definitely items.
3377 $outcome = true;
3378 } else if (!$this->ignoreactive) {
3379 // We will need to initialise the navigation structure to check if there are active items.
3380 $this->page->navigation->initialise($this->page);
3381 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3383 $this->hasitems = $outcome;
3384 return $outcome;
3388 * Turn on/off ignore active
3390 * @param bool $setting
3392 public function ignore_active($setting=true) {
3393 $this->ignoreactive = ($setting);
3397 * Gets a navigation node
3399 * @param string|int $key for referencing the navbar nodes
3400 * @param int $type breadcrumb_navigation_node::TYPE_*
3401 * @return breadcrumb_navigation_node|bool
3403 public function get($key, $type = null) {
3404 foreach ($this->children as &$child) {
3405 if ($child->key === $key && ($type == null || $type == $child->type)) {
3406 return $child;
3409 foreach ($this->prependchildren as &$child) {
3410 if ($child->key === $key && ($type == null || $type == $child->type)) {
3411 return $child;
3414 return false;
3417 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3419 * @return array
3421 public function get_items() {
3422 global $CFG;
3423 $items = array();
3424 // Make sure that navigation is initialised
3425 if (!$this->has_items()) {
3426 return $items;
3428 if ($this->items !== null) {
3429 return $this->items;
3432 if (count($this->children) > 0) {
3433 // Add the custom children.
3434 $items = array_reverse($this->children);
3437 // Check if navigation contains the active node
3438 if (!$this->ignoreactive) {
3439 // We will need to ensure the navigation has been initialised.
3440 $this->page->navigation->initialise($this->page);
3441 // Now find the active nodes on both the navigation and settings.
3442 $navigationactivenode = $this->page->navigation->find_active_node();
3443 $settingsactivenode = $this->page->settingsnav->find_active_node();
3445 if ($navigationactivenode && $settingsactivenode) {
3446 // Parse a combined navigation tree
3447 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3448 if (!$settingsactivenode->mainnavonly) {
3449 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3451 $settingsactivenode = $settingsactivenode->parent;
3453 if (!$this->includesettingsbase) {
3454 // Removes the first node from the settings (root node) from the list
3455 array_pop($items);
3457 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3458 if (!$navigationactivenode->mainnavonly) {
3459 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3461 if (!empty($CFG->navshowcategories) &&
3462 $navigationactivenode->type === self::TYPE_COURSE &&
3463 $navigationactivenode->parent->key === 'currentcourse') {
3464 foreach ($this->get_course_categories() as $item) {
3465 $items[] = new breadcrumb_navigation_node($item);
3468 $navigationactivenode = $navigationactivenode->parent;
3470 } else if ($navigationactivenode) {
3471 // Parse the navigation tree to get the active node
3472 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3473 if (!$navigationactivenode->mainnavonly) {
3474 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3476 if (!empty($CFG->navshowcategories) &&
3477 $navigationactivenode->type === self::TYPE_COURSE &&
3478 $navigationactivenode->parent->key === 'currentcourse') {
3479 foreach ($this->get_course_categories() as $item) {
3480 $items[] = new breadcrumb_navigation_node($item);
3483 $navigationactivenode = $navigationactivenode->parent;
3485 } else if ($settingsactivenode) {
3486 // Parse the settings navigation to get the active node
3487 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3488 if (!$settingsactivenode->mainnavonly) {
3489 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3491 $settingsactivenode = $settingsactivenode->parent;
3496 $items[] = new breadcrumb_navigation_node(array(
3497 'text' => $this->page->navigation->text,
3498 'shorttext' => $this->page->navigation->shorttext,
3499 'key' => $this->page->navigation->key,
3500 'action' => $this->page->navigation->action
3503 if (count($this->prependchildren) > 0) {
3504 // Add the custom children
3505 $items = array_merge($items, array_reverse($this->prependchildren));
3508 $last = reset($items);
3509 if ($last) {
3510 $last->set_last(true);
3512 $this->items = array_reverse($items);
3513 return $this->items;
3517 * Get the list of categories leading to this course.
3519 * This function is used by {@link navbar::get_items()} to add back the "courses"
3520 * node and category chain leading to the current course. Note that this is only ever
3521 * called for the current course, so we don't need to bother taking in any parameters.
3523 * @return array
3525 private function get_course_categories() {
3526 global $CFG;
3527 require_once($CFG->dirroot.'/course/lib.php');
3528 require_once($CFG->libdir.'/coursecatlib.php');
3530 $categories = array();
3531 $cap = 'moodle/category:viewhiddencategories';
3532 $showcategories = coursecat::count_all() > 1;
3534 if ($showcategories) {
3535 foreach ($this->page->categories as $category) {
3536 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3537 continue;
3539 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3540 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3541 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3542 if (!$category->visible) {
3543 $categorynode->hidden = true;
3545 $categories[] = $categorynode;
3549 // Don't show the 'course' node if enrolled in this course.
3550 if (!is_enrolled(context_course::instance($this->page->course->id, null, '', true))) {
3551 $courses = $this->page->navigation->get('courses');
3552 if (!$courses) {
3553 // Courses node may not be present.
3554 $courses = breadcrumb_navigation_node::create(
3555 get_string('courses'),
3556 new moodle_url('/course/index.php'),
3557 self::TYPE_CONTAINER
3560 $categories[] = $courses;
3563 return $categories;
3567 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3569 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3570 * the way nodes get added to allow us to simply call add and have the node added to the
3571 * end of the navbar
3573 * @param string $text
3574 * @param string|moodle_url|action_link $action An action to associate with this node.
3575 * @param int $type One of navigation_node::TYPE_*
3576 * @param string $shorttext
3577 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3578 * @param pix_icon $icon An optional icon to use for this node.
3579 * @return navigation_node
3581 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3582 if ($this->content !== null) {
3583 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3586 // Properties array used when creating the new navigation node
3587 $itemarray = array(
3588 'text' => $text,
3589 'type' => $type
3591 // Set the action if one was provided
3592 if ($action!==null) {
3593 $itemarray['action'] = $action;
3595 // Set the shorttext if one was provided
3596 if ($shorttext!==null) {
3597 $itemarray['shorttext'] = $shorttext;
3599 // Set the icon if one was provided
3600 if ($icon!==null) {
3601 $itemarray['icon'] = $icon;
3603 // Default the key to the number of children if not provided
3604 if ($key === null) {
3605 $key = count($this->children);
3607 // Set the key
3608 $itemarray['key'] = $key;
3609 // Set the parent to this node
3610 $itemarray['parent'] = $this;
3611 // Add the child using the navigation_node_collections add method
3612 $this->children[] = new breadcrumb_navigation_node($itemarray);
3613 return $this;
3617 * Prepends a new navigation_node to the start of the navbar
3619 * @param string $text
3620 * @param string|moodle_url|action_link $action An action to associate with this node.
3621 * @param int $type One of navigation_node::TYPE_*
3622 * @param string $shorttext
3623 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3624 * @param pix_icon $icon An optional icon to use for this node.
3625 * @return navigation_node
3627 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3628 if ($this->content !== null) {
3629 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3631 // Properties array used when creating the new navigation node.
3632 $itemarray = array(
3633 'text' => $text,
3634 'type' => $type
3636 // Set the action if one was provided.
3637 if ($action!==null) {
3638 $itemarray['action'] = $action;
3640 // Set the shorttext if one was provided.
3641 if ($shorttext!==null) {
3642 $itemarray['shorttext'] = $shorttext;
3644 // Set the icon if one was provided.
3645 if ($icon!==null) {
3646 $itemarray['icon'] = $icon;
3648 // Default the key to the number of children if not provided.
3649 if ($key === null) {
3650 $key = count($this->children);
3652 // Set the key.
3653 $itemarray['key'] = $key;
3654 // Set the parent to this node.
3655 $itemarray['parent'] = $this;
3656 // Add the child node to the prepend list.
3657 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3658 return $this;
3663 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3664 * in particular adding extra metadata for search engine robots to leverage.
3666 * @package core
3667 * @category navigation
3668 * @copyright 2015 Brendan Heywood
3669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3671 class breadcrumb_navigation_node extends navigation_node {
3673 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3674 private $last = false;
3677 * A proxy constructor
3679 * @param mixed $navnode A navigation_node or an array
3681 public function __construct($navnode) {
3682 if (is_array($navnode)) {
3683 parent::__construct($navnode);
3684 } else if ($navnode instanceof navigation_node) {
3686 // Just clone everything.
3687 $objvalues = get_object_vars($navnode);
3688 foreach ($objvalues as $key => $value) {
3689 $this->$key = $value;
3691 } else {
3692 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3697 * Getter for "last"
3698 * @return boolean
3700 public function is_last() {
3701 return $this->last;
3705 * Setter for "last"
3706 * @param $val boolean
3708 public function set_last($val) {
3709 $this->last = $val;
3714 * Subclass of navigation_node allowing different rendering for the flat navigation
3715 * in particular allowing dividers and indents.
3717 * @package core
3718 * @category navigation
3719 * @copyright 2016 Damyon Wiese
3720 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3722 class flat_navigation_node extends navigation_node {
3724 /** @var $indent integer The indent level */
3725 private $indent = 0;
3727 /** @var $showdivider bool Show a divider before this element */
3728 private $showdivider = false;
3731 * A proxy constructor
3733 * @param mixed $navnode A navigation_node or an array
3735 public function __construct($navnode, $indent) {
3736 if (is_array($navnode)) {
3737 parent::__construct($navnode);
3738 } else if ($navnode instanceof navigation_node) {
3740 // Just clone everything.
3741 $objvalues = get_object_vars($navnode);
3742 foreach ($objvalues as $key => $value) {
3743 $this->$key = $value;
3745 } else {
3746 throw new coding_exception('Not a valid flat_navigation_node');
3748 $this->indent = $indent;
3752 * Does this node represent a course section link.
3753 * @return boolean
3755 public function is_section() {
3756 return $this->type == navigation_node::TYPE_SECTION;
3760 * In flat navigation - sections are active if we are looking at activities in the section.
3761 * @return boolean
3763 public function isactive() {
3764 global $PAGE;
3766 if ($this->is_section()) {
3767 $active = $PAGE->navigation->find_active_node();
3768 while ($active = $active->parent) {
3769 if ($active->key == $this->key && $active->type == $this->type) {
3770 return true;
3774 return $this->isactive;
3778 * Getter for "showdivider"
3779 * @return boolean
3781 public function showdivider() {
3782 return $this->showdivider;
3786 * Setter for "showdivider"
3787 * @param $val boolean
3789 public function set_showdivider($val) {
3790 $this->showdivider = $val;
3794 * Getter for "indent"
3795 * @return boolean
3797 public function get_indent() {
3798 return $this->indent;
3802 * Setter for "indent"
3803 * @param $val boolean
3805 public function set_indent($val) {
3806 $this->indent = $val;
3812 * Class used to generate a collection of navigation nodes most closely related
3813 * to the current page.
3815 * @package core
3816 * @copyright 2016 Damyon Wiese
3817 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3819 class flat_navigation extends navigation_node_collection {
3820 /** @var moodle_page the moodle page that the navigation belongs to */
3821 protected $page;
3824 * Constructor.
3826 * @param moodle_page $page
3828 public function __construct(moodle_page &$page) {
3829 if (during_initial_install()) {
3830 return false;
3832 $this->page = $page;
3836 * Build the list of navigation nodes based on the current navigation and settings trees.
3839 public function initialise() {
3840 global $PAGE, $USER, $OUTPUT, $CFG;
3841 if (during_initial_install()) {
3842 return;
3845 $current = false;
3847 $course = $PAGE->course;
3849 $this->page->navigation->initialise();
3851 // First walk the nav tree looking for "flat_navigation" nodes.
3852 if ($course->id > 1) {
3853 // It's a real course.
3854 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3856 $coursecontext = context_course::instance($course->id, MUST_EXIST);
3857 // This is the name that will be shown for the course.
3858 $coursename = empty($CFG->navshowfullcoursenames) ?
3859 format_string($course->shortname, true, array('context' => $coursecontext)) :
3860 format_string($course->fullname, true, array('context' => $coursecontext));
3862 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
3863 $flat->key = 'coursehome';
3864 $flat->icon = new pix_icon('i/course', '');
3866 $courseformat = course_get_format($course);
3867 $coursenode = $PAGE->navigation->find_active_node();
3868 $targettype = navigation_node::TYPE_COURSE;
3870 // Single activity format has no course node - the course node is swapped for the activity node.
3871 if (!$courseformat->has_view_page()) {
3872 $targettype = navigation_node::TYPE_ACTIVITY;
3875 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
3876 $coursenode = $coursenode->parent;
3878 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
3879 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
3880 if ($coursenode && $coursenode->key != SITEID) {
3881 $this->add($flat);
3882 foreach ($coursenode->children as $child) {
3883 if ($child->action) {
3884 $flat = new flat_navigation_node($child, 0);
3885 $this->add($flat);
3890 $this->page->navigation->build_flat_navigation_list($this, true);
3891 } else {
3892 $this->page->navigation->build_flat_navigation_list($this, false);
3895 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
3896 if (!$admin) {
3897 // Try again - crazy nav tree!
3898 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
3900 if ($admin) {
3901 $flat = new flat_navigation_node($admin, 0);
3902 $flat->set_showdivider(true);
3903 $flat->key = 'sitesettings';
3904 $flat->icon = new pix_icon('t/preferences', '');
3905 $this->add($flat);
3908 // Add-a-block in editing mode.
3909 if (isset($this->page->theme->addblockposition) &&
3910 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
3911 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
3912 ($addable = $PAGE->blocks->get_addable_blocks())) {
3913 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
3914 $addablock = navigation_node::create(get_string('addblock'), $url);
3915 $flat = new flat_navigation_node($addablock, 0);
3916 $flat->set_showdivider(true);
3917 $flat->key = 'addblock';
3918 $flat->icon = new pix_icon('i/addblock', '');
3919 $this->add($flat);
3920 $blocks = [];
3921 foreach ($addable as $block) {
3922 $blocks[] = $block->name;
3924 $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
3925 $PAGE->requires->js_call_amd('core/addblockmodal', 'init', array($params));
3932 * Class used to manage the settings option for the current page
3934 * This class is used to manage the settings options in a tree format (recursively)
3935 * and was created initially for use with the settings blocks.
3937 * @package core
3938 * @category navigation
3939 * @copyright 2009 Sam Hemelryk
3940 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3942 class settings_navigation extends navigation_node {
3943 /** @var stdClass the current context */
3944 protected $context;
3945 /** @var moodle_page the moodle page that the navigation belongs to */
3946 protected $page;
3947 /** @var string contains administration section navigation_nodes */
3948 protected $adminsection;
3949 /** @var bool A switch to see if the navigation node is initialised */
3950 protected $initialised = false;
3951 /** @var array An array of users that the nodes can extend for. */
3952 protected $userstoextendfor = array();
3953 /** @var navigation_cache **/
3954 protected $cache;
3957 * Sets up the object with basic settings and preparse it for use
3959 * @param moodle_page $page
3961 public function __construct(moodle_page &$page) {
3962 if (during_initial_install()) {
3963 return false;
3965 $this->page = $page;
3966 // Initialise the main navigation. It is most important that this is done
3967 // before we try anything
3968 $this->page->navigation->initialise();
3969 // Initialise the navigation cache
3970 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3971 $this->children = new navigation_node_collection();
3975 * Initialise the settings navigation based on the current context
3977 * This function initialises the settings navigation tree for a given context
3978 * by calling supporting functions to generate major parts of the tree.
3981 public function initialise() {
3982 global $DB, $SESSION, $SITE;
3984 if (during_initial_install()) {
3985 return false;
3986 } else if ($this->initialised) {
3987 return true;
3989 $this->id = 'settingsnav';
3990 $this->context = $this->page->context;
3992 $context = $this->context;
3993 if ($context->contextlevel == CONTEXT_BLOCK) {
3994 $this->load_block_settings();
3995 $context = $context->get_parent_context();
3996 $this->context = $context;
3998 switch ($context->contextlevel) {
3999 case CONTEXT_SYSTEM:
4000 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4001 $this->load_front_page_settings(($context->id == $this->context->id));
4003 break;
4004 case CONTEXT_COURSECAT:
4005 $this->load_category_settings();
4006 break;
4007 case CONTEXT_COURSE:
4008 if ($this->page->course->id != $SITE->id) {
4009 $this->load_course_settings(($context->id == $this->context->id));
4010 } else {
4011 $this->load_front_page_settings(($context->id == $this->context->id));
4013 break;
4014 case CONTEXT_MODULE:
4015 $this->load_module_settings();
4016 $this->load_course_settings();
4017 break;
4018 case CONTEXT_USER:
4019 if ($this->page->course->id != $SITE->id) {
4020 $this->load_course_settings();
4022 break;
4025 $usersettings = $this->load_user_settings($this->page->course->id);
4027 $adminsettings = false;
4028 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4029 $isadminpage = $this->is_admin_tree_needed();
4031 if (has_capability('moodle/site:configview', context_system::instance())) {
4032 if (has_capability('moodle/site:config', context_system::instance())) {
4033 // Make sure this works even if config capability changes on the fly
4034 // and also make it fast for admin right after login.
4035 $SESSION->load_navigation_admin = 1;
4036 if ($isadminpage) {
4037 $adminsettings = $this->load_administration_settings();
4040 } else if (!isset($SESSION->load_navigation_admin)) {
4041 $adminsettings = $this->load_administration_settings();
4042 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4044 } else if ($SESSION->load_navigation_admin) {
4045 if ($isadminpage) {
4046 $adminsettings = $this->load_administration_settings();
4050 // Print empty navigation node, if needed.
4051 if ($SESSION->load_navigation_admin && !$isadminpage) {
4052 if ($adminsettings) {
4053 // Do not print settings tree on pages that do not need it, this helps with performance.
4054 $adminsettings->remove();
4055 $adminsettings = false;
4057 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4058 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4059 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4060 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4061 $siteadminnode->requiresajaxloading = 'true';
4066 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4067 $adminsettings->force_open();
4068 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4069 $usersettings->force_open();
4072 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4073 $this->load_local_plugin_settings();
4075 foreach ($this->children as $key=>$node) {
4076 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4077 // Site administration is shown as link.
4078 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4079 continue;
4081 $node->remove();
4084 $this->initialised = true;
4087 * Override the parent function so that we can add preceeding hr's and set a
4088 * root node class against all first level element
4090 * It does this by first calling the parent's add method {@link navigation_node::add()}
4091 * and then proceeds to use the key to set class and hr
4093 * @param string $text text to be used for the link.
4094 * @param string|moodle_url $url url for the new node
4095 * @param int $type the type of node navigation_node::TYPE_*
4096 * @param string $shorttext
4097 * @param string|int $key a key to access the node by.
4098 * @param pix_icon $icon An icon that appears next to the node.
4099 * @return navigation_node with the new node added to it.
4101 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4102 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4103 $node->add_class('root_node');
4104 return $node;
4108 * This function allows the user to add something to the start of the settings
4109 * navigation, which means it will be at the top of the settings navigation block
4111 * @param string $text text to be used for the link.
4112 * @param string|moodle_url $url url for the new node
4113 * @param int $type the type of node navigation_node::TYPE_*
4114 * @param string $shorttext
4115 * @param string|int $key a key to access the node by.
4116 * @param pix_icon $icon An icon that appears next to the node.
4117 * @return navigation_node $node with the new node added to it.
4119 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4120 $children = $this->children;
4121 $childrenclass = get_class($children);
4122 $this->children = new $childrenclass;
4123 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4124 foreach ($children as $child) {
4125 $this->children->add($child);
4127 return $node;
4131 * Does this page require loading of full admin tree or is
4132 * it enough rely on AJAX?
4134 * @return bool
4136 protected function is_admin_tree_needed() {
4137 if (self::$loadadmintree) {
4138 // Usually external admin page or settings page.
4139 return true;
4142 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4143 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4144 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4145 return false;
4147 return true;
4150 return false;
4154 * Load the site administration tree
4156 * This function loads the site administration tree by using the lib/adminlib library functions
4158 * @param navigation_node $referencebranch A reference to a branch in the settings
4159 * navigation tree
4160 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4161 * tree and start at the beginning
4162 * @return mixed A key to access the admin tree by
4164 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4165 global $CFG;
4167 // Check if we are just starting to generate this navigation.
4168 if ($referencebranch === null) {
4170 // Require the admin lib then get an admin structure
4171 if (!function_exists('admin_get_root')) {
4172 require_once($CFG->dirroot.'/lib/adminlib.php');
4174 $adminroot = admin_get_root(false, false);
4175 // This is the active section identifier
4176 $this->adminsection = $this->page->url->param('section');
4178 // Disable the navigation from automatically finding the active node
4179 navigation_node::$autofindactive = false;
4180 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4181 foreach ($adminroot->children as $adminbranch) {
4182 $this->load_administration_settings($referencebranch, $adminbranch);
4184 navigation_node::$autofindactive = true;
4186 // Use the admin structure to locate the active page
4187 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4188 $currentnode = $this;
4189 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4190 $currentnode = $currentnode->get($pathkey);
4192 if ($currentnode) {
4193 $currentnode->make_active();
4195 } else {
4196 $this->scan_for_active_node($referencebranch);
4198 return $referencebranch;
4199 } else if ($adminbranch->check_access()) {
4200 // We have a reference branch that we can access and is not hidden `hurrah`
4201 // Now we need to display it and any children it may have
4202 $url = null;
4203 $icon = null;
4204 if ($adminbranch instanceof admin_settingpage) {
4205 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
4206 } else if ($adminbranch instanceof admin_externalpage) {
4207 $url = $adminbranch->url;
4208 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4209 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
4212 // Add the branch
4213 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4215 if ($adminbranch->is_hidden()) {
4216 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4217 $reference->add_class('hidden');
4218 } else {
4219 $reference->display = false;
4223 // Check if we are generating the admin notifications and whether notificiations exist
4224 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4225 $reference->add_class('criticalnotification');
4227 // Check if this branch has children
4228 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4229 foreach ($adminbranch->children as $branch) {
4230 // Generate the child branches as well now using this branch as the reference
4231 $this->load_administration_settings($reference, $branch);
4233 } else {
4234 $reference->icon = new pix_icon('i/settings', '');
4240 * This function recursivily scans nodes until it finds the active node or there
4241 * are no more nodes.
4242 * @param navigation_node $node
4244 protected function scan_for_active_node(navigation_node $node) {
4245 if (!$node->check_if_active() && $node->children->count()>0) {
4246 foreach ($node->children as &$child) {
4247 $this->scan_for_active_node($child);
4253 * Gets a navigation node given an array of keys that represent the path to
4254 * the desired node.
4256 * @param array $path
4257 * @return navigation_node|false
4259 protected function get_by_path(array $path) {
4260 $node = $this->get(array_shift($path));
4261 foreach ($path as $key) {
4262 $node->get($key);
4264 return $node;
4268 * This function loads the course settings that are available for the user
4270 * @param bool $forceopen If set to true the course node will be forced open
4271 * @return navigation_node|false
4273 protected function load_course_settings($forceopen = false) {
4274 global $CFG;
4275 require_once($CFG->dirroot . '/course/lib.php');
4277 $course = $this->page->course;
4278 $coursecontext = context_course::instance($course->id);
4279 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4281 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4283 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4284 if ($forceopen) {
4285 $coursenode->force_open();
4289 if ($adminoptions->update) {
4290 // Add the course settings link
4291 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4292 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
4295 if ($this->page->user_allowed_editing()) {
4296 // Add the turn on/off settings
4298 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
4299 // We are on the course page, retain the current page params e.g. section.
4300 $baseurl = clone($this->page->url);
4301 $baseurl->param('sesskey', sesskey());
4302 } else {
4303 // Edit on the main course page.
4304 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
4307 $editurl = clone($baseurl);
4308 if ($this->page->user_is_editing()) {
4309 $editurl->param('edit', 'off');
4310 $editstring = get_string('turneditingoff');
4311 } else {
4312 $editurl->param('edit', 'on');
4313 $editstring = get_string('turneditingon');
4315 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
4318 if ($adminoptions->editcompletion) {
4319 // Add the course completion settings link
4320 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4321 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null,
4322 new pix_icon('i/settings', ''));
4325 if (!$adminoptions->update && $adminoptions->tags) {
4326 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4327 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4330 // add enrol nodes
4331 enrol_add_course_navigation($coursenode, $course);
4333 // Manage filters
4334 if ($adminoptions->filters) {
4335 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4336 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4339 // View course reports.
4340 if ($adminoptions->reports) {
4341 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'coursereports',
4342 new pix_icon('i/stats', ''));
4343 $coursereports = core_component::get_plugin_list('coursereport');
4344 foreach ($coursereports as $report => $dir) {
4345 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4346 if (file_exists($libfile)) {
4347 require_once($libfile);
4348 $reportfunction = $report.'_report_extend_navigation';
4349 if (function_exists($report.'_report_extend_navigation')) {
4350 $reportfunction($reportnav, $course, $coursecontext);
4355 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4356 foreach ($reports as $reportfunction) {
4357 $reportfunction($reportnav, $course, $coursecontext);
4361 // Check if we can view the gradebook's setup page.
4362 if ($adminoptions->gradebook) {
4363 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4364 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4365 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4368 // Add outcome if permitted
4369 if ($adminoptions->outcomes) {
4370 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4371 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4374 //Add badges navigation
4375 if ($adminoptions->badges) {
4376 require_once($CFG->libdir .'/badgeslib.php');
4377 badges_add_course_navigation($coursenode, $course);
4380 // Backup this course
4381 if ($adminoptions->backup) {
4382 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4383 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4386 // Restore to this course
4387 if ($adminoptions->restore) {
4388 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4389 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4392 // Import data from other courses
4393 if ($adminoptions->import) {
4394 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
4395 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4398 // Publish course on a hub
4399 if ($adminoptions->publish) {
4400 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
4401 $coursenode->add(get_string('publish', 'core_hub'), $url, self::TYPE_SETTING, null, 'publish',
4402 new pix_icon('i/publish', ''));
4405 // Reset this course
4406 if ($adminoptions->reset) {
4407 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4408 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4411 // Questions
4412 require_once($CFG->libdir . '/questionlib.php');
4413 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4415 if ($adminoptions->update) {
4416 // Repository Instances
4417 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4418 require_once($CFG->dirroot . '/repository/lib.php');
4419 $editabletypes = repository::get_editable_types($coursecontext);
4420 $haseditabletypes = !empty($editabletypes);
4421 unset($editabletypes);
4422 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4423 } else {
4424 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4426 if ($haseditabletypes) {
4427 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4428 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4432 // Manage files
4433 if ($adminoptions->files) {
4434 // hidden in new courses and courses where legacy files were turned off
4435 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4436 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4440 // Let plugins hook into course navigation.
4441 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4442 foreach ($pluginsfunction as $plugintype => $plugins) {
4443 // Ignore the report plugin as it was already loaded above.
4444 if ($plugintype == 'report') {
4445 continue;
4447 foreach ($plugins as $pluginfunction) {
4448 $pluginfunction($coursenode, $course, $coursecontext);
4452 // Return we are done
4453 return $coursenode;
4457 * This function calls the module function to inject module settings into the
4458 * settings navigation tree.
4460 * This only gets called if there is a corrosponding function in the modules
4461 * lib file.
4463 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4465 * @return navigation_node|false
4467 protected function load_module_settings() {
4468 global $CFG;
4470 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4471 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4472 $this->page->set_cm($cm, $this->page->course);
4475 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4476 if (file_exists($file)) {
4477 require_once($file);
4480 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4481 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4482 $modulenode->force_open();
4484 // Settings for the module
4485 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4486 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4487 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
4489 // Assign local roles
4490 if (count(get_assignable_roles($this->page->cm->context))>0) {
4491 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4492 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
4494 // Override roles
4495 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4496 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4497 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
4499 // Check role permissions
4500 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4501 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4502 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
4504 // Manage filters
4505 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4506 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4507 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
4509 // Add reports
4510 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4511 foreach ($reports as $reportfunction) {
4512 $reportfunction($modulenode, $this->page->cm);
4514 // Add a backup link
4515 $featuresfunc = $this->page->activityname.'_supports';
4516 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4517 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4518 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4521 // Restore this activity
4522 $featuresfunc = $this->page->activityname.'_supports';
4523 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4524 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4525 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4528 // Allow the active advanced grading method plugin to append its settings
4529 $featuresfunc = $this->page->activityname.'_supports';
4530 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4531 require_once($CFG->dirroot.'/grade/grading/lib.php');
4532 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4533 $gradingman->extend_settings_navigation($this, $modulenode);
4536 $function = $this->page->activityname.'_extend_settings_navigation';
4537 if (function_exists($function)) {
4538 $function($this, $modulenode);
4541 // Remove the module node if there are no children.
4542 if ($modulenode->children->count() <= 0) {
4543 $modulenode->remove();
4546 return $modulenode;
4550 * Loads the user settings block of the settings nav
4552 * This function is simply works out the userid and whether we need to load
4553 * just the current users profile settings, or the current user and the user the
4554 * current user is viewing.
4556 * This function has some very ugly code to work out the user, if anyone has
4557 * any bright ideas please feel free to intervene.
4559 * @param int $courseid The course id of the current course
4560 * @return navigation_node|false
4562 protected function load_user_settings($courseid = SITEID) {
4563 global $USER, $CFG;
4565 if (isguestuser() || !isloggedin()) {
4566 return false;
4569 $navusers = $this->page->navigation->get_extending_users();
4571 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4572 $usernode = null;
4573 foreach ($this->userstoextendfor as $userid) {
4574 if ($userid == $USER->id) {
4575 continue;
4577 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4578 if (is_null($usernode)) {
4579 $usernode = $node;
4582 foreach ($navusers as $user) {
4583 if ($user->id == $USER->id) {
4584 continue;
4586 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4587 if (is_null($usernode)) {
4588 $usernode = $node;
4591 $this->generate_user_settings($courseid, $USER->id);
4592 } else {
4593 $usernode = $this->generate_user_settings($courseid, $USER->id);
4595 return $usernode;
4599 * Extends the settings navigation for the given user.
4601 * Note: This method gets called automatically if you call
4602 * $PAGE->navigation->extend_for_user($userid)
4604 * @param int $userid
4606 public function extend_for_user($userid) {
4607 global $CFG;
4609 if (!in_array($userid, $this->userstoextendfor)) {
4610 $this->userstoextendfor[] = $userid;
4611 if ($this->initialised) {
4612 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4613 $children = array();
4614 foreach ($this->children as $child) {
4615 $children[] = $child;
4617 array_unshift($children, array_pop($children));
4618 $this->children = new navigation_node_collection();
4619 foreach ($children as $child) {
4620 $this->children->add($child);
4627 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4628 * what can be shown/done
4630 * @param int $courseid The current course' id
4631 * @param int $userid The user id to load for
4632 * @param string $gstitle The string to pass to get_string for the branch title
4633 * @return navigation_node|false
4635 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4636 global $DB, $CFG, $USER, $SITE;
4638 if ($courseid != $SITE->id) {
4639 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4640 $course = $this->page->course;
4641 } else {
4642 $select = context_helper::get_preload_record_columns_sql('ctx');
4643 $sql = "SELECT c.*, $select
4644 FROM {course} c
4645 JOIN {context} ctx ON c.id = ctx.instanceid
4646 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4647 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4648 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4649 context_helper::preload_from_record($course);
4651 } else {
4652 $course = $SITE;
4655 $coursecontext = context_course::instance($course->id); // Course context
4656 $systemcontext = context_system::instance();
4657 $currentuser = ($USER->id == $userid);
4659 if ($currentuser) {
4660 $user = $USER;
4661 $usercontext = context_user::instance($user->id); // User context
4662 } else {
4663 $select = context_helper::get_preload_record_columns_sql('ctx');
4664 $sql = "SELECT u.*, $select
4665 FROM {user} u
4666 JOIN {context} ctx ON u.id = ctx.instanceid
4667 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4668 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4669 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4670 if (!$user) {
4671 return false;
4673 context_helper::preload_from_record($user);
4675 // Check that the user can view the profile
4676 $usercontext = context_user::instance($user->id); // User context
4677 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4679 if ($course->id == $SITE->id) {
4680 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4681 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4682 return false;
4684 } else {
4685 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4686 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4687 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4688 return false;
4690 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4691 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4692 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4693 if ($courseid == $this->page->course->id) {
4694 $mygroups = get_fast_modinfo($this->page->course)->groups;
4695 } else {
4696 $mygroups = groups_get_user_groups($courseid);
4698 $usergroups = groups_get_user_groups($courseid, $userid);
4699 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4700 return false;
4706 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4708 $key = $gstitle;
4709 $prefurl = new moodle_url('/user/preferences.php');
4710 if ($gstitle != 'usercurrentsettings') {
4711 $key .= $userid;
4712 $prefurl->param('userid', $userid);
4715 // Add a user setting branch.
4716 if ($gstitle == 'usercurrentsettings') {
4717 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4718 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4719 // breadcrumb.
4720 $dashboard->display = false;
4721 if (get_home_page() == HOMEPAGE_MY) {
4722 $dashboard->mainnavonly = true;
4725 $iscurrentuser = ($user->id == $USER->id);
4727 $baseargs = array('id' => $user->id);
4728 if ($course->id != $SITE->id && !$iscurrentuser) {
4729 $baseargs['course'] = $course->id;
4730 $issitecourse = false;
4731 } else {
4732 // Load all categories and get the context for the system.
4733 $issitecourse = true;
4736 // Add the user profile to the dashboard.
4737 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4738 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4740 if (!empty($CFG->navadduserpostslinks)) {
4741 // Add nodes for forum posts and discussions if the user can view either or both
4742 // There are no capability checks here as the content of the page is based
4743 // purely on the forums the current user has access too.
4744 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4745 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4746 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4747 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4750 // Add blog nodes.
4751 if (!empty($CFG->enableblogs)) {
4752 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4753 require_once($CFG->dirroot.'/blog/lib.php');
4754 // Get all options for the user.
4755 $options = blog_get_options_for_user($user);
4756 $this->cache->set('userblogoptions'.$user->id, $options);
4757 } else {
4758 $options = $this->cache->{'userblogoptions'.$user->id};
4761 if (count($options) > 0) {
4762 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4763 foreach ($options as $type => $option) {
4764 if ($type == "rss") {
4765 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4766 new pix_icon('i/rss', ''));
4767 } else {
4768 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4774 // Add the messages link.
4775 // It is context based so can appear in the user's profile and in course participants information.
4776 if (!empty($CFG->messaging)) {
4777 $messageargs = array('user1' => $USER->id);
4778 if ($USER->id != $user->id) {
4779 $messageargs['user2'] = $user->id;
4781 $url = new moodle_url('/message/index.php', $messageargs);
4782 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4785 // Add the "My private files" link.
4786 // This link doesn't have a unique display for course context so only display it under the user's profile.
4787 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4788 $url = new moodle_url('/user/files.php');
4789 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
4792 // Add a node to view the users notes if permitted.
4793 if (!empty($CFG->enablenotes) &&
4794 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4795 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4796 if ($coursecontext->instanceid != SITEID) {
4797 $url->param('course', $coursecontext->instanceid);
4799 $profilenode->add(get_string('notes', 'notes'), $url);
4802 // Show the grades node.
4803 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
4804 require_once($CFG->dirroot . '/user/lib.php');
4805 // Set the grades node to link to the "Grades" page.
4806 if ($course->id == SITEID) {
4807 $url = user_mygrades_url($user->id, $course->id);
4808 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4809 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
4811 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
4814 // Let plugins hook into user navigation.
4815 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
4816 foreach ($pluginsfunction as $plugintype => $plugins) {
4817 if ($plugintype != 'report') {
4818 foreach ($plugins as $pluginfunction) {
4819 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
4824 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4825 $dashboard->add_node($usersetting);
4826 } else {
4827 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4828 $usersetting->display = false;
4830 $usersetting->id = 'usersettings';
4832 // Check if the user has been deleted.
4833 if ($user->deleted) {
4834 if (!has_capability('moodle/user:update', $coursecontext)) {
4835 // We can't edit the user so just show the user deleted message.
4836 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4837 } else {
4838 // We can edit the user so show the user deleted message and link it to the profile.
4839 if ($course->id == $SITE->id) {
4840 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4841 } else {
4842 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4844 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4846 return true;
4849 $userauthplugin = false;
4850 if (!empty($user->auth)) {
4851 $userauthplugin = get_auth_plugin($user->auth);
4854 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
4856 // Add the profile edit link.
4857 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4858 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
4859 has_capability('moodle/user:update', $systemcontext)) {
4860 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4861 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4862 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4863 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4864 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4865 $url = $userauthplugin->edit_profile_url();
4866 if (empty($url)) {
4867 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4869 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4874 // Change password link.
4875 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
4876 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4877 $passwordchangeurl = $userauthplugin->change_password_url();
4878 if (empty($passwordchangeurl)) {
4879 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4881 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
4884 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4885 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4886 has_capability('moodle/user:editprofile', $usercontext)) {
4887 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
4888 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
4891 $pluginmanager = core_plugin_manager::instance();
4892 $enabled = $pluginmanager->get_enabled_plugins('mod');
4893 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4894 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4895 has_capability('moodle/user:editprofile', $usercontext)) {
4896 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
4897 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
4900 $editors = editors_get_enabled();
4901 if (count($editors) > 1) {
4902 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4903 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4904 has_capability('moodle/user:editprofile', $usercontext)) {
4905 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
4906 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
4911 // Add "Course preferences" link.
4912 if (isloggedin() && !isguestuser($user)) {
4913 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4914 has_capability('moodle/user:editprofile', $usercontext)) {
4915 $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
4916 $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
4920 // Add "Calendar preferences" link.
4921 if (isloggedin() && !isguestuser($user)) {
4922 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4923 has_capability('moodle/user:editprofile', $usercontext)) {
4924 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
4925 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
4929 // View the roles settings.
4930 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
4931 'moodle/role:manage'), $usercontext)) {
4932 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4934 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4935 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4937 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4939 if (!empty($assignableroles)) {
4940 $url = new moodle_url('/admin/roles/assign.php',
4941 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4942 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4945 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4946 $url = new moodle_url('/admin/roles/permissions.php',
4947 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4948 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4951 $url = new moodle_url('/admin/roles/check.php',
4952 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4953 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4956 // Repositories.
4957 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
4958 require_once($CFG->dirroot . '/repository/lib.php');
4959 $editabletypes = repository::get_editable_types($usercontext);
4960 $haseditabletypes = !empty($editabletypes);
4961 unset($editabletypes);
4962 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
4963 } else {
4964 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
4966 if ($haseditabletypes) {
4967 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
4968 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
4969 array('contextid' => $usercontext->id)));
4972 // Portfolio.
4973 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4974 require_once($CFG->libdir . '/portfoliolib.php');
4975 if (portfolio_has_visible_instances()) {
4976 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4978 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4979 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4981 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4982 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4986 $enablemanagetokens = false;
4987 if (!empty($CFG->enablerssfeeds)) {
4988 $enablemanagetokens = true;
4989 } else if (!is_siteadmin($USER->id)
4990 && !empty($CFG->enablewebservices)
4991 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4992 $enablemanagetokens = true;
4994 // Security keys.
4995 if ($currentuser && $enablemanagetokens) {
4996 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4997 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5000 // Messaging.
5001 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5002 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5003 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5004 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5005 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5006 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5009 // Blogs.
5010 if ($currentuser && !empty($CFG->enableblogs)) {
5011 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5012 if (has_capability('moodle/blog:view', $systemcontext)) {
5013 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5014 navigation_node::TYPE_SETTING);
5016 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5017 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5018 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5019 navigation_node::TYPE_SETTING);
5020 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5021 navigation_node::TYPE_SETTING);
5023 // Remove the blog node if empty.
5024 $blog->trim_if_empty();
5027 // Badges.
5028 if ($currentuser && !empty($CFG->enablebadges)) {
5029 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5030 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5031 $url = new moodle_url('/badges/mybadges.php');
5032 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5034 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5035 navigation_node::TYPE_SETTING);
5036 if (!empty($CFG->badges_allowexternalbackpack)) {
5037 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5038 navigation_node::TYPE_SETTING);
5042 // Let plugins hook into user settings navigation.
5043 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5044 foreach ($pluginsfunction as $plugintype => $plugins) {
5045 foreach ($plugins as $pluginfunction) {
5046 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5050 return $usersetting;
5054 * Loads block specific settings in the navigation
5056 * @return navigation_node
5058 protected function load_block_settings() {
5059 global $CFG;
5061 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5062 $blocknode->force_open();
5064 // Assign local roles
5065 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5066 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5067 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5068 'roles', new pix_icon('i/assignroles', ''));
5071 // Override roles
5072 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5073 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5074 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5075 'permissions', new pix_icon('i/permissions', ''));
5077 // Check role permissions
5078 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5079 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5080 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5081 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5084 return $blocknode;
5088 * Loads category specific settings in the navigation
5090 * @return navigation_node
5092 protected function load_category_settings() {
5093 global $CFG;
5095 // We can land here while being in the context of a block, in which case we
5096 // should get the parent context which should be the category one. See self::initialise().
5097 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5098 $catcontext = $this->context->get_parent_context();
5099 } else {
5100 $catcontext = $this->context;
5103 // Let's make sure that we always have the right context when getting here.
5104 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5105 throw new coding_exception('Unexpected context while loading category settings.');
5108 $categorynodetype = navigation_node::TYPE_CONTAINER;
5109 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5110 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5111 $categorynode->force_open();
5113 if (can_edit_in_category($catcontext->instanceid)) {
5114 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5115 $editstring = get_string('managecategorythis');
5116 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5119 if (has_capability('moodle/category:manage', $catcontext)) {
5120 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5121 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5123 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5124 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5127 // Assign local roles
5128 $assignableroles = get_assignable_roles($catcontext);
5129 if (!empty($assignableroles)) {
5130 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5131 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5134 // Override roles
5135 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5136 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5137 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5139 // Check role permissions
5140 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5141 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5142 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5143 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5146 // Cohorts
5147 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5148 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5149 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5152 // Manage filters
5153 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5154 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5155 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5158 // Restore.
5159 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5160 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5161 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5164 // Let plugins hook into category settings navigation.
5165 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5166 foreach ($pluginsfunction as $plugintype => $plugins) {
5167 foreach ($plugins as $pluginfunction) {
5168 $pluginfunction($categorynode, $catcontext);
5172 return $categorynode;
5176 * Determine whether the user is assuming another role
5178 * This function checks to see if the user is assuming another role by means of
5179 * role switching. In doing this we compare each RSW key (context path) against
5180 * the current context path. This ensures that we can provide the switching
5181 * options against both the course and any page shown under the course.
5183 * @return bool|int The role(int) if the user is in another role, false otherwise
5185 protected function in_alternative_role() {
5186 global $USER;
5187 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5188 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5189 return $USER->access['rsw'][$this->page->context->path];
5191 foreach ($USER->access['rsw'] as $key=>$role) {
5192 if (strpos($this->context->path,$key)===0) {
5193 return $role;
5197 return false;
5201 * This function loads all of the front page settings into the settings navigation.
5202 * This function is called when the user is on the front page, or $COURSE==$SITE
5203 * @param bool $forceopen (optional)
5204 * @return navigation_node
5206 protected function load_front_page_settings($forceopen = false) {
5207 global $SITE, $CFG;
5208 require_once($CFG->dirroot . '/course/lib.php');
5210 $course = clone($SITE);
5211 $coursecontext = context_course::instance($course->id); // Course context
5212 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5214 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5215 if ($forceopen) {
5216 $frontpage->force_open();
5218 $frontpage->id = 'frontpagesettings';
5220 if ($this->page->user_allowed_editing()) {
5222 // Add the turn on/off settings
5223 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5224 if ($this->page->user_is_editing()) {
5225 $url->param('edit', 'off');
5226 $editstring = get_string('turneditingoff');
5227 } else {
5228 $url->param('edit', 'on');
5229 $editstring = get_string('turneditingon');
5231 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5234 if ($adminoptions->update) {
5235 // Add the course settings link
5236 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5237 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5240 // add enrol nodes
5241 enrol_add_course_navigation($frontpage, $course);
5243 // Manage filters
5244 if ($adminoptions->filters) {
5245 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5246 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5249 // View course reports.
5250 if ($adminoptions->reports) {
5251 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5252 new pix_icon('i/stats', ''));
5253 $coursereports = core_component::get_plugin_list('coursereport');
5254 foreach ($coursereports as $report=>$dir) {
5255 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5256 if (file_exists($libfile)) {
5257 require_once($libfile);
5258 $reportfunction = $report.'_report_extend_navigation';
5259 if (function_exists($report.'_report_extend_navigation')) {
5260 $reportfunction($frontpagenav, $course, $coursecontext);
5265 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5266 foreach ($reports as $reportfunction) {
5267 $reportfunction($frontpagenav, $course, $coursecontext);
5271 // Backup this course
5272 if ($adminoptions->backup) {
5273 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5274 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5277 // Restore to this course
5278 if ($adminoptions->restore) {
5279 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5280 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5283 // Questions
5284 require_once($CFG->libdir . '/questionlib.php');
5285 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5287 // Manage files
5288 if ($adminoptions->files) {
5289 //hiden in new installs
5290 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5291 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5294 // Let plugins hook into frontpage navigation.
5295 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5296 foreach ($pluginsfunction as $plugintype => $plugins) {
5297 foreach ($plugins as $pluginfunction) {
5298 $pluginfunction($frontpage, $course, $coursecontext);
5302 return $frontpage;
5306 * This function gives local plugins an opportunity to modify the settings navigation.
5308 protected function load_local_plugin_settings() {
5310 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5311 $function($this, $this->context);
5316 * This function marks the cache as volatile so it is cleared during shutdown
5318 public function clear_cache() {
5319 $this->cache->volatile();
5323 * Checks to see if there are child nodes available in the specific user's preference node.
5324 * If so, then they have the appropriate permissions view this user's preferences.
5326 * @since Moodle 2.9.3
5327 * @param int $userid The user's ID.
5328 * @return bool True if child nodes exist to view, otherwise false.
5330 public function can_view_user_preferences($userid) {
5331 if (is_siteadmin()) {
5332 return true;
5334 // See if any nodes are present in the preferences section for this user.
5335 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5336 if ($preferencenode && $preferencenode->has_children()) {
5337 // Run through each child node.
5338 foreach ($preferencenode->children as $childnode) {
5339 // If the child node has children then this user has access to a link in the preferences page.
5340 if ($childnode->has_children()) {
5341 return true;
5345 // No links found for the user to access on the preferences page.
5346 return false;
5351 * Class used to populate site admin navigation for ajax.
5353 * @package core
5354 * @category navigation
5355 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5356 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5358 class settings_navigation_ajax extends settings_navigation {
5360 * Constructs the navigation for use in an AJAX request
5362 * @param moodle_page $page
5364 public function __construct(moodle_page &$page) {
5365 $this->page = $page;
5366 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5367 $this->children = new navigation_node_collection();
5368 $this->initialise();
5372 * Initialise the site admin navigation.
5374 * @return array An array of the expandable nodes
5376 public function initialise() {
5377 if ($this->initialised || during_initial_install()) {
5378 return false;
5380 $this->context = $this->page->context;
5381 $this->load_administration_settings();
5383 // Check if local plugins is adding node to site admin.
5384 $this->load_local_plugin_settings();
5386 $this->initialised = true;
5391 * Simple class used to output a navigation branch in XML
5393 * @package core
5394 * @category navigation
5395 * @copyright 2009 Sam Hemelryk
5396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5398 class navigation_json {
5399 /** @var array An array of different node types */
5400 protected $nodetype = array('node','branch');
5401 /** @var array An array of node keys and types */
5402 protected $expandable = array();
5404 * Turns a branch and all of its children into XML
5406 * @param navigation_node $branch
5407 * @return string XML string
5409 public function convert($branch) {
5410 $xml = $this->convert_child($branch);
5411 return $xml;
5414 * Set the expandable items in the array so that we have enough information
5415 * to attach AJAX events
5416 * @param array $expandable
5418 public function set_expandable($expandable) {
5419 foreach ($expandable as $node) {
5420 $this->expandable[$node['key'].':'.$node['type']] = $node;
5424 * Recusively converts a child node and its children to XML for output
5426 * @param navigation_node $child The child to convert
5427 * @param int $depth Pointlessly used to track the depth of the XML structure
5428 * @return string JSON
5430 protected function convert_child($child, $depth=1) {
5431 if (!$child->display) {
5432 return '';
5434 $attributes = array();
5435 $attributes['id'] = $child->id;
5436 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5437 $attributes['type'] = $child->type;
5438 $attributes['key'] = $child->key;
5439 $attributes['class'] = $child->get_css_type();
5440 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5442 if ($child->icon instanceof pix_icon) {
5443 $attributes['icon'] = array(
5444 'component' => $child->icon->component,
5445 'pix' => $child->icon->pix,
5447 foreach ($child->icon->attributes as $key=>$value) {
5448 if ($key == 'class') {
5449 $attributes['icon']['classes'] = explode(' ', $value);
5450 } else if (!array_key_exists($key, $attributes['icon'])) {
5451 $attributes['icon'][$key] = $value;
5455 } else if (!empty($child->icon)) {
5456 $attributes['icon'] = (string)$child->icon;
5459 if ($child->forcetitle || $child->title !== $child->text) {
5460 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5462 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5463 $attributes['expandable'] = $child->key;
5464 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5467 if (count($child->classes)>0) {
5468 $attributes['class'] .= ' '.join(' ',$child->classes);
5470 if (is_string($child->action)) {
5471 $attributes['link'] = $child->action;
5472 } else if ($child->action instanceof moodle_url) {
5473 $attributes['link'] = $child->action->out();
5474 } else if ($child->action instanceof action_link) {
5475 $attributes['link'] = $child->action->url->out();
5477 $attributes['hidden'] = ($child->hidden);
5478 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5479 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5481 if ($child->children->count() > 0) {
5482 $attributes['children'] = array();
5483 foreach ($child->children as $subchild) {
5484 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5488 if ($depth > 1) {
5489 return $attributes;
5490 } else {
5491 return json_encode($attributes);
5497 * The cache class used by global navigation and settings navigation.
5499 * It is basically an easy access point to session with a bit of smarts to make
5500 * sure that the information that is cached is valid still.
5502 * Example use:
5503 * <code php>
5504 * if (!$cache->viewdiscussion()) {
5505 * // Code to do stuff and produce cachable content
5506 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5508 * $content = $cache->viewdiscussion;
5509 * </code>
5511 * @package core
5512 * @category navigation
5513 * @copyright 2009 Sam Hemelryk
5514 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5516 class navigation_cache {
5517 /** @var int represents the time created */
5518 protected $creation;
5519 /** @var array An array of session keys */
5520 protected $session;
5522 * The string to use to segregate this particular cache. It can either be
5523 * unique to start a fresh cache or if you want to share a cache then make
5524 * it the string used in the original cache.
5525 * @var string
5527 protected $area;
5528 /** @var int a time that the information will time out */
5529 protected $timeout;
5530 /** @var stdClass The current context */
5531 protected $currentcontext;
5532 /** @var int cache time information */
5533 const CACHETIME = 0;
5534 /** @var int cache user id */
5535 const CACHEUSERID = 1;
5536 /** @var int cache value */
5537 const CACHEVALUE = 2;
5538 /** @var null|array An array of navigation cache areas to expire on shutdown */
5539 public static $volatilecaches;
5542 * Contructor for the cache. Requires two arguments
5544 * @param string $area The string to use to segregate this particular cache
5545 * it can either be unique to start a fresh cache or if you want
5546 * to share a cache then make it the string used in the original
5547 * cache
5548 * @param int $timeout The number of seconds to time the information out after
5550 public function __construct($area, $timeout=1800) {
5551 $this->creation = time();
5552 $this->area = $area;
5553 $this->timeout = time() - $timeout;
5554 if (rand(0,100) === 0) {
5555 $this->garbage_collection();
5560 * Used to set up the cache within the SESSION.
5562 * This is called for each access and ensure that we don't put anything into the session before
5563 * it is required.
5565 protected function ensure_session_cache_initialised() {
5566 global $SESSION;
5567 if (empty($this->session)) {
5568 if (!isset($SESSION->navcache)) {
5569 $SESSION->navcache = new stdClass;
5571 if (!isset($SESSION->navcache->{$this->area})) {
5572 $SESSION->navcache->{$this->area} = array();
5574 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5579 * Magic Method to retrieve something by simply calling using = cache->key
5581 * @param mixed $key The identifier for the information you want out again
5582 * @return void|mixed Either void or what ever was put in
5584 public function __get($key) {
5585 if (!$this->cached($key)) {
5586 return;
5588 $information = $this->session[$key][self::CACHEVALUE];
5589 return unserialize($information);
5593 * Magic method that simply uses {@link set();} to store something in the cache
5595 * @param string|int $key
5596 * @param mixed $information
5598 public function __set($key, $information) {
5599 $this->set($key, $information);
5603 * Sets some information against the cache (session) for later retrieval
5605 * @param string|int $key
5606 * @param mixed $information
5608 public function set($key, $information) {
5609 global $USER;
5610 $this->ensure_session_cache_initialised();
5611 $information = serialize($information);
5612 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5615 * Check the existence of the identifier in the cache
5617 * @param string|int $key
5618 * @return bool
5620 public function cached($key) {
5621 global $USER;
5622 $this->ensure_session_cache_initialised();
5623 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) {
5624 return false;
5626 return true;
5629 * Compare something to it's equivilant in the cache
5631 * @param string $key
5632 * @param mixed $value
5633 * @param bool $serialise Whether to serialise the value before comparison
5634 * this should only be set to false if the value is already
5635 * serialised
5636 * @return bool If the value is the same false if it is not set or doesn't match
5638 public function compare($key, $value, $serialise = true) {
5639 if ($this->cached($key)) {
5640 if ($serialise) {
5641 $value = serialize($value);
5643 if ($this->session[$key][self::CACHEVALUE] === $value) {
5644 return true;
5647 return false;
5650 * Wipes the entire cache, good to force regeneration
5652 public function clear() {
5653 global $SESSION;
5654 unset($SESSION->navcache);
5655 $this->session = null;
5658 * Checks all cache entries and removes any that have expired, good ole cleanup
5660 protected function garbage_collection() {
5661 if (empty($this->session)) {
5662 return true;
5664 foreach ($this->session as $key=>$cachedinfo) {
5665 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5666 unset($this->session[$key]);
5672 * Marks the cache as being volatile (likely to change)
5674 * Any caches marked as volatile will be destroyed at the on shutdown by
5675 * {@link navigation_node::destroy_volatile_caches()} which is registered
5676 * as a shutdown function if any caches are marked as volatile.
5678 * @param bool $setting True to destroy the cache false not too
5680 public function volatile($setting = true) {
5681 if (self::$volatilecaches===null) {
5682 self::$volatilecaches = array();
5683 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5686 if ($setting) {
5687 self::$volatilecaches[$this->area] = $this->area;
5688 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5689 unset(self::$volatilecaches[$this->area]);
5694 * Destroys all caches marked as volatile
5696 * This function is static and works in conjunction with the static volatilecaches
5697 * property of navigation cache.
5698 * Because this function is static it manually resets the cached areas back to an
5699 * empty array.
5701 public static function destroy_volatile_caches() {
5702 global $SESSION;
5703 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5704 foreach (self::$volatilecaches as $area) {
5705 $SESSION->navcache->{$area} = array();
5707 } else {
5708 $SESSION->navcache = new stdClass;