on-demand release 3.8dev+
[moodle.git] / lib / navigationlib.php
blobebc3d7b613ec85b5d2a8f73ff9fd90de4cf897a1
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since Moodle 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
34 /**
35 * This class is used to represent a node in a navigation tree
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
43 * @package core
44 * @category navigation
45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF = 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH = 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN = null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY = 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
77 /** @var int Setting node type, used only within settings nav 80 */
78 const TYPE_USER = 80;
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE = 'courseindexpage';
90 /** @var int Parameter to aid the coder in tracking [optional] */
91 public $id = null;
92 /** @var string|int The identifier for the node, used to retrieve the node */
93 public $key = null;
94 /** @var string The text to use for the node */
95 public $text = null;
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
99 public $title = null;
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
102 /** @var moodle_url|action_link|null An action for the node (link) */
103 public $action = null;
104 /** @var pix_icon The path to an icon to use for this node */
105 public $icon = null;
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self::TYPE_UNKNOWN;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self::NODETYPE_LEAF;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
114 /** @var array An array of CSS classes for the node */
115 public $classes = array();
116 /** @var navigation_node_collection An array of child nodes */
117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
120 /** @var bool If set to true the node will be dimmed */
121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
131 public $parent = null;
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
136 /** @var array */
137 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
138 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
139 90 => 'container');
140 /** @var moodle_url */
141 protected static $fullmeurl = null;
142 /** @var bool toogles auto matching of active node */
143 public static $autofindactive = true;
144 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
145 protected static $loadadmintree = false;
146 /** @var mixed If set to an int, that section will be included even if it has no activities */
147 public $includesectionnum = false;
148 /** @var bool does the node need to be loaded via ajax */
149 public $requiresajaxloading = false;
150 /** @var bool If set to true this node will be added to the "flat" navigation */
151 public $showinflatnavigation = false;
154 * Constructs a new navigation_node
156 * @param array|string $properties Either an array of properties or a string to use
157 * as the text for the node
159 public function __construct($properties) {
160 if (is_array($properties)) {
161 // Check the array for each property that we allow to set at construction.
162 // text - The main content for the node
163 // shorttext - A short text if required for the node
164 // icon - The icon to display for the node
165 // type - The type of the node
166 // key - The key to use to identify the node
167 // parent - A reference to the nodes parent
168 // action - The action to attribute to this node, usually a URL to link to
169 if (array_key_exists('text', $properties)) {
170 $this->text = $properties['text'];
172 if (array_key_exists('shorttext', $properties)) {
173 $this->shorttext = $properties['shorttext'];
175 if (!array_key_exists('icon', $properties)) {
176 $properties['icon'] = new pix_icon('i/navigationitem', '');
178 $this->icon = $properties['icon'];
179 if ($this->icon instanceof pix_icon) {
180 if (empty($this->icon->attributes['class'])) {
181 $this->icon->attributes['class'] = 'navicon';
182 } else {
183 $this->icon->attributes['class'] .= ' navicon';
186 if (array_key_exists('type', $properties)) {
187 $this->type = $properties['type'];
188 } else {
189 $this->type = self::TYPE_CUSTOM;
191 if (array_key_exists('key', $properties)) {
192 $this->key = $properties['key'];
194 // This needs to happen last because of the check_if_active call that occurs
195 if (array_key_exists('action', $properties)) {
196 $this->action = $properties['action'];
197 if (is_string($this->action)) {
198 $this->action = new moodle_url($this->action);
200 if (self::$autofindactive) {
201 $this->check_if_active();
204 if (array_key_exists('parent', $properties)) {
205 $this->set_parent($properties['parent']);
207 } else if (is_string($properties)) {
208 $this->text = $properties;
210 if ($this->text === null) {
211 throw new coding_exception('You must set the text for the node when you create it.');
213 // Instantiate a new navigation node collection for this nodes children
214 $this->children = new navigation_node_collection();
218 * Checks if this node is the active node.
220 * This is determined by comparing the action for the node against the
221 * defined URL for the page. A match will see this node marked as active.
223 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
224 * @return bool
226 public function check_if_active($strength=URL_MATCH_EXACT) {
227 global $FULLME, $PAGE;
228 // Set fullmeurl if it hasn't already been set
229 if (self::$fullmeurl == null) {
230 if ($PAGE->has_set_url()) {
231 self::override_active_url(new moodle_url($PAGE->url));
232 } else {
233 self::override_active_url(new moodle_url($FULLME));
237 // Compare the action of this node against the fullmeurl
238 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
239 $this->make_active();
240 return true;
242 return false;
246 * True if this nav node has siblings in the tree.
248 * @return bool
250 public function has_siblings() {
251 if (empty($this->parent) || empty($this->parent->children)) {
252 return false;
254 if ($this->parent->children instanceof navigation_node_collection) {
255 $count = $this->parent->children->count();
256 } else {
257 $count = count($this->parent->children);
259 return ($count > 1);
263 * Get a list of sibling navigation nodes at the same level as this one.
265 * @return bool|array of navigation_node
267 public function get_siblings() {
268 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
269 // the in-page links or the breadcrumb links.
270 $siblings = false;
272 if ($this->has_siblings()) {
273 $siblings = [];
274 foreach ($this->parent->children as $child) {
275 if ($child->display) {
276 $siblings[] = $child;
280 return $siblings;
284 * This sets the URL that the URL of new nodes get compared to when locating
285 * the active node.
287 * The active node is the node that matches the URL set here. By default this
288 * is either $PAGE->url or if that hasn't been set $FULLME.
290 * @param moodle_url $url The url to use for the fullmeurl.
291 * @param bool $loadadmintree use true if the URL point to administration tree
293 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
294 // Clone the URL, in case the calling script changes their URL later.
295 self::$fullmeurl = new moodle_url($url);
296 // True means we do not want AJAX loaded admin tree, required for all admin pages.
297 if ($loadadmintree) {
298 // Do not change back to false if already set.
299 self::$loadadmintree = true;
304 * Use when page is linked from the admin tree,
305 * if not used navigation could not find the page using current URL
306 * because the tree is not fully loaded.
308 public static function require_admin_tree() {
309 self::$loadadmintree = true;
313 * Creates a navigation node, ready to add it as a child using add_node
314 * function. (The created node needs to be added before you can use it.)
315 * @param string $text
316 * @param moodle_url|action_link $action
317 * @param int $type
318 * @param string $shorttext
319 * @param string|int $key
320 * @param pix_icon $icon
321 * @return navigation_node
323 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
324 $shorttext=null, $key=null, pix_icon $icon=null) {
325 // Properties array used when creating the new navigation node
326 $itemarray = array(
327 'text' => $text,
328 'type' => $type
330 // Set the action if one was provided
331 if ($action!==null) {
332 $itemarray['action'] = $action;
334 // Set the shorttext if one was provided
335 if ($shorttext!==null) {
336 $itemarray['shorttext'] = $shorttext;
338 // Set the icon if one was provided
339 if ($icon!==null) {
340 $itemarray['icon'] = $icon;
342 // Set the key
343 $itemarray['key'] = $key;
344 // Construct and return
345 return new navigation_node($itemarray);
349 * Adds a navigation node as a child of this node.
351 * @param string $text
352 * @param moodle_url|action_link $action
353 * @param int $type
354 * @param string $shorttext
355 * @param string|int $key
356 * @param pix_icon $icon
357 * @return navigation_node
359 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
360 // Create child node
361 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
363 // Add the child to end and return
364 return $this->add_node($childnode);
368 * Adds a navigation node as a child of this one, given a $node object
369 * created using the create function.
370 * @param navigation_node $childnode Node to add
371 * @param string $beforekey
372 * @return navigation_node The added node
374 public function add_node(navigation_node $childnode, $beforekey=null) {
375 // First convert the nodetype for this node to a branch as it will now have children
376 if ($this->nodetype !== self::NODETYPE_BRANCH) {
377 $this->nodetype = self::NODETYPE_BRANCH;
379 // Set the parent to this node
380 $childnode->set_parent($this);
382 // Default the key to the number of children if not provided
383 if ($childnode->key === null) {
384 $childnode->key = $this->children->count();
387 // Add the child using the navigation_node_collections add method
388 $node = $this->children->add($childnode, $beforekey);
390 // If added node is a category node or the user is logged in and it's a course
391 // then mark added node as a branch (makes it expandable by AJAX)
392 $type = $childnode->type;
393 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
394 ($type === self::TYPE_SITE_ADMIN)) {
395 $node->nodetype = self::NODETYPE_BRANCH;
397 // If this node is hidden mark it's children as hidden also
398 if ($this->hidden) {
399 $node->hidden = true;
401 // Return added node (reference returned by $this->children->add()
402 return $node;
406 * Return a list of all the keys of all the child nodes.
407 * @return array the keys.
409 public function get_children_key_list() {
410 return $this->children->get_key_list();
414 * Searches for a node of the given type with the given key.
416 * This searches this node plus all of its children, and their children....
417 * If you know the node you are looking for is a child of this node then please
418 * use the get method instead.
420 * @param int|string $key The key of the node we are looking for
421 * @param int $type One of navigation_node::TYPE_*
422 * @return navigation_node|false
424 public function find($key, $type) {
425 return $this->children->find($key, $type);
429 * Walk the tree building up a list of all the flat navigation nodes.
431 * @param flat_navigation $nodes List of the found flat navigation nodes.
432 * @param boolean $showdivider Show a divider before the first node.
433 * @param string $label A label for the collection of navigation links.
435 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
436 if ($this->showinflatnavigation) {
437 $indent = 0;
438 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
439 $indent = 1;
441 $flat = new flat_navigation_node($this, $indent);
442 $flat->set_showdivider($showdivider, $label);
443 $nodes->add($flat);
445 foreach ($this->children as $child) {
446 $child->build_flat_navigation_list($nodes, false);
451 * Get the child of this node that has the given key + (optional) type.
453 * If you are looking for a node and want to search all children + their children
454 * then please use the find method instead.
456 * @param int|string $key The key of the node we are looking for
457 * @param int $type One of navigation_node::TYPE_*
458 * @return navigation_node|false
460 public function get($key, $type=null) {
461 return $this->children->get($key, $type);
465 * Removes this node.
467 * @return bool
469 public function remove() {
470 return $this->parent->children->remove($this->key, $this->type);
474 * Checks if this node has or could have any children
476 * @return bool Returns true if it has children or could have (by AJAX expansion)
478 public function has_children() {
479 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
483 * Marks this node as active and forces it open.
485 * Important: If you are here because you need to mark a node active to get
486 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
487 * You can use it to specify a different URL to match the active navigation node on
488 * rather than having to locate and manually mark a node active.
490 public function make_active() {
491 $this->isactive = true;
492 $this->add_class('active_tree_node');
493 $this->force_open();
494 if ($this->parent !== null) {
495 $this->parent->make_inactive();
500 * Marks a node as inactive and recusised back to the base of the tree
501 * doing the same to all parents.
503 public function make_inactive() {
504 $this->isactive = false;
505 $this->remove_class('active_tree_node');
506 if ($this->parent !== null) {
507 $this->parent->make_inactive();
512 * Forces this node to be open and at the same time forces open all
513 * parents until the root node.
515 * Recursive.
517 public function force_open() {
518 $this->forceopen = true;
519 if ($this->parent !== null) {
520 $this->parent->force_open();
525 * Adds a CSS class to this node.
527 * @param string $class
528 * @return bool
530 public function add_class($class) {
531 if (!in_array($class, $this->classes)) {
532 $this->classes[] = $class;
534 return true;
538 * Removes a CSS class from this node.
540 * @param string $class
541 * @return bool True if the class was successfully removed.
543 public function remove_class($class) {
544 if (in_array($class, $this->classes)) {
545 $key = array_search($class,$this->classes);
546 if ($key!==false) {
547 unset($this->classes[$key]);
548 return true;
551 return false;
555 * Sets the title for this node and forces Moodle to utilise it.
556 * @param string $title
558 public function title($title) {
559 $this->title = $title;
560 $this->forcetitle = true;
564 * Resets the page specific information on this node if it is being unserialised.
566 public function __wakeup(){
567 $this->forceopen = false;
568 $this->isactive = false;
569 $this->remove_class('active_tree_node');
573 * Checks if this node or any of its children contain the active node.
575 * Recursive.
577 * @return bool
579 public function contains_active_node() {
580 if ($this->isactive) {
581 return true;
582 } else {
583 foreach ($this->children as $child) {
584 if ($child->isactive || $child->contains_active_node()) {
585 return true;
589 return false;
593 * To better balance the admin tree, we want to group all the short top branches together.
595 * This means < 8 nodes and no subtrees.
597 * @return bool
599 public function is_short_branch() {
600 $limit = 8;
601 if ($this->children->count() >= $limit) {
602 return false;
604 foreach ($this->children as $child) {
605 if ($child->has_children()) {
606 return false;
609 return true;
613 * Finds the active node.
615 * Searches this nodes children plus all of the children for the active node
616 * and returns it if found.
618 * Recursive.
620 * @return navigation_node|false
622 public function find_active_node() {
623 if ($this->isactive) {
624 return $this;
625 } else {
626 foreach ($this->children as &$child) {
627 $outcome = $child->find_active_node();
628 if ($outcome !== false) {
629 return $outcome;
633 return false;
637 * Searches all children for the best matching active node
638 * @return navigation_node|false
640 public function search_for_active_node() {
641 if ($this->check_if_active(URL_MATCH_BASE)) {
642 return $this;
643 } else {
644 foreach ($this->children as &$child) {
645 $outcome = $child->search_for_active_node();
646 if ($outcome !== false) {
647 return $outcome;
651 return false;
655 * Gets the content for this node.
657 * @param bool $shorttext If true shorttext is used rather than the normal text
658 * @return string
660 public function get_content($shorttext=false) {
661 if ($shorttext && $this->shorttext!==null) {
662 return format_string($this->shorttext);
663 } else {
664 return format_string($this->text);
669 * Gets the title to use for this node.
671 * @return string
673 public function get_title() {
674 if ($this->forcetitle || $this->action != null){
675 return $this->title;
676 } else {
677 return '';
682 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
684 * @return boolean
686 public function has_action() {
687 return !empty($this->action);
691 * Used to easily determine if this link in the breadcrumbs is hidden.
693 * @return boolean
695 public function is_hidden() {
696 return $this->hidden;
700 * Gets the CSS class to add to this node to describe its type
702 * @return string
704 public function get_css_type() {
705 if (array_key_exists($this->type, $this->namedtypes)) {
706 return 'type_'.$this->namedtypes[$this->type];
708 return 'type_unknown';
712 * Finds all nodes that are expandable by AJAX
714 * @param array $expandable An array by reference to populate with expandable nodes.
716 public function find_expandable(array &$expandable) {
717 foreach ($this->children as &$child) {
718 if ($child->display && $child->has_children() && $child->children->count() == 0) {
719 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
720 $this->add_class('canexpand');
721 $child->requiresajaxloading = true;
722 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
724 $child->find_expandable($expandable);
729 * Finds all nodes of a given type (recursive)
731 * @param int $type One of navigation_node::TYPE_*
732 * @return array
734 public function find_all_of_type($type) {
735 $nodes = $this->children->type($type);
736 foreach ($this->children as &$node) {
737 $childnodes = $node->find_all_of_type($type);
738 $nodes = array_merge($nodes, $childnodes);
740 return $nodes;
744 * Removes this node if it is empty
746 public function trim_if_empty() {
747 if ($this->children->count() == 0) {
748 $this->remove();
753 * Creates a tab representation of this nodes children that can be used
754 * with print_tabs to produce the tabs on a page.
756 * call_user_func_array('print_tabs', $node->get_tabs_array());
758 * @param array $inactive
759 * @param bool $return
760 * @return array Array (tabs, selected, inactive, activated, return)
762 public function get_tabs_array(array $inactive=array(), $return=false) {
763 $tabs = array();
764 $rows = array();
765 $selected = null;
766 $activated = array();
767 foreach ($this->children as $node) {
768 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
769 if ($node->contains_active_node()) {
770 if ($node->children->count() > 0) {
771 $activated[] = $node->key;
772 foreach ($node->children as $child) {
773 if ($child->contains_active_node()) {
774 $selected = $child->key;
776 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
778 } else {
779 $selected = $node->key;
783 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
787 * Sets the parent for this node and if this node is active ensures that the tree is properly
788 * adjusted as well.
790 * @param navigation_node $parent
792 public function set_parent(navigation_node $parent) {
793 // Set the parent (thats the easy part)
794 $this->parent = $parent;
795 // Check if this node is active (this is checked during construction)
796 if ($this->isactive) {
797 // Force all of the parent nodes open so you can see this node
798 $this->parent->force_open();
799 // Make all parents inactive so that its clear where we are.
800 $this->parent->make_inactive();
805 * Hides the node and any children it has.
807 * @since Moodle 2.5
808 * @param array $typestohide Optional. An array of node types that should be hidden.
809 * If null all nodes will be hidden.
810 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
811 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
813 public function hide(array $typestohide = null) {
814 if ($typestohide === null || in_array($this->type, $typestohide)) {
815 $this->display = false;
816 if ($this->has_children()) {
817 foreach ($this->children as $child) {
818 $child->hide($typestohide);
825 * Get the action url for this navigation node.
826 * Called from templates.
828 * @since Moodle 3.2
830 public function action() {
831 if ($this->action instanceof moodle_url) {
832 return $this->action;
833 } else if ($this->action instanceof action_link) {
834 return $this->action->url;
836 return $this->action;
840 * Add the menu item to handle locking and unlocking of a conext.
842 * @param \navigation_node $node Node to add
843 * @param \context $context The context to be locked
845 protected function add_context_locking_node(\navigation_node $node, \context $context) {
846 global $CFG;
847 // Manage context locking.
848 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
849 $parentcontext = $context->get_parent_context();
850 if (empty($parentcontext) || !$parentcontext->locked) {
851 if ($context->locked) {
852 $lockicon = 'i/unlock';
853 $lockstring = get_string('managecontextunlock', 'admin');
854 } else {
855 $lockicon = 'i/lock';
856 $lockstring = get_string('managecontextlock', 'admin');
858 $node->add(
859 $lockstring,
860 new moodle_url(
861 '/admin/lock.php',
863 'id' => $context->id,
866 self::TYPE_SETTING,
867 null,
868 'contextlocking',
869 new pix_icon($lockicon, '')
878 * Navigation node collection
880 * This class is responsible for managing a collection of navigation nodes.
881 * It is required because a node's unique identifier is a combination of both its
882 * key and its type.
884 * Originally an array was used with a string key that was a combination of the two
885 * however it was decided that a better solution would be to use a class that
886 * implements the standard IteratorAggregate interface.
888 * @package core
889 * @category navigation
890 * @copyright 2010 Sam Hemelryk
891 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
893 class navigation_node_collection implements IteratorAggregate, Countable {
895 * A multidimensional array to where the first key is the type and the second
896 * key is the nodes key.
897 * @var array
899 protected $collection = array();
901 * An array that contains references to nodes in the same order they were added.
902 * This is maintained as a progressive array.
903 * @var array
905 protected $orderedcollection = array();
907 * A reference to the last node that was added to the collection
908 * @var navigation_node
910 protected $last = null;
912 * The total number of items added to this array.
913 * @var int
915 protected $count = 0;
918 * Label for collection of nodes.
919 * @var string
921 protected $collectionlabel = '';
924 * Adds a navigation node to the collection
926 * @param navigation_node $node Node to add
927 * @param string $beforekey If specified, adds before a node with this key,
928 * otherwise adds at end
929 * @return navigation_node Added node
931 public function add(navigation_node $node, $beforekey=null) {
932 global $CFG;
933 $key = $node->key;
934 $type = $node->type;
936 // First check we have a 2nd dimension for this type
937 if (!array_key_exists($type, $this->orderedcollection)) {
938 $this->orderedcollection[$type] = array();
940 // Check for a collision and report if debugging is turned on
941 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
942 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
945 // Find the key to add before
946 $newindex = $this->count;
947 $last = true;
948 if ($beforekey !== null) {
949 foreach ($this->collection as $index => $othernode) {
950 if ($othernode->key === $beforekey) {
951 $newindex = $index;
952 $last = false;
953 break;
956 if ($newindex === $this->count) {
957 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
958 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
962 // Add the node to the appropriate place in the by-type structure (which
963 // is not ordered, despite the variable name)
964 $this->orderedcollection[$type][$key] = $node;
965 if (!$last) {
966 // Update existing references in the ordered collection (which is the
967 // one that isn't called 'ordered') to shuffle them along if required
968 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
969 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
972 // Add a reference to the node to the progressive collection.
973 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
974 // Update the last property to a reference to this new node.
975 $this->last = $this->orderedcollection[$type][$key];
977 // Reorder the array by index if needed
978 if (!$last) {
979 ksort($this->collection);
981 $this->count++;
982 // Return the reference to the now added node
983 return $node;
987 * Return a list of all the keys of all the nodes.
988 * @return array the keys.
990 public function get_key_list() {
991 $keys = array();
992 foreach ($this->collection as $node) {
993 $keys[] = $node->key;
995 return $keys;
999 * Set a label for this collection.
1001 * @param string $label
1003 public function set_collectionlabel($label) {
1004 $this->collectionlabel = $label;
1008 * Return a label for this collection.
1010 * @return string
1012 public function get_collectionlabel() {
1013 return $this->collectionlabel;
1017 * Fetches a node from this collection.
1019 * @param string|int $key The key of the node we want to find.
1020 * @param int $type One of navigation_node::TYPE_*.
1021 * @return navigation_node|null
1023 public function get($key, $type=null) {
1024 if ($type !== null) {
1025 // If the type is known then we can simply check and fetch
1026 if (!empty($this->orderedcollection[$type][$key])) {
1027 return $this->orderedcollection[$type][$key];
1029 } else {
1030 // Because we don't know the type we look in the progressive array
1031 foreach ($this->collection as $node) {
1032 if ($node->key === $key) {
1033 return $node;
1037 return false;
1041 * Searches for a node with matching key and type.
1043 * This function searches both the nodes in this collection and all of
1044 * the nodes in each collection belonging to the nodes in this collection.
1046 * Recursive.
1048 * @param string|int $key The key of the node we want to find.
1049 * @param int $type One of navigation_node::TYPE_*.
1050 * @return navigation_node|null
1052 public function find($key, $type=null) {
1053 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1054 return $this->orderedcollection[$type][$key];
1055 } else {
1056 $nodes = $this->getIterator();
1057 // Search immediate children first
1058 foreach ($nodes as &$node) {
1059 if ($node->key === $key && ($type === null || $type === $node->type)) {
1060 return $node;
1063 // Now search each childs children
1064 foreach ($nodes as &$node) {
1065 $result = $node->children->find($key, $type);
1066 if ($result !== false) {
1067 return $result;
1071 return false;
1075 * Fetches the last node that was added to this collection
1077 * @return navigation_node
1079 public function last() {
1080 return $this->last;
1084 * Fetches all nodes of a given type from this collection
1086 * @param string|int $type node type being searched for.
1087 * @return array ordered collection
1089 public function type($type) {
1090 if (!array_key_exists($type, $this->orderedcollection)) {
1091 $this->orderedcollection[$type] = array();
1093 return $this->orderedcollection[$type];
1096 * Removes the node with the given key and type from the collection
1098 * @param string|int $key The key of the node we want to find.
1099 * @param int $type
1100 * @return bool
1102 public function remove($key, $type=null) {
1103 $child = $this->get($key, $type);
1104 if ($child !== false) {
1105 foreach ($this->collection as $colkey => $node) {
1106 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1107 unset($this->collection[$colkey]);
1108 $this->collection = array_values($this->collection);
1109 break;
1112 unset($this->orderedcollection[$child->type][$child->key]);
1113 $this->count--;
1114 return true;
1116 return false;
1120 * Gets the number of nodes in this collection
1122 * This option uses an internal count rather than counting the actual options to avoid
1123 * a performance hit through the count function.
1125 * @return int
1127 public function count() {
1128 return $this->count;
1131 * Gets an array iterator for the collection.
1133 * This is required by the IteratorAggregator interface and is used by routines
1134 * such as the foreach loop.
1136 * @return ArrayIterator
1138 public function getIterator() {
1139 return new ArrayIterator($this->collection);
1144 * The global navigation class used for... the global navigation
1146 * This class is used by PAGE to store the global navigation for the site
1147 * and is then used by the settings nav and navbar to save on processing and DB calls
1149 * See
1150 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1151 * {@link lib/ajax/getnavbranch.php} Called by ajax
1153 * @package core
1154 * @category navigation
1155 * @copyright 2009 Sam Hemelryk
1156 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1158 class global_navigation extends navigation_node {
1159 /** @var moodle_page The Moodle page this navigation object belongs to. */
1160 protected $page;
1161 /** @var bool switch to let us know if the navigation object is initialised*/
1162 protected $initialised = false;
1163 /** @var array An array of course information */
1164 protected $mycourses = array();
1165 /** @var navigation_node[] An array for containing root navigation nodes */
1166 protected $rootnodes = array();
1167 /** @var bool A switch for whether to show empty sections in the navigation */
1168 protected $showemptysections = true;
1169 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1170 protected $showcategories = null;
1171 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1172 protected $showmycategories = null;
1173 /** @var array An array of stdClasses for users that the navigation is extended for */
1174 protected $extendforuser = array();
1175 /** @var navigation_cache */
1176 protected $cache;
1177 /** @var array An array of course ids that are present in the navigation */
1178 protected $addedcourses = array();
1179 /** @var bool */
1180 protected $allcategoriesloaded = false;
1181 /** @var array An array of category ids that are included in the navigation */
1182 protected $addedcategories = array();
1183 /** @var int expansion limit */
1184 protected $expansionlimit = 0;
1185 /** @var int userid to allow parent to see child's profile page navigation */
1186 protected $useridtouseforparentchecks = 0;
1187 /** @var cache_session A cache that stores information on expanded courses */
1188 protected $cacheexpandcourse = null;
1190 /** Used when loading categories to load all top level categories [parent = 0] **/
1191 const LOAD_ROOT_CATEGORIES = 0;
1192 /** Used when loading categories to load all categories **/
1193 const LOAD_ALL_CATEGORIES = -1;
1196 * Constructs a new global navigation
1198 * @param moodle_page $page The page this navigation object belongs to
1200 public function __construct(moodle_page $page) {
1201 global $CFG, $SITE, $USER;
1203 if (during_initial_install()) {
1204 return;
1207 if (get_home_page() == HOMEPAGE_SITE) {
1208 // We are using the site home for the root element
1209 $properties = array(
1210 'key' => 'home',
1211 'type' => navigation_node::TYPE_SYSTEM,
1212 'text' => get_string('home'),
1213 'action' => new moodle_url('/'),
1214 'icon' => new pix_icon('i/home', '')
1216 } else {
1217 // We are using the users my moodle for the root element
1218 $properties = array(
1219 'key' => 'myhome',
1220 'type' => navigation_node::TYPE_SYSTEM,
1221 'text' => get_string('myhome'),
1222 'action' => new moodle_url('/my/'),
1223 'icon' => new pix_icon('i/dashboard', '')
1227 // Use the parents constructor.... good good reuse
1228 parent::__construct($properties);
1229 $this->showinflatnavigation = true;
1231 // Initalise and set defaults
1232 $this->page = $page;
1233 $this->forceopen = true;
1234 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1238 * Mutator to set userid to allow parent to see child's profile
1239 * page navigation. See MDL-25805 for initial issue. Linked to it
1240 * is an issue explaining why this is a REALLY UGLY HACK thats not
1241 * for you to use!
1243 * @param int $userid userid of profile page that parent wants to navigate around.
1245 public function set_userid_for_parent_checks($userid) {
1246 $this->useridtouseforparentchecks = $userid;
1251 * Initialises the navigation object.
1253 * This causes the navigation object to look at the current state of the page
1254 * that it is associated with and then load the appropriate content.
1256 * This should only occur the first time that the navigation structure is utilised
1257 * which will normally be either when the navbar is called to be displayed or
1258 * when a block makes use of it.
1260 * @return bool
1262 public function initialise() {
1263 global $CFG, $SITE, $USER;
1264 // Check if it has already been initialised
1265 if ($this->initialised || during_initial_install()) {
1266 return true;
1268 $this->initialised = true;
1270 // Set up the five base root nodes. These are nodes where we will put our
1271 // content and are as follows:
1272 // site: Navigation for the front page.
1273 // myprofile: User profile information goes here.
1274 // currentcourse: The course being currently viewed.
1275 // mycourses: The users courses get added here.
1276 // courses: Additional courses are added here.
1277 // users: Other users information loaded here.
1278 $this->rootnodes = array();
1279 if (get_home_page() == HOMEPAGE_SITE) {
1280 // The home element should be my moodle because the root element is the site
1281 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1282 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1283 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', ''));
1284 $this->rootnodes['home']->showinflatnavigation = true;
1286 } else {
1287 // The home element should be the site because the root node is my moodle
1288 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1289 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
1290 $this->rootnodes['home']->showinflatnavigation = true;
1291 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1292 // We need to stop automatic redirection
1293 $this->rootnodes['home']->action->param('redirect', '0');
1296 $this->rootnodes['site'] = $this->add_course($SITE);
1297 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1298 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1299 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
1300 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1301 if (!core_course_category::user_top()) {
1302 $this->rootnodes['courses']->hide();
1304 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1306 // We always load the frontpage course to ensure it is available without
1307 // JavaScript enabled.
1308 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1309 $this->load_course_sections($SITE, $this->rootnodes['site']);
1311 $course = $this->page->course;
1312 $this->load_courses_enrolled();
1314 // $issite gets set to true if the current pages course is the sites frontpage course
1315 $issite = ($this->page->course->id == $SITE->id);
1317 // Determine if the user is enrolled in any course.
1318 $enrolledinanycourse = enrol_user_sees_own_courses();
1320 $this->rootnodes['currentcourse']->mainnavonly = true;
1321 if ($enrolledinanycourse) {
1322 $this->rootnodes['mycourses']->isexpandable = true;
1323 $this->rootnodes['mycourses']->showinflatnavigation = true;
1324 if ($CFG->navshowallcourses) {
1325 // When we show all courses we need to show both the my courses and the regular courses branch.
1326 $this->rootnodes['courses']->isexpandable = true;
1328 } else {
1329 $this->rootnodes['courses']->isexpandable = true;
1331 $this->rootnodes['mycourses']->forceopen = true;
1333 $canviewcourseprofile = true;
1335 // Next load context specific content into the navigation
1336 switch ($this->page->context->contextlevel) {
1337 case CONTEXT_SYSTEM :
1338 // Nothing left to do here I feel.
1339 break;
1340 case CONTEXT_COURSECAT :
1341 // This is essential, we must load categories.
1342 $this->load_all_categories($this->page->context->instanceid, true);
1343 break;
1344 case CONTEXT_BLOCK :
1345 case CONTEXT_COURSE :
1346 if ($issite) {
1347 // Nothing left to do here.
1348 break;
1351 // Load the course associated with the current page into the navigation.
1352 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1353 // If the course wasn't added then don't try going any further.
1354 if (!$coursenode) {
1355 $canviewcourseprofile = false;
1356 break;
1359 // If the user is not enrolled then we only want to show the
1360 // course node and not populate it.
1362 // Not enrolled, can't view, and hasn't switched roles
1363 if (!can_access_course($course, null, '', true)) {
1364 if ($coursenode->isexpandable === true) {
1365 // Obviously the situation has changed, update the cache and adjust the node.
1366 // This occurs if the user access to a course has been revoked (one way or another) after
1367 // initially logging in for this session.
1368 $this->get_expand_course_cache()->set($course->id, 1);
1369 $coursenode->isexpandable = true;
1370 $coursenode->nodetype = self::NODETYPE_BRANCH;
1372 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1373 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1374 if (!$this->current_user_is_parent_role()) {
1375 $coursenode->make_active();
1376 $canviewcourseprofile = false;
1377 break;
1379 } else if ($coursenode->isexpandable === false) {
1380 // Obviously the situation has changed, update the cache and adjust the node.
1381 // This occurs if the user has been granted access to a course (one way or another) after initially
1382 // logging in for this session.
1383 $this->get_expand_course_cache()->set($course->id, 1);
1384 $coursenode->isexpandable = true;
1385 $coursenode->nodetype = self::NODETYPE_BRANCH;
1388 // Add the essentials such as reports etc...
1389 $this->add_course_essentials($coursenode, $course);
1390 // Extend course navigation with it's sections/activities
1391 $this->load_course_sections($course, $coursenode);
1392 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1393 $coursenode->make_active();
1396 break;
1397 case CONTEXT_MODULE :
1398 if ($issite) {
1399 // If this is the site course then most information will have
1400 // already been loaded.
1401 // However we need to check if there is more content that can
1402 // yet be loaded for the specific module instance.
1403 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1404 if ($activitynode) {
1405 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1407 break;
1410 $course = $this->page->course;
1411 $cm = $this->page->cm;
1413 // Load the course associated with the page into the navigation
1414 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1416 // If the course wasn't added then don't try going any further.
1417 if (!$coursenode) {
1418 $canviewcourseprofile = false;
1419 break;
1422 // If the user is not enrolled then we only want to show the
1423 // course node and not populate it.
1424 if (!can_access_course($course, null, '', true)) {
1425 $coursenode->make_active();
1426 $canviewcourseprofile = false;
1427 break;
1430 $this->add_course_essentials($coursenode, $course);
1432 // Load the course sections into the page
1433 $this->load_course_sections($course, $coursenode, null, $cm);
1434 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1435 if (!empty($activity)) {
1436 // Finally load the cm specific navigaton information
1437 $this->load_activity($cm, $course, $activity);
1438 // Check if we have an active ndoe
1439 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1440 // And make the activity node active.
1441 $activity->make_active();
1444 break;
1445 case CONTEXT_USER :
1446 if ($issite) {
1447 // The users profile information etc is already loaded
1448 // for the front page.
1449 break;
1451 $course = $this->page->course;
1452 // Load the course associated with the user into the navigation
1453 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1455 // If the course wasn't added then don't try going any further.
1456 if (!$coursenode) {
1457 $canviewcourseprofile = false;
1458 break;
1461 // If the user is not enrolled then we only want to show the
1462 // course node and not populate it.
1463 if (!can_access_course($course, null, '', true)) {
1464 $coursenode->make_active();
1465 $canviewcourseprofile = false;
1466 break;
1468 $this->add_course_essentials($coursenode, $course);
1469 $this->load_course_sections($course, $coursenode);
1470 break;
1473 // Load for the current user
1474 $this->load_for_user();
1475 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1476 $this->load_for_user(null, true);
1478 // Load each extending user into the navigation.
1479 foreach ($this->extendforuser as $user) {
1480 if ($user->id != $USER->id) {
1481 $this->load_for_user($user);
1485 // Give the local plugins a chance to include some navigation if they want.
1486 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1487 $function($this);
1490 // Remove any empty root nodes
1491 foreach ($this->rootnodes as $node) {
1492 // Dont remove the home node
1493 /** @var navigation_node $node */
1494 if (!in_array($node->key, ['home', 'myhome']) && !$node->has_children() && !$node->isactive) {
1495 $node->remove();
1499 if (!$this->contains_active_node()) {
1500 $this->search_for_active_node();
1503 // If the user is not logged in modify the navigation structure as detailed
1504 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1505 if (!isloggedin()) {
1506 $activities = clone($this->rootnodes['site']->children);
1507 $this->rootnodes['site']->remove();
1508 $children = clone($this->children);
1509 $this->children = new navigation_node_collection();
1510 foreach ($activities as $child) {
1511 $this->children->add($child);
1513 foreach ($children as $child) {
1514 $this->children->add($child);
1517 return true;
1521 * Returns true if the current user is a parent of the user being currently viewed.
1523 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1524 * other user being viewed this function returns false.
1525 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1527 * @since Moodle 2.4
1528 * @return bool
1530 protected function current_user_is_parent_role() {
1531 global $USER, $DB;
1532 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1533 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1534 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1535 return false;
1537 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1538 return true;
1541 return false;
1545 * Returns true if courses should be shown within categories on the navigation.
1547 * @param bool $ismycourse Set to true if you are calculating this for a course.
1548 * @return bool
1550 protected function show_categories($ismycourse = false) {
1551 global $CFG, $DB;
1552 if ($ismycourse) {
1553 return $this->show_my_categories();
1555 if ($this->showcategories === null) {
1556 $show = false;
1557 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1558 $show = true;
1559 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1560 $show = true;
1562 $this->showcategories = $show;
1564 return $this->showcategories;
1568 * Returns true if we should show categories in the My Courses branch.
1569 * @return bool
1571 protected function show_my_categories() {
1572 global $CFG;
1573 if ($this->showmycategories === null) {
1574 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site();
1576 return $this->showmycategories;
1580 * Loads the courses in Moodle into the navigation.
1582 * @global moodle_database $DB
1583 * @param string|array $categoryids An array containing categories to load courses
1584 * for, OR null to load courses for all categories.
1585 * @return array An array of navigation_nodes one for each course
1587 protected function load_all_courses($categoryids = null) {
1588 global $CFG, $DB, $SITE;
1590 // Work out the limit of courses.
1591 $limit = 20;
1592 if (!empty($CFG->navcourselimit)) {
1593 $limit = $CFG->navcourselimit;
1596 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1598 // If we are going to show all courses AND we are showing categories then
1599 // to save us repeated DB calls load all of the categories now
1600 if ($this->show_categories()) {
1601 $this->load_all_categories($toload);
1604 // Will be the return of our efforts
1605 $coursenodes = array();
1607 // Check if we need to show categories.
1608 if ($this->show_categories()) {
1609 // Hmmm we need to show categories... this is going to be painful.
1610 // We now need to fetch up to $limit courses for each category to
1611 // be displayed.
1612 if ($categoryids !== null) {
1613 if (!is_array($categoryids)) {
1614 $categoryids = array($categoryids);
1616 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1617 $categorywhere = 'WHERE cc.id '.$categorywhere;
1618 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1619 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1620 $categoryparams = array();
1621 } else {
1622 $categorywhere = '';
1623 $categoryparams = array();
1626 // First up we are going to get the categories that we are going to
1627 // need so that we can determine how best to load the courses from them.
1628 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1629 FROM {course_categories} cc
1630 LEFT JOIN {course} c ON c.category = cc.id
1631 {$categorywhere}
1632 GROUP BY cc.id";
1633 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1634 $fullfetch = array();
1635 $partfetch = array();
1636 foreach ($categories as $category) {
1637 if (!$this->can_add_more_courses_to_category($category->id)) {
1638 continue;
1640 if ($category->coursecount > $limit * 5) {
1641 $partfetch[] = $category->id;
1642 } else if ($category->coursecount > 0) {
1643 $fullfetch[] = $category->id;
1646 $categories->close();
1648 if (count($fullfetch)) {
1649 // First up fetch all of the courses in categories where we know that we are going to
1650 // need the majority of courses.
1651 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1652 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1653 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1654 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1655 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1656 FROM {course} c
1657 $ccjoin
1658 WHERE c.category {$categoryids}
1659 ORDER BY c.sortorder ASC";
1660 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1661 foreach ($coursesrs as $course) {
1662 if ($course->id == $SITE->id) {
1663 // This should not be necessary, frontpage is not in any category.
1664 continue;
1666 if (array_key_exists($course->id, $this->addedcourses)) {
1667 // It is probably better to not include the already loaded courses
1668 // directly in SQL because inequalities may confuse query optimisers
1669 // and may interfere with query caching.
1670 continue;
1672 if (!$this->can_add_more_courses_to_category($course->category)) {
1673 continue;
1675 context_helper::preload_from_record($course);
1676 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1677 continue;
1679 $coursenodes[$course->id] = $this->add_course($course);
1681 $coursesrs->close();
1684 if (count($partfetch)) {
1685 // Next we will work our way through the categories where we will likely only need a small
1686 // proportion of the courses.
1687 foreach ($partfetch as $categoryid) {
1688 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1689 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1690 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1691 FROM {course} c
1692 $ccjoin
1693 WHERE c.category = :categoryid
1694 ORDER BY c.sortorder ASC";
1695 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1696 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1697 foreach ($coursesrs as $course) {
1698 if ($course->id == $SITE->id) {
1699 // This should not be necessary, frontpage is not in any category.
1700 continue;
1702 if (array_key_exists($course->id, $this->addedcourses)) {
1703 // It is probably better to not include the already loaded courses
1704 // directly in SQL because inequalities may confuse query optimisers
1705 // and may interfere with query caching.
1706 // This also helps to respect expected $limit on repeated executions.
1707 continue;
1709 if (!$this->can_add_more_courses_to_category($course->category)) {
1710 break;
1712 context_helper::preload_from_record($course);
1713 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1714 continue;
1716 $coursenodes[$course->id] = $this->add_course($course);
1718 $coursesrs->close();
1721 } else {
1722 // Prepare the SQL to load the courses and their contexts
1723 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1724 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1725 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1726 $courseparams['contextlevel'] = CONTEXT_COURSE;
1727 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1728 FROM {course} c
1729 $ccjoin
1730 WHERE c.id {$courseids}
1731 ORDER BY c.sortorder ASC";
1732 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1733 foreach ($coursesrs as $course) {
1734 if ($course->id == $SITE->id) {
1735 // frotpage is not wanted here
1736 continue;
1738 if ($this->page->course && ($this->page->course->id == $course->id)) {
1739 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1740 continue;
1742 context_helper::preload_from_record($course);
1743 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1744 continue;
1746 $coursenodes[$course->id] = $this->add_course($course);
1747 if (count($coursenodes) >= $limit) {
1748 break;
1751 $coursesrs->close();
1754 return $coursenodes;
1758 * Returns true if more courses can be added to the provided category.
1760 * @param int|navigation_node|stdClass $category
1761 * @return bool
1763 protected function can_add_more_courses_to_category($category) {
1764 global $CFG;
1765 $limit = 20;
1766 if (!empty($CFG->navcourselimit)) {
1767 $limit = (int)$CFG->navcourselimit;
1769 if (is_numeric($category)) {
1770 if (!array_key_exists($category, $this->addedcategories)) {
1771 return true;
1773 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1774 } else if ($category instanceof navigation_node) {
1775 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1776 return false;
1778 $coursecount = count($category->children->type(self::TYPE_COURSE));
1779 } else if (is_object($category) && property_exists($category,'id')) {
1780 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1782 return ($coursecount <= $limit);
1786 * Loads all categories (top level or if an id is specified for that category)
1788 * @param int $categoryid The category id to load or null/0 to load all base level categories
1789 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1790 * as the requested category and any parent categories.
1791 * @return navigation_node|void returns a navigation node if a category has been loaded.
1793 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1794 global $CFG, $DB;
1796 // Check if this category has already been loaded
1797 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1798 return true;
1801 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1802 $sqlselect = "SELECT cc.*, $catcontextsql
1803 FROM {course_categories} cc
1804 JOIN {context} ctx ON cc.id = ctx.instanceid";
1805 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1806 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1807 $params = array();
1809 $categoriestoload = array();
1810 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1811 // We are going to load all categories regardless... prepare to fire
1812 // on the database server!
1813 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1814 // We are going to load all of the first level categories (categories without parents)
1815 $sqlwhere .= " AND cc.parent = 0";
1816 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1817 // The category itself has been loaded already so we just need to ensure its subcategories
1818 // have been loaded
1819 $addedcategories = $this->addedcategories;
1820 unset($addedcategories[$categoryid]);
1821 if (count($addedcategories) > 0) {
1822 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1823 if ($showbasecategories) {
1824 // We need to include categories with parent = 0 as well
1825 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1826 } else {
1827 // All we need is categories that match the parent
1828 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1831 $params['categoryid'] = $categoryid;
1832 } else {
1833 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1834 // and load this category plus all its parents and subcategories
1835 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1836 $categoriestoload = explode('/', trim($category->path, '/'));
1837 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1838 // We are going to use select twice so double the params
1839 $params = array_merge($params, $params);
1840 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1841 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1844 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1845 $categories = array();
1846 foreach ($categoriesrs as $category) {
1847 // Preload the context.. we'll need it when adding the category in order
1848 // to format the category name.
1849 context_helper::preload_from_record($category);
1850 if (array_key_exists($category->id, $this->addedcategories)) {
1851 // Do nothing, its already been added.
1852 } else if ($category->parent == '0') {
1853 // This is a root category lets add it immediately
1854 $this->add_category($category, $this->rootnodes['courses']);
1855 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1856 // This categories parent has already been added we can add this immediately
1857 $this->add_category($category, $this->addedcategories[$category->parent]);
1858 } else {
1859 $categories[] = $category;
1862 $categoriesrs->close();
1864 // Now we have an array of categories we need to add them to the navigation.
1865 while (!empty($categories)) {
1866 $category = reset($categories);
1867 if (array_key_exists($category->id, $this->addedcategories)) {
1868 // Do nothing
1869 } else if ($category->parent == '0') {
1870 $this->add_category($category, $this->rootnodes['courses']);
1871 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1872 $this->add_category($category, $this->addedcategories[$category->parent]);
1873 } else {
1874 // This category isn't in the navigation and niether is it's parent (yet).
1875 // We need to go through the category path and add all of its components in order.
1876 $path = explode('/', trim($category->path, '/'));
1877 foreach ($path as $catid) {
1878 if (!array_key_exists($catid, $this->addedcategories)) {
1879 // This category isn't in the navigation yet so add it.
1880 $subcategory = $categories[$catid];
1881 if ($subcategory->parent == '0') {
1882 // Yay we have a root category - this likely means we will now be able
1883 // to add categories without problems.
1884 $this->add_category($subcategory, $this->rootnodes['courses']);
1885 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1886 // The parent is in the category (as we'd expect) so add it now.
1887 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1888 // Remove the category from the categories array.
1889 unset($categories[$catid]);
1890 } else {
1891 // We should never ever arrive here - if we have then there is a bigger
1892 // problem at hand.
1893 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1898 // Remove the category from the categories array now that we know it has been added.
1899 unset($categories[$category->id]);
1901 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1902 $this->allcategoriesloaded = true;
1904 // Check if there are any categories to load.
1905 if (count($categoriestoload) > 0) {
1906 $readytoloadcourses = array();
1907 foreach ($categoriestoload as $category) {
1908 if ($this->can_add_more_courses_to_category($category)) {
1909 $readytoloadcourses[] = $category;
1912 if (count($readytoloadcourses)) {
1913 $this->load_all_courses($readytoloadcourses);
1917 // Look for all categories which have been loaded
1918 if (!empty($this->addedcategories)) {
1919 $categoryids = array();
1920 foreach ($this->addedcategories as $category) {
1921 if ($this->can_add_more_courses_to_category($category)) {
1922 $categoryids[] = $category->key;
1925 if ($categoryids) {
1926 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1927 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1928 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1929 FROM {course_categories} cc
1930 JOIN {course} c ON c.category = cc.id
1931 WHERE cc.id {$categoriessql}
1932 GROUP BY cc.id
1933 HAVING COUNT(c.id) > :limit";
1934 $excessivecategories = $DB->get_records_sql($sql, $params);
1935 foreach ($categories as &$category) {
1936 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1937 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1938 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1946 * Adds a structured category to the navigation in the correct order/place
1948 * @param stdClass $category category to be added in navigation.
1949 * @param navigation_node $parent parent navigation node
1950 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1951 * @return void.
1953 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1954 if (array_key_exists($category->id, $this->addedcategories)) {
1955 return;
1957 $canview = core_course_category::can_view_category($category);
1958 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null;
1959 $context = context_coursecat::instance($category->id);
1960 $categoryname = $canview ? format_string($category->name, true, array('context' => $context)) :
1961 get_string('categoryhidden');
1962 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1963 if (!$canview) {
1964 // User does not have required capabilities to view category.
1965 $categorynode->display = false;
1966 } else if (!$category->visible) {
1967 // Category is hidden but user has capability to view hidden categories.
1968 $categorynode->hidden = true;
1970 $this->addedcategories[$category->id] = $categorynode;
1974 * Loads the given course into the navigation
1976 * @param stdClass $course
1977 * @return navigation_node
1979 protected function load_course(stdClass $course) {
1980 global $SITE;
1981 if ($course->id == $SITE->id) {
1982 // This is always loaded during initialisation
1983 return $this->rootnodes['site'];
1984 } else if (array_key_exists($course->id, $this->addedcourses)) {
1985 // The course has already been loaded so return a reference
1986 return $this->addedcourses[$course->id];
1987 } else {
1988 // Add the course
1989 return $this->add_course($course);
1994 * Loads all of the courses section into the navigation.
1996 * This function calls method from current course format, see
1997 * {@link format_base::extend_course_navigation()}
1998 * If course module ($cm) is specified but course format failed to create the node,
1999 * the activity node is created anyway.
2001 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
2003 * @param stdClass $course Database record for the course
2004 * @param navigation_node $coursenode The course node within the navigation
2005 * @param null|int $sectionnum If specified load the contents of section with this relative number
2006 * @param null|cm_info $cm If specified make sure that activity node is created (either
2007 * in containg section or by calling load_stealth_activity() )
2009 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2010 global $CFG, $SITE;
2011 require_once($CFG->dirroot.'/course/lib.php');
2012 if (isset($cm->sectionnum)) {
2013 $sectionnum = $cm->sectionnum;
2015 if ($sectionnum !== null) {
2016 $this->includesectionnum = $sectionnum;
2018 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2019 if (isset($cm->id)) {
2020 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2021 if (empty($activity)) {
2022 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2028 * Generates an array of sections and an array of activities for the given course.
2030 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2032 * @param stdClass $course
2033 * @return array Array($sections, $activities)
2035 protected function generate_sections_and_activities(stdClass $course) {
2036 global $CFG;
2037 require_once($CFG->dirroot.'/course/lib.php');
2039 $modinfo = get_fast_modinfo($course);
2040 $sections = $modinfo->get_section_info_all();
2042 // For course formats using 'numsections' trim the sections list
2043 $courseformatoptions = course_get_format($course)->get_format_options();
2044 if (isset($courseformatoptions['numsections'])) {
2045 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
2048 $activities = array();
2050 foreach ($sections as $key => $section) {
2051 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2052 $sections[$key] = clone($section);
2053 unset($sections[$key]->summary);
2054 $sections[$key]->hasactivites = false;
2055 if (!array_key_exists($section->section, $modinfo->sections)) {
2056 continue;
2058 foreach ($modinfo->sections[$section->section] as $cmid) {
2059 $cm = $modinfo->cms[$cmid];
2060 $activity = new stdClass;
2061 $activity->id = $cm->id;
2062 $activity->course = $course->id;
2063 $activity->section = $section->section;
2064 $activity->name = $cm->name;
2065 $activity->icon = $cm->icon;
2066 $activity->iconcomponent = $cm->iconcomponent;
2067 $activity->hidden = (!$cm->visible);
2068 $activity->modname = $cm->modname;
2069 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2070 $activity->onclick = $cm->onclick;
2071 $url = $cm->url;
2072 if (!$url) {
2073 $activity->url = null;
2074 $activity->display = false;
2075 } else {
2076 $activity->url = $url->out();
2077 $activity->display = $cm->is_visible_on_course_page() ? true : false;
2078 if (self::module_extends_navigation($cm->modname)) {
2079 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2082 $activities[$cmid] = $activity;
2083 if ($activity->display) {
2084 $sections[$key]->hasactivites = true;
2089 return array($sections, $activities);
2093 * Generically loads the course sections into the course's navigation.
2095 * @param stdClass $course
2096 * @param navigation_node $coursenode
2097 * @return array An array of course section nodes
2099 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2100 global $CFG, $DB, $USER, $SITE;
2101 require_once($CFG->dirroot.'/course/lib.php');
2103 list($sections, $activities) = $this->generate_sections_and_activities($course);
2105 $navigationsections = array();
2106 foreach ($sections as $sectionid => $section) {
2107 $section = clone($section);
2108 if ($course->id == $SITE->id) {
2109 $this->load_section_activities($coursenode, $section->section, $activities);
2110 } else {
2111 if (!$section->uservisible || (!$this->showemptysections &&
2112 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2113 continue;
2116 $sectionname = get_section_name($course, $section);
2117 $url = course_get_url($course, $section->section, array('navigation' => true));
2119 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2120 null, $section->id, new pix_icon('i/section', ''));
2121 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2122 $sectionnode->hidden = (!$section->visible || !$section->available);
2123 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2124 $this->load_section_activities($sectionnode, $section->section, $activities);
2126 $section->sectionnode = $sectionnode;
2127 $navigationsections[$sectionid] = $section;
2130 return $navigationsections;
2134 * Loads all of the activities for a section into the navigation structure.
2136 * @param navigation_node $sectionnode
2137 * @param int $sectionnumber
2138 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2139 * @param stdClass $course The course object the section and activities relate to.
2140 * @return array Array of activity nodes
2142 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2143 global $CFG, $SITE;
2144 // A static counter for JS function naming
2145 static $legacyonclickcounter = 0;
2147 $activitynodes = array();
2148 if (empty($activities)) {
2149 return $activitynodes;
2152 if (!is_object($course)) {
2153 $activity = reset($activities);
2154 $courseid = $activity->course;
2155 } else {
2156 $courseid = $course->id;
2158 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2160 foreach ($activities as $activity) {
2161 if ($activity->section != $sectionnumber) {
2162 continue;
2164 if ($activity->icon) {
2165 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2166 } else {
2167 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2170 // Prepare the default name and url for the node
2171 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2172 $action = new moodle_url($activity->url);
2174 // Check if the onclick property is set (puke!)
2175 if (!empty($activity->onclick)) {
2176 // Increment the counter so that we have a unique number.
2177 $legacyonclickcounter++;
2178 // Generate the function name we will use
2179 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2180 $propogrationhandler = '';
2181 // Check if we need to cancel propogation. Remember inline onclick
2182 // events would return false if they wanted to prevent propogation and the
2183 // default action.
2184 if (strpos($activity->onclick, 'return false')) {
2185 $propogrationhandler = 'e.halt();';
2187 // Decode the onclick - it has already been encoded for display (puke)
2188 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2189 // Build the JS function the click event will call
2190 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2191 $this->page->requires->js_amd_inline($jscode);
2192 // Override the default url with the new action link
2193 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2196 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2197 $activitynode->title(get_string('modulename', $activity->modname));
2198 $activitynode->hidden = $activity->hidden;
2199 $activitynode->display = $showactivities && $activity->display;
2200 $activitynode->nodetype = $activity->nodetype;
2201 $activitynodes[$activity->id] = $activitynode;
2204 return $activitynodes;
2207 * Loads a stealth module from unavailable section
2208 * @param navigation_node $coursenode
2209 * @param stdClass $modinfo
2210 * @return navigation_node or null if not accessible
2212 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2213 if (empty($modinfo->cms[$this->page->cm->id])) {
2214 return null;
2216 $cm = $modinfo->cms[$this->page->cm->id];
2217 if ($cm->icon) {
2218 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2219 } else {
2220 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2222 $url = $cm->url;
2223 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2224 $activitynode->title(get_string('modulename', $cm->modname));
2225 $activitynode->hidden = (!$cm->visible);
2226 if (!$cm->is_visible_on_course_page()) {
2227 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2228 // Also there may be no exception at all in case when teacher is logged in as student.
2229 $activitynode->display = false;
2230 } else if (!$url) {
2231 // Don't show activities that don't have links!
2232 $activitynode->display = false;
2233 } else if (self::module_extends_navigation($cm->modname)) {
2234 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2236 return $activitynode;
2239 * Loads the navigation structure for the given activity into the activities node.
2241 * This method utilises a callback within the modules lib.php file to load the
2242 * content specific to activity given.
2244 * The callback is a method: {modulename}_extend_navigation()
2245 * Examples:
2246 * * {@link forum_extend_navigation()}
2247 * * {@link workshop_extend_navigation()}
2249 * @param cm_info|stdClass $cm
2250 * @param stdClass $course
2251 * @param navigation_node $activity
2252 * @return bool
2254 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2255 global $CFG, $DB;
2257 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2258 if (!($cm instanceof cm_info)) {
2259 $modinfo = get_fast_modinfo($course);
2260 $cm = $modinfo->get_cm($cm->id);
2262 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2263 $activity->make_active();
2264 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2265 $function = $cm->modname.'_extend_navigation';
2267 if (file_exists($file)) {
2268 require_once($file);
2269 if (function_exists($function)) {
2270 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2271 $function($activity, $course, $activtyrecord, $cm);
2275 // Allow the active advanced grading method plugin to append module navigation
2276 $featuresfunc = $cm->modname.'_supports';
2277 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2278 require_once($CFG->dirroot.'/grade/grading/lib.php');
2279 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2280 $gradingman->extend_navigation($this, $activity);
2283 return $activity->has_children();
2286 * Loads user specific information into the navigation in the appropriate place.
2288 * If no user is provided the current user is assumed.
2290 * @param stdClass $user
2291 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2292 * @return bool
2294 protected function load_for_user($user=null, $forceforcontext=false) {
2295 global $DB, $CFG, $USER, $SITE;
2297 require_once($CFG->dirroot . '/course/lib.php');
2299 if ($user === null) {
2300 // We can't require login here but if the user isn't logged in we don't
2301 // want to show anything
2302 if (!isloggedin() || isguestuser()) {
2303 return false;
2305 $user = $USER;
2306 } else if (!is_object($user)) {
2307 // If the user is not an object then get them from the database
2308 $select = context_helper::get_preload_record_columns_sql('ctx');
2309 $sql = "SELECT u.*, $select
2310 FROM {user} u
2311 JOIN {context} ctx ON u.id = ctx.instanceid
2312 WHERE u.id = :userid AND
2313 ctx.contextlevel = :contextlevel";
2314 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2315 context_helper::preload_from_record($user);
2318 $iscurrentuser = ($user->id == $USER->id);
2320 $usercontext = context_user::instance($user->id);
2322 // Get the course set against the page, by default this will be the site
2323 $course = $this->page->course;
2324 $baseargs = array('id'=>$user->id);
2325 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2326 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2327 $baseargs['course'] = $course->id;
2328 $coursecontext = context_course::instance($course->id);
2329 $issitecourse = false;
2330 } else {
2331 // Load all categories and get the context for the system
2332 $coursecontext = context_system::instance();
2333 $issitecourse = true;
2336 // Create a node to add user information under.
2337 $usersnode = null;
2338 if (!$issitecourse) {
2339 // Not the current user so add it to the participants node for the current course.
2340 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2341 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2342 } else if ($USER->id != $user->id) {
2343 // This is the site so add a users node to the root branch.
2344 $usersnode = $this->rootnodes['users'];
2345 if (course_can_view_participants($coursecontext)) {
2346 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2348 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2350 if (!$usersnode) {
2351 // We should NEVER get here, if the course hasn't been populated
2352 // with a participants node then the navigaiton either wasn't generated
2353 // for it (you are missing a require_login or set_context call) or
2354 // you don't have access.... in the interests of no leaking informatin
2355 // we simply quit...
2356 return false;
2358 // Add a branch for the current user.
2359 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2360 $viewprofile = true;
2361 if (!$iscurrentuser) {
2362 require_once($CFG->dirroot . '/user/lib.php');
2363 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2364 $viewprofile = false;
2365 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2366 $viewprofile = false;
2368 if (!$viewprofile) {
2369 $viewprofile = user_can_view_profile($user, null, $usercontext);
2373 // Now, conditionally add the user node.
2374 if ($viewprofile) {
2375 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2376 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2377 } else {
2378 $usernode = $usersnode->add(get_string('user'));
2381 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2382 $usernode->make_active();
2385 // Add user information to the participants or user node.
2386 if ($issitecourse) {
2388 // If the user is the current user or has permission to view the details of the requested
2389 // user than add a view profile link.
2390 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2391 has_capability('moodle/user:viewdetails', $usercontext)) {
2392 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2393 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2394 } else {
2395 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2399 if (!empty($CFG->navadduserpostslinks)) {
2400 // Add nodes for forum posts and discussions if the user can view either or both
2401 // There are no capability checks here as the content of the page is based
2402 // purely on the forums the current user has access too.
2403 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2404 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2405 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2406 array_merge($baseargs, array('mode' => 'discussions'))));
2409 // Add blog nodes.
2410 if (!empty($CFG->enableblogs)) {
2411 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2412 require_once($CFG->dirroot.'/blog/lib.php');
2413 // Get all options for the user.
2414 $options = blog_get_options_for_user($user);
2415 $this->cache->set('userblogoptions'.$user->id, $options);
2416 } else {
2417 $options = $this->cache->{'userblogoptions'.$user->id};
2420 if (count($options) > 0) {
2421 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2422 foreach ($options as $type => $option) {
2423 if ($type == "rss") {
2424 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2425 new pix_icon('i/rss', ''));
2426 } else {
2427 $blogs->add($option['string'], $option['link']);
2433 // Add the messages link.
2434 // It is context based so can appear in the user's profile and in course participants information.
2435 if (!empty($CFG->messaging)) {
2436 $messageargs = array('user1' => $USER->id);
2437 if ($USER->id != $user->id) {
2438 $messageargs['user2'] = $user->id;
2440 $url = new moodle_url('/message/index.php', $messageargs);
2441 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2444 // Add the "My private files" link.
2445 // This link doesn't have a unique display for course context so only display it under the user's profile.
2446 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2447 $url = new moodle_url('/user/files.php');
2448 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2451 // Add a node to view the users notes if permitted.
2452 if (!empty($CFG->enablenotes) &&
2453 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2454 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2455 if ($coursecontext->instanceid != SITEID) {
2456 $url->param('course', $coursecontext->instanceid);
2458 $usernode->add(get_string('notes', 'notes'), $url);
2461 // Show the grades node.
2462 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2463 require_once($CFG->dirroot . '/user/lib.php');
2464 // Set the grades node to link to the "Grades" page.
2465 if ($course->id == SITEID) {
2466 $url = user_mygrades_url($user->id, $course->id);
2467 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2468 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2470 if ($USER->id != $user->id) {
2471 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2472 } else {
2473 $usernode->add(get_string('grades', 'grades'), $url);
2477 // If the user is the current user add the repositories for the current user.
2478 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2479 if (!$iscurrentuser &&
2480 $course->id == $SITE->id &&
2481 has_capability('moodle/user:viewdetails', $usercontext) &&
2482 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2484 // Add view grade report is permitted.
2485 $reports = core_component::get_plugin_list('gradereport');
2486 arsort($reports); // User is last, we want to test it first.
2488 $userscourses = enrol_get_users_courses($user->id, false, '*');
2489 $userscoursesnode = $usernode->add(get_string('courses'));
2491 $count = 0;
2492 foreach ($userscourses as $usercourse) {
2493 if ($count === (int)$CFG->navcourselimit) {
2494 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2495 $userscoursesnode->add(get_string('showallcourses'), $url);
2496 break;
2498 $count++;
2499 $usercoursecontext = context_course::instance($usercourse->id);
2500 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2501 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2502 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2504 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2505 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2506 foreach ($reports as $plugin => $plugindir) {
2507 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2508 // Stop when the first visible plugin is found.
2509 $gradeavailable = true;
2510 break;
2515 if ($gradeavailable) {
2516 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2517 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2518 new pix_icon('i/grades', ''));
2521 // Add a node to view the users notes if permitted.
2522 if (!empty($CFG->enablenotes) &&
2523 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2524 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2525 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2528 if (can_access_course($usercourse, $user->id, '', true)) {
2529 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2530 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2533 $reporttab = $usercoursenode->add(get_string('activityreports'));
2535 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2536 foreach ($reportfunctions as $reportfunction) {
2537 $reportfunction($reporttab, $user, $usercourse);
2540 $reporttab->trim_if_empty();
2544 // Let plugins hook into user navigation.
2545 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2546 foreach ($pluginsfunction as $plugintype => $plugins) {
2547 if ($plugintype != 'report') {
2548 foreach ($plugins as $pluginfunction) {
2549 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2554 return true;
2558 * This method simply checks to see if a given module can extend the navigation.
2560 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2562 * @param string $modname
2563 * @return bool
2565 public static function module_extends_navigation($modname) {
2566 global $CFG;
2567 static $extendingmodules = array();
2568 if (!array_key_exists($modname, $extendingmodules)) {
2569 $extendingmodules[$modname] = false;
2570 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2571 if (file_exists($file)) {
2572 $function = $modname.'_extend_navigation';
2573 require_once($file);
2574 $extendingmodules[$modname] = (function_exists($function));
2577 return $extendingmodules[$modname];
2580 * Extends the navigation for the given user.
2582 * @param stdClass $user A user from the database
2584 public function extend_for_user($user) {
2585 $this->extendforuser[] = $user;
2589 * Returns all of the users the navigation is being extended for
2591 * @return array An array of extending users.
2593 public function get_extending_users() {
2594 return $this->extendforuser;
2597 * Adds the given course to the navigation structure.
2599 * @param stdClass $course
2600 * @param bool $forcegeneric
2601 * @param bool $ismycourse
2602 * @return navigation_node
2604 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2605 global $CFG, $SITE;
2607 // We found the course... we can return it now :)
2608 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2609 return $this->addedcourses[$course->id];
2612 $coursecontext = context_course::instance($course->id);
2614 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) {
2615 if (is_role_switched($course->id)) {
2616 // user has to be able to access course in order to switch, let's skip the visibility test here
2617 } else if (!core_course_category::can_view_course_info($course)) {
2618 return false;
2622 $issite = ($course->id == $SITE->id);
2623 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2624 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2625 // This is the name that will be shown for the course.
2626 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2628 if ($coursetype == self::COURSE_CURRENT) {
2629 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2630 return $coursenode;
2631 } else {
2632 $coursetype = self::COURSE_OTHER;
2636 // Can the user expand the course to see its content.
2637 $canexpandcourse = true;
2638 if ($issite) {
2639 $parent = $this;
2640 $url = null;
2641 if (empty($CFG->usesitenameforsitepages)) {
2642 $coursename = get_string('sitepages');
2644 } else if ($coursetype == self::COURSE_CURRENT) {
2645 $parent = $this->rootnodes['currentcourse'];
2646 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2647 $canexpandcourse = $this->can_expand_course($course);
2648 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2649 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2650 // Nothing to do here the above statement set $parent to the category within mycourses.
2651 } else {
2652 $parent = $this->rootnodes['mycourses'];
2654 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2655 } else {
2656 $parent = $this->rootnodes['courses'];
2657 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2658 // They can only expand the course if they can access it.
2659 $canexpandcourse = $this->can_expand_course($course);
2660 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2661 if (!$this->is_category_fully_loaded($course->category)) {
2662 // We need to load the category structure for this course
2663 $this->load_all_categories($course->category, false);
2665 if (array_key_exists($course->category, $this->addedcategories)) {
2666 $parent = $this->addedcategories[$course->category];
2667 // This could lead to the course being created so we should check whether it is the case again
2668 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2669 return $this->addedcourses[$course->id];
2675 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
2676 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2678 $coursenode->hidden = (!$course->visible);
2679 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2680 if ($canexpandcourse) {
2681 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2682 $coursenode->nodetype = self::NODETYPE_BRANCH;
2683 $coursenode->isexpandable = true;
2684 } else {
2685 $coursenode->nodetype = self::NODETYPE_LEAF;
2686 $coursenode->isexpandable = false;
2688 if (!$forcegeneric) {
2689 $this->addedcourses[$course->id] = $coursenode;
2692 return $coursenode;
2696 * Returns a cache instance to use for the expand course cache.
2697 * @return cache_session
2699 protected function get_expand_course_cache() {
2700 if ($this->cacheexpandcourse === null) {
2701 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2703 return $this->cacheexpandcourse;
2707 * Checks if a user can expand a course in the navigation.
2709 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2710 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2711 * permits stale data.
2712 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2713 * will be stale.
2714 * It is brought up to date in only one of two ways.
2715 * 1. The user logs out and in again.
2716 * 2. The user browses to the course they've just being given access to.
2718 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2720 * @param stdClass $course
2721 * @return bool
2723 protected function can_expand_course($course) {
2724 $cache = $this->get_expand_course_cache();
2725 $canexpand = $cache->get($course->id);
2726 if ($canexpand === false) {
2727 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2728 $canexpand = (int)$canexpand;
2729 $cache->set($course->id, $canexpand);
2731 return ($canexpand === 1);
2735 * Returns true if the category has already been loaded as have any child categories
2737 * @param int $categoryid
2738 * @return bool
2740 protected function is_category_fully_loaded($categoryid) {
2741 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2745 * Adds essential course nodes to the navigation for the given course.
2747 * This method adds nodes such as reports, blogs and participants
2749 * @param navigation_node $coursenode
2750 * @param stdClass $course
2751 * @return bool returns true on successful addition of a node.
2753 public function add_course_essentials($coursenode, stdClass $course) {
2754 global $CFG, $SITE;
2755 require_once($CFG->dirroot . '/course/lib.php');
2757 if ($course->id == $SITE->id) {
2758 return $this->add_front_page_course_essentials($coursenode, $course);
2761 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2762 return true;
2765 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2767 //Participants
2768 if ($navoptions->participants) {
2769 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2770 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2772 if ($navoptions->blogs) {
2773 $blogsurls = new moodle_url('/blog/index.php');
2774 if ($currentgroup = groups_get_course_group($course, true)) {
2775 $blogsurls->param('groupid', $currentgroup);
2776 } else {
2777 $blogsurls->param('courseid', $course->id);
2779 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2782 if ($navoptions->notes) {
2783 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2785 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2786 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2789 // Badges.
2790 if ($navoptions->badges) {
2791 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2793 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2794 navigation_node::TYPE_SETTING, null, 'badgesview',
2795 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2798 // Check access to the course and competencies page.
2799 if ($navoptions->competencies) {
2800 // Just a link to course competency.
2801 $title = get_string('competencies', 'core_competency');
2802 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2803 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2804 new pix_icon('i/competencies', ''));
2806 if ($navoptions->grades) {
2807 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2808 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2809 'grades', new pix_icon('i/grades', ''));
2810 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2811 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
2812 $gradenode->make_active();
2816 return true;
2819 * This generates the structure of the course that won't be generated when
2820 * the modules and sections are added.
2822 * Things such as the reports branch, the participants branch, blogs... get
2823 * added to the course node by this method.
2825 * @param navigation_node $coursenode
2826 * @param stdClass $course
2827 * @return bool True for successfull generation
2829 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2830 global $CFG, $USER, $COURSE, $SITE;
2831 require_once($CFG->dirroot . '/course/lib.php');
2833 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2834 return true;
2837 $sitecontext = context_system::instance();
2838 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2840 // Hidden node that we use to determine if the front page navigation is loaded.
2841 // This required as there are not other guaranteed nodes that may be loaded.
2842 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2844 // Participants.
2845 if ($navoptions->participants) {
2846 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2849 // Blogs.
2850 if ($navoptions->blogs) {
2851 $blogsurls = new moodle_url('/blog/index.php');
2852 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2855 $filterselect = 0;
2857 // Badges.
2858 if ($navoptions->badges) {
2859 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2860 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2863 // Notes.
2864 if ($navoptions->notes) {
2865 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2866 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2869 // Tags
2870 if ($navoptions->tags) {
2871 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2872 self::TYPE_SETTING, null, 'tags');
2875 // Search.
2876 if ($navoptions->search) {
2877 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2878 self::TYPE_SETTING, null, 'search');
2881 if ($navoptions->calendar) {
2882 $courseid = $COURSE->id;
2883 $params = array('view' => 'month');
2884 if ($courseid != $SITE->id) {
2885 $params['course'] = $courseid;
2888 // Calendar
2889 $calendarurl = new moodle_url('/calendar/view.php', $params);
2890 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2891 self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
2892 $node->showinflatnavigation = true;
2895 if (isloggedin()) {
2896 $usercontext = context_user::instance($USER->id);
2897 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2898 $url = new moodle_url('/user/files.php');
2899 $node = $coursenode->add(get_string('privatefiles'), $url,
2900 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2901 $node->display = false;
2902 $node->showinflatnavigation = true;
2906 return true;
2910 * Clears the navigation cache
2912 public function clear_cache() {
2913 $this->cache->clear();
2917 * Sets an expansion limit for the navigation
2919 * The expansion limit is used to prevent the display of content that has a type
2920 * greater than the provided $type.
2922 * Can be used to ensure things such as activities or activity content don't get
2923 * shown on the navigation.
2924 * They are still generated in order to ensure the navbar still makes sense.
2926 * @param int $type One of navigation_node::TYPE_*
2927 * @return bool true when complete.
2929 public function set_expansion_limit($type) {
2930 global $SITE;
2931 $nodes = $this->find_all_of_type($type);
2933 // We only want to hide specific types of nodes.
2934 // Only nodes that represent "structure" in the navigation tree should be hidden.
2935 // If we hide all nodes then we risk hiding vital information.
2936 $typestohide = array(
2937 self::TYPE_CATEGORY,
2938 self::TYPE_COURSE,
2939 self::TYPE_SECTION,
2940 self::TYPE_ACTIVITY
2943 foreach ($nodes as $node) {
2944 // We need to generate the full site node
2945 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2946 continue;
2948 foreach ($node->children as $child) {
2949 $child->hide($typestohide);
2952 return true;
2955 * Attempts to get the navigation with the given key from this nodes children.
2957 * This function only looks at this nodes children, it does NOT look recursivily.
2958 * If the node can't be found then false is returned.
2960 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2962 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2963 * may be of more use to you.
2965 * @param string|int $key The key of the node you wish to receive.
2966 * @param int $type One of navigation_node::TYPE_*
2967 * @return navigation_node|false
2969 public function get($key, $type = null) {
2970 if (!$this->initialised) {
2971 $this->initialise();
2973 return parent::get($key, $type);
2977 * Searches this nodes children and their children to find a navigation node
2978 * with the matching key and type.
2980 * This method is recursive and searches children so until either a node is
2981 * found or there are no more nodes to search.
2983 * If you know that the node being searched for is a child of this node
2984 * then use the {@link global_navigation::get()} method instead.
2986 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2987 * may be of more use to you.
2989 * @param string|int $key The key of the node you wish to receive.
2990 * @param int $type One of navigation_node::TYPE_*
2991 * @return navigation_node|false
2993 public function find($key, $type) {
2994 if (!$this->initialised) {
2995 $this->initialise();
2997 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2998 return $this->rootnodes[$key];
3000 return parent::find($key, $type);
3004 * They've expanded the 'my courses' branch.
3006 protected function load_courses_enrolled() {
3007 global $CFG;
3009 $limit = (int) $CFG->navcourselimit;
3011 $courses = enrol_get_my_courses('*');
3012 $flatnavcourses = [];
3014 // Go through the courses and see which ones we want to display in the flatnav.
3015 foreach ($courses as $course) {
3016 $classify = course_classify_for_timeline($course);
3018 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3019 $flatnavcourses[$course->id] = $course;
3023 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3024 $numtotalcourses = count($courses);
3025 $numtotalflatnavcourses = count($flatnavcourses);
3027 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3028 $courses = array_slice($courses, 0, $limit, true);
3029 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3031 // Get the number of courses we are going to show for each.
3032 $numshowncourses = count($courses);
3033 $numshownflatnavcourses = count($flatnavcourses);
3034 if ($numshowncourses && $this->show_my_categories()) {
3035 // Generate an array containing unique values of all the courses' categories.
3036 $categoryids = array();
3037 foreach ($courses as $course) {
3038 if (in_array($course->category, $categoryids)) {
3039 continue;
3041 $categoryids[] = $course->category;
3044 // Array of category IDs that include the categories of the user's courses and the related course categories.
3045 $fullpathcategoryids = [];
3046 // Get the course categories for the enrolled courses' category IDs.
3047 $mycoursecategories = core_course_category::get_many($categoryids);
3048 // Loop over each of these categories and build the category tree using each category's path.
3049 foreach ($mycoursecategories as $mycoursecat) {
3050 $pathcategoryids = explode('/', $mycoursecat->path);
3051 // First element of the exploded path is empty since paths begin with '/'.
3052 array_shift($pathcategoryids);
3053 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3054 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3057 // Fetch all of the categories related to the user's courses.
3058 $pathcategories = core_course_category::get_many($fullpathcategoryids);
3059 // Loop over each of these categories and build the category tree.
3060 foreach ($pathcategories as $coursecat) {
3061 // No need to process categories that have already been added.
3062 if (isset($this->addedcategories[$coursecat->id])) {
3063 continue;
3065 // Skip categories that are not visible.
3066 if (!$coursecat->is_uservisible()) {
3067 continue;
3070 // Get this course category's parent node.
3071 $parent = null;
3072 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3073 $parent = $this->addedcategories[$coursecat->parent];
3075 if (!$parent) {
3076 // If it has no parent, then it should be right under the My courses node.
3077 $parent = $this->rootnodes['mycourses'];
3080 // Build the category object based from the coursecat object.
3081 $mycategory = new stdClass();
3082 $mycategory->id = $coursecat->id;
3083 $mycategory->name = $coursecat->name;
3084 $mycategory->visible = $coursecat->visible;
3086 // Add this category to the nav tree.
3087 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
3091 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3092 foreach ($courses as $course) {
3093 $node = $this->add_course($course, false, self::COURSE_MY);
3094 if ($node) {
3095 $node->showinflatnavigation = false;
3096 // Check if we should also add this to the flat nav as well.
3097 if (isset($flatnavcourses[$course->id])) {
3098 $node->showinflatnavigation = true;
3103 // Go through each course in the flatnav now.
3104 foreach ($flatnavcourses as $course) {
3105 // Check if we haven't already added it.
3106 if (!isset($courses[$course->id])) {
3107 // Ok, add it to the flatnav only.
3108 $node = $this->add_course($course, false, self::COURSE_MY);
3109 $node->display = false;
3110 $node->showinflatnavigation = true;
3114 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3115 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3116 // Show a link to the course page if there are more courses the user is enrolled in.
3117 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3118 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3119 $url = new moodle_url('/my/');
3120 $parent = $this->rootnodes['mycourses'];
3121 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3123 if ($showmorelinkinnav) {
3124 $coursenode->display = true;
3127 if ($showmorelinkinflatnav) {
3128 $coursenode->showinflatnavigation = true;
3135 * The global navigation class used especially for AJAX requests.
3137 * The primary methods that are used in the global navigation class have been overriden
3138 * to ensure that only the relevant branch is generated at the root of the tree.
3139 * This can be done because AJAX is only used when the backwards structure for the
3140 * requested branch exists.
3141 * This has been done only because it shortens the amounts of information that is generated
3142 * which of course will speed up the response time.. because no one likes laggy AJAX.
3144 * @package core
3145 * @category navigation
3146 * @copyright 2009 Sam Hemelryk
3147 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3149 class global_navigation_for_ajax extends global_navigation {
3151 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3152 protected $branchtype;
3154 /** @var int the instance id */
3155 protected $instanceid;
3157 /** @var array Holds an array of expandable nodes */
3158 protected $expandable = array();
3161 * Constructs the navigation for use in an AJAX request
3163 * @param moodle_page $page moodle_page object
3164 * @param int $branchtype
3165 * @param int $id
3167 public function __construct($page, $branchtype, $id) {
3168 $this->page = $page;
3169 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3170 $this->children = new navigation_node_collection();
3171 $this->branchtype = $branchtype;
3172 $this->instanceid = $id;
3173 $this->initialise();
3176 * Initialise the navigation given the type and id for the branch to expand.
3178 * @return array An array of the expandable nodes
3180 public function initialise() {
3181 global $DB, $SITE;
3183 if ($this->initialised || during_initial_install()) {
3184 return $this->expandable;
3186 $this->initialised = true;
3188 $this->rootnodes = array();
3189 $this->rootnodes['site'] = $this->add_course($SITE);
3190 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3191 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3192 // The courses branch is always displayed, and is always expandable (although may be empty).
3193 // This mimicks what is done during {@link global_navigation::initialise()}.
3194 $this->rootnodes['courses']->isexpandable = true;
3196 // Branchtype will be one of navigation_node::TYPE_*
3197 switch ($this->branchtype) {
3198 case 0:
3199 if ($this->instanceid === 'mycourses') {
3200 $this->load_courses_enrolled();
3201 } else if ($this->instanceid === 'courses') {
3202 $this->load_courses_other();
3204 break;
3205 case self::TYPE_CATEGORY :
3206 $this->load_category($this->instanceid);
3207 break;
3208 case self::TYPE_MY_CATEGORY :
3209 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3210 break;
3211 case self::TYPE_COURSE :
3212 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3213 if (!can_access_course($course, null, '', true)) {
3214 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3215 // add the course node and break. This leads to an empty node.
3216 $this->add_course($course);
3217 break;
3219 require_course_login($course, true, null, false, true);
3220 $this->page->set_context(context_course::instance($course->id));
3221 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3222 $this->add_course_essentials($coursenode, $course);
3223 $this->load_course_sections($course, $coursenode);
3224 break;
3225 case self::TYPE_SECTION :
3226 $sql = 'SELECT c.*, cs.section AS sectionnumber
3227 FROM {course} c
3228 LEFT JOIN {course_sections} cs ON cs.course = c.id
3229 WHERE cs.id = ?';
3230 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3231 require_course_login($course, true, null, false, true);
3232 $this->page->set_context(context_course::instance($course->id));
3233 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3234 $this->add_course_essentials($coursenode, $course);
3235 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3236 break;
3237 case self::TYPE_ACTIVITY :
3238 $sql = "SELECT c.*
3239 FROM {course} c
3240 JOIN {course_modules} cm ON cm.course = c.id
3241 WHERE cm.id = :cmid";
3242 $params = array('cmid' => $this->instanceid);
3243 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3244 $modinfo = get_fast_modinfo($course);
3245 $cm = $modinfo->get_cm($this->instanceid);
3246 require_course_login($course, true, $cm, false, true);
3247 $this->page->set_context(context_module::instance($cm->id));
3248 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
3249 $this->load_course_sections($course, $coursenode, null, $cm);
3250 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3251 if ($activitynode) {
3252 $modulenode = $this->load_activity($cm, $course, $activitynode);
3254 break;
3255 default:
3256 throw new Exception('Unknown type');
3257 return $this->expandable;
3260 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3261 $this->load_for_user(null, true);
3264 $this->find_expandable($this->expandable);
3265 return $this->expandable;
3269 * They've expanded the general 'courses' branch.
3271 protected function load_courses_other() {
3272 $this->load_all_courses();
3276 * Loads a single category into the AJAX navigation.
3278 * This function is special in that it doesn't concern itself with the parent of
3279 * the requested category or its siblings.
3280 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3281 * request that.
3283 * @global moodle_database $DB
3284 * @param int $categoryid id of category to load in navigation.
3285 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3286 * @return void.
3288 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3289 global $CFG, $DB;
3291 $limit = 20;
3292 if (!empty($CFG->navcourselimit)) {
3293 $limit = (int)$CFG->navcourselimit;
3296 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3297 $sql = "SELECT cc.*, $catcontextsql
3298 FROM {course_categories} cc
3299 JOIN {context} ctx ON cc.id = ctx.instanceid
3300 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3301 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3302 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3303 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3304 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3305 $categorylist = array();
3306 $subcategories = array();
3307 $basecategory = null;
3308 foreach ($categories as $category) {
3309 $categorylist[] = $category->id;
3310 context_helper::preload_from_record($category);
3311 if ($category->id == $categoryid) {
3312 $this->add_category($category, $this, $nodetype);
3313 $basecategory = $this->addedcategories[$category->id];
3314 } else {
3315 $subcategories[$category->id] = $category;
3318 $categories->close();
3321 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3322 // else show all courses.
3323 if ($nodetype === self::TYPE_MY_CATEGORY) {
3324 $courses = enrol_get_my_courses('*');
3325 $categoryids = array();
3327 // Only search for categories if basecategory was found.
3328 if (!is_null($basecategory)) {
3329 // Get course parent category ids.
3330 foreach ($courses as $course) {
3331 $categoryids[] = $course->category;
3334 // Get a unique list of category ids which a part of the path
3335 // to user's courses.
3336 $coursesubcategories = array();
3337 $addedsubcategories = array();
3339 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3340 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3342 foreach ($categories as $category){
3343 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3345 $categories->close();
3346 $coursesubcategories = array_unique($coursesubcategories);
3348 // Only add a subcategory if it is part of the path to user's course and
3349 // wasn't already added.
3350 foreach ($subcategories as $subid => $subcategory) {
3351 if (in_array($subid, $coursesubcategories) &&
3352 !in_array($subid, $addedsubcategories)) {
3353 $this->add_category($subcategory, $basecategory, $nodetype);
3354 $addedsubcategories[] = $subid;
3359 foreach ($courses as $course) {
3360 // Add course if it's in category.
3361 if (in_array($course->category, $categorylist)) {
3362 $this->add_course($course, true, self::COURSE_MY);
3365 } else {
3366 if (!is_null($basecategory)) {
3367 foreach ($subcategories as $key=>$category) {
3368 $this->add_category($category, $basecategory, $nodetype);
3371 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3372 foreach ($courses as $course) {
3373 $this->add_course($course);
3375 $courses->close();
3380 * Returns an array of expandable nodes
3381 * @return array
3383 public function get_expandable() {
3384 return $this->expandable;
3389 * Navbar class
3391 * This class is used to manage the navbar, which is initialised from the navigation
3392 * object held by PAGE
3394 * @package core
3395 * @category navigation
3396 * @copyright 2009 Sam Hemelryk
3397 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3399 class navbar extends navigation_node {
3400 /** @var bool A switch for whether the navbar is initialised or not */
3401 protected $initialised = false;
3402 /** @var mixed keys used to reference the nodes on the navbar */
3403 protected $keys = array();
3404 /** @var null|string content of the navbar */
3405 protected $content = null;
3406 /** @var moodle_page object the moodle page that this navbar belongs to */
3407 protected $page;
3408 /** @var bool A switch for whether to ignore the active navigation information */
3409 protected $ignoreactive = false;
3410 /** @var bool A switch to let us know if we are in the middle of an install */
3411 protected $duringinstall = false;
3412 /** @var bool A switch for whether the navbar has items */
3413 protected $hasitems = false;
3414 /** @var array An array of navigation nodes for the navbar */
3415 protected $items;
3416 /** @var array An array of child node objects */
3417 public $children = array();
3418 /** @var bool A switch for whether we want to include the root node in the navbar */
3419 public $includesettingsbase = false;
3420 /** @var breadcrumb_navigation_node[] $prependchildren */
3421 protected $prependchildren = array();
3424 * The almighty constructor
3426 * @param moodle_page $page
3428 public function __construct(moodle_page $page) {
3429 global $CFG;
3430 if (during_initial_install()) {
3431 $this->duringinstall = true;
3432 return false;
3434 $this->page = $page;
3435 $this->text = get_string('home');
3436 $this->shorttext = get_string('home');
3437 $this->action = new moodle_url($CFG->wwwroot);
3438 $this->nodetype = self::NODETYPE_BRANCH;
3439 $this->type = self::TYPE_SYSTEM;
3443 * Quick check to see if the navbar will have items in.
3445 * @return bool Returns true if the navbar will have items, false otherwise
3447 public function has_items() {
3448 if ($this->duringinstall) {
3449 return false;
3450 } else if ($this->hasitems !== false) {
3451 return true;
3453 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3454 // There have been manually added items - there are definitely items.
3455 $outcome = true;
3456 } else if (!$this->ignoreactive) {
3457 // We will need to initialise the navigation structure to check if there are active items.
3458 $this->page->navigation->initialise($this->page);
3459 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3461 $this->hasitems = $outcome;
3462 return $outcome;
3466 * Turn on/off ignore active
3468 * @param bool $setting
3470 public function ignore_active($setting=true) {
3471 $this->ignoreactive = ($setting);
3475 * Gets a navigation node
3477 * @param string|int $key for referencing the navbar nodes
3478 * @param int $type breadcrumb_navigation_node::TYPE_*
3479 * @return breadcrumb_navigation_node|bool
3481 public function get($key, $type = null) {
3482 foreach ($this->children as &$child) {
3483 if ($child->key === $key && ($type == null || $type == $child->type)) {
3484 return $child;
3487 foreach ($this->prependchildren as &$child) {
3488 if ($child->key === $key && ($type == null || $type == $child->type)) {
3489 return $child;
3492 return false;
3495 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3497 * @return array
3499 public function get_items() {
3500 global $CFG;
3501 $items = array();
3502 // Make sure that navigation is initialised
3503 if (!$this->has_items()) {
3504 return $items;
3506 if ($this->items !== null) {
3507 return $this->items;
3510 if (count($this->children) > 0) {
3511 // Add the custom children.
3512 $items = array_reverse($this->children);
3515 // Check if navigation contains the active node
3516 if (!$this->ignoreactive) {
3517 // We will need to ensure the navigation has been initialised.
3518 $this->page->navigation->initialise($this->page);
3519 // Now find the active nodes on both the navigation and settings.
3520 $navigationactivenode = $this->page->navigation->find_active_node();
3521 $settingsactivenode = $this->page->settingsnav->find_active_node();
3523 if ($navigationactivenode && $settingsactivenode) {
3524 // Parse a combined navigation tree
3525 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3526 if (!$settingsactivenode->mainnavonly) {
3527 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3529 $settingsactivenode = $settingsactivenode->parent;
3531 if (!$this->includesettingsbase) {
3532 // Removes the first node from the settings (root node) from the list
3533 array_pop($items);
3535 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3536 if (!$navigationactivenode->mainnavonly) {
3537 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3539 if (!empty($CFG->navshowcategories) &&
3540 $navigationactivenode->type === self::TYPE_COURSE &&
3541 $navigationactivenode->parent->key === 'currentcourse') {
3542 foreach ($this->get_course_categories() as $item) {
3543 $items[] = new breadcrumb_navigation_node($item);
3546 $navigationactivenode = $navigationactivenode->parent;
3548 } else if ($navigationactivenode) {
3549 // Parse the navigation tree to get the active node
3550 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3551 if (!$navigationactivenode->mainnavonly) {
3552 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3554 if (!empty($CFG->navshowcategories) &&
3555 $navigationactivenode->type === self::TYPE_COURSE &&
3556 $navigationactivenode->parent->key === 'currentcourse') {
3557 foreach ($this->get_course_categories() as $item) {
3558 $items[] = new breadcrumb_navigation_node($item);
3561 $navigationactivenode = $navigationactivenode->parent;
3563 } else if ($settingsactivenode) {
3564 // Parse the settings navigation to get the active node
3565 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3566 if (!$settingsactivenode->mainnavonly) {
3567 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3569 $settingsactivenode = $settingsactivenode->parent;
3574 $items[] = new breadcrumb_navigation_node(array(
3575 'text' => $this->page->navigation->text,
3576 'shorttext' => $this->page->navigation->shorttext,
3577 'key' => $this->page->navigation->key,
3578 'action' => $this->page->navigation->action
3581 if (count($this->prependchildren) > 0) {
3582 // Add the custom children
3583 $items = array_merge($items, array_reverse($this->prependchildren));
3586 $last = reset($items);
3587 if ($last) {
3588 $last->set_last(true);
3590 $this->items = array_reverse($items);
3591 return $this->items;
3595 * Get the list of categories leading to this course.
3597 * This function is used by {@link navbar::get_items()} to add back the "courses"
3598 * node and category chain leading to the current course. Note that this is only ever
3599 * called for the current course, so we don't need to bother taking in any parameters.
3601 * @return array
3603 private function get_course_categories() {
3604 global $CFG;
3605 require_once($CFG->dirroot.'/course/lib.php');
3607 $categories = array();
3608 $cap = 'moodle/category:viewhiddencategories';
3609 $showcategories = !core_course_category::is_simple_site();
3611 if ($showcategories) {
3612 foreach ($this->page->categories as $category) {
3613 $context = context_coursecat::instance($category->id);
3614 if (!core_course_category::can_view_category($category)) {
3615 continue;
3617 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3618 $name = format_string($category->name, true, array('context' => $context));
3619 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3620 if (!$category->visible) {
3621 $categorynode->hidden = true;
3623 $categories[] = $categorynode;
3627 // Don't show the 'course' node if enrolled in this course.
3628 if (!is_enrolled(context_course::instance($this->page->course->id, null, '', true))) {
3629 $courses = $this->page->navigation->get('courses');
3630 if (!$courses) {
3631 // Courses node may not be present.
3632 $courses = breadcrumb_navigation_node::create(
3633 get_string('courses'),
3634 new moodle_url('/course/index.php'),
3635 self::TYPE_CONTAINER
3638 $categories[] = $courses;
3641 return $categories;
3645 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3647 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3648 * the way nodes get added to allow us to simply call add and have the node added to the
3649 * end of the navbar
3651 * @param string $text
3652 * @param string|moodle_url|action_link $action An action to associate with this node.
3653 * @param int $type One of navigation_node::TYPE_*
3654 * @param string $shorttext
3655 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3656 * @param pix_icon $icon An optional icon to use for this node.
3657 * @return navigation_node
3659 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3660 if ($this->content !== null) {
3661 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3664 // Properties array used when creating the new navigation node
3665 $itemarray = array(
3666 'text' => $text,
3667 'type' => $type
3669 // Set the action if one was provided
3670 if ($action!==null) {
3671 $itemarray['action'] = $action;
3673 // Set the shorttext if one was provided
3674 if ($shorttext!==null) {
3675 $itemarray['shorttext'] = $shorttext;
3677 // Set the icon if one was provided
3678 if ($icon!==null) {
3679 $itemarray['icon'] = $icon;
3681 // Default the key to the number of children if not provided
3682 if ($key === null) {
3683 $key = count($this->children);
3685 // Set the key
3686 $itemarray['key'] = $key;
3687 // Set the parent to this node
3688 $itemarray['parent'] = $this;
3689 // Add the child using the navigation_node_collections add method
3690 $this->children[] = new breadcrumb_navigation_node($itemarray);
3691 return $this;
3695 * Prepends a new navigation_node to the start of the navbar
3697 * @param string $text
3698 * @param string|moodle_url|action_link $action An action to associate with this node.
3699 * @param int $type One of navigation_node::TYPE_*
3700 * @param string $shorttext
3701 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3702 * @param pix_icon $icon An optional icon to use for this node.
3703 * @return navigation_node
3705 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3706 if ($this->content !== null) {
3707 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3709 // Properties array used when creating the new navigation node.
3710 $itemarray = array(
3711 'text' => $text,
3712 'type' => $type
3714 // Set the action if one was provided.
3715 if ($action!==null) {
3716 $itemarray['action'] = $action;
3718 // Set the shorttext if one was provided.
3719 if ($shorttext!==null) {
3720 $itemarray['shorttext'] = $shorttext;
3722 // Set the icon if one was provided.
3723 if ($icon!==null) {
3724 $itemarray['icon'] = $icon;
3726 // Default the key to the number of children if not provided.
3727 if ($key === null) {
3728 $key = count($this->children);
3730 // Set the key.
3731 $itemarray['key'] = $key;
3732 // Set the parent to this node.
3733 $itemarray['parent'] = $this;
3734 // Add the child node to the prepend list.
3735 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3736 return $this;
3741 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3742 * in particular adding extra metadata for search engine robots to leverage.
3744 * @package core
3745 * @category navigation
3746 * @copyright 2015 Brendan Heywood
3747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3749 class breadcrumb_navigation_node extends navigation_node {
3751 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3752 private $last = false;
3755 * A proxy constructor
3757 * @param mixed $navnode A navigation_node or an array
3759 public function __construct($navnode) {
3760 if (is_array($navnode)) {
3761 parent::__construct($navnode);
3762 } else if ($navnode instanceof navigation_node) {
3764 // Just clone everything.
3765 $objvalues = get_object_vars($navnode);
3766 foreach ($objvalues as $key => $value) {
3767 $this->$key = $value;
3769 } else {
3770 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3775 * Getter for "last"
3776 * @return boolean
3778 public function is_last() {
3779 return $this->last;
3783 * Setter for "last"
3784 * @param $val boolean
3786 public function set_last($val) {
3787 $this->last = $val;
3792 * Subclass of navigation_node allowing different rendering for the flat navigation
3793 * in particular allowing dividers and indents.
3795 * @package core
3796 * @category navigation
3797 * @copyright 2016 Damyon Wiese
3798 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3800 class flat_navigation_node extends navigation_node {
3802 /** @var $indent integer The indent level */
3803 private $indent = 0;
3805 /** @var $showdivider bool Show a divider before this element */
3806 private $showdivider = false;
3808 /** @var $collectionlabel string Label for a group of nodes */
3809 private $collectionlabel = '';
3812 * A proxy constructor
3814 * @param mixed $navnode A navigation_node or an array
3816 public function __construct($navnode, $indent) {
3817 if (is_array($navnode)) {
3818 parent::__construct($navnode);
3819 } else if ($navnode instanceof navigation_node) {
3821 // Just clone everything.
3822 $objvalues = get_object_vars($navnode);
3823 foreach ($objvalues as $key => $value) {
3824 $this->$key = $value;
3826 } else {
3827 throw new coding_exception('Not a valid flat_navigation_node');
3829 $this->indent = $indent;
3833 * Setter, a label is required for a flat navigation node that shows a divider.
3835 * @param string $label
3837 public function set_collectionlabel($label) {
3838 $this->collectionlabel = $label;
3842 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
3844 * @return string
3846 public function get_collectionlabel() {
3847 if (!empty($this->collectionlabel)) {
3848 return $this->collectionlabel;
3850 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) {
3851 return $this->parent->get_collectionlabel();
3853 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3854 return '';
3858 * Does this node represent a course section link.
3859 * @return boolean
3861 public function is_section() {
3862 return $this->type == navigation_node::TYPE_SECTION;
3866 * In flat navigation - sections are active if we are looking at activities in the section.
3867 * @return boolean
3869 public function isactive() {
3870 global $PAGE;
3872 if ($this->is_section()) {
3873 $active = $PAGE->navigation->find_active_node();
3874 while ($active = $active->parent) {
3875 if ($active->key == $this->key && $active->type == $this->type) {
3876 return true;
3880 return $this->isactive;
3884 * Getter for "showdivider"
3885 * @return boolean
3887 public function showdivider() {
3888 return $this->showdivider;
3892 * Setter for "showdivider"
3893 * @param $val boolean
3894 * @param $label string Label for the group of nodes
3896 public function set_showdivider($val, $label = '') {
3897 $this->showdivider = $val;
3898 if ($this->showdivider && empty($label)) {
3899 debugging('Navigation region requires a label', DEBUG_DEVELOPER);
3900 } else {
3901 $this->set_collectionlabel($label);
3906 * Getter for "indent"
3907 * @return boolean
3909 public function get_indent() {
3910 return $this->indent;
3914 * Setter for "indent"
3915 * @param $val boolean
3917 public function set_indent($val) {
3918 $this->indent = $val;
3923 * Class used to generate a collection of navigation nodes most closely related
3924 * to the current page.
3926 * @package core
3927 * @copyright 2016 Damyon Wiese
3928 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3930 class flat_navigation extends navigation_node_collection {
3931 /** @var moodle_page the moodle page that the navigation belongs to */
3932 protected $page;
3935 * Constructor.
3937 * @param moodle_page $page
3939 public function __construct(moodle_page &$page) {
3940 if (during_initial_install()) {
3941 return false;
3943 $this->page = $page;
3947 * Build the list of navigation nodes based on the current navigation and settings trees.
3950 public function initialise() {
3951 global $PAGE, $USER, $OUTPUT, $CFG;
3952 if (during_initial_install()) {
3953 return;
3956 $current = false;
3958 $course = $PAGE->course;
3960 $this->page->navigation->initialise();
3962 // First walk the nav tree looking for "flat_navigation" nodes.
3963 if ($course->id > 1) {
3964 // It's a real course.
3965 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3967 $coursecontext = context_course::instance($course->id, MUST_EXIST);
3968 // This is the name that will be shown for the course.
3969 $coursename = empty($CFG->navshowfullcoursenames) ?
3970 format_string($course->shortname, true, array('context' => $coursecontext)) :
3971 format_string($course->fullname, true, array('context' => $coursecontext));
3973 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
3974 $flat->set_collectionlabel($coursename);
3975 $flat->key = 'coursehome';
3976 $flat->icon = new pix_icon('i/course', '');
3978 $courseformat = course_get_format($course);
3979 $coursenode = $PAGE->navigation->find_active_node();
3980 $targettype = navigation_node::TYPE_COURSE;
3982 // Single activity format has no course node - the course node is swapped for the activity node.
3983 if (!$courseformat->has_view_page()) {
3984 $targettype = navigation_node::TYPE_ACTIVITY;
3987 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
3988 $coursenode = $coursenode->parent;
3990 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
3991 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
3992 if ($coursenode && $coursenode->key != SITEID) {
3993 $this->add($flat);
3994 foreach ($coursenode->children as $child) {
3995 if ($child->action) {
3996 $flat = new flat_navigation_node($child, 0);
3997 $this->add($flat);
4002 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
4003 } else {
4004 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
4007 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
4008 if (!$admin) {
4009 // Try again - crazy nav tree!
4010 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
4012 if ($admin) {
4013 $flat = new flat_navigation_node($admin, 0);
4014 $flat->set_showdivider(true, get_string('sitesettings'));
4015 $flat->key = 'sitesettings';
4016 $flat->icon = new pix_icon('t/preferences', '');
4017 $this->add($flat);
4020 // Add-a-block in editing mode.
4021 if (isset($this->page->theme->addblockposition) &&
4022 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
4023 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
4024 ($addable = $PAGE->blocks->get_addable_blocks())) {
4025 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
4026 $addablock = navigation_node::create(get_string('addblock'), $url);
4027 $flat = new flat_navigation_node($addablock, 0);
4028 $flat->set_showdivider(true, get_string('blocksaddedit'));
4029 $flat->key = 'addblock';
4030 $flat->icon = new pix_icon('i/addblock', '');
4031 $this->add($flat);
4032 $blocks = [];
4033 foreach ($addable as $block) {
4034 $blocks[] = $block->name;
4036 $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
4037 $PAGE->requires->js_call_amd('core/addblockmodal', 'init', array($params));
4043 * Override the parent so we can set a label for this collection if it has not been set yet.
4045 * @param navigation_node $node Node to add
4046 * @param string $beforekey If specified, adds before a node with this key,
4047 * otherwise adds at end
4048 * @return navigation_node Added node
4050 public function add(navigation_node $node, $beforekey=null) {
4051 $result = parent::add($node, $beforekey);
4052 // Extend the parent to get a name for the collection of nodes if required.
4053 if (empty($this->collectionlabel)) {
4054 if ($node instanceof flat_navigation_node) {
4055 $this->set_collectionlabel($node->get_collectionlabel());
4059 return $result;
4064 * Class used to manage the settings option for the current page
4066 * This class is used to manage the settings options in a tree format (recursively)
4067 * and was created initially for use with the settings blocks.
4069 * @package core
4070 * @category navigation
4071 * @copyright 2009 Sam Hemelryk
4072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4074 class settings_navigation extends navigation_node {
4075 /** @var stdClass the current context */
4076 protected $context;
4077 /** @var moodle_page the moodle page that the navigation belongs to */
4078 protected $page;
4079 /** @var string contains administration section navigation_nodes */
4080 protected $adminsection;
4081 /** @var bool A switch to see if the navigation node is initialised */
4082 protected $initialised = false;
4083 /** @var array An array of users that the nodes can extend for. */
4084 protected $userstoextendfor = array();
4085 /** @var navigation_cache **/
4086 protected $cache;
4089 * Sets up the object with basic settings and preparse it for use
4091 * @param moodle_page $page
4093 public function __construct(moodle_page &$page) {
4094 if (during_initial_install()) {
4095 return false;
4097 $this->page = $page;
4098 // Initialise the main navigation. It is most important that this is done
4099 // before we try anything
4100 $this->page->navigation->initialise();
4101 // Initialise the navigation cache
4102 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
4103 $this->children = new navigation_node_collection();
4107 * Initialise the settings navigation based on the current context
4109 * This function initialises the settings navigation tree for a given context
4110 * by calling supporting functions to generate major parts of the tree.
4113 public function initialise() {
4114 global $DB, $SESSION, $SITE;
4116 if (during_initial_install()) {
4117 return false;
4118 } else if ($this->initialised) {
4119 return true;
4121 $this->id = 'settingsnav';
4122 $this->context = $this->page->context;
4124 $context = $this->context;
4125 if ($context->contextlevel == CONTEXT_BLOCK) {
4126 $this->load_block_settings();
4127 $context = $context->get_parent_context();
4128 $this->context = $context;
4130 switch ($context->contextlevel) {
4131 case CONTEXT_SYSTEM:
4132 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4133 $this->load_front_page_settings(($context->id == $this->context->id));
4135 break;
4136 case CONTEXT_COURSECAT:
4137 $this->load_category_settings();
4138 break;
4139 case CONTEXT_COURSE:
4140 if ($this->page->course->id != $SITE->id) {
4141 $this->load_course_settings(($context->id == $this->context->id));
4142 } else {
4143 $this->load_front_page_settings(($context->id == $this->context->id));
4145 break;
4146 case CONTEXT_MODULE:
4147 $this->load_module_settings();
4148 $this->load_course_settings();
4149 break;
4150 case CONTEXT_USER:
4151 if ($this->page->course->id != $SITE->id) {
4152 $this->load_course_settings();
4154 break;
4157 $usersettings = $this->load_user_settings($this->page->course->id);
4159 $adminsettings = false;
4160 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4161 $isadminpage = $this->is_admin_tree_needed();
4163 if (has_capability('moodle/site:configview', context_system::instance())) {
4164 if (has_capability('moodle/site:config', context_system::instance())) {
4165 // Make sure this works even if config capability changes on the fly
4166 // and also make it fast for admin right after login.
4167 $SESSION->load_navigation_admin = 1;
4168 if ($isadminpage) {
4169 $adminsettings = $this->load_administration_settings();
4172 } else if (!isset($SESSION->load_navigation_admin)) {
4173 $adminsettings = $this->load_administration_settings();
4174 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4176 } else if ($SESSION->load_navigation_admin) {
4177 if ($isadminpage) {
4178 $adminsettings = $this->load_administration_settings();
4182 // Print empty navigation node, if needed.
4183 if ($SESSION->load_navigation_admin && !$isadminpage) {
4184 if ($adminsettings) {
4185 // Do not print settings tree on pages that do not need it, this helps with performance.
4186 $adminsettings->remove();
4187 $adminsettings = false;
4189 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4190 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4191 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4192 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4193 $siteadminnode->requiresajaxloading = 'true';
4198 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4199 $adminsettings->force_open();
4200 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4201 $usersettings->force_open();
4204 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4205 $this->load_local_plugin_settings();
4207 foreach ($this->children as $key=>$node) {
4208 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4209 // Site administration is shown as link.
4210 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4211 continue;
4213 $node->remove();
4216 $this->initialised = true;
4219 * Override the parent function so that we can add preceeding hr's and set a
4220 * root node class against all first level element
4222 * It does this by first calling the parent's add method {@link navigation_node::add()}
4223 * and then proceeds to use the key to set class and hr
4225 * @param string $text text to be used for the link.
4226 * @param string|moodle_url $url url for the new node
4227 * @param int $type the type of node navigation_node::TYPE_*
4228 * @param string $shorttext
4229 * @param string|int $key a key to access the node by.
4230 * @param pix_icon $icon An icon that appears next to the node.
4231 * @return navigation_node with the new node added to it.
4233 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4234 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4235 $node->add_class('root_node');
4236 return $node;
4240 * This function allows the user to add something to the start of the settings
4241 * navigation, which means it will be at the top of the settings navigation block
4243 * @param string $text text to be used for the link.
4244 * @param string|moodle_url $url url for the new node
4245 * @param int $type the type of node navigation_node::TYPE_*
4246 * @param string $shorttext
4247 * @param string|int $key a key to access the node by.
4248 * @param pix_icon $icon An icon that appears next to the node.
4249 * @return navigation_node $node with the new node added to it.
4251 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4252 $children = $this->children;
4253 $childrenclass = get_class($children);
4254 $this->children = new $childrenclass;
4255 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4256 foreach ($children as $child) {
4257 $this->children->add($child);
4259 return $node;
4263 * Does this page require loading of full admin tree or is
4264 * it enough rely on AJAX?
4266 * @return bool
4268 protected function is_admin_tree_needed() {
4269 if (self::$loadadmintree) {
4270 // Usually external admin page or settings page.
4271 return true;
4274 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4275 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4276 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4277 return false;
4279 return true;
4282 return false;
4286 * Load the site administration tree
4288 * This function loads the site administration tree by using the lib/adminlib library functions
4290 * @param navigation_node $referencebranch A reference to a branch in the settings
4291 * navigation tree
4292 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4293 * tree and start at the beginning
4294 * @return mixed A key to access the admin tree by
4296 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4297 global $CFG;
4299 // Check if we are just starting to generate this navigation.
4300 if ($referencebranch === null) {
4302 // Require the admin lib then get an admin structure
4303 if (!function_exists('admin_get_root')) {
4304 require_once($CFG->dirroot.'/lib/adminlib.php');
4306 $adminroot = admin_get_root(false, false);
4307 // This is the active section identifier
4308 $this->adminsection = $this->page->url->param('section');
4310 // Disable the navigation from automatically finding the active node
4311 navigation_node::$autofindactive = false;
4312 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4313 foreach ($adminroot->children as $adminbranch) {
4314 $this->load_administration_settings($referencebranch, $adminbranch);
4316 navigation_node::$autofindactive = true;
4318 // Use the admin structure to locate the active page
4319 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4320 $currentnode = $this;
4321 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4322 $currentnode = $currentnode->get($pathkey);
4324 if ($currentnode) {
4325 $currentnode->make_active();
4327 } else {
4328 $this->scan_for_active_node($referencebranch);
4330 return $referencebranch;
4331 } else if ($adminbranch->check_access()) {
4332 // We have a reference branch that we can access and is not hidden `hurrah`
4333 // Now we need to display it and any children it may have
4334 $url = null;
4335 $icon = null;
4336 if ($adminbranch instanceof admin_settingpage) {
4337 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
4338 } else if ($adminbranch instanceof admin_externalpage) {
4339 $url = $adminbranch->url;
4340 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4341 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
4344 // Add the branch
4345 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4347 if ($adminbranch->is_hidden()) {
4348 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4349 $reference->add_class('hidden');
4350 } else {
4351 $reference->display = false;
4355 // Check if we are generating the admin notifications and whether notificiations exist
4356 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4357 $reference->add_class('criticalnotification');
4359 // Check if this branch has children
4360 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4361 foreach ($adminbranch->children as $branch) {
4362 // Generate the child branches as well now using this branch as the reference
4363 $this->load_administration_settings($reference, $branch);
4365 } else {
4366 $reference->icon = new pix_icon('i/settings', '');
4372 * This function recursivily scans nodes until it finds the active node or there
4373 * are no more nodes.
4374 * @param navigation_node $node
4376 protected function scan_for_active_node(navigation_node $node) {
4377 if (!$node->check_if_active() && $node->children->count()>0) {
4378 foreach ($node->children as &$child) {
4379 $this->scan_for_active_node($child);
4385 * Gets a navigation node given an array of keys that represent the path to
4386 * the desired node.
4388 * @param array $path
4389 * @return navigation_node|false
4391 protected function get_by_path(array $path) {
4392 $node = $this->get(array_shift($path));
4393 foreach ($path as $key) {
4394 $node->get($key);
4396 return $node;
4400 * This function loads the course settings that are available for the user
4402 * @param bool $forceopen If set to true the course node will be forced open
4403 * @return navigation_node|false
4405 protected function load_course_settings($forceopen = false) {
4406 global $CFG;
4407 require_once($CFG->dirroot . '/course/lib.php');
4409 $course = $this->page->course;
4410 $coursecontext = context_course::instance($course->id);
4411 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4413 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4415 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4416 if ($forceopen) {
4417 $coursenode->force_open();
4421 if ($adminoptions->update) {
4422 // Add the course settings link
4423 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4424 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
4427 if ($this->page->user_allowed_editing()) {
4428 // Add the turn on/off settings
4430 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
4431 // We are on the course page, retain the current page params e.g. section.
4432 $baseurl = clone($this->page->url);
4433 $baseurl->param('sesskey', sesskey());
4434 } else {
4435 // Edit on the main course page.
4436 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
4439 $editurl = clone($baseurl);
4440 if ($this->page->user_is_editing()) {
4441 $editurl->param('edit', 'off');
4442 $editstring = get_string('turneditingoff');
4443 } else {
4444 $editurl->param('edit', 'on');
4445 $editstring = get_string('turneditingon');
4447 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
4450 if ($adminoptions->editcompletion) {
4451 // Add the course completion settings link
4452 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4453 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null,
4454 new pix_icon('i/settings', ''));
4457 if (!$adminoptions->update && $adminoptions->tags) {
4458 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4459 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4462 // add enrol nodes
4463 enrol_add_course_navigation($coursenode, $course);
4465 // Manage filters
4466 if ($adminoptions->filters) {
4467 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4468 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4471 // View course reports.
4472 if ($adminoptions->reports) {
4473 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'coursereports',
4474 new pix_icon('i/stats', ''));
4475 $coursereports = core_component::get_plugin_list('coursereport');
4476 foreach ($coursereports as $report => $dir) {
4477 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4478 if (file_exists($libfile)) {
4479 require_once($libfile);
4480 $reportfunction = $report.'_report_extend_navigation';
4481 if (function_exists($report.'_report_extend_navigation')) {
4482 $reportfunction($reportnav, $course, $coursecontext);
4487 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4488 foreach ($reports as $reportfunction) {
4489 $reportfunction($reportnav, $course, $coursecontext);
4493 // Check if we can view the gradebook's setup page.
4494 if ($adminoptions->gradebook) {
4495 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4496 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4497 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4500 // Add the context locking node.
4501 $this->add_context_locking_node($coursenode, $coursecontext);
4503 // Add outcome if permitted
4504 if ($adminoptions->outcomes) {
4505 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4506 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4509 //Add badges navigation
4510 if ($adminoptions->badges) {
4511 require_once($CFG->libdir .'/badgeslib.php');
4512 badges_add_course_navigation($coursenode, $course);
4515 // Backup this course
4516 if ($adminoptions->backup) {
4517 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4518 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4521 // Restore to this course
4522 if ($adminoptions->restore) {
4523 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4524 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4527 // Import data from other courses
4528 if ($adminoptions->import) {
4529 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
4530 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4533 // Reset this course
4534 if ($adminoptions->reset) {
4535 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4536 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4539 // Questions
4540 require_once($CFG->libdir . '/questionlib.php');
4541 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4543 if ($adminoptions->update) {
4544 // Repository Instances
4545 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4546 require_once($CFG->dirroot . '/repository/lib.php');
4547 $editabletypes = repository::get_editable_types($coursecontext);
4548 $haseditabletypes = !empty($editabletypes);
4549 unset($editabletypes);
4550 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4551 } else {
4552 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4554 if ($haseditabletypes) {
4555 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4556 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4560 // Manage files
4561 if ($adminoptions->files) {
4562 // hidden in new courses and courses where legacy files were turned off
4563 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4564 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4568 // Let plugins hook into course navigation.
4569 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4570 foreach ($pluginsfunction as $plugintype => $plugins) {
4571 // Ignore the report plugin as it was already loaded above.
4572 if ($plugintype == 'report') {
4573 continue;
4575 foreach ($plugins as $pluginfunction) {
4576 $pluginfunction($coursenode, $course, $coursecontext);
4580 // Return we are done
4581 return $coursenode;
4585 * This function calls the module function to inject module settings into the
4586 * settings navigation tree.
4588 * This only gets called if there is a corrosponding function in the modules
4589 * lib file.
4591 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4593 * @return navigation_node|false
4595 protected function load_module_settings() {
4596 global $CFG;
4598 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4599 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4600 $this->page->set_cm($cm, $this->page->course);
4603 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4604 if (file_exists($file)) {
4605 require_once($file);
4608 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4609 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4610 $modulenode->force_open();
4612 // Settings for the module
4613 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4614 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4615 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
4617 // Assign local roles
4618 if (count(get_assignable_roles($this->page->cm->context))>0) {
4619 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4620 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
4622 // Override roles
4623 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4624 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4625 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
4627 // Check role permissions
4628 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4629 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4630 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
4633 // Add the context locking node.
4634 $this->add_context_locking_node($modulenode, $this->page->cm->context);
4636 // Manage filters
4637 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4638 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4639 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
4641 // Add reports
4642 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4643 foreach ($reports as $reportfunction) {
4644 $reportfunction($modulenode, $this->page->cm);
4646 // Add a backup link
4647 $featuresfunc = $this->page->activityname.'_supports';
4648 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4649 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4650 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4653 // Restore this activity
4654 $featuresfunc = $this->page->activityname.'_supports';
4655 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4656 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4657 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4660 // Allow the active advanced grading method plugin to append its settings
4661 $featuresfunc = $this->page->activityname.'_supports';
4662 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4663 require_once($CFG->dirroot.'/grade/grading/lib.php');
4664 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4665 $gradingman->extend_settings_navigation($this, $modulenode);
4668 $function = $this->page->activityname.'_extend_settings_navigation';
4669 if (function_exists($function)) {
4670 $function($this, $modulenode);
4673 // Remove the module node if there are no children.
4674 if ($modulenode->children->count() <= 0) {
4675 $modulenode->remove();
4678 return $modulenode;
4682 * Loads the user settings block of the settings nav
4684 * This function is simply works out the userid and whether we need to load
4685 * just the current users profile settings, or the current user and the user the
4686 * current user is viewing.
4688 * This function has some very ugly code to work out the user, if anyone has
4689 * any bright ideas please feel free to intervene.
4691 * @param int $courseid The course id of the current course
4692 * @return navigation_node|false
4694 protected function load_user_settings($courseid = SITEID) {
4695 global $USER, $CFG;
4697 if (isguestuser() || !isloggedin()) {
4698 return false;
4701 $navusers = $this->page->navigation->get_extending_users();
4703 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4704 $usernode = null;
4705 foreach ($this->userstoextendfor as $userid) {
4706 if ($userid == $USER->id) {
4707 continue;
4709 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4710 if (is_null($usernode)) {
4711 $usernode = $node;
4714 foreach ($navusers as $user) {
4715 if ($user->id == $USER->id) {
4716 continue;
4718 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4719 if (is_null($usernode)) {
4720 $usernode = $node;
4723 $this->generate_user_settings($courseid, $USER->id);
4724 } else {
4725 $usernode = $this->generate_user_settings($courseid, $USER->id);
4727 return $usernode;
4731 * Extends the settings navigation for the given user.
4733 * Note: This method gets called automatically if you call
4734 * $PAGE->navigation->extend_for_user($userid)
4736 * @param int $userid
4738 public function extend_for_user($userid) {
4739 global $CFG;
4741 if (!in_array($userid, $this->userstoextendfor)) {
4742 $this->userstoextendfor[] = $userid;
4743 if ($this->initialised) {
4744 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4745 $children = array();
4746 foreach ($this->children as $child) {
4747 $children[] = $child;
4749 array_unshift($children, array_pop($children));
4750 $this->children = new navigation_node_collection();
4751 foreach ($children as $child) {
4752 $this->children->add($child);
4759 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4760 * what can be shown/done
4762 * @param int $courseid The current course' id
4763 * @param int $userid The user id to load for
4764 * @param string $gstitle The string to pass to get_string for the branch title
4765 * @return navigation_node|false
4767 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4768 global $DB, $CFG, $USER, $SITE;
4770 if ($courseid != $SITE->id) {
4771 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4772 $course = $this->page->course;
4773 } else {
4774 $select = context_helper::get_preload_record_columns_sql('ctx');
4775 $sql = "SELECT c.*, $select
4776 FROM {course} c
4777 JOIN {context} ctx ON c.id = ctx.instanceid
4778 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4779 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4780 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4781 context_helper::preload_from_record($course);
4783 } else {
4784 $course = $SITE;
4787 $coursecontext = context_course::instance($course->id); // Course context
4788 $systemcontext = context_system::instance();
4789 $currentuser = ($USER->id == $userid);
4791 if ($currentuser) {
4792 $user = $USER;
4793 $usercontext = context_user::instance($user->id); // User context
4794 } else {
4795 $select = context_helper::get_preload_record_columns_sql('ctx');
4796 $sql = "SELECT u.*, $select
4797 FROM {user} u
4798 JOIN {context} ctx ON u.id = ctx.instanceid
4799 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4800 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4801 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4802 if (!$user) {
4803 return false;
4805 context_helper::preload_from_record($user);
4807 // Check that the user can view the profile
4808 $usercontext = context_user::instance($user->id); // User context
4809 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4811 if ($course->id == $SITE->id) {
4812 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4813 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4814 return false;
4816 } else {
4817 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4818 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4819 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4820 return false;
4822 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4823 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4824 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4825 if ($courseid == $this->page->course->id) {
4826 $mygroups = get_fast_modinfo($this->page->course)->groups;
4827 } else {
4828 $mygroups = groups_get_user_groups($courseid);
4830 $usergroups = groups_get_user_groups($courseid, $userid);
4831 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4832 return false;
4838 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4840 $key = $gstitle;
4841 $prefurl = new moodle_url('/user/preferences.php');
4842 if ($gstitle != 'usercurrentsettings') {
4843 $key .= $userid;
4844 $prefurl->param('userid', $userid);
4847 // Add a user setting branch.
4848 if ($gstitle == 'usercurrentsettings') {
4849 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4850 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4851 // breadcrumb.
4852 $dashboard->display = false;
4853 if (get_home_page() == HOMEPAGE_MY) {
4854 $dashboard->mainnavonly = true;
4857 $iscurrentuser = ($user->id == $USER->id);
4859 $baseargs = array('id' => $user->id);
4860 if ($course->id != $SITE->id && !$iscurrentuser) {
4861 $baseargs['course'] = $course->id;
4862 $issitecourse = false;
4863 } else {
4864 // Load all categories and get the context for the system.
4865 $issitecourse = true;
4868 // Add the user profile to the dashboard.
4869 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4870 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4872 if (!empty($CFG->navadduserpostslinks)) {
4873 // Add nodes for forum posts and discussions if the user can view either or both
4874 // There are no capability checks here as the content of the page is based
4875 // purely on the forums the current user has access too.
4876 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4877 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4878 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4879 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4882 // Add blog nodes.
4883 if (!empty($CFG->enableblogs)) {
4884 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4885 require_once($CFG->dirroot.'/blog/lib.php');
4886 // Get all options for the user.
4887 $options = blog_get_options_for_user($user);
4888 $this->cache->set('userblogoptions'.$user->id, $options);
4889 } else {
4890 $options = $this->cache->{'userblogoptions'.$user->id};
4893 if (count($options) > 0) {
4894 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4895 foreach ($options as $type => $option) {
4896 if ($type == "rss") {
4897 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4898 new pix_icon('i/rss', ''));
4899 } else {
4900 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4906 // Add the messages link.
4907 // It is context based so can appear in the user's profile and in course participants information.
4908 if (!empty($CFG->messaging)) {
4909 $messageargs = array('user1' => $USER->id);
4910 if ($USER->id != $user->id) {
4911 $messageargs['user2'] = $user->id;
4913 $url = new moodle_url('/message/index.php', $messageargs);
4914 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4917 // Add the "My private files" link.
4918 // This link doesn't have a unique display for course context so only display it under the user's profile.
4919 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4920 $url = new moodle_url('/user/files.php');
4921 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
4924 // Add a node to view the users notes if permitted.
4925 if (!empty($CFG->enablenotes) &&
4926 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4927 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4928 if ($coursecontext->instanceid != SITEID) {
4929 $url->param('course', $coursecontext->instanceid);
4931 $profilenode->add(get_string('notes', 'notes'), $url);
4934 // Show the grades node.
4935 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
4936 require_once($CFG->dirroot . '/user/lib.php');
4937 // Set the grades node to link to the "Grades" page.
4938 if ($course->id == SITEID) {
4939 $url = user_mygrades_url($user->id, $course->id);
4940 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4941 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
4943 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
4946 // Let plugins hook into user navigation.
4947 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
4948 foreach ($pluginsfunction as $plugintype => $plugins) {
4949 if ($plugintype != 'report') {
4950 foreach ($plugins as $pluginfunction) {
4951 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
4956 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4957 $dashboard->add_node($usersetting);
4958 } else {
4959 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4960 $usersetting->display = false;
4962 $usersetting->id = 'usersettings';
4964 // Check if the user has been deleted.
4965 if ($user->deleted) {
4966 if (!has_capability('moodle/user:update', $coursecontext)) {
4967 // We can't edit the user so just show the user deleted message.
4968 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4969 } else {
4970 // We can edit the user so show the user deleted message and link it to the profile.
4971 if ($course->id == $SITE->id) {
4972 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4973 } else {
4974 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4976 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4978 return true;
4981 $userauthplugin = false;
4982 if (!empty($user->auth)) {
4983 $userauthplugin = get_auth_plugin($user->auth);
4986 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
4988 // Add the profile edit link.
4989 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4990 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
4991 has_capability('moodle/user:update', $systemcontext)) {
4992 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4993 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4994 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4995 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4996 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4997 $url = $userauthplugin->edit_profile_url();
4998 if (empty($url)) {
4999 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
5001 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
5006 // Change password link.
5007 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
5008 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5009 $passwordchangeurl = $userauthplugin->change_password_url();
5010 if (empty($passwordchangeurl)) {
5011 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
5013 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
5016 // Default homepage.
5017 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER));
5018 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5019 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5020 has_capability('moodle/user:editprofile', $usercontext)) {
5021 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]);
5022 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser');
5026 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5027 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5028 has_capability('moodle/user:editprofile', $usercontext)) {
5029 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
5030 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
5033 $pluginmanager = core_plugin_manager::instance();
5034 $enabled = $pluginmanager->get_enabled_plugins('mod');
5035 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5036 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5037 has_capability('moodle/user:editprofile', $usercontext)) {
5038 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
5039 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
5042 $editors = editors_get_enabled();
5043 if (count($editors) > 1) {
5044 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5045 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5046 has_capability('moodle/user:editprofile', $usercontext)) {
5047 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
5048 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
5053 // Add "Course preferences" link.
5054 if (isloggedin() && !isguestuser($user)) {
5055 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5056 has_capability('moodle/user:editprofile', $usercontext)) {
5057 $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
5058 $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
5062 // Add "Calendar preferences" link.
5063 if (isloggedin() && !isguestuser($user)) {
5064 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5065 has_capability('moodle/user:editprofile', $usercontext)) {
5066 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
5067 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
5071 // View the roles settings.
5072 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5073 'moodle/role:manage'), $usercontext)) {
5074 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
5076 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
5077 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
5079 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
5081 if (!empty($assignableroles)) {
5082 $url = new moodle_url('/admin/roles/assign.php',
5083 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5084 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
5087 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
5088 $url = new moodle_url('/admin/roles/permissions.php',
5089 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5090 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
5093 $url = new moodle_url('/admin/roles/check.php',
5094 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
5095 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
5098 // Repositories.
5099 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
5100 require_once($CFG->dirroot . '/repository/lib.php');
5101 $editabletypes = repository::get_editable_types($usercontext);
5102 $haseditabletypes = !empty($editabletypes);
5103 unset($editabletypes);
5104 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
5105 } else {
5106 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
5108 if ($haseditabletypes) {
5109 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
5110 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5111 array('contextid' => $usercontext->id)));
5114 // Portfolio.
5115 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
5116 require_once($CFG->libdir . '/portfoliolib.php');
5117 if (portfolio_has_visible_instances()) {
5118 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
5120 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
5121 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
5123 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
5124 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
5128 $enablemanagetokens = false;
5129 if (!empty($CFG->enablerssfeeds)) {
5130 $enablemanagetokens = true;
5131 } else if (!is_siteadmin($USER->id)
5132 && !empty($CFG->enablewebservices)
5133 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
5134 $enablemanagetokens = true;
5136 // Security keys.
5137 if ($currentuser && $enablemanagetokens) {
5138 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
5139 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5142 // Messaging.
5143 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
5144 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
5145 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
5146 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
5147 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
5148 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
5151 // Blogs.
5152 if ($currentuser && !empty($CFG->enableblogs)) {
5153 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
5154 if (has_capability('moodle/blog:view', $systemcontext)) {
5155 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5156 navigation_node::TYPE_SETTING);
5158 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
5159 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5160 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5161 navigation_node::TYPE_SETTING);
5162 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5163 navigation_node::TYPE_SETTING);
5165 // Remove the blog node if empty.
5166 $blog->trim_if_empty();
5169 // Badges.
5170 if ($currentuser && !empty($CFG->enablebadges)) {
5171 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5172 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5173 $url = new moodle_url('/badges/mybadges.php');
5174 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5176 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5177 navigation_node::TYPE_SETTING);
5178 if (!empty($CFG->badges_allowexternalbackpack)) {
5179 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5180 navigation_node::TYPE_SETTING);
5184 // Let plugins hook into user settings navigation.
5185 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5186 foreach ($pluginsfunction as $plugintype => $plugins) {
5187 foreach ($plugins as $pluginfunction) {
5188 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5192 return $usersetting;
5196 * Loads block specific settings in the navigation
5198 * @return navigation_node
5200 protected function load_block_settings() {
5201 global $CFG;
5203 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5204 $blocknode->force_open();
5206 // Assign local roles
5207 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5208 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5209 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5210 'roles', new pix_icon('i/assignroles', ''));
5213 // Override roles
5214 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5215 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5216 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5217 'permissions', new pix_icon('i/permissions', ''));
5219 // Check role permissions
5220 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5221 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5222 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5223 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5226 // Add the context locking node.
5227 $this->add_context_locking_node($blocknode, $this->context);
5229 return $blocknode;
5233 * Loads category specific settings in the navigation
5235 * @return navigation_node
5237 protected function load_category_settings() {
5238 global $CFG;
5240 // We can land here while being in the context of a block, in which case we
5241 // should get the parent context which should be the category one. See self::initialise().
5242 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5243 $catcontext = $this->context->get_parent_context();
5244 } else {
5245 $catcontext = $this->context;
5248 // Let's make sure that we always have the right context when getting here.
5249 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5250 throw new coding_exception('Unexpected context while loading category settings.');
5253 $categorynodetype = navigation_node::TYPE_CONTAINER;
5254 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5255 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5256 $categorynode->force_open();
5258 if (can_edit_in_category($catcontext->instanceid)) {
5259 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5260 $editstring = get_string('managecategorythis');
5261 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5264 if (has_capability('moodle/category:manage', $catcontext)) {
5265 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5266 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5268 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5269 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5272 // Assign local roles
5273 $assignableroles = get_assignable_roles($catcontext);
5274 if (!empty($assignableroles)) {
5275 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5276 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5279 // Override roles
5280 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5281 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5282 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5284 // Check role permissions
5285 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5286 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5287 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5288 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5291 // Add the context locking node.
5292 $this->add_context_locking_node($categorynode, $catcontext);
5294 // Cohorts
5295 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5296 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5297 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5300 // Manage filters
5301 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5302 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5303 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5306 // Restore.
5307 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5308 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5309 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5312 // Let plugins hook into category settings navigation.
5313 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5314 foreach ($pluginsfunction as $plugintype => $plugins) {
5315 foreach ($plugins as $pluginfunction) {
5316 $pluginfunction($categorynode, $catcontext);
5320 return $categorynode;
5324 * Determine whether the user is assuming another role
5326 * This function checks to see if the user is assuming another role by means of
5327 * role switching. In doing this we compare each RSW key (context path) against
5328 * the current context path. This ensures that we can provide the switching
5329 * options against both the course and any page shown under the course.
5331 * @return bool|int The role(int) if the user is in another role, false otherwise
5333 protected function in_alternative_role() {
5334 global $USER;
5335 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5336 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5337 return $USER->access['rsw'][$this->page->context->path];
5339 foreach ($USER->access['rsw'] as $key=>$role) {
5340 if (strpos($this->context->path,$key)===0) {
5341 return $role;
5345 return false;
5349 * This function loads all of the front page settings into the settings navigation.
5350 * This function is called when the user is on the front page, or $COURSE==$SITE
5351 * @param bool $forceopen (optional)
5352 * @return navigation_node
5354 protected function load_front_page_settings($forceopen = false) {
5355 global $SITE, $CFG;
5356 require_once($CFG->dirroot . '/course/lib.php');
5358 $course = clone($SITE);
5359 $coursecontext = context_course::instance($course->id); // Course context
5360 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5362 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5363 if ($forceopen) {
5364 $frontpage->force_open();
5366 $frontpage->id = 'frontpagesettings';
5368 if ($this->page->user_allowed_editing()) {
5370 // Add the turn on/off settings
5371 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5372 if ($this->page->user_is_editing()) {
5373 $url->param('edit', 'off');
5374 $editstring = get_string('turneditingoff');
5375 } else {
5376 $url->param('edit', 'on');
5377 $editstring = get_string('turneditingon');
5379 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5382 if ($adminoptions->update) {
5383 // Add the course settings link
5384 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5385 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5388 // add enrol nodes
5389 enrol_add_course_navigation($frontpage, $course);
5391 // Manage filters
5392 if ($adminoptions->filters) {
5393 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5394 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5397 // View course reports.
5398 if ($adminoptions->reports) {
5399 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5400 new pix_icon('i/stats', ''));
5401 $coursereports = core_component::get_plugin_list('coursereport');
5402 foreach ($coursereports as $report=>$dir) {
5403 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5404 if (file_exists($libfile)) {
5405 require_once($libfile);
5406 $reportfunction = $report.'_report_extend_navigation';
5407 if (function_exists($report.'_report_extend_navigation')) {
5408 $reportfunction($frontpagenav, $course, $coursecontext);
5413 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5414 foreach ($reports as $reportfunction) {
5415 $reportfunction($frontpagenav, $course, $coursecontext);
5419 // Backup this course
5420 if ($adminoptions->backup) {
5421 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5422 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5425 // Restore to this course
5426 if ($adminoptions->restore) {
5427 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5428 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5431 // Questions
5432 require_once($CFG->libdir . '/questionlib.php');
5433 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5435 // Manage files
5436 if ($adminoptions->files) {
5437 //hiden in new installs
5438 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5439 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5442 // Let plugins hook into frontpage navigation.
5443 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5444 foreach ($pluginsfunction as $plugintype => $plugins) {
5445 foreach ($plugins as $pluginfunction) {
5446 $pluginfunction($frontpage, $course, $coursecontext);
5450 return $frontpage;
5454 * This function gives local plugins an opportunity to modify the settings navigation.
5456 protected function load_local_plugin_settings() {
5458 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5459 $function($this, $this->context);
5464 * This function marks the cache as volatile so it is cleared during shutdown
5466 public function clear_cache() {
5467 $this->cache->volatile();
5471 * Checks to see if there are child nodes available in the specific user's preference node.
5472 * If so, then they have the appropriate permissions view this user's preferences.
5474 * @since Moodle 2.9.3
5475 * @param int $userid The user's ID.
5476 * @return bool True if child nodes exist to view, otherwise false.
5478 public function can_view_user_preferences($userid) {
5479 if (is_siteadmin()) {
5480 return true;
5482 // See if any nodes are present in the preferences section for this user.
5483 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5484 if ($preferencenode && $preferencenode->has_children()) {
5485 // Run through each child node.
5486 foreach ($preferencenode->children as $childnode) {
5487 // If the child node has children then this user has access to a link in the preferences page.
5488 if ($childnode->has_children()) {
5489 return true;
5493 // No links found for the user to access on the preferences page.
5494 return false;
5499 * Class used to populate site admin navigation for ajax.
5501 * @package core
5502 * @category navigation
5503 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5504 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5506 class settings_navigation_ajax extends settings_navigation {
5508 * Constructs the navigation for use in an AJAX request
5510 * @param moodle_page $page
5512 public function __construct(moodle_page &$page) {
5513 $this->page = $page;
5514 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5515 $this->children = new navigation_node_collection();
5516 $this->initialise();
5520 * Initialise the site admin navigation.
5522 * @return array An array of the expandable nodes
5524 public function initialise() {
5525 if ($this->initialised || during_initial_install()) {
5526 return false;
5528 $this->context = $this->page->context;
5529 $this->load_administration_settings();
5531 // Check if local plugins is adding node to site admin.
5532 $this->load_local_plugin_settings();
5534 $this->initialised = true;
5539 * Simple class used to output a navigation branch in XML
5541 * @package core
5542 * @category navigation
5543 * @copyright 2009 Sam Hemelryk
5544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5546 class navigation_json {
5547 /** @var array An array of different node types */
5548 protected $nodetype = array('node','branch');
5549 /** @var array An array of node keys and types */
5550 protected $expandable = array();
5552 * Turns a branch and all of its children into XML
5554 * @param navigation_node $branch
5555 * @return string XML string
5557 public function convert($branch) {
5558 $xml = $this->convert_child($branch);
5559 return $xml;
5562 * Set the expandable items in the array so that we have enough information
5563 * to attach AJAX events
5564 * @param array $expandable
5566 public function set_expandable($expandable) {
5567 foreach ($expandable as $node) {
5568 $this->expandable[$node['key'].':'.$node['type']] = $node;
5572 * Recusively converts a child node and its children to XML for output
5574 * @param navigation_node $child The child to convert
5575 * @param int $depth Pointlessly used to track the depth of the XML structure
5576 * @return string JSON
5578 protected function convert_child($child, $depth=1) {
5579 if (!$child->display) {
5580 return '';
5582 $attributes = array();
5583 $attributes['id'] = $child->id;
5584 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5585 $attributes['type'] = $child->type;
5586 $attributes['key'] = $child->key;
5587 $attributes['class'] = $child->get_css_type();
5588 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5590 if ($child->icon instanceof pix_icon) {
5591 $attributes['icon'] = array(
5592 'component' => $child->icon->component,
5593 'pix' => $child->icon->pix,
5595 foreach ($child->icon->attributes as $key=>$value) {
5596 if ($key == 'class') {
5597 $attributes['icon']['classes'] = explode(' ', $value);
5598 } else if (!array_key_exists($key, $attributes['icon'])) {
5599 $attributes['icon'][$key] = $value;
5603 } else if (!empty($child->icon)) {
5604 $attributes['icon'] = (string)$child->icon;
5607 if ($child->forcetitle || $child->title !== $child->text) {
5608 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5610 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5611 $attributes['expandable'] = $child->key;
5612 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5615 if (count($child->classes)>0) {
5616 $attributes['class'] .= ' '.join(' ',$child->classes);
5618 if (is_string($child->action)) {
5619 $attributes['link'] = $child->action;
5620 } else if ($child->action instanceof moodle_url) {
5621 $attributes['link'] = $child->action->out();
5622 } else if ($child->action instanceof action_link) {
5623 $attributes['link'] = $child->action->url->out();
5625 $attributes['hidden'] = ($child->hidden);
5626 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5627 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5629 if ($child->children->count() > 0) {
5630 $attributes['children'] = array();
5631 foreach ($child->children as $subchild) {
5632 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5636 if ($depth > 1) {
5637 return $attributes;
5638 } else {
5639 return json_encode($attributes);
5645 * The cache class used by global navigation and settings navigation.
5647 * It is basically an easy access point to session with a bit of smarts to make
5648 * sure that the information that is cached is valid still.
5650 * Example use:
5651 * <code php>
5652 * if (!$cache->viewdiscussion()) {
5653 * // Code to do stuff and produce cachable content
5654 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5656 * $content = $cache->viewdiscussion;
5657 * </code>
5659 * @package core
5660 * @category navigation
5661 * @copyright 2009 Sam Hemelryk
5662 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5664 class navigation_cache {
5665 /** @var int represents the time created */
5666 protected $creation;
5667 /** @var array An array of session keys */
5668 protected $session;
5670 * The string to use to segregate this particular cache. It can either be
5671 * unique to start a fresh cache or if you want to share a cache then make
5672 * it the string used in the original cache.
5673 * @var string
5675 protected $area;
5676 /** @var int a time that the information will time out */
5677 protected $timeout;
5678 /** @var stdClass The current context */
5679 protected $currentcontext;
5680 /** @var int cache time information */
5681 const CACHETIME = 0;
5682 /** @var int cache user id */
5683 const CACHEUSERID = 1;
5684 /** @var int cache value */
5685 const CACHEVALUE = 2;
5686 /** @var null|array An array of navigation cache areas to expire on shutdown */
5687 public static $volatilecaches;
5690 * Contructor for the cache. Requires two arguments
5692 * @param string $area The string to use to segregate this particular cache
5693 * it can either be unique to start a fresh cache or if you want
5694 * to share a cache then make it the string used in the original
5695 * cache
5696 * @param int $timeout The number of seconds to time the information out after
5698 public function __construct($area, $timeout=1800) {
5699 $this->creation = time();
5700 $this->area = $area;
5701 $this->timeout = time() - $timeout;
5702 if (rand(0,100) === 0) {
5703 $this->garbage_collection();
5708 * Used to set up the cache within the SESSION.
5710 * This is called for each access and ensure that we don't put anything into the session before
5711 * it is required.
5713 protected function ensure_session_cache_initialised() {
5714 global $SESSION;
5715 if (empty($this->session)) {
5716 if (!isset($SESSION->navcache)) {
5717 $SESSION->navcache = new stdClass;
5719 if (!isset($SESSION->navcache->{$this->area})) {
5720 $SESSION->navcache->{$this->area} = array();
5722 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5727 * Magic Method to retrieve something by simply calling using = cache->key
5729 * @param mixed $key The identifier for the information you want out again
5730 * @return void|mixed Either void or what ever was put in
5732 public function __get($key) {
5733 if (!$this->cached($key)) {
5734 return;
5736 $information = $this->session[$key][self::CACHEVALUE];
5737 return unserialize($information);
5741 * Magic method that simply uses {@link set();} to store something in the cache
5743 * @param string|int $key
5744 * @param mixed $information
5746 public function __set($key, $information) {
5747 $this->set($key, $information);
5751 * Sets some information against the cache (session) for later retrieval
5753 * @param string|int $key
5754 * @param mixed $information
5756 public function set($key, $information) {
5757 global $USER;
5758 $this->ensure_session_cache_initialised();
5759 $information = serialize($information);
5760 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5763 * Check the existence of the identifier in the cache
5765 * @param string|int $key
5766 * @return bool
5768 public function cached($key) {
5769 global $USER;
5770 $this->ensure_session_cache_initialised();
5771 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) {
5772 return false;
5774 return true;
5777 * Compare something to it's equivilant in the cache
5779 * @param string $key
5780 * @param mixed $value
5781 * @param bool $serialise Whether to serialise the value before comparison
5782 * this should only be set to false if the value is already
5783 * serialised
5784 * @return bool If the value is the same false if it is not set or doesn't match
5786 public function compare($key, $value, $serialise = true) {
5787 if ($this->cached($key)) {
5788 if ($serialise) {
5789 $value = serialize($value);
5791 if ($this->session[$key][self::CACHEVALUE] === $value) {
5792 return true;
5795 return false;
5798 * Wipes the entire cache, good to force regeneration
5800 public function clear() {
5801 global $SESSION;
5802 unset($SESSION->navcache);
5803 $this->session = null;
5806 * Checks all cache entries and removes any that have expired, good ole cleanup
5808 protected function garbage_collection() {
5809 if (empty($this->session)) {
5810 return true;
5812 foreach ($this->session as $key=>$cachedinfo) {
5813 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5814 unset($this->session[$key]);
5820 * Marks the cache as being volatile (likely to change)
5822 * Any caches marked as volatile will be destroyed at the on shutdown by
5823 * {@link navigation_node::destroy_volatile_caches()} which is registered
5824 * as a shutdown function if any caches are marked as volatile.
5826 * @param bool $setting True to destroy the cache false not too
5828 public function volatile($setting = true) {
5829 if (self::$volatilecaches===null) {
5830 self::$volatilecaches = array();
5831 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5834 if ($setting) {
5835 self::$volatilecaches[$this->area] = $this->area;
5836 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5837 unset(self::$volatilecaches[$this->area]);
5842 * Destroys all caches marked as volatile
5844 * This function is static and works in conjunction with the static volatilecaches
5845 * property of navigation cache.
5846 * Because this function is static it manually resets the cached areas back to an
5847 * empty array.
5849 public static function destroy_volatile_caches() {
5850 global $SESSION;
5851 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5852 foreach (self::$volatilecaches as $area) {
5853 $SESSION->navcache->{$area} = array();
5855 } else {
5856 $SESSION->navcache = new stdClass;